Refactoring: Editor::markAllMisspellingsAndBadGrammarInRanges should be refactored.
[WebKit-https.git] / Source / WebCore / editing / Editor.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "Editor.h"
29
30 #include "AXObjectCache.h"
31 #include "ApplyStyleCommand.h"
32 #include "CSSComputedStyleDeclaration.h"
33 #include "CSSMutableStyleDeclaration.h"
34 #include "CSSProperty.h"
35 #include "CSSPropertyNames.h"
36 #include "CSSStyleSelector.h"
37 #include "CSSValueKeywords.h"
38 #include "CachedResourceLoader.h"
39 #include "ClipboardEvent.h"
40 #include "CompositionEvent.h"
41 #include "SpellingCorrectionController.h"
42 #include "CreateLinkCommand.h"
43 #include "DeleteButtonController.h"
44 #include "DeleteSelectionCommand.h"
45 #include "DocumentFragment.h"
46 #include "DocumentMarkerController.h"
47 #include "EditingText.h"
48 #include "EditorClient.h"
49 #include "EventHandler.h"
50 #include "EventNames.h"
51 #include "FocusController.h"
52 #include "Frame.h"
53 #include "FrameTree.h"
54 #include "FrameView.h"
55 #include "GraphicsContext.h"
56 #include "HTMLFormControlElement.h"
57 #include "HTMLFrameOwnerElement.h"
58 #include "HTMLNames.h"
59 #include "HTMLTextAreaElement.h"
60 #include "HitTestResult.h"
61 #include "IndentOutdentCommand.h"
62 #include "InsertListCommand.h"
63 #include "KeyboardEvent.h"
64 #include "KillRing.h"
65 #include "ModifySelectionListLevel.h"
66 #include "NodeList.h"
67 #include "Page.h"
68 #include "Pasteboard.h"
69 #include "TextCheckingHelper.h"
70 #include "RemoveFormatCommand.h"
71 #include "RenderBlock.h"
72 #include "RenderPart.h"
73 #include "RenderTextControl.h"
74 #include "RenderedPosition.h"
75 #include "ReplaceSelectionCommand.h"
76 #include "Settings.h"
77 #include "Sound.h"
78 #include "SpellChecker.h"
79 #include "SpellingCorrectionCommand.h"
80 #include "Text.h"
81 #include "TextCheckerClient.h"
82 #include "TextCheckingHelper.h"
83 #include "TextEvent.h"
84 #include "TextIterator.h"
85 #include "TypingCommand.h"
86 #include "UserTypingGestureIndicator.h"
87 #include "htmlediting.h"
88 #include "markup.h"
89 #include "visible_units.h"
90 #include <wtf/UnusedParam.h>
91 #include <wtf/unicode/CharacterNames.h>
92 #include <wtf/unicode/Unicode.h>
93
94 namespace WebCore {
95
96 using namespace std;
97 using namespace HTMLNames;
98 using namespace WTF;
99 using namespace Unicode;
100
101 // When an event handler has moved the selection outside of a text control
102 // we should use the target control's selection for this editing operation.
103 VisibleSelection Editor::selectionForCommand(Event* event)
104 {
105     VisibleSelection selection = m_frame->selection()->selection();
106     if (!event)
107         return selection;
108     // If the target is a text control, and the current selection is outside of its shadow tree,
109     // then use the saved selection for that text control.
110     HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
111     HTMLTextFormControlElement* textFromControlOfTarget = toTextFormControl(event->target()->toNode());
112     if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
113         if (RefPtr<Range> range = textFromControlOfTarget->selection())
114             return VisibleSelection(range.get(), DOWNSTREAM, selection.isDirectional());
115     }
116     return selection;
117 }
118
119 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
120 EditingBehavior Editor::behavior() const
121 {
122     if (!m_frame || !m_frame->settings())
123         return EditingBehavior(EditingMacBehavior);
124
125     return EditingBehavior(m_frame->settings()->editingBehaviorType());
126 }
127
128 EditorClient* Editor::client() const
129 {
130     if (Page* page = m_frame->page())
131         return page->editorClient();
132     return 0;
133 }
134
135
136 TextCheckerClient* Editor::textChecker() const
137 {
138     if (EditorClient* owner = client())
139         return owner->textChecker();
140     return 0;
141 }
142
143 void Editor::handleKeyboardEvent(KeyboardEvent* event)
144 {
145     if (EditorClient* c = client())
146         c->handleKeyboardEvent(event);
147 }
148
149 void Editor::handleInputMethodKeydown(KeyboardEvent* event)
150 {
151     if (EditorClient* c = client())
152         c->handleInputMethodKeydown(event);
153 }
154
155 bool Editor::handleTextEvent(TextEvent* event)
156 {
157     // Default event handling for Drag and Drop will be handled by DragController
158     // so we leave the event for it.
159     if (event->isDrop())
160         return false;
161
162     if (event->isPaste()) {
163         if (event->pastingFragment())
164             replaceSelectionWithFragment(event->pastingFragment(), false, event->shouldSmartReplace(), event->shouldMatchStyle());
165         else 
166             replaceSelectionWithText(event->data(), false, event->shouldSmartReplace());
167         return true;
168     }
169
170     String data = event->data();
171     if (data == "\n") {
172         if (event->isLineBreak())
173             return insertLineBreak();
174         return insertParagraphSeparator();
175     }
176
177     return insertTextWithoutSendingTextEvent(data, false, event);
178 }
179
180 bool Editor::canEdit() const
181 {
182     return m_frame->selection()->rootEditableElement();
183 }
184
185 bool Editor::canEditRichly() const
186 {
187     return m_frame->selection()->isContentRichlyEditable();
188 }
189
190 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
191 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
192 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
193 // normally selectable to implement copy/paste (like divs, or a document body).
194
195 bool Editor::canDHTMLCut()
196 {
197     return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
198 }
199
200 bool Editor::canDHTMLCopy()
201 {
202     return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
203 }
204
205 bool Editor::canDHTMLPaste()
206 {
207     return !dispatchCPPEvent(eventNames().beforepasteEvent, ClipboardNumb);
208 }
209
210 bool Editor::canCut() const
211 {
212     return canCopy() && canDelete();
213 }
214
215 static HTMLImageElement* imageElementFromImageDocument(Document* document)
216 {
217     if (!document)
218         return 0;
219     if (!document->isImageDocument())
220         return 0;
221     
222     HTMLElement* body = document->body();
223     if (!body)
224         return 0;
225     
226     Node* node = body->firstChild();
227     if (!node)
228         return 0;    
229     if (!node->hasTagName(imgTag))
230         return 0;
231     return static_cast<HTMLImageElement*>(node);
232 }
233
234 bool Editor::canCopy() const
235 {
236     if (imageElementFromImageDocument(m_frame->document()))
237         return true;
238     FrameSelection* selection = m_frame->selection();
239     return selection->isRange() && !selection->isInPasswordField();
240 }
241
242 bool Editor::canPaste() const
243 {
244     return canEdit();
245 }
246
247 bool Editor::canDelete() const
248 {
249     FrameSelection* selection = m_frame->selection();
250     return selection->isRange() && selection->rootEditableElement();
251 }
252
253 bool Editor::canDeleteRange(Range* range) const
254 {
255     ExceptionCode ec = 0;
256     Node* startContainer = range->startContainer(ec);
257     Node* endContainer = range->endContainer(ec);
258     if (!startContainer || !endContainer)
259         return false;
260     
261     if (!startContainer->rendererIsEditable() || !endContainer->rendererIsEditable())
262         return false;
263     
264     if (range->collapsed(ec)) {
265         VisiblePosition start(range->startPosition(), DOWNSTREAM);
266         VisiblePosition previous = start.previous();
267         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
268         if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer->rootEditableElement())
269             return false;
270     }
271     return true;
272 }
273
274 bool Editor::smartInsertDeleteEnabled()
275 {   
276     return client() && client()->smartInsertDeleteEnabled();
277 }
278     
279 bool Editor::canSmartCopyOrDelete()
280 {
281     return client() && client()->smartInsertDeleteEnabled() && m_frame->selection()->granularity() == WordGranularity;
282 }
283
284 bool Editor::isSelectTrailingWhitespaceEnabled()
285 {
286     return client() && client()->isSelectTrailingWhitespaceEnabled();
287 }
288
289 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
290 {
291     if (!canEdit())
292         return false;
293
294     if (m_frame->selection()->isRange()) {
295         if (isTypingAction) {
296             TypingCommand::deleteKeyPressed(m_frame->document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
297             revealSelectionAfterEditingOperation();
298         } else {
299             if (killRing)
300                 addToKillRing(selectedRange().get(), false);
301             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
302             // Implicitly calls revealSelectionAfterEditingOperation().
303         }
304     } else {
305         TypingCommand::Options options = 0;
306         if (canSmartCopyOrDelete())
307             options |= TypingCommand::SmartDelete;
308         if (killRing)
309             options |= TypingCommand::KillRing;
310         switch (direction) {
311         case DirectionForward:
312         case DirectionRight:
313             TypingCommand::forwardDeleteKeyPressed(m_frame->document(), options, granularity);
314             break;
315         case DirectionBackward:
316         case DirectionLeft:
317             TypingCommand::deleteKeyPressed(m_frame->document(), options, granularity);
318             break;
319         }
320         revealSelectionAfterEditingOperation();
321     }
322
323     // FIXME: We should to move this down into deleteKeyPressed.
324     // clear the "start new kill ring sequence" setting, because it was set to true
325     // when the selection was updated by deleting the range
326     if (killRing)
327         setStartNewKillRingSequence(false);
328
329     return true;
330 }
331
332 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
333 {
334     if (m_frame->selection()->isNone())
335         return;
336     
337     applyCommand(DeleteSelectionCommand::create(m_frame->document(), smartDelete));
338 }
339
340 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
341 {
342     Node* target = findEventTargetFromSelection();
343     if (!target)
344         return;
345     ExceptionCode ec = 0;
346     target->dispatchEvent(TextEvent::createForPlainTextPaste(m_frame->domWindow(), pastingText, smartReplace), ec);
347 }
348
349 void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool smartReplace, bool matchStyle)
350 {
351     Node* target = findEventTargetFromSelection();
352     if (!target)
353         return;
354     ExceptionCode ec = 0;
355     target->dispatchEvent(TextEvent::createForFragmentPaste(m_frame->domWindow(), pastingFragment, smartReplace, matchStyle), ec);
356 }
357
358 void Editor::pasteAsPlainTextBypassingDHTML()
359 {
360     pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
361 }
362
363 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard)
364 {
365     String text = pasteboard->plainText(m_frame);
366     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
367         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
368 }
369
370 #if !PLATFORM(MAC)
371 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
372 {
373     RefPtr<Range> range = selectedRange();
374     bool chosePlainText;
375     RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, range, allowPlainText, chosePlainText);
376     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
377         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(pasteboard), chosePlainText);
378 }
379 #endif
380
381 bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
382 {
383     return client() && client()->smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
384 }
385
386 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
387 {
388     if (!client())
389         return false;
390     
391     if (fragment) {
392         Node* child = fragment->firstChild();
393         if (child && fragment->lastChild() == child && child->isCharacterDataNode())
394             return client()->shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);        
395     }
396
397     return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
398 }
399
400 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
401 {
402     if (m_frame->selection()->isNone() || !fragment)
403         return;
404
405     ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting;
406     if (selectReplacement)
407         options |= ReplaceSelectionCommand::SelectReplacement;
408     if (smartReplace)
409         options |= ReplaceSelectionCommand::SmartReplace;
410     if (matchStyle)
411         options |= ReplaceSelectionCommand::MatchStyle;
412     applyCommand(ReplaceSelectionCommand::create(m_frame->document(), fragment, options, EditActionPaste));
413     revealSelectionAfterEditingOperation();
414
415     Node* nodeToCheck = m_frame->selection()->rootEditableElement();
416     if (!nodeToCheck)
417         return;
418
419     m_spellChecker->requestCheckingFor(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar),
420         Range::create(m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck)));
421 }
422
423 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
424 {
425     replaceSelectionWithFragment(createFragmentFromText(selectedRange().get(), text), selectReplacement, smartReplace, true); 
426 }
427
428 PassRefPtr<Range> Editor::selectedRange()
429 {
430     if (!m_frame)
431         return 0;
432     return m_frame->selection()->toNormalizedRange();
433 }
434
435 bool Editor::shouldDeleteRange(Range* range) const
436 {
437     ExceptionCode ec;
438     if (!range || range->collapsed(ec))
439         return false;
440     
441     if (!canDeleteRange(range))
442         return false;
443
444     return client() && client()->shouldDeleteRange(range);
445 }
446
447 bool Editor::tryDHTMLCopy()
448 {   
449     if (m_frame->selection()->isInPasswordField())
450         return false;
451
452     return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
453 }
454
455 bool Editor::tryDHTMLCut()
456 {
457     if (m_frame->selection()->isInPasswordField())
458         return false;
459     
460     return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
461 }
462
463 bool Editor::tryDHTMLPaste()
464 {
465     return !dispatchCPPEvent(eventNames().pasteEvent, ClipboardReadable);
466 }
467
468 void Editor::writeSelectionToPasteboard(Pasteboard* pasteboard)
469 {
470     pasteboard->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame);
471 }
472
473 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
474 {
475     return client() && client()->shouldInsertText(text, range, action);
476 }
477
478 bool Editor::shouldShowDeleteInterface(HTMLElement* element) const
479 {
480     return client() && client()->shouldShowDeleteInterface(element);
481 }
482
483 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection)
484 {
485     if (client())
486         client()->respondToChangedSelection(m_frame);
487     setStartNewKillRingSequence(true);
488     m_deleteButtonController->respondToChangedSelection(oldSelection);
489     m_spellingCorrector->respondToChangedSelection(oldSelection);
490 }
491
492 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
493 {
494     if (AXObjectCache::accessibilityEnabled()) {
495         Node* node = endingSelection.start().deprecatedNode();
496         if (node)
497             m_frame->document()->axObjectCache()->postNotification(node->renderer(), AXObjectCache::AXValueChanged, false);
498     }
499
500     updateMarkersForWordsAffectedByEditing(true);
501
502     if (client())
503         client()->respondToChangedContents();
504 }
505
506 WritingDirection Editor::textDirectionForSelection(bool& hasNestedOrMultipleEmbeddings) const
507 {
508     hasNestedOrMultipleEmbeddings = true;
509
510     if (m_frame->selection()->isNone())
511         return NaturalWritingDirection;
512
513     Position position = m_frame->selection()->selection().start().downstream();
514
515     Node* node = position.deprecatedNode();
516     if (!node)
517         return NaturalWritingDirection;
518
519     Position end;
520     if (m_frame->selection()->isRange()) {
521         end = m_frame->selection()->selection().end().upstream();
522
523         Node* pastLast = Range::create(m_frame->document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
524         for (Node* n = node; n && n != pastLast; n = n->traverseNextNode()) {
525             if (!n->isStyledElement())
526                 continue;
527
528             RefPtr<CSSComputedStyleDeclaration> style = computedStyle(n);
529             RefPtr<CSSValue> unicodeBidi = style->getPropertyCSSValue(CSSPropertyUnicodeBidi);
530             if (!unicodeBidi || !unicodeBidi->isPrimitiveValue())
531                 continue;
532
533             int unicodeBidiValue = static_cast<CSSPrimitiveValue*>(unicodeBidi.get())->getIdent();
534             if (unicodeBidiValue == CSSValueEmbed || unicodeBidiValue == CSSValueBidiOverride)
535                 return NaturalWritingDirection;
536         }
537     }
538
539     if (m_frame->selection()->isCaret()) {
540         RefPtr<EditingStyle> typingStyle = m_frame->selection()->typingStyle();
541         WritingDirection direction;
542         if (typingStyle && typingStyle->textDirection(direction)) {
543             hasNestedOrMultipleEmbeddings = false;
544             return direction;
545         }
546         node = m_frame->selection()->selection().visibleStart().deepEquivalent().deprecatedNode();
547     }
548
549     // The selection is either a caret with no typing attributes or a range in which no embedding is added, so just use the start position
550     // to decide.
551     Node* block = enclosingBlock(node);
552     WritingDirection foundDirection = NaturalWritingDirection;
553
554     for (; node != block; node = node->parentNode()) {
555         if (!node->isStyledElement())
556             continue;
557
558         RefPtr<CSSComputedStyleDeclaration> style = computedStyle(node);
559         RefPtr<CSSValue> unicodeBidi = style->getPropertyCSSValue(CSSPropertyUnicodeBidi);
560         if (!unicodeBidi || !unicodeBidi->isPrimitiveValue())
561             continue;
562
563         int unicodeBidiValue = static_cast<CSSPrimitiveValue*>(unicodeBidi.get())->getIdent();
564         if (unicodeBidiValue == CSSValueNormal)
565             continue;
566
567         if (unicodeBidiValue == CSSValueBidiOverride)
568             return NaturalWritingDirection;
569
570         ASSERT(unicodeBidiValue == CSSValueEmbed);
571         RefPtr<CSSValue> direction = style->getPropertyCSSValue(CSSPropertyDirection);
572         if (!direction || !direction->isPrimitiveValue())
573             continue;
574
575         int directionValue = static_cast<CSSPrimitiveValue*>(direction.get())->getIdent();
576         if (directionValue != CSSValueLtr && directionValue != CSSValueRtl)
577             continue;
578
579         if (foundDirection != NaturalWritingDirection)
580             return NaturalWritingDirection;
581
582         // In the range case, make sure that the embedding element persists until the end of the range.
583         if (m_frame->selection()->isRange() && !end.deprecatedNode()->isDescendantOf(node))
584             return NaturalWritingDirection;
585
586         foundDirection = directionValue == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection;
587     }
588     hasNestedOrMultipleEmbeddings = false;
589     return foundDirection;
590 }
591
592 bool Editor::hasBidiSelection() const
593 {
594     if (m_frame->selection()->isNone())
595         return false;
596
597     Node* startNode;
598     if (m_frame->selection()->isRange()) {
599         startNode = m_frame->selection()->selection().start().downstream().deprecatedNode();
600         Node* endNode = m_frame->selection()->selection().end().upstream().deprecatedNode();
601         if (enclosingBlock(startNode) != enclosingBlock(endNode))
602             return false;
603     } else
604         startNode = m_frame->selection()->selection().visibleStart().deepEquivalent().deprecatedNode();
605
606     RenderObject* renderer = startNode->renderer();
607     while (renderer && !renderer->isRenderBlock())
608         renderer = renderer->parent();
609
610     if (!renderer)
611         return false;
612
613     RenderStyle* style = renderer->style();
614     if (!style->isLeftToRightDirection())
615         return true;
616
617     return toRenderBlock(renderer)->containsNonZeroBidiLevel();
618 }
619
620 TriState Editor::selectionUnorderedListState() const
621 {
622     if (m_frame->selection()->isCaret()) {
623         if (enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag))
624             return TrueTriState;
625     } else if (m_frame->selection()->isRange()) {
626         Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag);
627         Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), ulTag);
628         if (startNode && endNode && startNode == endNode)
629             return TrueTriState;
630     }
631
632     return FalseTriState;
633 }
634
635 TriState Editor::selectionOrderedListState() const
636 {
637     if (m_frame->selection()->isCaret()) {
638         if (enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag))
639             return TrueTriState;
640     } else if (m_frame->selection()->isRange()) {
641         Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag);
642         Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), olTag);
643         if (startNode && endNode && startNode == endNode)
644             return TrueTriState;
645     }
646
647     return FalseTriState;
648 }
649
650 PassRefPtr<Node> Editor::insertOrderedList()
651 {
652     if (!canEditRichly())
653         return 0;
654         
655     RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::OrderedList);
656     revealSelectionAfterEditingOperation();
657     return newList;
658 }
659
660 PassRefPtr<Node> Editor::insertUnorderedList()
661 {
662     if (!canEditRichly())
663         return 0;
664         
665     RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::UnorderedList);
666     revealSelectionAfterEditingOperation();
667     return newList;
668 }
669
670 bool Editor::canIncreaseSelectionListLevel()
671 {
672     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(m_frame->document());
673 }
674
675 bool Editor::canDecreaseSelectionListLevel()
676 {
677     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(m_frame->document());
678 }
679
680 PassRefPtr<Node> Editor::increaseSelectionListLevel()
681 {
682     if (!canEditRichly() || m_frame->selection()->isNone())
683         return 0;
684     
685     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(m_frame->document());
686     revealSelectionAfterEditingOperation();
687     return newList;
688 }
689
690 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
691 {
692     if (!canEditRichly() || m_frame->selection()->isNone())
693         return 0;
694     
695     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(m_frame->document());
696     revealSelectionAfterEditingOperation();
697     return newList.release();
698 }
699
700 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
701 {
702     if (!canEditRichly() || m_frame->selection()->isNone())
703         return 0;
704     
705     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(m_frame->document());
706     revealSelectionAfterEditingOperation();
707     return newList.release();
708 }
709
710 void Editor::decreaseSelectionListLevel()
711 {
712     if (!canEditRichly() || m_frame->selection()->isNone())
713         return;
714     
715     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(m_frame->document());
716     revealSelectionAfterEditingOperation();
717 }
718
719 void Editor::removeFormattingAndStyle()
720 {
721     applyCommand(RemoveFormatCommand::create(m_frame->document()));
722 }
723
724 void Editor::clearLastEditCommand() 
725 {
726     m_lastEditCommand.clear();
727 }
728
729 // Returns whether caller should continue with "the default processing", which is the same as 
730 // the event handler NOT setting the return value to false
731 bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy)
732 {
733     Node* target = findEventTargetFromSelection();
734     if (!target)
735         return true;
736     
737     RefPtr<Clipboard> clipboard = newGeneralClipboard(policy, m_frame);
738
739     ExceptionCode ec = 0;
740     RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
741     target->dispatchEvent(evt, ec);
742     bool noDefaultProcessing = evt->defaultPrevented();
743     if (noDefaultProcessing && policy == ClipboardWritable) {
744         Pasteboard* pasteboard = Pasteboard::generalPasteboard();
745         pasteboard->clear();
746         pasteboard->writeClipboard(clipboard.get());
747     }
748
749     // invalidate clipboard here for security
750     clipboard->setAccessPolicy(ClipboardNumb);
751     
752     return !noDefaultProcessing;
753 }
754
755 Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
756 {
757     Node* target = selection.start().element();
758     if (!target)
759         target = m_frame->document()->body();
760     if (!target)
761         return 0;
762     return target->shadowAncestorNode();
763
764 }
765
766 Node* Editor::findEventTargetFromSelection() const
767 {
768     return findEventTargetFrom(m_frame->selection()->selection());
769 }
770
771 void Editor::applyStyle(CSSStyleDeclaration* style, EditAction editingAction)
772 {
773     switch (m_frame->selection()->selectionType()) {
774     case VisibleSelection::NoSelection:
775         // do nothing
776         break;
777     case VisibleSelection::CaretSelection:
778         computeAndSetTypingStyle(style, editingAction);
779         break;
780     case VisibleSelection::RangeSelection:
781         if (style)
782             applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction));
783         break;
784     }
785 }
786     
787 bool Editor::shouldApplyStyle(CSSStyleDeclaration* style, Range* range)
788 {   
789     return client()->shouldApplyStyle(style, range);
790 }
791     
792 void Editor::applyParagraphStyle(CSSStyleDeclaration* style, EditAction editingAction)
793 {
794     switch (m_frame->selection()->selectionType()) {
795     case VisibleSelection::NoSelection:
796         // do nothing
797         break;
798     case VisibleSelection::CaretSelection:
799     case VisibleSelection::RangeSelection:
800         if (style)
801             applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties));
802         break;
803     }
804 }
805
806 void Editor::applyStyleToSelection(CSSStyleDeclaration* style, EditAction editingAction)
807 {
808     if (!style || !style->length() || !canEditRichly())
809         return;
810
811     if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
812         applyStyle(style, editingAction);
813 }
814
815 void Editor::applyParagraphStyleToSelection(CSSStyleDeclaration* style, EditAction editingAction)
816 {
817     if (!style || !style->length() || !canEditRichly())
818         return;
819     
820     if (client() && client()->shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
821         applyParagraphStyle(style, editingAction);
822 }
823
824 bool Editor::selectionStartHasStyle(int propertyID, const String& value) const
825 {
826     return EditingStyle::create(propertyID, value)->triStateOfStyle(
827         EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(), propertyID == CSSPropertyBackgroundColor).get());
828 }
829
830 TriState Editor::selectionHasStyle(int propertyID, const String& value) const
831 {
832     return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame->selection()->selection());
833 }
834
835 String Editor::selectionStartCSSPropertyValue(int propertyID)
836 {
837     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(),
838         propertyID == CSSPropertyBackgroundColor);
839     if (!selectionStyle || !selectionStyle->style())
840         return String();
841
842     if (propertyID == CSSPropertyFontSize)
843         return String::number(selectionStyle->legacyFontSize(m_frame->document()));
844     return selectionStyle->style()->getPropertyValue(propertyID);
845 }
846
847 void Editor::indent()
848 {
849     applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Indent));
850 }
851
852 void Editor::outdent()
853 {
854     applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Outdent));
855 }
856
857 static void dispatchEditableContentChangedEvents(const EditCommand& command)
858 {
859     Element* startRoot = command.startingRootEditableElement();
860     Element* endRoot = command.endingRootEditableElement();
861     ExceptionCode ec;
862     if (startRoot)
863         startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), ec);
864     if (endRoot && endRoot != startRoot)
865         endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), ec);
866 }
867
868 void Editor::appliedEditing(PassRefPtr<EditCommand> cmd)
869 {
870     m_frame->document()->updateLayout();
871
872     dispatchEditableContentChangedEvents(*cmd);
873     VisibleSelection newSelection(cmd->endingSelection());
874
875     m_spellingCorrector->respondToAppliedEditing(cmd.get());
876
877     // Don't clear the typing style with this selection change.  We do those things elsewhere if necessary.
878     changeSelectionAfterCommand(newSelection, false, false);
879
880     if (!cmd->preservesTypingStyle())
881         m_frame->selection()->clearTypingStyle();
882
883     // Command will be equal to last edit command only in the case of typing
884     if (m_lastEditCommand.get() == cmd)
885         ASSERT(cmd->isTypingCommand());
886     else {
887         // Only register a new undo command if the command passed in is
888         // different from the last command
889         m_lastEditCommand = cmd;
890         if (client())
891             client()->registerCommandForUndo(m_lastEditCommand);
892     }
893     respondToChangedContents(newSelection);
894 }
895
896 void Editor::unappliedEditing(PassRefPtr<EditCommand> cmd)
897 {
898     m_frame->document()->updateLayout();
899     
900     dispatchEditableContentChangedEvents(*cmd);
901     
902     VisibleSelection newSelection(cmd->startingSelection());
903     changeSelectionAfterCommand(newSelection, true, true);
904     m_spellingCorrector->respondToUnappliedEditing(cmd.get());
905     
906     m_lastEditCommand = 0;
907     if (client())
908         client()->registerCommandForRedo(cmd);
909     respondToChangedContents(newSelection);
910 }
911
912 void Editor::reappliedEditing(PassRefPtr<EditCommand> cmd)
913 {
914     m_frame->document()->updateLayout();
915     
916     dispatchEditableContentChangedEvents(*cmd);
917     
918     VisibleSelection newSelection(cmd->endingSelection());
919     changeSelectionAfterCommand(newSelection, true, true);
920     
921     m_lastEditCommand = 0;
922     if (client())
923         client()->registerCommandForUndo(cmd);
924     respondToChangedContents(newSelection);
925 }
926
927 Editor::Editor(Frame* frame)
928     : m_frame(frame)
929     , m_deleteButtonController(adoptPtr(new DeleteButtonController(frame)))
930     , m_ignoreCompositionSelectionChange(false)
931     , m_shouldStartNewKillRingSequence(false)
932     // This is off by default, since most editors want this behavior (this matches IE but not FF).
933     , m_shouldStyleWithCSS(false)
934     , m_killRing(adoptPtr(new KillRing))
935     , m_spellChecker(adoptPtr(new SpellChecker(frame)))
936     , m_spellingCorrector(adoptPtr(new SpellingCorrectionController(frame)))
937     , m_areMarkedTextMatchesHighlighted(false)
938 {
939 }
940
941 Editor::~Editor()
942 {
943 }
944
945 void Editor::clear()
946 {
947     m_compositionNode = 0;
948     m_customCompositionUnderlines.clear();
949     m_shouldStyleWithCSS = false;
950 }
951
952 bool Editor::insertText(const String& text, Event* triggeringEvent)
953 {
954     return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
955 }
956
957 bool Editor::insertTextForConfirmedComposition(const String& text)
958 {
959     return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
960 }
961
962 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
963 {
964     if (text.isEmpty())
965         return false;
966
967     VisibleSelection selection = selectionForCommand(triggeringEvent);
968     if (!selection.isContentEditable())
969         return false;
970     RefPtr<Range> range = selection.toNormalizedRange();
971
972     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
973         return true;
974
975     if (!text.isEmpty())
976         updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
977
978     bool shouldConsiderApplyingAutocorrection = false;
979     if (text == " " || text == "\t")
980         shouldConsiderApplyingAutocorrection = true;
981
982     if (text.length() == 1 && isPunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
983         shouldConsiderApplyingAutocorrection = true;
984
985     bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
986
987     // Get the selection to use for the event that triggered this insertText.
988     // If the event handler changed the selection, we may want to use a different selection
989     // that is contained in the event target.
990     selection = selectionForCommand(triggeringEvent);
991     if (selection.isContentEditable()) {
992         if (Node* selectionStart = selection.start().deprecatedNode()) {
993             RefPtr<Document> document = selectionStart->document();
994
995             // Insert the text
996             TypingCommand::Options options = 0;
997             if (selectInsertedText)
998                 options |= TypingCommand::SelectInsertedText;
999             if (autocorrectionWasApplied)
1000                 options |= TypingCommand::RetainAutocorrectionIndicator;
1001             TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
1002
1003             // Reveal the current selection
1004             if (Frame* editedFrame = document->frame())
1005                 if (Page* page = editedFrame->page())
1006                     page->focusController()->focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1007         }
1008     }
1009
1010     return true;
1011 }
1012
1013 bool Editor::insertLineBreak()
1014 {
1015     if (!canEdit())
1016         return false;
1017
1018     if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1019         return true;
1020
1021     bool autocorrectionIsApplied = m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
1022     TypingCommand::insertLineBreak(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1023     revealSelectionAfterEditingOperation();
1024
1025     return true;
1026 }
1027
1028 bool Editor::insertParagraphSeparator()
1029 {
1030     if (!canEdit())
1031         return false;
1032
1033     if (!canEditRichly())
1034         return insertLineBreak();
1035
1036     if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1037         return true;
1038
1039     bool autocorrectionIsApplied = m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
1040     TypingCommand::insertParagraphSeparator(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1041     revealSelectionAfterEditingOperation();
1042
1043     return true;
1044 }
1045
1046 void Editor::cut()
1047 {
1048     if (tryDHTMLCut())
1049         return; // DHTML did the whole operation
1050     if (!canCut()) {
1051         systemBeep();
1052         return;
1053     }
1054     RefPtr<Range> selection = selectedRange();
1055     if (shouldDeleteRange(selection.get())) {
1056         updateMarkersForWordsAffectedByEditing(true);
1057         if (enclosingTextFormControl(m_frame->selection()->start()))
1058             Pasteboard::generalPasteboard()->writePlainText(selectedText());
1059         else
1060             Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame);
1061         didWriteSelectionToPasteboard();
1062         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1063     }
1064 }
1065
1066 void Editor::copy()
1067 {
1068     if (tryDHTMLCopy())
1069         return; // DHTML did the whole operation
1070     if (!canCopy()) {
1071         systemBeep();
1072         return;
1073     }
1074
1075     if (enclosingTextFormControl(m_frame->selection()->start()))
1076         Pasteboard::generalPasteboard()->writePlainText(selectedText());
1077     else {
1078         Document* document = m_frame->document();
1079         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
1080             Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
1081         else
1082             Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame);
1083     }
1084
1085     didWriteSelectionToPasteboard();
1086 }
1087
1088 void Editor::paste()
1089 {
1090     ASSERT(m_frame->document());
1091     if (tryDHTMLPaste())
1092         return; // DHTML did the whole operation
1093     if (!canPaste())
1094         return;
1095     updateMarkersForWordsAffectedByEditing(false);
1096     CachedResourceLoader* loader = m_frame->document()->cachedResourceLoader();
1097     ResourceCacheValidationSuppressor validationSuppressor(loader);
1098     if (m_frame->selection()->isContentRichlyEditable())
1099         pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
1100     else
1101         pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1102 }
1103
1104 void Editor::pasteAsPlainText()
1105 {
1106     if (tryDHTMLPaste())
1107         return;
1108     if (!canPaste())
1109         return;
1110     updateMarkersForWordsAffectedByEditing(false);
1111     pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1112 }
1113
1114 void Editor::performDelete()
1115 {
1116     if (!canDelete()) {
1117         systemBeep();
1118         return;
1119     }
1120
1121     addToKillRing(selectedRange().get(), false);
1122     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1123
1124     // clear the "start new kill ring sequence" setting, because it was set to true
1125     // when the selection was updated by deleting the range
1126     setStartNewKillRingSequence(false);
1127 }
1128
1129 void Editor::copyURL(const KURL& url, const String& title)
1130 {
1131     Pasteboard::generalPasteboard()->writeURL(url, title, m_frame);
1132 }
1133
1134 void Editor::copyImage(const HitTestResult& result)
1135 {
1136     KURL url = result.absoluteLinkURL();
1137     if (url.isEmpty())
1138         url = result.absoluteImageURL();
1139
1140     Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
1141 }
1142
1143 bool Editor::isContinuousSpellCheckingEnabled()
1144 {
1145     return client() && client()->isContinuousSpellCheckingEnabled();
1146 }
1147
1148 void Editor::toggleContinuousSpellChecking()
1149 {
1150     if (client())
1151         client()->toggleContinuousSpellChecking();
1152 }
1153
1154 bool Editor::isGrammarCheckingEnabled()
1155 {
1156     return client() && client()->isGrammarCheckingEnabled();
1157 }
1158
1159 void Editor::toggleGrammarChecking()
1160 {
1161     if (client())
1162         client()->toggleGrammarChecking();
1163 }
1164
1165 int Editor::spellCheckerDocumentTag()
1166 {
1167     return client() ? client()->spellCheckerDocumentTag() : 0;
1168 }
1169
1170 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1171
1172 void Editor::uppercaseWord()
1173 {
1174     if (client())
1175         client()->uppercaseWord();
1176 }
1177
1178 void Editor::lowercaseWord()
1179 {
1180     if (client())
1181         client()->lowercaseWord();
1182 }
1183
1184 void Editor::capitalizeWord()
1185 {
1186     if (client())
1187         client()->capitalizeWord();
1188 }
1189
1190 void Editor::showSubstitutionsPanel()
1191 {
1192     if (!client()) {
1193         LOG_ERROR("No NSSpellChecker");
1194         return;
1195     }
1196
1197     if (client()->substitutionsPanelIsShowing()) {
1198         client()->showSubstitutionsPanel(false);
1199         return;
1200     }
1201     client()->showSubstitutionsPanel(true);
1202 }
1203
1204 bool Editor::substitutionsPanelIsShowing()
1205 {
1206     if (!client())
1207         return false;
1208     return client()->substitutionsPanelIsShowing();
1209 }
1210
1211 void Editor::toggleSmartInsertDelete()
1212 {
1213     if (client())
1214         client()->toggleSmartInsertDelete();
1215 }
1216
1217 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1218 {
1219     return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1220 }
1221
1222 void Editor::toggleAutomaticQuoteSubstitution()
1223 {
1224     if (client())
1225         client()->toggleAutomaticQuoteSubstitution();
1226 }
1227
1228 bool Editor::isAutomaticLinkDetectionEnabled()
1229 {
1230     return client() && client()->isAutomaticLinkDetectionEnabled();
1231 }
1232
1233 void Editor::toggleAutomaticLinkDetection()
1234 {
1235     if (client())
1236         client()->toggleAutomaticLinkDetection();
1237 }
1238
1239 bool Editor::isAutomaticDashSubstitutionEnabled()
1240 {
1241     return client() && client()->isAutomaticDashSubstitutionEnabled();
1242 }
1243
1244 void Editor::toggleAutomaticDashSubstitution()
1245 {
1246     if (client())
1247         client()->toggleAutomaticDashSubstitution();
1248 }
1249
1250 bool Editor::isAutomaticTextReplacementEnabled()
1251 {
1252     return client() && client()->isAutomaticTextReplacementEnabled();
1253 }
1254
1255 void Editor::toggleAutomaticTextReplacement()
1256 {
1257     if (client())
1258         client()->toggleAutomaticTextReplacement();
1259 }
1260
1261 bool Editor::isAutomaticSpellingCorrectionEnabled()
1262 {
1263     return m_spellingCorrector->isAutomaticSpellingCorrectionEnabled();
1264 }
1265
1266 void Editor::toggleAutomaticSpellingCorrection()
1267 {
1268     if (client())
1269         client()->toggleAutomaticSpellingCorrection();
1270 }
1271
1272 #endif
1273
1274 bool Editor::shouldEndEditing(Range* range)
1275 {
1276     return client() && client()->shouldEndEditing(range);
1277 }
1278
1279 bool Editor::shouldBeginEditing(Range* range)
1280 {
1281     return client() && client()->shouldBeginEditing(range);
1282 }
1283
1284 void Editor::clearUndoRedoOperations()
1285 {
1286     if (client())
1287         client()->clearUndoRedoOperations();
1288 }
1289
1290 bool Editor::canUndo()
1291 {
1292     return client() && client()->canUndo();
1293 }
1294
1295 void Editor::undo()
1296 {
1297     if (client())
1298         client()->undo();
1299 }
1300
1301 bool Editor::canRedo()
1302 {
1303     return client() && client()->canRedo();
1304 }
1305
1306 void Editor::redo()
1307 {
1308     if (client())
1309         client()->redo();
1310 }
1311
1312 void Editor::didBeginEditing()
1313 {
1314     if (client())
1315         client()->didBeginEditing();
1316 }
1317
1318 void Editor::didEndEditing()
1319 {
1320     if (client())
1321         client()->didEndEditing();
1322 }
1323
1324 void Editor::didWriteSelectionToPasteboard()
1325 {
1326     if (client())
1327         client()->didWriteSelectionToPasteboard();
1328 }
1329
1330 void Editor::toggleBold()
1331 {
1332     command("ToggleBold").execute();
1333 }
1334
1335 void Editor::toggleUnderline()
1336 {
1337     command("ToggleUnderline").execute();
1338 }
1339
1340 void Editor::setBaseWritingDirection(WritingDirection direction)
1341 {
1342     Node* focusedNode = frame()->document()->focusedNode();
1343     if (toTextFormControl(focusedNode)) {
1344         if (direction == NaturalWritingDirection)
1345             return;
1346         toHTMLElement(focusedNode)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
1347         focusedNode->dispatchInputEvent();
1348         frame()->document()->updateStyleIfNeeded();
1349         return;
1350     }
1351
1352     RefPtr<CSSMutableStyleDeclaration> style = CSSMutableStyleDeclaration::create();
1353     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1354     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1355 }
1356
1357 void Editor::selectComposition()
1358 {
1359     RefPtr<Range> range = compositionRange();
1360     if (!range)
1361         return;
1362     
1363     // The composition can start inside a composed character sequence, so we have to override checks.
1364     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1365     VisibleSelection selection;
1366     selection.setWithoutValidation(range->startPosition(), range->endPosition());
1367     m_frame->selection()->setSelection(selection, 0);
1368 }
1369
1370 void Editor::confirmComposition()
1371 {
1372     if (!m_compositionNode)
1373         return;
1374     setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
1375 }
1376
1377 void Editor::cancelComposition()
1378 {
1379     if (!m_compositionNode)
1380         return;
1381     setComposition(emptyString(), CancelComposition);
1382 }
1383
1384 void Editor::confirmComposition(const String& text)
1385 {
1386     setComposition(text, ConfirmComposition);
1387 }
1388
1389 void Editor::setComposition(const String& text, SetCompositionMode mode)
1390 {
1391     ASSERT(mode == ConfirmComposition || mode == CancelComposition);
1392     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1393
1394     setIgnoreCompositionSelectionChange(true);
1395
1396     if (mode == CancelComposition)
1397         ASSERT(text == emptyString());
1398     else
1399         selectComposition();
1400
1401     if (m_frame->selection()->isNone()) {
1402         setIgnoreCompositionSelectionChange(false);
1403         return;
1404     }
1405     
1406     // Dispatch a compositionend event to the focused node.
1407     // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
1408     // the DOM Event specification.
1409     Node* target = m_frame->document()->focusedNode();
1410     if (target) {
1411         RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
1412         ExceptionCode ec = 0;
1413         target->dispatchEvent(event, ec);
1414     }
1415
1416     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1417     // will delete the old composition with an optimized replace operation.
1418     if (text.isEmpty())
1419         TypingCommand::deleteSelection(m_frame->document(), 0);
1420
1421     m_compositionNode = 0;
1422     m_customCompositionUnderlines.clear();
1423
1424     insertTextForConfirmedComposition(text);
1425
1426     if (mode == CancelComposition) {
1427         // An open typing command that disagrees about current selection would cause issues with typing later on.
1428         TypingCommand::closeTyping(m_lastEditCommand.get());
1429     }
1430
1431     setIgnoreCompositionSelectionChange(false);
1432 }
1433
1434 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1435 {
1436     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1437
1438     setIgnoreCompositionSelectionChange(true);
1439
1440     // Updates styles before setting selection for composition to prevent
1441     // inserting the previous composition text into text nodes oddly.
1442     // See https://bugs.webkit.org/show_bug.cgi?id=46868
1443     m_frame->document()->updateStyleIfNeeded();
1444
1445     selectComposition();
1446
1447     if (m_frame->selection()->isNone()) {
1448         setIgnoreCompositionSelectionChange(false);
1449         return;
1450     }
1451
1452     Node* target = m_frame->document()->focusedNode();
1453     if (target) {
1454         // Dispatch an appropriate composition event to the focused node.
1455         // We check the composition status and choose an appropriate composition event since this
1456         // function is used for three purposes:
1457         // 1. Starting a new composition.
1458         //    Send a compositionstart event when this function creates a new composition node, i.e.
1459         //    m_compositionNode == 0 && !text.isEmpty().
1460         // 2. Updating the existing composition node.
1461         //    Send a compositionupdate event when this function updates the existing composition
1462         //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
1463         // 3. Canceling the ongoing composition.
1464         //    Send a compositionend event when function deletes the existing composition node, i.e.
1465         //    m_compositionNode != 0 && test.isEmpty().
1466         RefPtr<CompositionEvent> event;
1467         if (!m_compositionNode) {
1468             // We should send a compositionstart event only when the given text is not empty because this
1469             // function doesn't create a composition node when the text is empty.
1470             if (!text.isEmpty())
1471                 event = CompositionEvent::create(eventNames().compositionstartEvent, m_frame->domWindow(), text);
1472         } else {
1473             if (!text.isEmpty())
1474                 event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
1475             else
1476               event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
1477         }
1478         ExceptionCode ec = 0;
1479         if (event.get())
1480             target->dispatchEvent(event, ec);
1481     }
1482
1483     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1484     // will delete the old composition with an optimized replace operation.
1485     if (text.isEmpty())
1486         TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
1487
1488     m_compositionNode = 0;
1489     m_customCompositionUnderlines.clear();
1490
1491     if (!text.isEmpty()) {
1492         TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
1493
1494         // Find out what node has the composition now.
1495         Position base = m_frame->selection()->base().downstream();
1496         Position extent = m_frame->selection()->extent();
1497         Node* baseNode = base.deprecatedNode();
1498         unsigned baseOffset = base.deprecatedEditingOffset();
1499         Node* extentNode = extent.deprecatedNode();
1500         unsigned extentOffset = extent.deprecatedEditingOffset();
1501
1502         if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
1503             m_compositionNode = static_cast<Text*>(baseNode);
1504             m_compositionStart = baseOffset;
1505             m_compositionEnd = extentOffset;
1506             m_customCompositionUnderlines = underlines;
1507             size_t numUnderlines = m_customCompositionUnderlines.size();
1508             for (size_t i = 0; i < numUnderlines; ++i) {
1509                 m_customCompositionUnderlines[i].startOffset += baseOffset;
1510                 m_customCompositionUnderlines[i].endOffset += baseOffset;
1511             }
1512             if (baseNode->renderer())
1513                 baseNode->renderer()->repaint();
1514
1515             unsigned start = min(baseOffset + selectionStart, extentOffset);
1516             unsigned end = min(max(start, baseOffset + selectionEnd), extentOffset);
1517             RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);                
1518             m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1519         }
1520     }
1521
1522     setIgnoreCompositionSelectionChange(false);
1523 }
1524
1525 void Editor::ignoreSpelling()
1526 {
1527     if (!client())
1528         return;
1529         
1530     RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1531     if (selectedRange)
1532         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1533
1534     String text = selectedText();
1535     ASSERT(text.length());
1536     textChecker()->ignoreWordInSpellDocument(text);
1537 }
1538
1539 void Editor::learnSpelling()
1540 {
1541     if (!client())
1542         return;
1543         
1544     // FIXME: On Mac OS X, when use "learn" button on "Spelling and Grammar" panel, we don't call this function. It should remove misspelling markers around the learned word, see <rdar://problem/5396072>.
1545
1546     RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1547     if (selectedRange)
1548         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1549
1550     String text = selectedText();
1551     ASSERT(text.length());
1552     textChecker()->learnWord(text);
1553 }
1554
1555 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1556 {
1557     ExceptionCode ec = 0;
1558
1559     // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1560     // then we wrap and search from the doc start to (approximately) where we started.
1561     
1562     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
1563     // repeated "check spelling" commands work.
1564     VisibleSelection selection(frame()->selection()->selection());
1565     RefPtr<Range> spellingSearchRange(rangeOfContents(frame()->document()));
1566
1567     bool startedWithSelection = false;
1568     if (selection.start().deprecatedNode()) {
1569         startedWithSelection = true;
1570         if (startBeforeSelection) {
1571             VisiblePosition start(selection.visibleStart());
1572             // We match AppKit's rule: Start 1 character before the selection.
1573             VisiblePosition oneBeforeStart = start.previous();
1574             setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1575         } else
1576             setStart(spellingSearchRange.get(), selection.visibleEnd());
1577     }
1578
1579     Position position = spellingSearchRange->startPosition();
1580     if (!isEditablePosition(position)) {
1581         // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1582         // selection is editable.
1583         // This can happen in Mail for a mix of non-editable and editable content (like Stationary), 
1584         // when spell checking the whole document before sending the message.
1585         // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1586
1587         position = firstEditablePositionAfterPositionInRoot(position, frame()->document()->documentElement()).deepEquivalent();
1588         if (position.isNull())
1589             return;
1590         
1591         Position rangeCompliantPosition = position.parentAnchoredEquivalent();
1592         spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), ec);
1593         startedWithSelection = false; // won't need to wrap
1594     }
1595     
1596     // topNode defines the whole range we want to operate on 
1597     Node* topNode = highestEditableRoot(position);
1598     // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
1599     spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), ec);
1600
1601     // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1602     // at a word boundary. Going back by one char and then forward by a word does the trick.
1603     if (startedWithSelection) {
1604         VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1605         if (oneBeforeStart.isNotNull())
1606             setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1607         // else we were already at the start of the editable node
1608     }
1609     
1610     if (spellingSearchRange->collapsed(ec))
1611         return; // nothing to search in
1612     
1613     // Get the spell checker if it is available
1614     if (!client())
1615         return;
1616         
1617     // We go to the end of our first range instead of the start of it, just to be sure
1618     // we don't get foiled by any word boundary problems at the start.  It means we might
1619     // do a tiny bit more searching.
1620     Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer(ec);
1621     int searchEndOffsetAfterWrap = spellingSearchRange->endOffset(ec);
1622     
1623     int misspellingOffset = 0;
1624     GrammarDetail grammarDetail;
1625     int grammarPhraseOffset = 0;
1626     RefPtr<Range> grammarSearchRange;
1627     String badGrammarPhrase;
1628     String misspelledWord;
1629
1630     bool isSpelling = true;
1631     int foundOffset = 0;
1632     String foundItem;
1633     RefPtr<Range> firstMisspellingRange;
1634     if (unifiedTextCheckerEnabled()) {
1635         grammarSearchRange = spellingSearchRange->cloneRange(ec);
1636         foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1637         if (isSpelling) {
1638             misspelledWord = foundItem;
1639             misspellingOffset = foundOffset;
1640         } else {
1641             badGrammarPhrase = foundItem;
1642             grammarPhraseOffset = foundOffset;
1643         }
1644     } else {
1645         misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1646
1647 #if USE(GRAMMAR_CHECKING)
1648         grammarSearchRange = spellingSearchRange->cloneRange(ec);
1649         if (!misspelledWord.isEmpty()) {
1650             // Stop looking at start of next misspelled word
1651             CharacterIterator chars(grammarSearchRange.get());
1652             chars.advance(misspellingOffset);
1653             grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1654         }
1655     
1656         if (isGrammarCheckingEnabled())
1657             badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1658 #endif
1659     }
1660     
1661     // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
1662     // block rather than at a selection).
1663     if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
1664         spellingSearchRange->setStart(topNode, 0, ec);
1665         // going until the end of the very first chunk we tested is far enough
1666         spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, ec);
1667         
1668         if (unifiedTextCheckerEnabled()) {
1669             grammarSearchRange = spellingSearchRange->cloneRange(ec);
1670             foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1671             if (isSpelling) {
1672                 misspelledWord = foundItem;
1673                 misspellingOffset = foundOffset;
1674             } else {
1675                 badGrammarPhrase = foundItem;
1676                 grammarPhraseOffset = foundOffset;
1677             }
1678         } else {
1679             misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1680
1681 #if USE(GRAMMAR_CHECKING)
1682             grammarSearchRange = spellingSearchRange->cloneRange(ec);
1683             if (!misspelledWord.isEmpty()) {
1684                 // Stop looking at start of next misspelled word
1685                 CharacterIterator chars(grammarSearchRange.get());
1686                 chars.advance(misspellingOffset);
1687                 grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1688             }
1689
1690             if (isGrammarCheckingEnabled())
1691                 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1692 #endif
1693         }
1694     }
1695     
1696     if (!badGrammarPhrase.isEmpty()) {
1697         ASSERT(WTF_USE_GRAMMAR_CHECKING);
1698         // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
1699         // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
1700         // panel, and store a marker so we draw the green squiggle later.
1701         
1702         ASSERT(badGrammarPhrase.length() > 0);
1703         ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
1704         
1705         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
1706         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
1707         frame()->selection()->setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
1708         frame()->selection()->revealSelection();
1709         
1710         client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
1711         frame()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
1712     } else if (!misspelledWord.isEmpty()) {
1713         // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
1714         // a marker so we draw the red squiggle later.
1715         
1716         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
1717         frame()->selection()->setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
1718         frame()->selection()->revealSelection();
1719         
1720         client()->updateSpellingUIWithMisspelledWord(misspelledWord);
1721         frame()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
1722     }
1723 }
1724
1725 bool Editor::isSelectionMisspelled()
1726 {
1727     String selectedString = selectedText();
1728     int length = selectedString.length();
1729     if (!length)
1730         return false;
1731
1732     if (!client())
1733         return false;
1734     
1735     int misspellingLocation = -1;
1736     int misspellingLength = 0;
1737     textChecker()->checkSpellingOfString(selectedString.characters(), length, &misspellingLocation, &misspellingLength);
1738     
1739     // The selection only counts as misspelled if the selected text is exactly one misspelled word
1740     if (misspellingLength != length)
1741         return false;
1742     
1743     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
1744     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
1745     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
1746     // or a grammar error.
1747     client()->updateSpellingUIWithMisspelledWord(selectedString);
1748     
1749     return true;
1750 }
1751
1752 bool Editor::isSelectionUngrammatical()
1753 {
1754 #if USE(GRAMMAR_CHECKING)
1755     Vector<String> ignoredGuesses;
1756     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1757     if (!range)
1758         return false;
1759     return TextCheckingHelper(client(), range).isUngrammatical(ignoredGuesses);
1760 #else
1761     return false;
1762 #endif
1763 }
1764
1765 Vector<String> Editor::guessesForUngrammaticalSelection()
1766 {
1767 #if USE(GRAMMAR_CHECKING)
1768     Vector<String> guesses;
1769     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1770     if (!range)
1771         return guesses;
1772     // Ignore the result of isUngrammatical; we just want the guesses, whether or not there are any
1773     TextCheckingHelper(client(), range).isUngrammatical(guesses);
1774     return guesses;
1775 #else
1776     return Vector<String>();
1777 #endif
1778 }
1779
1780 Vector<String> Editor::guessesForMisspelledSelection()
1781 {
1782     String selectedString = selectedText();
1783     ASSERT(selectedString.length());
1784
1785     Vector<String> guesses;
1786     if (client())
1787         textChecker()->getGuessesForWord(selectedString, String(), guesses);
1788     return guesses;
1789 }
1790
1791 Vector<String> Editor::guessesForMisspelledOrUngrammaticalSelection(bool& misspelled, bool& ungrammatical)
1792 {
1793     if (unifiedTextCheckerEnabled()) {
1794         RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1795         if (!range)
1796             return Vector<String>();
1797         return TextCheckingHelper(client(), range).guessesForMisspelledOrUngrammaticalRange(isGrammarCheckingEnabled(), misspelled, ungrammatical);
1798     }
1799
1800     misspelled = isSelectionMisspelled();
1801     if (misspelled) {
1802         ungrammatical = false;
1803         return guessesForMisspelledSelection();
1804     }
1805     if (isGrammarCheckingEnabled() && isSelectionUngrammatical()) {
1806         ungrammatical = true;
1807         return guessesForUngrammaticalSelection();
1808     }
1809     ungrammatical = false;
1810     return Vector<String>();
1811 }
1812
1813 void Editor::showSpellingGuessPanel()
1814 {
1815     if (!client()) {
1816         LOG_ERROR("No NSSpellChecker");
1817         return;
1818     }
1819
1820     if (client()->spellingUIIsShowing()) {
1821         client()->showSpellingUI(false);
1822         return;
1823     }
1824     
1825     advanceToNextMisspelling(true);
1826     client()->showSpellingUI(true);
1827 }
1828
1829 bool Editor::spellingPanelIsShowing()
1830 {
1831     if (!client())
1832         return false;
1833     return client()->spellingUIIsShowing();
1834 }
1835
1836 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1837 {
1838     RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
1839     if (selectedRange) {
1840         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1841         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Grammar);
1842     }
1843 }
1844
1845 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1846 {
1847     markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
1848 }
1849
1850 void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
1851 {
1852 #if !USE(AUTOMATIC_TEXT_REPLACEMENT)
1853     UNUSED_PARAM(doReplacement);
1854 #endif
1855
1856     if (unifiedTextCheckerEnabled()) {
1857         m_spellingCorrector->applyPendingCorrection(selectionAfterTyping);
1858
1859         TextCheckingTypeMask textCheckingOptions = 0;
1860
1861         if (isContinuousSpellCheckingEnabled())
1862             textCheckingOptions |= TextCheckingTypeSpelling;
1863
1864 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1865         if (doReplacement
1866             && (isAutomaticQuoteSubstitutionEnabled()
1867                 || isAutomaticLinkDetectionEnabled()
1868                 || isAutomaticDashSubstitutionEnabled()
1869                 || isAutomaticTextReplacementEnabled()
1870                 || ((textCheckingOptions & TextCheckingTypeSpelling) && isAutomaticSpellingCorrectionEnabled())))
1871             textCheckingOptions |= TextCheckingTypeReplacement;
1872 #endif
1873         if (!(textCheckingOptions & (TextCheckingTypeSpelling | TextCheckingTypeReplacement)))
1874             return;
1875
1876         if (isGrammarCheckingEnabled())
1877             textCheckingOptions |= TextCheckingTypeGrammar;
1878
1879         VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
1880         if (textCheckingOptions & TextCheckingTypeGrammar) {
1881             VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
1882             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
1883         } else
1884             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
1885         return;
1886     }
1887
1888     if (!isContinuousSpellCheckingEnabled())
1889         return;
1890
1891     // Check spelling of one word
1892     RefPtr<Range> misspellingRange;
1893     markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
1894
1895     // Autocorrect the misspelled word.
1896     if (!misspellingRange)
1897         return;
1898     
1899     // Get the misspelled word.
1900     const String misspelledWord = plainText(misspellingRange.get());
1901     String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
1902
1903     // If autocorrected word is non empty, replace the misspelled word by this word.
1904     if (!autocorrectedString.isEmpty()) {
1905         VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
1906         if (newSelection != frame()->selection()->selection()) {
1907             if (!frame()->selection()->shouldChangeSelection(newSelection))
1908                 return;
1909             frame()->selection()->setSelection(newSelection);
1910         }
1911
1912         if (!frame()->editor()->shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
1913             return;
1914         frame()->editor()->replaceSelectionWithText(autocorrectedString, false, false);
1915
1916         // Reset the charet one character further.
1917         frame()->selection()->moveTo(frame()->selection()->end());
1918         frame()->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
1919     }
1920
1921     if (!isGrammarCheckingEnabled())
1922         return;
1923     
1924     // Check grammar of entire sentence
1925     markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
1926 }
1927     
1928 void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
1929 {
1930     // This function is called with a selection already expanded to word boundaries.
1931     // Might be nice to assert that here.
1932     
1933     // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
1934     // grammar checking can only be on if spell checking is also on.
1935     if (!isContinuousSpellCheckingEnabled())
1936         return;
1937     
1938     RefPtr<Range> searchRange(selection.toNormalizedRange());
1939     if (!searchRange)
1940         return;
1941     
1942     // If we're not in an editable node, bail.
1943     Node* editableNode = searchRange->startContainer();
1944     if (!editableNode || !editableNode->rendererIsEditable())
1945         return;
1946
1947     if (!isSpellCheckingEnabledFor(editableNode))
1948         return;
1949
1950     // Get the spell checker if it is available
1951     if (!client())
1952         return;
1953     
1954     TextCheckingHelper checker(client(), searchRange);
1955     if (checkSpelling)
1956         checker.markAllMisspellings(firstMisspellingRange);
1957     else {
1958         ASSERT(WTF_USE_GRAMMAR_CHECKING);
1959         if (isGrammarCheckingEnabled())
1960             checker.markAllBadGrammar();
1961     }    
1962 }
1963
1964 bool Editor::isSpellCheckingEnabledFor(Node* node) const
1965 {
1966     if (!node)
1967         return false;
1968     const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
1969     if (!focusedElement)
1970         return false;
1971     return focusedElement->isSpellCheckingEnabled();
1972 }
1973
1974 bool Editor::isSpellCheckingEnabledInFocusedNode() const
1975 {
1976     return isSpellCheckingEnabledFor(m_frame->selection()->start().deprecatedNode());
1977 }
1978
1979 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
1980 {
1981     markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
1982 }
1983     
1984 void Editor::markBadGrammar(const VisibleSelection& selection)
1985 {
1986     ASSERT(WTF_USE_GRAMMAR_CHECKING);
1987     RefPtr<Range> firstMisspellingRange;
1988     markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
1989 }
1990
1991 void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
1992 {
1993     ASSERT(unifiedTextCheckerEnabled());
1994
1995     // There shouldn't be pending autocorrection at this moment.
1996     ASSERT(!m_spellingCorrector->hasPendingCorrection());
1997
1998     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
1999     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2000
2001     // This function is called with selections already expanded to word boundaries.
2002     if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
2003         return;
2004
2005     // If we're not in an editable node, bail.
2006     Node* editableNode = spellingRange->startContainer();
2007     if (!editableNode || !editableNode->rendererIsEditable())
2008         return;
2009
2010     if (!isSpellCheckingEnabledFor(editableNode))
2011         return;
2012
2013     TextCheckingParagraph spellingParagraph(spellingRange);
2014     TextCheckingParagraph grammarParagraph(shouldMarkGrammar ? grammarRange : 0);
2015
2016     if (shouldMarkGrammar ? (spellingParagraph.isRangeEmpty() && grammarParagraph.isEmpty()) : spellingParagraph.isEmpty())
2017         return;
2018
2019     bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
2020     if (asynchronous) {
2021         if (shouldMarkGrammar)
2022             m_spellChecker->requestCheckingFor(resolveTextCheckingTypeMask(textCheckingOptions), grammarParagraph.paragraphRange());
2023         else
2024             m_spellChecker->requestCheckingFor(resolveTextCheckingTypeMask(textCheckingOptions), spellingParagraph.paragraphRange());
2025         return;
2026     }
2027
2028     Vector<TextCheckingResult> results;
2029     if (shouldMarkGrammar)
2030         checkTextOfParagraph(textChecker(), grammarParagraph.textCharacters(), grammarParagraph.textLength(), 
2031                                             resolveTextCheckingTypeMask(textCheckingOptions), results);
2032     else
2033         checkTextOfParagraph(textChecker(), spellingParagraph.textCharacters(), spellingParagraph.textLength(), 
2034                                             resolveTextCheckingTypeMask(textCheckingOptions), results);
2035
2036     markAndReplaceFor(textCheckingOptions, results, spellingParagraph, grammarParagraph);
2037 }
2038
2039 void Editor::markAndReplaceFor(TextCheckingTypeMask textCheckingOptions, const Vector<TextCheckingResult>& results, const TextCheckingParagraph& spellingParagraph, const TextCheckingParagraph& grammarParagraph)
2040 {
2041     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
2042     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2043     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
2044     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2045     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
2046
2047     // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2048     int selectionOffset = 0;
2049     int ambiguousBoundaryOffset = -1;
2050     bool selectionChanged = false;
2051     bool restoreSelectionAfterChange = false;
2052     bool adjustSelectionForParagraphBoundaries = false;
2053
2054     if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2055         if (m_frame->selection()->selectionType() == VisibleSelection::CaretSelection) {
2056             // Attempt to save the caret position so we can restore it later if needed
2057             Position caretPosition = m_frame->selection()->end();
2058             selectionOffset = spellingParagraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
2059             restoreSelectionAfterChange = true;
2060             if (selectionOffset > 0 && (selectionOffset > spellingParagraph.textLength() || spellingParagraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2061                 adjustSelectionForParagraphBoundaries = true;
2062             if (selectionOffset > 0 && selectionOffset <= spellingParagraph.textLength() && isAmbiguousBoundaryCharacter(spellingParagraph.textCharAt(selectionOffset - 1)))
2063                 ambiguousBoundaryOffset = selectionOffset - 1;
2064         }
2065     }
2066
2067     // If this checking is only for showing correction panel, we shouldn't bother to mark misspellings.
2068     if (shouldShowCorrectionPanel)
2069         shouldMarkSpelling = false;
2070
2071     int offsetDueToReplacement = 0;
2072
2073     for (unsigned i = 0; i < results.size(); i++) {
2074         int spellingRangeEndOffset = spellingParagraph.checkingEnd() + offsetDueToReplacement;
2075         const TextCheckingResult* result = &results[i];
2076         int resultLocation = result->location + offsetDueToReplacement;
2077         int resultLength = result->length;
2078         bool resultEndsAtAmbiguousBoundary = ambiguousBoundaryOffset >= 0 && resultLocation + resultLength == ambiguousBoundaryOffset;
2079
2080         // Only mark misspelling if:
2081         // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2082         // 2. Result falls within spellingRange.
2083         // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2084         //    "wouldn'" as misspelled right after apostrophe is typed.
2085         if (shouldMarkSpelling && result->type == TextCheckingTypeSpelling && resultLocation >= spellingParagraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2086             ASSERT(resultLength > 0 && resultLocation >= 0);
2087             RefPtr<Range> misspellingRange = spellingParagraph.subrange(resultLocation, resultLength);
2088             if (!m_spellingCorrector->isSpellingMarkerAllowed(misspellingRange))
2089                 continue;
2090             misspellingRange->startContainer()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
2091         } else if (shouldMarkGrammar && result->type == TextCheckingTypeGrammar && grammarParagraph.checkingRangeCovers(resultLocation, resultLength)) {
2092             ASSERT(resultLength > 0 && resultLocation >= 0);
2093             for (unsigned j = 0; j < result->details.size(); j++) {
2094                 const GrammarDetail* detail = &result->details[j];
2095                 ASSERT(detail->length > 0 && detail->location >= 0);
2096                 if (grammarParagraph.checkingRangeCovers(resultLocation + detail->location, detail->length)) {
2097                     RefPtr<Range> badGrammarRange = grammarParagraph.subrange(resultLocation + detail->location, detail->length);
2098                     badGrammarRange->startContainer()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription);
2099                 }
2100             }
2101         } else if (resultLocation + resultLength <= spellingRangeEndOffset && resultLocation + resultLength >= spellingParagraph.checkingStart()
2102                     && (result->type == TextCheckingTypeLink
2103                     || result->type == TextCheckingTypeQuote
2104                     || result->type == TextCheckingTypeDash
2105                     || result->type == TextCheckingTypeReplacement
2106                     || result->type == TextCheckingTypeCorrection)) {
2107             // In this case the result range just has to touch the spelling range, so we can handle replacing non-word text such as punctuation.
2108             ASSERT(resultLength > 0 && resultLocation >= 0);
2109
2110             if (shouldShowCorrectionPanel && (resultLocation + resultLength < spellingRangeEndOffset || result->type != TextCheckingTypeCorrection))
2111                 continue;
2112
2113             int replacementLength = result->replacement.length();
2114
2115             // Apply replacement if:
2116             // 1. The replacement length is non-zero.
2117             // 2. The result doesn't end at an ambiguous boundary.
2118             //    (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2119             bool doReplacement = replacementLength > 0 && !resultEndsAtAmbiguousBoundary;
2120             RefPtr<Range> rangeToReplace = spellingParagraph.subrange(resultLocation, resultLength);
2121             VisibleSelection selectionToReplace(rangeToReplace.get(), DOWNSTREAM);
2122
2123             // adding links should be done only immediately after they are typed
2124             if (result->type == TextCheckingTypeLink && selectionOffset > resultLocation + resultLength + 1)
2125                 continue;
2126
2127             if (!(shouldPerformReplacement || shouldShowCorrectionPanel) || !doReplacement)
2128                 continue;
2129
2130             String replacedString = plainText(rangeToReplace.get());
2131             bool existingMarkersPermitReplacement = m_spellingCorrector->processMarkersOnTextToBeReplacedByResult(result, rangeToReplace.get(), replacedString);
2132             if (!existingMarkersPermitReplacement)
2133                 continue;
2134
2135             if (shouldShowCorrectionPanel) {
2136 #if !USE(AUTOCORRECTION_PANEL)
2137                 ASSERT_NOT_REACHED();
2138 #endif
2139                 // shouldShowCorrectionPanel can be true only when the panel is available.
2140                 if (resultLocation + resultLength == spellingRangeEndOffset) {
2141                     // We only show the correction panel on the last word.
2142                     m_spellingCorrector->show(rangeToReplace, result->replacement);
2143                     break;
2144                 }
2145                 // If this function is called for showing correction panel, we ignore other correction or replacement.
2146                 continue;
2147             }
2148
2149             if (selectionToReplace != m_frame->selection()->selection()) {
2150                 if (!m_frame->selection()->shouldChangeSelection(selectionToReplace))
2151                     continue;
2152             }
2153
2154             if (result->type == TextCheckingTypeLink) {
2155                 m_frame->selection()->setSelection(selectionToReplace);
2156                 selectionChanged = true;
2157                 restoreSelectionAfterChange = false;
2158                 if (canEditRichly())
2159                     applyCommand(CreateLinkCommand::create(m_frame->document(), result->replacement));
2160             } else if (canEdit() && shouldInsertText(result->replacement, rangeToReplace.get(), EditorInsertActionTyped)) {
2161                 applyCommand(SpellingCorrectionCommand::create(rangeToReplace, result->replacement));
2162
2163                 if (AXObjectCache::accessibilityEnabled()) {
2164                     if (Element* root = m_frame->selection()->selection().rootEditableElement())
2165                         m_frame->document()->axObjectCache()->postNotification(root->renderer(), AXObjectCache::AXAutocorrectionOccured, true);
2166                 }
2167
2168                 selectionChanged = true;
2169                 offsetDueToReplacement += replacementLength - resultLength;
2170                 if (resultLocation < selectionOffset) {
2171                     selectionOffset += replacementLength - resultLength;
2172                     if (ambiguousBoundaryOffset >= 0)
2173                         ambiguousBoundaryOffset = selectionOffset - 1;
2174                 }
2175
2176                 // Add a marker so that corrections can easily be undone and won't be re-corrected.
2177                 if (result->type == TextCheckingTypeCorrection)
2178                     m_spellingCorrector->markCorrection(spellingParagraph.subrange(resultLocation, replacementLength), replacedString);
2179             }
2180         }
2181     }
2182
2183     if (selectionChanged) {
2184         TextCheckingParagraph extendedParagraph(spellingParagraph);
2185         // Restore the caret position if we have made any replacements
2186         extendedParagraph.expandRangeToNextEnd();
2187         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2188             RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
2189             m_frame->selection()->moveTo(selectionRange->endPosition(), DOWNSTREAM);
2190             if (adjustSelectionForParagraphBoundaries)
2191                 m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2192         } else {
2193             // If this fails for any reason, the fallback is to go one position beyond the last replacement
2194             m_frame->selection()->moveTo(m_frame->selection()->end());
2195             m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2196         }
2197     }
2198 }
2199
2200 void Editor::changeBackToReplacedString(const String& replacedString)
2201 {
2202     ASSERT(unifiedTextCheckerEnabled());
2203
2204     if (replacedString.isEmpty())
2205         return;
2206
2207     RefPtr<Range> selection = selectedRange();
2208     if (!shouldInsertText(replacedString, selection.get(), EditorInsertActionPasted))
2209         return;
2210     
2211     m_spellingCorrector->recordAutocorrectionResponseReversed(replacedString, selection);
2212     TextCheckingParagraph paragraph(selection);
2213     replaceSelectionWithText(replacedString, false, false);
2214     RefPtr<Range> changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2215     changedRange->startContainer()->document()->markers()->addMarker(changedRange.get(), DocumentMarker::Replacement, String());
2216     m_spellingCorrector->markReversed(changedRange.get());
2217 }
2218
2219
2220 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2221 {
2222     if (unifiedTextCheckerEnabled()) {
2223         if (!isContinuousSpellCheckingEnabled())
2224             return;
2225         TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling | TextCheckingTypeCorrection;
2226         if (markGrammar && isGrammarCheckingEnabled())
2227             textCheckingOptions |= TextCheckingTypeGrammar;
2228         markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
2229         return;
2230     }
2231
2232     RefPtr<Range> firstMisspellingRange;
2233     markMisspellings(spellingSelection, firstMisspellingRange);
2234     if (markGrammar)
2235         markBadGrammar(grammarSelection);
2236 }
2237
2238 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2239 {
2240     m_spellingCorrector->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2241 }
2242
2243 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2244 {
2245     if (!m_spellingCorrector->shouldRemoveMarkersUponEditing())
2246         return;
2247
2248     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2249     // several scenarios:
2250     // 1. Insert in the middle of a word.
2251     // 2. Appending non whitespace at the beginning of word.
2252     // 3. Appending non whitespace at the end of word.
2253     // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2254     // remove the markers on that word.
2255     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2256     // selection, and remove words between the selection boundaries.
2257     //
2258     VisiblePosition startOfSelection = frame()->selection()->selection().start();
2259     VisiblePosition endOfSelection = frame()->selection()->selection().end();
2260     if (startOfSelection.isNull())
2261         return;
2262     // First word is the word that ends after or on the start of selection.
2263     VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2264     VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2265     // Last word is the word that begins before or on the end of selection
2266     VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2267     VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2268
2269     if (startOfFirstWord.isNull()) {
2270         startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2271         endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2272     }
2273     
2274     if (endOfLastWord.isNull()) {
2275         startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2276         endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2277     }
2278
2279     // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2280     // we choose next word as the first word.
2281     if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2282         startOfFirstWord = nextWordPosition(startOfFirstWord);
2283         endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2284         if (startOfFirstWord == endOfSelection)
2285             return;
2286     }
2287
2288     // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2289     // we choose previous word as the last word.
2290     if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2291         startOfLastWord = previousWordPosition(startOfLastWord);
2292         endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2293         if (endOfLastWord == startOfSelection)
2294             return;
2295     }
2296
2297     if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2298         return;
2299
2300     // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2301     // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2302     // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2303     // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2304     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2305     // of marker that contains the word in question, and remove marker on that whole range.
2306     Document* document = m_frame->document();
2307     RefPtr<Range> wordRange = Range::create(document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2308
2309     document->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2310     document->markers()->clearDescriptionOnMarkersIntersectingRange(wordRange.get(), DocumentMarker::Replacement);
2311 }
2312
2313 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2314 {
2315     m_spellingCorrector->deletedAutocorrectionAtPosition(position, originalString);
2316 }
2317
2318 PassRefPtr<Range> Editor::rangeForPoint(const LayoutPoint& windowPoint)
2319 {
2320     Document* document = m_frame->documentAtPoint(windowPoint);
2321     if (!document)
2322         return 0;
2323     
2324     Frame* frame = document->frame();
2325     ASSERT(frame);
2326     FrameView* frameView = frame->view();
2327     if (!frameView)
2328         return 0;
2329     LayoutPoint framePoint = frameView->windowToContents(windowPoint);
2330     VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2331     return avoidIntersectionWithNode(selection.toNormalizedRange().get(), m_deleteButtonController->containerElement());
2332 }
2333
2334 void Editor::revealSelectionAfterEditingOperation()
2335 {
2336     if (m_ignoreCompositionSelectionChange)
2337         return;
2338
2339     m_frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
2340 }
2341
2342 void Editor::setIgnoreCompositionSelectionChange(bool ignore)
2343 {
2344     if (m_ignoreCompositionSelectionChange == ignore)
2345         return;
2346
2347     m_ignoreCompositionSelectionChange = ignore;
2348     if (!ignore)
2349         revealSelectionAfterEditingOperation();
2350 }
2351
2352 PassRefPtr<Range> Editor::compositionRange() const
2353 {
2354     if (!m_compositionNode)
2355         return 0;
2356     unsigned length = m_compositionNode->length();
2357     unsigned start = min(m_compositionStart, length);
2358     unsigned end = min(max(start, m_compositionEnd), length);
2359     if (start >= end)
2360         return 0;
2361     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
2362 }
2363
2364 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
2365 {
2366     if (!m_compositionNode)
2367         return false;
2368     Position start = m_frame->selection()->start();
2369     if (start.deprecatedNode() != m_compositionNode)
2370         return false;
2371     Position end = m_frame->selection()->end();
2372     if (end.deprecatedNode() != m_compositionNode)
2373         return false;
2374
2375     if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
2376         return false;
2377     if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
2378         return false;
2379
2380     selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
2381     selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
2382     return true;
2383 }
2384
2385 void Editor::transpose()
2386 {
2387     if (!canEdit())
2388         return;
2389
2390      VisibleSelection selection = m_frame->selection()->selection();
2391      if (!selection.isCaret())
2392          return;
2393
2394     // Make a selection that goes back one character and forward two characters.
2395     VisiblePosition caret = selection.visibleStart();
2396     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
2397     VisiblePosition previous = next.previous();
2398     if (next == previous)
2399         return;
2400     previous = previous.previous();
2401     if (!inSameParagraph(next, previous))
2402         return;
2403     RefPtr<Range> range = makeRange(previous, next);
2404     if (!range)
2405         return;
2406     VisibleSelection newSelection(range.get(), DOWNSTREAM);
2407
2408     // Transpose the two characters.
2409     String text = plainText(range.get());
2410     if (text.length() != 2)
2411         return;
2412     String transposed = text.right(1) + text.left(1);
2413
2414     // Select the two characters.
2415     if (newSelection != m_frame->selection()->selection()) {
2416         if (!m_frame->selection()->shouldChangeSelection(newSelection))
2417             return;
2418         m_frame->selection()->setSelection(newSelection);
2419     }
2420
2421     // Insert the transposed characters.
2422     if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
2423         return;
2424     replaceSelectionWithText(transposed, false, false);
2425 }
2426
2427 void Editor::addToKillRing(Range* range, bool prepend)
2428 {
2429     if (m_shouldStartNewKillRingSequence)
2430         killRing()->startNewSequence();
2431
2432     String text = plainText(range);
2433     if (prepend)
2434         killRing()->prepend(text);
2435     else
2436         killRing()->append(text);
2437     m_shouldStartNewKillRingSequence = false;
2438 }
2439
2440 void Editor::startCorrectionPanelTimer()
2441 {
2442     m_spellingCorrector->startCorrectionPanelTimer(CorrectionPanelInfo::PanelTypeCorrection);
2443 }
2444
2445 void Editor::handleCorrectionPanelResult(const String& correction)
2446 {
2447     m_spellingCorrector->handleCorrectionPanelResult(correction);
2448 }
2449
2450
2451 void Editor::dismissCorrectionPanelAsIgnored()
2452 {
2453     m_spellingCorrector->dismiss(ReasonForDismissingCorrectionPanelIgnored);
2454 }
2455
2456 bool Editor::insideVisibleArea(const LayoutPoint& point) const
2457 {
2458     if (m_frame->excludeFromTextSearch())
2459         return false;
2460     
2461     // Right now, we only check the visibility of a point for disconnected frames. For all other
2462     // frames, we assume visibility.
2463     Frame* frame = m_frame->isDisconnected() ? m_frame : m_frame->tree()->top(true);
2464     if (!frame->isDisconnected())
2465         return true;
2466     
2467     RenderPart* renderer = frame->ownerRenderer();
2468     if (!renderer)
2469         return false;
2470
2471     RenderBlock* container = renderer->containingBlock();
2472     if (!(container->style()->overflowX() == OHIDDEN || container->style()->overflowY() == OHIDDEN))
2473         return true;
2474
2475     LayoutRect rectInPageCoords = container->overflowClipRect(IntPoint(), 0); // FIXME: Incorrect for CSS regions.
2476     LayoutRect rectInFrameCoords = LayoutRect(renderer->x() * -1, renderer->y() * -1,
2477                                               rectInPageCoords.width(), rectInPageCoords.height());
2478
2479     return rectInFrameCoords.contains(point);
2480 }
2481
2482 bool Editor::insideVisibleArea(Range* range) const
2483 {
2484     if (!range)
2485         return true;
2486
2487     if (m_frame->excludeFromTextSearch())
2488         return false;
2489     
2490     // Right now, we only check the visibility of a range for disconnected frames. For all other
2491     // frames, we assume visibility.
2492     Frame* frame = m_frame->isDisconnected() ? m_frame : m_frame->tree()->top(true);
2493     if (!frame->isDisconnected())
2494         return true;
2495     
2496     RenderPart* renderer = frame->ownerRenderer();
2497     if (!renderer)
2498         return false;
2499
2500     RenderBlock* container = renderer->containingBlock();
2501     if (!(container->style()->overflowX() == OHIDDEN || container->style()->overflowY() == OHIDDEN))
2502         return true;
2503
2504     LayoutRect rectInPageCoords = container->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
2505     LayoutRect rectInFrameCoords = LayoutRect(renderer->x() * -1, renderer->y() * -1,
2506                                     rectInPageCoords.width(), rectInPageCoords.height());
2507     LayoutRect resultRect = range->boundingBox();
2508     
2509     return rectInFrameCoords.contains(resultRect);
2510 }
2511
2512 PassRefPtr<Range> Editor::firstVisibleRange(const String& target, FindOptions options)
2513 {
2514     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2515     RefPtr<Range> resultRange = findPlainText(searchRange.get(), target, options & ~Backwards);
2516     ExceptionCode ec = 0;
2517
2518     while (!insideVisibleArea(resultRange.get())) {
2519         searchRange->setStartAfter(resultRange->endContainer(), ec);
2520         if (searchRange->startContainer() == searchRange->endContainer())
2521             return Range::create(m_frame->document());
2522         resultRange = findPlainText(searchRange.get(), target, options & ~Backwards);
2523     }
2524     
2525     return resultRange;
2526 }
2527
2528 PassRefPtr<Range> Editor::lastVisibleRange(const String& target, FindOptions options)
2529 {
2530     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2531     RefPtr<Range> resultRange = findPlainText(searchRange.get(), target, options | Backwards);
2532     ExceptionCode ec = 0;
2533
2534     while (!insideVisibleArea(resultRange.get())) {
2535         searchRange->setEndBefore(resultRange->startContainer(), ec);
2536         if (searchRange->startContainer() == searchRange->endContainer())
2537             return Range::create(m_frame->document());
2538         resultRange = findPlainText(searchRange.get(), target, options | Backwards);
2539     }
2540     
2541     return resultRange;
2542 }
2543
2544 PassRefPtr<Range> Editor::nextVisibleRange(Range* currentRange, const String& target, FindOptions options)
2545 {
2546     if (m_frame->excludeFromTextSearch())
2547         return Range::create(m_frame->document());
2548
2549     RefPtr<Range> resultRange = currentRange;
2550     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2551     ExceptionCode ec = 0;
2552     bool forward = !(options & Backwards);
2553     for ( ; !insideVisibleArea(resultRange.get()); resultRange = findPlainText(searchRange.get(), target, options)) {
2554         if (resultRange->collapsed(ec)) {
2555             if (!resultRange->startContainer()->isInShadowTree())
2556                 break;
2557             searchRange = rangeOfContents(m_frame->document());
2558             if (forward)
2559                 searchRange->setStartAfter(resultRange->startContainer()->shadowAncestorNode(), ec);
2560             else
2561                 searchRange->setEndBefore(resultRange->startContainer()->shadowAncestorNode(), ec);
2562             continue;
2563         }
2564
2565         if (forward)
2566             searchRange->setStartAfter(resultRange->endContainer(), ec);
2567         else
2568             searchRange->setEndBefore(resultRange->startContainer(), ec);
2569
2570         Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
2571         if (searchRange->collapsed(ec) && shadowTreeRoot) {
2572             if (forward)
2573                 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
2574             else
2575                 searchRange->setStartBefore(shadowTreeRoot, ec);
2576         }
2577         
2578         if (searchRange->startContainer()->isDocumentNode() && searchRange->endContainer()->isDocumentNode())
2579             break;
2580     }
2581     
2582     if (insideVisibleArea(resultRange.get()))
2583         return resultRange;
2584     
2585     if (!(options & WrapAround))
2586         return Range::create(m_frame->document());
2587
2588     if (options & Backwards)
2589         return lastVisibleRange(target, options);
2590
2591     return firstVisibleRange(target, options);
2592 }
2593
2594 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, bool closeTyping, bool clearTypingStyle)
2595 {
2596     // If the new selection is orphaned, then don't update the selection.
2597     if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
2598         return;
2599
2600     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
2601     // because there is work that it must do in this situation.
2602     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
2603     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
2604     bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection()->selection();
2605     if (selectionDidNotChangeDOMPosition || m_frame->selection()->shouldChangeSelection(newSelection)) {
2606         FrameSelection::SetSelectionOptions options = 0;
2607         if (closeTyping)
2608             options |= FrameSelection::CloseTyping;
2609         if (clearTypingStyle)
2610             options |= FrameSelection::ClearTypingStyle;
2611         m_frame->selection()->setSelection(newSelection, options);
2612     }
2613
2614     // Some editing operations change the selection visually without affecting its position within the DOM.
2615     // For example when you press return in the following (the caret is marked by ^):
2616     // <div contentEditable="true"><div>^Hello</div></div>
2617     // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
2618     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
2619     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
2620     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
2621     if (selectionDidNotChangeDOMPosition)
2622         client()->respondToChangedSelection(m_frame);
2623 }
2624
2625 String Editor::selectedText() const
2626 {
2627     // We remove '\0' characters because they are not visibly rendered to the user.
2628     return plainText(m_frame->selection()->toNormalizedRange().get()).replace(0, "");
2629 }
2630
2631 IntRect Editor::firstRectForRange(Range* range) const
2632 {
2633     int extraWidthToEndOfLine = 0;
2634     ASSERT(range->startContainer());
2635     ASSERT(range->endContainer());
2636
2637     LayoutRect startCaretRect = RenderedPosition(VisiblePosition(range->startPosition()).deepEquivalent(), DOWNSTREAM).absoluteRect(extraWidthToEndOfLine);
2638     if (startCaretRect == LayoutRect())
2639         return IntRect();
2640
2641     LayoutRect endCaretRect = RenderedPosition(VisiblePosition(range->endPosition()).deepEquivalent(), UPSTREAM).absoluteRect();
2642     if (endCaretRect == LayoutRect())
2643         return IntRect();
2644
2645     if (startCaretRect.y() == endCaretRect.y()) {
2646         // start and end are on the same line
2647         return IntRect(min(startCaretRect.x(), endCaretRect.x()),
2648             startCaretRect.y(),
2649             abs(endCaretRect.x() - startCaretRect.x()),
2650             max(startCaretRect.height(), endCaretRect.height()));
2651     }
2652
2653     // start and end aren't on the same line, so go from start to the end of its line
2654     return IntRect(startCaretRect.x(),
2655         startCaretRect.y(),
2656         startCaretRect.width() + extraWidthToEndOfLine,
2657         startCaretRect.height());
2658 }
2659
2660 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
2661 {
2662     return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
2663 }
2664
2665 void Editor::computeAndSetTypingStyle(CSSStyleDeclaration* style, EditAction editingAction)
2666 {
2667     if (!style || !style->length()) {
2668         m_frame->selection()->clearTypingStyle();
2669         return;
2670     }
2671
2672     // Calculate the current typing style.
2673     RefPtr<EditingStyle> typingStyle;
2674     if (m_frame->selection()->typingStyle()) {
2675         typingStyle = m_frame->selection()->typingStyle()->copy();
2676         typingStyle->overrideWithStyle(style->makeMutable().get());
2677     } else
2678         typingStyle = EditingStyle::create(style);
2679
2680     typingStyle->prepareToApplyAt(m_frame->selection()->selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
2681
2682     // Handle block styles, substracting these from the typing style.
2683     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
2684     if (!blockStyle->isEmpty())
2685         applyCommand(ApplyStyleCommand::create(m_frame->document(), blockStyle.get(), editingAction));
2686
2687     // Set the remaining style as the typing style.
2688     m_frame->selection()->setTypingStyle(typingStyle);
2689 }
2690
2691 void Editor::textFieldDidBeginEditing(Element* e)
2692 {
2693     if (client())
2694         client()->textFieldDidBeginEditing(e);
2695 }
2696
2697 void Editor::textFieldDidEndEditing(Element* e)
2698 {
2699     dismissCorrectionPanelAsIgnored();
2700     if (client())
2701         client()->textFieldDidEndEditing(e);
2702 }
2703
2704 void Editor::textDidChangeInTextField(Element* e)
2705 {
2706     if (client())
2707         client()->textDidChangeInTextField(e);
2708 }
2709
2710 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
2711 {
2712     if (client())
2713         return client()->doTextFieldCommandFromEvent(e, ke);
2714
2715     return false;
2716 }
2717
2718 void Editor::textWillBeDeletedInTextField(Element* input)
2719 {
2720     if (client())
2721         client()->textWillBeDeletedInTextField(input);
2722 }
2723
2724 void Editor::textDidChangeInTextArea(Element* e)
2725 {
2726     if (client())
2727         client()->textDidChangeInTextArea(e);
2728 }
2729
2730 void Editor::applyEditingStyleToBodyElement() const
2731 {
2732     RefPtr<NodeList> list = m_frame->document()->getElementsByTagName("body");
2733     unsigned len = list->length();
2734     for (unsigned i = 0; i < len; i++)
2735         applyEditingStyleToElement(static_cast<Element*>(list->item(i)));
2736 }
2737
2738 void Editor::applyEditingStyleToElement(Element* element) const
2739 {
2740     if (!element)
2741         return;
2742
2743     CSSStyleDeclaration* style = element->style();
2744     ASSERT(style);
2745     if (!style)
2746         return;
2747
2748     ExceptionCode ec = 0;
2749     style->setProperty(CSSPropertyWordWrap, "break-word", false, ec);
2750     ASSERT(!ec);
2751     style->setProperty(CSSPropertyWebkitNbspMode, "space", false, ec);
2752     ASSERT(!ec);
2753     style->setProperty(CSSPropertyWebkitLineBreak, "after-white-space", false, ec);
2754     ASSERT(!ec);
2755 }
2756
2757 // Searches from the beginning of the document if nothing is selected.
2758 bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
2759 {
2760     FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0);
2761     return findString(target, options);
2762 }
2763
2764 bool Editor::findString(const String& target, FindOptions options)
2765 {
2766     VisibleSelection selection = m_frame->selection()->selection();
2767
2768     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
2769
2770     if (!resultRange)
2771         return false;
2772
2773     m_frame->selection()->setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
2774     m_frame->selection()->revealSelection();
2775     return true;
2776 }
2777
2778 PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
2779 {
2780     if (target.isEmpty())
2781         return 0;
2782
2783     if (m_frame->excludeFromTextSearch())
2784         return 0;
2785
2786     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
2787     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
2788     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2789
2790     bool forward = !(options & Backwards);
2791     bool startInReferenceRange = referenceRange && (options & StartInSelection);
2792     if (referenceRange) {
2793         if (forward)
2794             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
2795         else
2796             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
2797     }
2798
2799     RefPtr<Node> shadowTreeRoot = referenceRange && referenceRange->startContainer() ? referenceRange->startContainer()->nonBoundaryShadowTreeRootNode() : 0;
2800     if (shadowTreeRoot) {
2801         if (forward)
2802             searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2803         else
2804             searchRange->setStart(shadowTreeRoot.get(), 0);
2805     }
2806
2807     RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options));
2808     // If we started in the reference range and the found range exactly matches the reference range, find again.
2809     // Build a selection with the found range to remove collapsed whitespace.
2810     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
2811     if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
2812         searchRange = rangeOfContents(m_frame->document());
2813         if (forward)
2814             searchRange->setStart(referenceRange->endPosition());
2815         else
2816             searchRange->setEnd(referenceRange->startPosition());
2817
2818         if (shadowTreeRoot) {
2819             if (forward)
2820                 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2821             else
2822                 searchRange->setStart(shadowTreeRoot.get(), 0);
2823         }
2824
2825         resultRange = findPlainText(searchRange.get(), target, options);
2826     }
2827
2828     // If nothing was found in the shadow tree, search in main content following the shadow tree.
2829     if (resultRange->collapsed() && shadowTreeRoot) {
2830         searchRange = rangeOfContents(m_frame->document());
2831         if (forward)
2832             searchRange->setStartAfter(shadowTreeRoot->shadowAncestorNode());
2833         else
2834             searchRange->setEndBefore(shadowTreeRoot->shadowAncestorNode());
2835
2836         resultRange = findPlainText(searchRange.get(), target, options);
2837     }
2838
2839     if (!insideVisibleArea(resultRange.get())) {
2840         resultRange = nextVisibleRange(resultRange.get(), target, options);
2841         if (!resultRange)
2842             return 0;
2843     }
2844
2845     // If we didn't find anything and we're wrapping, search again in the entire document (this will
2846     // redundantly re-search the area already searched in some cases).
2847     if (resultRange->collapsed() && options & WrapAround) {
2848         searchRange = rangeOfContents(m_frame->document());
2849         resultRange = findPlainText(searchRange.get(), target, options);
2850         // We used to return false here if we ended up with the same range that we started with
2851         // (e.g., the reference range was already the only instance of this text). But we decided that
2852         // this should be a success case instead, so we'll just fall through in that case.
2853     }
2854
2855     return resultRange->collapsed() ? 0 : resultRange.release();
2856 }
2857
2858 static bool isFrameInRange(Frame* frame, Range* range)
2859 {
2860     bool inRange = false;
2861     for (HTMLFrameOwnerElement* ownerElement = frame->ownerElement(); ownerElement; ownerElement = ownerElement->document()->ownerElement()) {
2862         if (ownerElement->document() == range->ownerDocument()) {
2863             ExceptionCode ec = 0;
2864             inRange = range->intersectsNode(ownerElement, ec);
2865             break;
2866         }
2867     }
2868     return inRange;
2869 }
2870
2871 unsigned Editor::countMatchesForText(const String& target, FindOptions options, unsigned limit, bool markMatches)
2872 {
2873     return countMatchesForText(target, 0, options, limit, markMatches);
2874 }
2875
2876 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches)
2877 {
2878     if (target.isEmpty())
2879         return 0;
2880
2881     RefPtr<Range> searchRange;
2882     if (range) {
2883         if (range->ownerDocument() == m_frame->document())
2884             searchRange = range;
2885         else if (!isFrameInRange(m_frame, range))
2886             return 0;
2887     }
2888     if (!searchRange)
2889         searchRange = rangeOfContents(m_frame->document());
2890
2891     Node* originalEndContainer = searchRange->endContainer();
2892     int originalEndOffset = searchRange->endOffset();
2893
2894     ExceptionCode exception = 0;
2895     unsigned matchCount = 0;
2896     do {
2897         RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options & ~Backwards));
2898         if (resultRange->collapsed(exception)) {
2899             if (!resultRange->startContainer()->isInShadowTree())
2900                 break;
2901
2902             searchRange->setStartAfter(resultRange->startContainer()->shadowAncestorNode(), exception);
2903             searchRange->setEnd(originalEndContainer, originalEndOffset, exception);
2904             continue;
2905         }
2906
2907         // Only treat the result as a match if it is visible
2908         if (insideVisibleArea(resultRange.get())) {
2909             ++matchCount;
2910             if (markMatches)
2911                 m_frame->document()->markers()->addMarker(resultRange.get(), DocumentMarker::TextMatch);
2912         }
2913
2914         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
2915         if (limit > 0 && matchCount >= limit)
2916             break;
2917
2918         // Set the new start for the search range to be the end of the previous
2919         // result range. There is no need to use a VisiblePosition here,
2920         // since findPlainText will use a TextIterator to go over the visible
2921         // text nodes. 
2922         searchRange->setStart(resultRange->endContainer(exception), resultRange->endOffset(exception), exception);
2923
2924         Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
2925         if (searchRange->collapsed(exception) && shadowTreeRoot)
2926             searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), exception);
2927     } while (true);
2928
2929     if (markMatches) {
2930         // Do a "fake" paint in order to execute the code that computes the rendered rect for each text match.
2931         if (m_frame->view() && m_frame->contentRenderer()) {
2932             m_frame->document()->updateLayout(); // Ensure layout is up to date.
2933             LayoutRect visibleRect = m_frame->view()->visibleContentRect();
2934             if (!visibleRect.isEmpty()) {
2935                 GraphicsContext context((PlatformGraphicsContext*)0);
2936                 context.setPaintingDisabled(true);
2937
2938                 PaintBehavior oldBehavior = m_frame->view()->paintBehavior();
2939                 m_frame->view()->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
2940                 m_frame->view()->paintContents(&context, visibleRect);
2941                 m_frame->view()->setPaintBehavior(oldBehavior);
2942             }
2943         }
2944     }
2945
2946     return matchCount;
2947 }
2948
2949 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
2950 {
2951     if (flag == m_areMarkedTextMatchesHighlighted)
2952         return;
2953
2954     m_areMarkedTextMatchesHighlighted = flag;
2955     m_frame->document()->markers()->repaintMarkers(DocumentMarker::TextMatch);
2956 }
2957
2958 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
2959 {
2960     m_spellingCorrector->stopPendingCorrection(oldSelection);
2961
2962     bool closeTyping = options & FrameSelection::CloseTyping;
2963     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
2964     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
2965     if (isContinuousSpellCheckingEnabled) {
2966         VisibleSelection newAdjacentWords;
2967         VisibleSelection newSelectedSentence;
2968         bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
2969         if (m_frame->selection()->selection().isContentEditable() || caretBrowsing) {
2970             VisiblePosition newStart(m_frame->selection()->selection().visibleStart());
2971             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
2972             if (isContinuousGrammarCheckingEnabled)
2973                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
2974         }
2975
2976         // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
2977         bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
2978
2979         // When typing we check spelling elsewhere, so don't redo it here.
2980         // If this is a change in selection resulting from a delete operation,
2981         // oldSelection may no longer be in the document.
2982         if (shouldCheckSpellingAndGrammar && closeTyping && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
2983             VisiblePosition oldStart(oldSelection.visibleStart());
2984             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
2985             if (oldAdjacentWords != newAdjacentWords) {
2986                 if (isContinuousGrammarCheckingEnabled) {
2987                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
2988                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
2989                 } else
2990                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
2991             }
2992         }
2993
2994 #if !PLATFORM(MAC) || (PLATFORM(MAC) && (defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_SNOW_LEOPARD)))
2995         // This only erases markers that are in the first unit (word or sentence) of the selection.
2996         // Perhaps peculiar, but it matches AppKit on these Mac OS X versions.
2997         if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
2998             m_frame->document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
2999 #endif
3000         if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3001             m_frame->document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3002     }
3003
3004     // When continuous spell checking is off, existing markers disappear after the selection changes.
3005     if (!isContinuousSpellCheckingEnabled)
3006         m_frame->document()->markers()->removeMarkers(DocumentMarker::Spelling);
3007     if (!isContinuousGrammarCheckingEnabled)
3008         m_frame->document()->markers()->removeMarkers(DocumentMarker::Grammar);
3009
3010     respondToChangedSelection(oldSelection);
3011 }
3012
3013 static Node* findFirstMarkable(Node* node)
3014 {
3015     while (node) {
3016         if (!node->renderer())
3017             return 0;
3018         if (node->renderer()->isText())
3019             return node;
3020         if (node->renderer()->isTextControl())
3021             node = toRenderTextControl(node->renderer())->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3022         else if (node->firstChild())
3023             node = node->firstChild();
3024         else
3025             node = node->nextSibling();
3026     }
3027
3028     return 0;
3029 }
3030
3031 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3032 {
3033     Node* node = findFirstMarkable(m_frame->selection()->start().deprecatedNode());
3034     if (!node)
3035         return false;
3036
3037     unsigned int startOffset = static_cast<unsigned int>(from);
3038     unsigned int endOffset = static_cast<unsigned int>(from + length);
3039     Vector<DocumentMarker*> markers = m_frame->document()->markers()->markersFor(node);
3040     for (size_t i = 0; i < markers.size(); ++i) {
3041         DocumentMarker* marker = markers[i];
3042         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3043             return true;
3044     }
3045
3046     return false;
3047 }       
3048
3049 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
3050 {
3051     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3052     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3053     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3054     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3055
3056     TextCheckingTypeMask checkingTypes = 0;
3057     if (shouldMarkSpelling)
3058         checkingTypes |= TextCheckingTypeSpelling;
3059     if (shouldMarkGrammar)
3060         checkingTypes |= TextCheckingTypeGrammar;
3061     if (shouldCheckForCorrection)
3062         checkingTypes |= TextCheckingTypeCorrection;
3063
3064 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3065     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3066     if (shouldPerformReplacement) {
3067         if (isAutomaticLinkDetectionEnabled())
3068             checkingTypes |= TextCheckingTypeLink;
3069         if (isAutomaticQuoteSubstitutionEnabled())
3070             checkingTypes |= TextCheckingTypeQuote;
3071         if (isAutomaticDashSubstitutionEnabled())
3072             checkingTypes |= TextCheckingTypeDash;
3073         if (isAutomaticTextReplacementEnabled())
3074             checkingTypes |= TextCheckingTypeReplacement;
3075         if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3076             checkingTypes |= TextCheckingTypeCorrection;
3077     }
3078 #endif
3079
3080     return checkingTypes;
3081 }
3082
3083 void Editor::deviceScaleFactorChanged()
3084 {
3085     m_deleteButtonController->deviceScaleFactorChanged();
3086 }
3087
3088 bool Editor::unifiedTextCheckerEnabled() const
3089 {
3090     return WebCore::unifiedTextCheckerEnabled(m_frame);
3091 }
3092
3093 } // namespace WebCore