261f562e8ca90d579d0ab8b5d5a5c0a2112a635e
[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     RefPtr<Range> rangeToCheck = Range::create(m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
420     m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), rangeToCheck, rangeToCheck));
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(Element* startRoot, Element* endRoot)
858 {
859     ExceptionCode ec;
860     if (startRoot)
861         startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), ec);
862     if (endRoot && endRoot != startRoot)
863         endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), ec);
864 }
865
866 void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
867 {
868     m_frame->document()->updateLayout();
869
870     EditCommandComposition* composition = cmd->composition();
871     ASSERT(composition);
872     dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
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(toCompositeEditCommand(m_lastEditCommand.get())->ensureComposition());
892     }
893
894     respondToChangedContents(newSelection);
895 }
896
897 void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
898 {
899     m_frame->document()->updateLayout();
900     
901     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
902     
903     VisibleSelection newSelection(cmd->startingSelection());
904     changeSelectionAfterCommand(newSelection, true, true);
905     m_spellingCorrector->respondToUnappliedEditing(cmd.get());
906     
907     m_lastEditCommand = 0;
908     if (client())
909         client()->registerCommandForRedo(cmd);
910     respondToChangedContents(newSelection);
911 }
912
913 void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
914 {
915     m_frame->document()->updateLayout();
916     
917     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
918     
919     VisibleSelection newSelection(cmd->endingSelection());
920     changeSelectionAfterCommand(newSelection, true, true);
921     
922     m_lastEditCommand = 0;
923     if (client())
924         client()->registerCommandForUndo(cmd);
925     respondToChangedContents(newSelection);
926 }
927
928 Editor::Editor(Frame* frame)
929     : m_frame(frame)
930     , m_deleteButtonController(adoptPtr(new DeleteButtonController(frame)))
931     , m_ignoreCompositionSelectionChange(false)
932     , m_shouldStartNewKillRingSequence(false)
933     // This is off by default, since most editors want this behavior (this matches IE but not FF).
934     , m_shouldStyleWithCSS(false)
935     , m_killRing(adoptPtr(new KillRing))
936     , m_spellChecker(adoptPtr(new SpellChecker(frame)))
937     , m_spellingCorrector(adoptPtr(new SpellingCorrectionController(frame)))
938     , m_areMarkedTextMatchesHighlighted(false)
939 {
940 }
941
942 Editor::~Editor()
943 {
944 }
945
946 void Editor::clear()
947 {
948     m_compositionNode = 0;
949     m_customCompositionUnderlines.clear();
950     m_shouldStyleWithCSS = false;
951 }
952
953 bool Editor::insertText(const String& text, Event* triggeringEvent)
954 {
955     return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
956 }
957
958 bool Editor::insertTextForConfirmedComposition(const String& text)
959 {
960     return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
961 }
962
963 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
964 {
965     if (text.isEmpty())
966         return false;
967
968     VisibleSelection selection = selectionForCommand(triggeringEvent);
969     if (!selection.isContentEditable())
970         return false;
971     RefPtr<Range> range = selection.toNormalizedRange();
972
973     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
974         return true;
975
976     if (!text.isEmpty())
977         updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
978
979     bool shouldConsiderApplyingAutocorrection = false;
980     if (text == " " || text == "\t")
981         shouldConsiderApplyingAutocorrection = true;
982
983     if (text.length() == 1 && isPunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
984         shouldConsiderApplyingAutocorrection = true;
985
986     bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
987
988     // Get the selection to use for the event that triggered this insertText.
989     // If the event handler changed the selection, we may want to use a different selection
990     // that is contained in the event target.
991     selection = selectionForCommand(triggeringEvent);
992     if (selection.isContentEditable()) {
993         if (Node* selectionStart = selection.start().deprecatedNode()) {
994             RefPtr<Document> document = selectionStart->document();
995
996             // Insert the text
997             TypingCommand::Options options = 0;
998             if (selectInsertedText)
999                 options |= TypingCommand::SelectInsertedText;
1000             if (autocorrectionWasApplied)
1001                 options |= TypingCommand::RetainAutocorrectionIndicator;
1002             TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
1003
1004             // Reveal the current selection
1005             if (Frame* editedFrame = document->frame())
1006                 if (Page* page = editedFrame->page())
1007                     page->focusController()->focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
1008         }
1009     }
1010
1011     return true;
1012 }
1013
1014 bool Editor::insertLineBreak()
1015 {
1016     if (!canEdit())
1017         return false;
1018
1019     if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1020         return true;
1021
1022     bool autocorrectionIsApplied = m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
1023     TypingCommand::insertLineBreak(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1024     revealSelectionAfterEditingOperation();
1025
1026     return true;
1027 }
1028
1029 bool Editor::insertParagraphSeparator()
1030 {
1031     if (!canEdit())
1032         return false;
1033
1034     if (!canEditRichly())
1035         return insertLineBreak();
1036
1037     if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
1038         return true;
1039
1040     bool autocorrectionIsApplied = m_spellingCorrector->applyAutocorrectionBeforeTypingIfAppropriate();
1041     TypingCommand::insertParagraphSeparator(m_frame->document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1042     revealSelectionAfterEditingOperation();
1043
1044     return true;
1045 }
1046
1047 void Editor::cut()
1048 {
1049     if (tryDHTMLCut())
1050         return; // DHTML did the whole operation
1051     if (!canCut()) {
1052         systemBeep();
1053         return;
1054     }
1055     RefPtr<Range> selection = selectedRange();
1056     if (shouldDeleteRange(selection.get())) {
1057         updateMarkersForWordsAffectedByEditing(true);
1058         if (enclosingTextFormControl(m_frame->selection()->start()))
1059             Pasteboard::generalPasteboard()->writePlainText(selectedText());
1060         else
1061             Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), m_frame);
1062         didWriteSelectionToPasteboard();
1063         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1064     }
1065 }
1066
1067 void Editor::copy()
1068 {
1069     if (tryDHTMLCopy())
1070         return; // DHTML did the whole operation
1071     if (!canCopy()) {
1072         systemBeep();
1073         return;
1074     }
1075
1076     if (enclosingTextFormControl(m_frame->selection()->start()))
1077         Pasteboard::generalPasteboard()->writePlainText(selectedText());
1078     else {
1079         Document* document = m_frame->document();
1080         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
1081             Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
1082         else
1083             Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame);
1084     }
1085
1086     didWriteSelectionToPasteboard();
1087 }
1088
1089 void Editor::paste()
1090 {
1091     ASSERT(m_frame->document());
1092     if (tryDHTMLPaste())
1093         return; // DHTML did the whole operation
1094     if (!canPaste())
1095         return;
1096     updateMarkersForWordsAffectedByEditing(false);
1097     CachedResourceLoader* loader = m_frame->document()->cachedResourceLoader();
1098     ResourceCacheValidationSuppressor validationSuppressor(loader);
1099     if (m_frame->selection()->isContentRichlyEditable())
1100         pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
1101     else
1102         pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1103 }
1104
1105 void Editor::pasteAsPlainText()
1106 {
1107     if (tryDHTMLPaste())
1108         return;
1109     if (!canPaste())
1110         return;
1111     updateMarkersForWordsAffectedByEditing(false);
1112     pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
1113 }
1114
1115 void Editor::performDelete()
1116 {
1117     if (!canDelete()) {
1118         systemBeep();
1119         return;
1120     }
1121
1122     addToKillRing(selectedRange().get(), false);
1123     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1124
1125     // clear the "start new kill ring sequence" setting, because it was set to true
1126     // when the selection was updated by deleting the range
1127     setStartNewKillRingSequence(false);
1128 }
1129
1130 void Editor::copyURL(const KURL& url, const String& title)
1131 {
1132     Pasteboard::generalPasteboard()->writeURL(url, title, m_frame);
1133 }
1134
1135 void Editor::copyImage(const HitTestResult& result)
1136 {
1137     KURL url = result.absoluteLinkURL();
1138     if (url.isEmpty())
1139         url = result.absoluteImageURL();
1140
1141     Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
1142 }
1143
1144 bool Editor::isContinuousSpellCheckingEnabled()
1145 {
1146     return client() && client()->isContinuousSpellCheckingEnabled();
1147 }
1148
1149 void Editor::toggleContinuousSpellChecking()
1150 {
1151     if (client())
1152         client()->toggleContinuousSpellChecking();
1153 }
1154
1155 bool Editor::isGrammarCheckingEnabled()
1156 {
1157     return client() && client()->isGrammarCheckingEnabled();
1158 }
1159
1160 void Editor::toggleGrammarChecking()
1161 {
1162     if (client())
1163         client()->toggleGrammarChecking();
1164 }
1165
1166 int Editor::spellCheckerDocumentTag()
1167 {
1168     return client() ? client()->spellCheckerDocumentTag() : 0;
1169 }
1170
1171 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1172
1173 void Editor::uppercaseWord()
1174 {
1175     if (client())
1176         client()->uppercaseWord();
1177 }
1178
1179 void Editor::lowercaseWord()
1180 {
1181     if (client())
1182         client()->lowercaseWord();
1183 }
1184
1185 void Editor::capitalizeWord()
1186 {
1187     if (client())
1188         client()->capitalizeWord();
1189 }
1190
1191 void Editor::showSubstitutionsPanel()
1192 {
1193     if (!client()) {
1194         LOG_ERROR("No NSSpellChecker");
1195         return;
1196     }
1197
1198     if (client()->substitutionsPanelIsShowing()) {
1199         client()->showSubstitutionsPanel(false);
1200         return;
1201     }
1202     client()->showSubstitutionsPanel(true);
1203 }
1204
1205 bool Editor::substitutionsPanelIsShowing()
1206 {
1207     if (!client())
1208         return false;
1209     return client()->substitutionsPanelIsShowing();
1210 }
1211
1212 void Editor::toggleSmartInsertDelete()
1213 {
1214     if (client())
1215         client()->toggleSmartInsertDelete();
1216 }
1217
1218 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1219 {
1220     return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1221 }
1222
1223 void Editor::toggleAutomaticQuoteSubstitution()
1224 {
1225     if (client())
1226         client()->toggleAutomaticQuoteSubstitution();
1227 }
1228
1229 bool Editor::isAutomaticLinkDetectionEnabled()
1230 {
1231     return client() && client()->isAutomaticLinkDetectionEnabled();
1232 }
1233
1234 void Editor::toggleAutomaticLinkDetection()
1235 {
1236     if (client())
1237         client()->toggleAutomaticLinkDetection();
1238 }
1239
1240 bool Editor::isAutomaticDashSubstitutionEnabled()
1241 {
1242     return client() && client()->isAutomaticDashSubstitutionEnabled();
1243 }
1244
1245 void Editor::toggleAutomaticDashSubstitution()
1246 {
1247     if (client())
1248         client()->toggleAutomaticDashSubstitution();
1249 }
1250
1251 bool Editor::isAutomaticTextReplacementEnabled()
1252 {
1253     return client() && client()->isAutomaticTextReplacementEnabled();
1254 }
1255
1256 void Editor::toggleAutomaticTextReplacement()
1257 {
1258     if (client())
1259         client()->toggleAutomaticTextReplacement();
1260 }
1261
1262 bool Editor::isAutomaticSpellingCorrectionEnabled()
1263 {
1264     return m_spellingCorrector->isAutomaticSpellingCorrectionEnabled();
1265 }
1266
1267 void Editor::toggleAutomaticSpellingCorrection()
1268 {
1269     if (client())
1270         client()->toggleAutomaticSpellingCorrection();
1271 }
1272
1273 #endif
1274
1275 bool Editor::shouldEndEditing(Range* range)
1276 {
1277     return client() && client()->shouldEndEditing(range);
1278 }
1279
1280 bool Editor::shouldBeginEditing(Range* range)
1281 {
1282     return client() && client()->shouldBeginEditing(range);
1283 }
1284
1285 void Editor::clearUndoRedoOperations()
1286 {
1287     if (client())
1288         client()->clearUndoRedoOperations();
1289 }
1290
1291 bool Editor::canUndo()
1292 {
1293     return client() && client()->canUndo();
1294 }
1295
1296 void Editor::undo()
1297 {
1298     if (client())
1299         client()->undo();
1300 }
1301
1302 bool Editor::canRedo()
1303 {
1304     return client() && client()->canRedo();
1305 }
1306
1307 void Editor::redo()
1308 {
1309     if (client())
1310         client()->redo();
1311 }
1312
1313 void Editor::didBeginEditing()
1314 {
1315     if (client())
1316         client()->didBeginEditing();
1317 }
1318
1319 void Editor::didEndEditing()
1320 {
1321     if (client())
1322         client()->didEndEditing();
1323 }
1324
1325 void Editor::didWriteSelectionToPasteboard()
1326 {
1327     if (client())
1328         client()->didWriteSelectionToPasteboard();
1329 }
1330
1331 void Editor::toggleBold()
1332 {
1333     command("ToggleBold").execute();
1334 }
1335
1336 void Editor::toggleUnderline()
1337 {
1338     command("ToggleUnderline").execute();
1339 }
1340
1341 void Editor::setBaseWritingDirection(WritingDirection direction)
1342 {
1343     Node* focusedNode = frame()->document()->focusedNode();
1344     if (toTextFormControl(focusedNode)) {
1345         if (direction == NaturalWritingDirection)
1346             return;
1347         toHTMLElement(focusedNode)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
1348         focusedNode->dispatchInputEvent();
1349         frame()->document()->updateStyleIfNeeded();
1350         return;
1351     }
1352
1353     RefPtr<CSSMutableStyleDeclaration> style = CSSMutableStyleDeclaration::create();
1354     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1355     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1356 }
1357
1358 void Editor::selectComposition()
1359 {
1360     RefPtr<Range> range = compositionRange();
1361     if (!range)
1362         return;
1363     
1364     // The composition can start inside a composed character sequence, so we have to override checks.
1365     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
1366     VisibleSelection selection;
1367     selection.setWithoutValidation(range->startPosition(), range->endPosition());
1368     m_frame->selection()->setSelection(selection, 0);
1369 }
1370
1371 void Editor::confirmComposition()
1372 {
1373     if (!m_compositionNode)
1374         return;
1375     setComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
1376 }
1377
1378 void Editor::cancelComposition()
1379 {
1380     if (!m_compositionNode)
1381         return;
1382     setComposition(emptyString(), CancelComposition);
1383 }
1384
1385 void Editor::confirmComposition(const String& text)
1386 {
1387     setComposition(text, ConfirmComposition);
1388 }
1389
1390 void Editor::setComposition(const String& text, SetCompositionMode mode)
1391 {
1392     ASSERT(mode == ConfirmComposition || mode == CancelComposition);
1393     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1394
1395     setIgnoreCompositionSelectionChange(true);
1396
1397     if (mode == CancelComposition)
1398         ASSERT(text == emptyString());
1399     else
1400         selectComposition();
1401
1402     if (m_frame->selection()->isNone()) {
1403         setIgnoreCompositionSelectionChange(false);
1404         return;
1405     }
1406     
1407     // Dispatch a compositionend event to the focused node.
1408     // We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
1409     // the DOM Event specification.
1410     Node* target = m_frame->document()->focusedNode();
1411     if (target) {
1412         RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
1413         ExceptionCode ec = 0;
1414         target->dispatchEvent(event, ec);
1415     }
1416
1417     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1418     // will delete the old composition with an optimized replace operation.
1419     if (text.isEmpty())
1420         TypingCommand::deleteSelection(m_frame->document(), 0);
1421
1422     m_compositionNode = 0;
1423     m_customCompositionUnderlines.clear();
1424
1425     insertTextForConfirmedComposition(text);
1426
1427     if (mode == CancelComposition) {
1428         // An open typing command that disagrees about current selection would cause issues with typing later on.
1429         TypingCommand::closeTyping(m_frame);
1430     }
1431
1432     setIgnoreCompositionSelectionChange(false);
1433 }
1434
1435 void Editor::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
1436 {
1437     UserTypingGestureIndicator typingGestureIndicator(m_frame);
1438
1439     setIgnoreCompositionSelectionChange(true);
1440
1441     // Updates styles before setting selection for composition to prevent
1442     // inserting the previous composition text into text nodes oddly.
1443     // See https://bugs.webkit.org/show_bug.cgi?id=46868
1444     m_frame->document()->updateStyleIfNeeded();
1445
1446     selectComposition();
1447
1448     if (m_frame->selection()->isNone()) {
1449         setIgnoreCompositionSelectionChange(false);
1450         return;
1451     }
1452
1453     Node* target = m_frame->document()->focusedNode();
1454     if (target) {
1455         // Dispatch an appropriate composition event to the focused node.
1456         // We check the composition status and choose an appropriate composition event since this
1457         // function is used for three purposes:
1458         // 1. Starting a new composition.
1459         //    Send a compositionstart event when this function creates a new composition node, i.e.
1460         //    m_compositionNode == 0 && !text.isEmpty().
1461         // 2. Updating the existing composition node.
1462         //    Send a compositionupdate event when this function updates the existing composition
1463         //    node, i.e. m_compositionNode != 0 && !text.isEmpty().
1464         // 3. Canceling the ongoing composition.
1465         //    Send a compositionend event when function deletes the existing composition node, i.e.
1466         //    m_compositionNode != 0 && test.isEmpty().
1467         RefPtr<CompositionEvent> event;
1468         if (!m_compositionNode) {
1469             // We should send a compositionstart event only when the given text is not empty because this
1470             // function doesn't create a composition node when the text is empty.
1471             if (!text.isEmpty())
1472                 event = CompositionEvent::create(eventNames().compositionstartEvent, m_frame->domWindow(), text);
1473         } else {
1474             if (!text.isEmpty())
1475                 event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
1476             else
1477               event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
1478         }
1479         ExceptionCode ec = 0;
1480         if (event.get())
1481             target->dispatchEvent(event, ec);
1482     }
1483
1484     // If text is empty, then delete the old composition here.  If text is non-empty, InsertTextCommand::input
1485     // will delete the old composition with an optimized replace operation.
1486     if (text.isEmpty())
1487         TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
1488
1489     m_compositionNode = 0;
1490     m_customCompositionUnderlines.clear();
1491
1492     if (!text.isEmpty()) {
1493         TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
1494
1495         // Find out what node has the composition now.
1496         Position base = m_frame->selection()->base().downstream();
1497         Position extent = m_frame->selection()->extent();
1498         Node* baseNode = base.deprecatedNode();
1499         unsigned baseOffset = base.deprecatedEditingOffset();
1500         Node* extentNode = extent.deprecatedNode();
1501         unsigned extentOffset = extent.deprecatedEditingOffset();
1502
1503         if (baseNode && baseNode == extentNode && baseNode->isTextNode() && baseOffset + text.length() == extentOffset) {
1504             m_compositionNode = static_cast<Text*>(baseNode);
1505             m_compositionStart = baseOffset;
1506             m_compositionEnd = extentOffset;
1507             m_customCompositionUnderlines = underlines;
1508             size_t numUnderlines = m_customCompositionUnderlines.size();
1509             for (size_t i = 0; i < numUnderlines; ++i) {
1510                 m_customCompositionUnderlines[i].startOffset += baseOffset;
1511                 m_customCompositionUnderlines[i].endOffset += baseOffset;
1512             }
1513             if (baseNode->renderer())
1514                 baseNode->renderer()->repaint();
1515
1516             unsigned start = min(baseOffset + selectionStart, extentOffset);
1517             unsigned end = min(max(start, baseOffset + selectionEnd), extentOffset);
1518             RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);                
1519             m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
1520         }
1521     }
1522
1523     setIgnoreCompositionSelectionChange(false);
1524 }
1525
1526 void Editor::ignoreSpelling()
1527 {
1528     if (!client())
1529         return;
1530         
1531     RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1532     if (selectedRange)
1533         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1534
1535     String text = selectedText();
1536     ASSERT(text.length());
1537     textChecker()->ignoreWordInSpellDocument(text);
1538 }
1539
1540 void Editor::learnSpelling()
1541 {
1542     if (!client())
1543         return;
1544         
1545     // 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>.
1546
1547     RefPtr<Range> selectedRange = frame()->selection()->toNormalizedRange();
1548     if (selectedRange)
1549         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1550
1551     String text = selectedText();
1552     ASSERT(text.length());
1553     textChecker()->learnWord(text);
1554 }
1555
1556 void Editor::advanceToNextMisspelling(bool startBeforeSelection)
1557 {
1558     ExceptionCode ec = 0;
1559
1560     // The basic approach is to search in two phases - from the selection end to the end of the doc, and
1561     // then we wrap and search from the doc start to (approximately) where we started.
1562     
1563     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
1564     // repeated "check spelling" commands work.
1565     VisibleSelection selection(frame()->selection()->selection());
1566     RefPtr<Range> spellingSearchRange(rangeOfContents(frame()->document()));
1567
1568     bool startedWithSelection = false;
1569     if (selection.start().deprecatedNode()) {
1570         startedWithSelection = true;
1571         if (startBeforeSelection) {
1572             VisiblePosition start(selection.visibleStart());
1573             // We match AppKit's rule: Start 1 character before the selection.
1574             VisiblePosition oneBeforeStart = start.previous();
1575             setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
1576         } else
1577             setStart(spellingSearchRange.get(), selection.visibleEnd());
1578     }
1579
1580     Position position = spellingSearchRange->startPosition();
1581     if (!isEditablePosition(position)) {
1582         // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
1583         // selection is editable.
1584         // This can happen in Mail for a mix of non-editable and editable content (like Stationary), 
1585         // when spell checking the whole document before sending the message.
1586         // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
1587
1588         position = firstEditablePositionAfterPositionInRoot(position, frame()->document()->documentElement()).deepEquivalent();
1589         if (position.isNull())
1590             return;
1591         
1592         Position rangeCompliantPosition = position.parentAnchoredEquivalent();
1593         spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), ec);
1594         startedWithSelection = false; // won't need to wrap
1595     }
1596     
1597     // topNode defines the whole range we want to operate on 
1598     Node* topNode = highestEditableRoot(position);
1599     // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
1600     spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), ec);
1601
1602     // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
1603     // at a word boundary. Going back by one char and then forward by a word does the trick.
1604     if (startedWithSelection) {
1605         VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
1606         if (oneBeforeStart.isNotNull())
1607             setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
1608         // else we were already at the start of the editable node
1609     }
1610     
1611     if (spellingSearchRange->collapsed(ec))
1612         return; // nothing to search in
1613     
1614     // Get the spell checker if it is available
1615     if (!client())
1616         return;
1617         
1618     // We go to the end of our first range instead of the start of it, just to be sure
1619     // we don't get foiled by any word boundary problems at the start.  It means we might
1620     // do a tiny bit more searching.
1621     Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer(ec);
1622     int searchEndOffsetAfterWrap = spellingSearchRange->endOffset(ec);
1623     
1624     int misspellingOffset = 0;
1625     GrammarDetail grammarDetail;
1626     int grammarPhraseOffset = 0;
1627     RefPtr<Range> grammarSearchRange;
1628     String badGrammarPhrase;
1629     String misspelledWord;
1630
1631     bool isSpelling = true;
1632     int foundOffset = 0;
1633     String foundItem;
1634     RefPtr<Range> firstMisspellingRange;
1635     if (unifiedTextCheckerEnabled()) {
1636         grammarSearchRange = spellingSearchRange->cloneRange(ec);
1637         foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1638         if (isSpelling) {
1639             misspelledWord = foundItem;
1640             misspellingOffset = foundOffset;
1641         } else {
1642             badGrammarPhrase = foundItem;
1643             grammarPhraseOffset = foundOffset;
1644         }
1645     } else {
1646         misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1647
1648 #if USE(GRAMMAR_CHECKING)
1649         grammarSearchRange = spellingSearchRange->cloneRange(ec);
1650         if (!misspelledWord.isEmpty()) {
1651             // Stop looking at start of next misspelled word
1652             CharacterIterator chars(grammarSearchRange.get());
1653             chars.advance(misspellingOffset);
1654             grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1655         }
1656     
1657         if (isGrammarCheckingEnabled())
1658             badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1659 #endif
1660     }
1661     
1662     // 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
1663     // block rather than at a selection).
1664     if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
1665         spellingSearchRange->setStart(topNode, 0, ec);
1666         // going until the end of the very first chunk we tested is far enough
1667         spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, ec);
1668         
1669         if (unifiedTextCheckerEnabled()) {
1670             grammarSearchRange = spellingSearchRange->cloneRange(ec);
1671             foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
1672             if (isSpelling) {
1673                 misspelledWord = foundItem;
1674                 misspellingOffset = foundOffset;
1675             } else {
1676                 badGrammarPhrase = foundItem;
1677                 grammarPhraseOffset = foundOffset;
1678             }
1679         } else {
1680             misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
1681
1682 #if USE(GRAMMAR_CHECKING)
1683             grammarSearchRange = spellingSearchRange->cloneRange(ec);
1684             if (!misspelledWord.isEmpty()) {
1685                 // Stop looking at start of next misspelled word
1686                 CharacterIterator chars(grammarSearchRange.get());
1687                 chars.advance(misspellingOffset);
1688                 grammarSearchRange->setEnd(chars.range()->startContainer(ec), chars.range()->startOffset(ec), ec);
1689             }
1690
1691             if (isGrammarCheckingEnabled())
1692                 badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
1693 #endif
1694         }
1695     }
1696     
1697     if (!badGrammarPhrase.isEmpty()) {
1698         ASSERT(WTF_USE_GRAMMAR_CHECKING);
1699         // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
1700         // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
1701         // panel, and store a marker so we draw the green squiggle later.
1702         
1703         ASSERT(badGrammarPhrase.length() > 0);
1704         ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
1705         
1706         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
1707         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
1708         frame()->selection()->setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
1709         frame()->selection()->revealSelection();
1710         
1711         client()->updateSpellingUIWithGrammarString(badGrammarPhrase, grammarDetail);
1712         frame()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
1713     } else if (!misspelledWord.isEmpty()) {
1714         // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
1715         // a marker so we draw the red squiggle later.
1716         
1717         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
1718         frame()->selection()->setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
1719         frame()->selection()->revealSelection();
1720         
1721         client()->updateSpellingUIWithMisspelledWord(misspelledWord);
1722         frame()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
1723     }
1724 }
1725
1726 bool Editor::isSelectionMisspelled()
1727 {
1728     String selectedString = selectedText();
1729     int length = selectedString.length();
1730     if (!length)
1731         return false;
1732
1733     if (!client())
1734         return false;
1735     
1736     int misspellingLocation = -1;
1737     int misspellingLength = 0;
1738     textChecker()->checkSpellingOfString(selectedString.characters(), length, &misspellingLocation, &misspellingLength);
1739     
1740     // The selection only counts as misspelled if the selected text is exactly one misspelled word
1741     if (misspellingLength != length)
1742         return false;
1743     
1744     // Update the spelling panel to be displaying this error (whether or not the spelling panel is on screen).
1745     // This is necessary to make a subsequent call to [NSSpellChecker ignoreWord:inSpellDocumentWithTag:] work
1746     // correctly; that call behaves differently based on whether the spelling panel is displaying a misspelling
1747     // or a grammar error.
1748     client()->updateSpellingUIWithMisspelledWord(selectedString);
1749     
1750     return true;
1751 }
1752
1753 bool Editor::isSelectionUngrammatical()
1754 {
1755 #if USE(GRAMMAR_CHECKING)
1756     Vector<String> ignoredGuesses;
1757     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1758     if (!range)
1759         return false;
1760     return TextCheckingHelper(client(), range).isUngrammatical(ignoredGuesses);
1761 #else
1762     return false;
1763 #endif
1764 }
1765
1766 Vector<String> Editor::guessesForUngrammaticalSelection()
1767 {
1768 #if USE(GRAMMAR_CHECKING)
1769     Vector<String> guesses;
1770     RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1771     if (!range)
1772         return guesses;
1773     // Ignore the result of isUngrammatical; we just want the guesses, whether or not there are any
1774     TextCheckingHelper(client(), range).isUngrammatical(guesses);
1775     return guesses;
1776 #else
1777     return Vector<String>();
1778 #endif
1779 }
1780
1781 Vector<String> Editor::guessesForMisspelledSelection()
1782 {
1783     String selectedString = selectedText();
1784     ASSERT(selectedString.length());
1785
1786     Vector<String> guesses;
1787     if (client())
1788         textChecker()->getGuessesForWord(selectedString, String(), guesses);
1789     return guesses;
1790 }
1791
1792 Vector<String> Editor::guessesForMisspelledOrUngrammaticalSelection(bool& misspelled, bool& ungrammatical)
1793 {
1794     if (unifiedTextCheckerEnabled()) {
1795         RefPtr<Range> range = frame()->selection()->toNormalizedRange();
1796         if (!range)
1797             return Vector<String>();
1798         return TextCheckingHelper(client(), range).guessesForMisspelledOrUngrammaticalRange(isGrammarCheckingEnabled(), misspelled, ungrammatical);
1799     }
1800
1801     misspelled = isSelectionMisspelled();
1802     if (misspelled) {
1803         ungrammatical = false;
1804         return guessesForMisspelledSelection();
1805     }
1806     if (isGrammarCheckingEnabled() && isSelectionUngrammatical()) {
1807         ungrammatical = true;
1808         return guessesForUngrammaticalSelection();
1809     }
1810     ungrammatical = false;
1811     return Vector<String>();
1812 }
1813
1814 void Editor::showSpellingGuessPanel()
1815 {
1816     if (!client()) {
1817         LOG_ERROR("No NSSpellChecker");
1818         return;
1819     }
1820
1821     if (client()->spellingUIIsShowing()) {
1822         client()->showSpellingUI(false);
1823         return;
1824     }
1825     
1826     advanceToNextMisspelling(true);
1827     client()->showSpellingUI(true);
1828 }
1829
1830 bool Editor::spellingPanelIsShowing()
1831 {
1832     if (!client())
1833         return false;
1834     return client()->spellingUIIsShowing();
1835 }
1836
1837 void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1838 {
1839     RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
1840     if (selectedRange) {
1841         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
1842         frame()->document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Grammar);
1843     }
1844 }
1845
1846 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
1847 {
1848     markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
1849 }
1850
1851 void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping, bool doReplacement)
1852 {
1853 #if !USE(AUTOMATIC_TEXT_REPLACEMENT)
1854     UNUSED_PARAM(doReplacement);
1855 #endif
1856
1857     if (unifiedTextCheckerEnabled()) {
1858         m_spellingCorrector->applyPendingCorrection(selectionAfterTyping);
1859
1860         TextCheckingTypeMask textCheckingOptions = 0;
1861
1862         if (isContinuousSpellCheckingEnabled())
1863             textCheckingOptions |= TextCheckingTypeSpelling;
1864
1865 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1866         if (doReplacement
1867             && (isAutomaticQuoteSubstitutionEnabled()
1868                 || isAutomaticLinkDetectionEnabled()
1869                 || isAutomaticDashSubstitutionEnabled()
1870                 || isAutomaticTextReplacementEnabled()
1871                 || ((textCheckingOptions & TextCheckingTypeSpelling) && isAutomaticSpellingCorrectionEnabled())))
1872             textCheckingOptions |= TextCheckingTypeReplacement;
1873 #endif
1874         if (!(textCheckingOptions & (TextCheckingTypeSpelling | TextCheckingTypeReplacement)))
1875             return;
1876
1877         if (isGrammarCheckingEnabled())
1878             textCheckingOptions |= TextCheckingTypeGrammar;
1879
1880         VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
1881         if (textCheckingOptions & TextCheckingTypeGrammar) {
1882             VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
1883             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
1884         } else
1885             markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
1886         return;
1887     }
1888
1889     if (!isContinuousSpellCheckingEnabled())
1890         return;
1891
1892     // Check spelling of one word
1893     RefPtr<Range> misspellingRange;
1894     markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
1895
1896     // Autocorrect the misspelled word.
1897     if (!misspellingRange)
1898         return;
1899     
1900     // Get the misspelled word.
1901     const String misspelledWord = plainText(misspellingRange.get());
1902     String autocorrectedString = textChecker()->getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
1903
1904     // If autocorrected word is non empty, replace the misspelled word by this word.
1905     if (!autocorrectedString.isEmpty()) {
1906         VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
1907         if (newSelection != frame()->selection()->selection()) {
1908             if (!frame()->selection()->shouldChangeSelection(newSelection))
1909                 return;
1910             frame()->selection()->setSelection(newSelection);
1911         }
1912
1913         if (!frame()->editor()->shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
1914             return;
1915         frame()->editor()->replaceSelectionWithText(autocorrectedString, false, false);
1916
1917         // Reset the charet one character further.
1918         frame()->selection()->moveTo(frame()->selection()->end());
1919         frame()->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
1920     }
1921
1922     if (!isGrammarCheckingEnabled())
1923         return;
1924     
1925     // Check grammar of entire sentence
1926     markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
1927 }
1928     
1929 void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
1930 {
1931     // This function is called with a selection already expanded to word boundaries.
1932     // Might be nice to assert that here.
1933     
1934     // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
1935     // grammar checking can only be on if spell checking is also on.
1936     if (!isContinuousSpellCheckingEnabled())
1937         return;
1938     
1939     RefPtr<Range> searchRange(selection.toNormalizedRange());
1940     if (!searchRange)
1941         return;
1942     
1943     // If we're not in an editable node, bail.
1944     Node* editableNode = searchRange->startContainer();
1945     if (!editableNode || !editableNode->rendererIsEditable())
1946         return;
1947
1948     if (!isSpellCheckingEnabledFor(editableNode))
1949         return;
1950
1951     // Get the spell checker if it is available
1952     if (!client())
1953         return;
1954     
1955     TextCheckingHelper checker(client(), searchRange);
1956     if (checkSpelling)
1957         checker.markAllMisspellings(firstMisspellingRange);
1958     else {
1959         ASSERT(WTF_USE_GRAMMAR_CHECKING);
1960         if (isGrammarCheckingEnabled())
1961             checker.markAllBadGrammar();
1962     }    
1963 }
1964
1965 bool Editor::isSpellCheckingEnabledFor(Node* node) const
1966 {
1967     if (!node)
1968         return false;
1969     const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
1970     if (!focusedElement)
1971         return false;
1972     return focusedElement->isSpellCheckingEnabled();
1973 }
1974
1975 bool Editor::isSpellCheckingEnabledInFocusedNode() const
1976 {
1977     return isSpellCheckingEnabledFor(m_frame->selection()->start().deprecatedNode());
1978 }
1979
1980 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
1981 {
1982     markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
1983 }
1984     
1985 void Editor::markBadGrammar(const VisibleSelection& selection)
1986 {
1987     ASSERT(WTF_USE_GRAMMAR_CHECKING);
1988     RefPtr<Range> firstMisspellingRange;
1989     markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
1990 }
1991
1992 void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
1993 {
1994     ASSERT(unifiedTextCheckerEnabled());
1995
1996     // There shouldn't be pending autocorrection at this moment.
1997     ASSERT(!m_spellingCorrector->hasPendingCorrection());
1998
1999     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2000     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2001
2002     // This function is called with selections already expanded to word boundaries.
2003     if (!client() || !spellingRange || (shouldMarkGrammar && !grammarRange))
2004         return;
2005
2006     // If we're not in an editable node, bail.
2007     Node* editableNode = spellingRange->startContainer();
2008     if (!editableNode || !editableNode->rendererIsEditable())
2009         return;
2010
2011     if (!isSpellCheckingEnabledFor(editableNode))
2012         return;
2013
2014     Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
2015     TextCheckingParagraph paragraphToCheck(rangeToCheck);
2016     if (paragraphToCheck.isRangeEmpty() || paragraphToCheck.isEmpty())
2017         return;
2018     RefPtr<Range> paragraphRange = paragraphToCheck.paragraphRange();
2019
2020     bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled() && !shouldShowCorrectionPanel;
2021
2022     // In asynchronous mode, we intentionally check paragraph-wide sentence.
2023     RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), asynchronous ? paragraphRange : rangeToCheck, paragraphRange);
2024
2025     if (asynchronous) {
2026         m_spellChecker->requestCheckingFor(request);
2027         return;
2028     }
2029
2030     Vector<TextCheckingResult> results;
2031     checkTextOfParagraph(textChecker(), paragraphToCheck.textCharacters(), paragraphToCheck.textLength(),
2032         resolveTextCheckingTypeMask(textCheckingOptions), results);
2033     markAndReplaceFor(request, results);
2034 }
2035
2036 void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
2037 {
2038     ASSERT(request);
2039
2040     TextCheckingTypeMask textCheckingOptions = request->mask();
2041     TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
2042
2043     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
2044     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
2045     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
2046     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
2047     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
2048
2049     // Expand the range to encompass entire paragraphs, since text checking needs that much context.
2050     int selectionOffset = 0;
2051     int ambiguousBoundaryOffset = -1;
2052     bool selectionChanged = false;
2053     bool restoreSelectionAfterChange = false;
2054     bool adjustSelectionForParagraphBoundaries = false;
2055
2056     if (shouldPerformReplacement || shouldMarkSpelling || shouldCheckForCorrection) {
2057         if (m_frame->selection()->selectionType() == VisibleSelection::CaretSelection) {
2058             // Attempt to save the caret position so we can restore it later if needed
2059             Position caretPosition = m_frame->selection()->end();
2060             selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
2061             restoreSelectionAfterChange = true;
2062             if (selectionOffset > 0 && (selectionOffset > paragraph.textLength() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
2063                 adjustSelectionForParagraphBoundaries = true;
2064             if (selectionOffset > 0 && selectionOffset <= paragraph.textLength() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
2065                 ambiguousBoundaryOffset = selectionOffset - 1;
2066         }
2067     }
2068
2069     // If this checking is only for showing correction panel, we shouldn't bother to mark misspellings.
2070     if (shouldShowCorrectionPanel)
2071         shouldMarkSpelling = false;
2072
2073     int offsetDueToReplacement = 0;
2074
2075     for (unsigned i = 0; i < results.size(); i++) {
2076         int spellingRangeEndOffset = paragraph.checkingEnd() + offsetDueToReplacement;
2077         const TextCheckingResult* result = &results[i];
2078         int resultLocation = result->location + offsetDueToReplacement;
2079         int resultLength = result->length;
2080         bool resultEndsAtAmbiguousBoundary = ambiguousBoundaryOffset >= 0 && resultLocation + resultLength == ambiguousBoundaryOffset;
2081
2082         // Only mark misspelling if:
2083         // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
2084         // 2. Result falls within spellingRange.
2085         // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
2086         //    "wouldn'" as misspelled right after apostrophe is typed.
2087         if (shouldMarkSpelling && result->type == TextCheckingTypeSpelling && resultLocation >= paragraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
2088             ASSERT(resultLength > 0 && resultLocation >= 0);
2089             RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
2090             if (!m_spellingCorrector->isSpellingMarkerAllowed(misspellingRange))
2091                 continue;
2092             misspellingRange->startContainer()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
2093         } else if (shouldMarkGrammar && result->type == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
2094             ASSERT(resultLength > 0 && resultLocation >= 0);
2095             for (unsigned j = 0; j < result->details.size(); j++) {
2096                 const GrammarDetail* detail = &result->details[j];
2097                 ASSERT(detail->length > 0 && detail->location >= 0);
2098                 if (paragraph.checkingRangeCovers(resultLocation + detail->location, detail->length)) {
2099                     RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail->location, detail->length);
2100                     badGrammarRange->startContainer()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription);
2101                 }
2102             }
2103         } else if (resultLocation + resultLength <= spellingRangeEndOffset && resultLocation + resultLength >= paragraph.checkingStart()
2104                     && (result->type == TextCheckingTypeLink
2105                     || result->type == TextCheckingTypeQuote
2106                     || result->type == TextCheckingTypeDash
2107                     || result->type == TextCheckingTypeReplacement
2108                     || result->type == TextCheckingTypeCorrection)) {
2109             // In this case the result range just has to touch the spelling range, so we can handle replacing non-word text such as punctuation.
2110             ASSERT(resultLength > 0 && resultLocation >= 0);
2111
2112             if (shouldShowCorrectionPanel && (resultLocation + resultLength < spellingRangeEndOffset || result->type != TextCheckingTypeCorrection))
2113                 continue;
2114
2115             int replacementLength = result->replacement.length();
2116
2117             // Apply replacement if:
2118             // 1. The replacement length is non-zero.
2119             // 2. The result doesn't end at an ambiguous boundary.
2120             //    (FIXME: this is required until 6853027 is fixed and text checking can do this for us
2121             bool doReplacement = replacementLength > 0 && !resultEndsAtAmbiguousBoundary;
2122             RefPtr<Range> rangeToReplace = paragraph.subrange(resultLocation, resultLength);
2123             VisibleSelection selectionToReplace(rangeToReplace.get(), DOWNSTREAM);
2124
2125             // adding links should be done only immediately after they are typed
2126             if (result->type == TextCheckingTypeLink && selectionOffset > resultLocation + resultLength + 1)
2127                 continue;
2128
2129             if (!(shouldPerformReplacement || shouldShowCorrectionPanel) || !doReplacement)
2130                 continue;
2131
2132             String replacedString = plainText(rangeToReplace.get());
2133             bool existingMarkersPermitReplacement = m_spellingCorrector->processMarkersOnTextToBeReplacedByResult(result, rangeToReplace.get(), replacedString);
2134             if (!existingMarkersPermitReplacement)
2135                 continue;
2136
2137             if (shouldShowCorrectionPanel) {
2138 #if !USE(AUTOCORRECTION_PANEL)
2139                 ASSERT_NOT_REACHED();
2140 #endif
2141                 // shouldShowCorrectionPanel can be true only when the panel is available.
2142                 if (resultLocation + resultLength == spellingRangeEndOffset) {
2143                     // We only show the correction panel on the last word.
2144                     m_spellingCorrector->show(rangeToReplace, result->replacement);
2145                     break;
2146                 }
2147                 // If this function is called for showing correction panel, we ignore other correction or replacement.
2148                 continue;
2149             }
2150
2151             if (selectionToReplace != m_frame->selection()->selection()) {
2152                 if (!m_frame->selection()->shouldChangeSelection(selectionToReplace))
2153                     continue;
2154             }
2155
2156             if (result->type == TextCheckingTypeLink) {
2157                 m_frame->selection()->setSelection(selectionToReplace);
2158                 selectionChanged = true;
2159                 restoreSelectionAfterChange = false;
2160                 if (canEditRichly())
2161                     applyCommand(CreateLinkCommand::create(m_frame->document(), result->replacement));
2162             } else if (canEdit() && shouldInsertText(result->replacement, rangeToReplace.get(), EditorInsertActionTyped)) {
2163                 applyCommand(SpellingCorrectionCommand::create(rangeToReplace, result->replacement));
2164
2165                 if (AXObjectCache::accessibilityEnabled()) {
2166                     if (Element* root = m_frame->selection()->selection().rootEditableElement())
2167                         m_frame->document()->axObjectCache()->postNotification(root->renderer(), AXObjectCache::AXAutocorrectionOccured, true);
2168                 }
2169
2170                 selectionChanged = true;
2171                 offsetDueToReplacement += replacementLength - resultLength;
2172                 if (resultLocation < selectionOffset) {
2173                     selectionOffset += replacementLength - resultLength;
2174                     if (ambiguousBoundaryOffset >= 0)
2175                         ambiguousBoundaryOffset = selectionOffset - 1;
2176                 }
2177
2178                 // Add a marker so that corrections can easily be undone and won't be re-corrected.
2179                 if (result->type == TextCheckingTypeCorrection)
2180                     m_spellingCorrector->markCorrection(paragraph.subrange(resultLocation, replacementLength), replacedString);
2181             }
2182         }
2183     }
2184
2185     if (selectionChanged) {
2186         TextCheckingParagraph extendedParagraph(paragraph);
2187         // Restore the caret position if we have made any replacements
2188         extendedParagraph.expandRangeToNextEnd();
2189         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
2190             RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
2191             m_frame->selection()->moveTo(selectionRange->endPosition(), DOWNSTREAM);
2192             if (adjustSelectionForParagraphBoundaries)
2193                 m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2194         } else {
2195             // If this fails for any reason, the fallback is to go one position beyond the last replacement
2196             m_frame->selection()->moveTo(m_frame->selection()->end());
2197             m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
2198         }
2199     }
2200 }
2201
2202 void Editor::changeBackToReplacedString(const String& replacedString)
2203 {
2204     ASSERT(unifiedTextCheckerEnabled());
2205
2206     if (replacedString.isEmpty())
2207         return;
2208
2209     RefPtr<Range> selection = selectedRange();
2210     if (!shouldInsertText(replacedString, selection.get(), EditorInsertActionPasted))
2211         return;
2212     
2213     m_spellingCorrector->recordAutocorrectionResponseReversed(replacedString, selection);
2214     TextCheckingParagraph paragraph(selection);
2215     replaceSelectionWithText(replacedString, false, false);
2216     RefPtr<Range> changedRange = paragraph.subrange(paragraph.checkingStart(), replacedString.length());
2217     changedRange->startContainer()->document()->markers()->addMarker(changedRange.get(), DocumentMarker::Replacement, String());
2218     m_spellingCorrector->markReversed(changedRange.get());
2219 }
2220
2221
2222 void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
2223 {
2224     if (unifiedTextCheckerEnabled()) {
2225         if (!isContinuousSpellCheckingEnabled())
2226             return;
2227         TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling | TextCheckingTypeCorrection;
2228         if (markGrammar && isGrammarCheckingEnabled())
2229             textCheckingOptions |= TextCheckingTypeGrammar;
2230         markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
2231         return;
2232     }
2233
2234     RefPtr<Range> firstMisspellingRange;
2235     markMisspellings(spellingSelection, firstMisspellingRange);
2236     if (markGrammar)
2237         markBadGrammar(grammarSelection);
2238 }
2239
2240 void Editor::unappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction)
2241 {
2242     m_spellingCorrector->respondToUnappliedSpellCorrection(selectionOfCorrected, corrected, correction);
2243 }
2244
2245 void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
2246 {
2247     if (!m_spellingCorrector->shouldRemoveMarkersUponEditing())
2248         return;
2249
2250     // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
2251     // several scenarios:
2252     // 1. Insert in the middle of a word.
2253     // 2. Appending non whitespace at the beginning of word.
2254     // 3. Appending non whitespace at the end of word.
2255     // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
2256     // remove the markers on that word.
2257     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
2258     // selection, and remove words between the selection boundaries.
2259     //
2260     VisiblePosition startOfSelection = frame()->selection()->selection().start();
2261     VisiblePosition endOfSelection = frame()->selection()->selection().end();
2262     if (startOfSelection.isNull())
2263         return;
2264     // First word is the word that ends after or on the start of selection.
2265     VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
2266     VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
2267     // Last word is the word that begins before or on the end of selection
2268     VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
2269     VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
2270
2271     if (startOfFirstWord.isNull()) {
2272         startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
2273         endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
2274     }
2275     
2276     if (endOfLastWord.isNull()) {
2277         startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
2278         endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
2279     }
2280
2281     // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
2282     // we choose next word as the first word.
2283     if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
2284         startOfFirstWord = nextWordPosition(startOfFirstWord);
2285         endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
2286         if (startOfFirstWord == endOfSelection)
2287             return;
2288     }
2289
2290     // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
2291     // we choose previous word as the last word.
2292     if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
2293         startOfLastWord = previousWordPosition(startOfLastWord);
2294         endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
2295         if (endOfLastWord == startOfSelection)
2296             return;
2297     }
2298
2299     if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
2300         return;
2301
2302     // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
2303     // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
2304     // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
2305     // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
2306     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
2307     // of marker that contains the word in question, and remove marker on that whole range.
2308     Document* document = m_frame->document();
2309     RefPtr<Range> wordRange = Range::create(document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
2310
2311     document->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::CorrectionIndicator | DocumentMarker::SpellCheckingExemption, DocumentMarkerController::RemovePartiallyOverlappingMarker);
2312     document->markers()->clearDescriptionOnMarkersIntersectingRange(wordRange.get(), DocumentMarker::Replacement);
2313 }
2314
2315 void Editor::deletedAutocorrectionAtPosition(const Position& position, const String& originalString)
2316 {
2317     m_spellingCorrector->deletedAutocorrectionAtPosition(position, originalString);
2318 }
2319
2320 PassRefPtr<Range> Editor::rangeForPoint(const LayoutPoint& windowPoint)
2321 {
2322     Document* document = m_frame->documentAtPoint(windowPoint);
2323     if (!document)
2324         return 0;
2325     
2326     Frame* frame = document->frame();
2327     ASSERT(frame);
2328     FrameView* frameView = frame->view();
2329     if (!frameView)
2330         return 0;
2331     LayoutPoint framePoint = frameView->windowToContents(windowPoint);
2332     VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
2333     return avoidIntersectionWithNode(selection.toNormalizedRange().get(), m_deleteButtonController->containerElement());
2334 }
2335
2336 void Editor::revealSelectionAfterEditingOperation()
2337 {
2338     if (m_ignoreCompositionSelectionChange)
2339         return;
2340
2341     m_frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded);
2342 }
2343
2344 void Editor::setIgnoreCompositionSelectionChange(bool ignore)
2345 {
2346     if (m_ignoreCompositionSelectionChange == ignore)
2347         return;
2348
2349     m_ignoreCompositionSelectionChange = ignore;
2350     if (!ignore)
2351         revealSelectionAfterEditingOperation();
2352 }
2353
2354 PassRefPtr<Range> Editor::compositionRange() const
2355 {
2356     if (!m_compositionNode)
2357         return 0;
2358     unsigned length = m_compositionNode->length();
2359     unsigned start = min(m_compositionStart, length);
2360     unsigned end = min(max(start, m_compositionEnd), length);
2361     if (start >= end)
2362         return 0;
2363     return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
2364 }
2365
2366 bool Editor::getCompositionSelection(unsigned& selectionStart, unsigned& selectionEnd) const
2367 {
2368     if (!m_compositionNode)
2369         return false;
2370     Position start = m_frame->selection()->start();
2371     if (start.deprecatedNode() != m_compositionNode)
2372         return false;
2373     Position end = m_frame->selection()->end();
2374     if (end.deprecatedNode() != m_compositionNode)
2375         return false;
2376
2377     if (static_cast<unsigned>(start.deprecatedEditingOffset()) < m_compositionStart)
2378         return false;
2379     if (static_cast<unsigned>(end.deprecatedEditingOffset()) > m_compositionEnd)
2380         return false;
2381
2382     selectionStart = start.deprecatedEditingOffset() - m_compositionStart;
2383     selectionEnd = start.deprecatedEditingOffset() - m_compositionEnd;
2384     return true;
2385 }
2386
2387 void Editor::transpose()
2388 {
2389     if (!canEdit())
2390         return;
2391
2392      VisibleSelection selection = m_frame->selection()->selection();
2393      if (!selection.isCaret())
2394          return;
2395
2396     // Make a selection that goes back one character and forward two characters.
2397     VisiblePosition caret = selection.visibleStart();
2398     VisiblePosition next = isEndOfParagraph(caret) ? caret : caret.next();
2399     VisiblePosition previous = next.previous();
2400     if (next == previous)
2401         return;
2402     previous = previous.previous();
2403     if (!inSameParagraph(next, previous))
2404         return;
2405     RefPtr<Range> range = makeRange(previous, next);
2406     if (!range)
2407         return;
2408     VisibleSelection newSelection(range.get(), DOWNSTREAM);
2409
2410     // Transpose the two characters.
2411     String text = plainText(range.get());
2412     if (text.length() != 2)
2413         return;
2414     String transposed = text.right(1) + text.left(1);
2415
2416     // Select the two characters.
2417     if (newSelection != m_frame->selection()->selection()) {
2418         if (!m_frame->selection()->shouldChangeSelection(newSelection))
2419             return;
2420         m_frame->selection()->setSelection(newSelection);
2421     }
2422
2423     // Insert the transposed characters.
2424     if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
2425         return;
2426     replaceSelectionWithText(transposed, false, false);
2427 }
2428
2429 void Editor::addToKillRing(Range* range, bool prepend)
2430 {
2431     if (m_shouldStartNewKillRingSequence)
2432         killRing()->startNewSequence();
2433
2434     String text = plainText(range);
2435     if (prepend)
2436         killRing()->prepend(text);
2437     else
2438         killRing()->append(text);
2439     m_shouldStartNewKillRingSequence = false;
2440 }
2441
2442 void Editor::startCorrectionPanelTimer()
2443 {
2444     m_spellingCorrector->startCorrectionPanelTimer(CorrectionPanelInfo::PanelTypeCorrection);
2445 }
2446
2447 void Editor::handleCorrectionPanelResult(const String& correction)
2448 {
2449     m_spellingCorrector->handleCorrectionPanelResult(correction);
2450 }
2451
2452
2453 void Editor::dismissCorrectionPanelAsIgnored()
2454 {
2455     m_spellingCorrector->dismiss(ReasonForDismissingCorrectionPanelIgnored);
2456 }
2457
2458 bool Editor::insideVisibleArea(const LayoutPoint& point) const
2459 {
2460     if (m_frame->excludeFromTextSearch())
2461         return false;
2462     
2463     // Right now, we only check the visibility of a point for disconnected frames. For all other
2464     // frames, we assume visibility.
2465     Frame* frame = m_frame->isDisconnected() ? m_frame : m_frame->tree()->top(true);
2466     if (!frame->isDisconnected())
2467         return true;
2468     
2469     RenderPart* renderer = frame->ownerRenderer();
2470     if (!renderer)
2471         return false;
2472
2473     RenderBlock* container = renderer->containingBlock();
2474     if (!(container->style()->overflowX() == OHIDDEN || container->style()->overflowY() == OHIDDEN))
2475         return true;
2476
2477     LayoutRect rectInPageCoords = container->overflowClipRect(IntPoint(), 0); // FIXME: Incorrect for CSS regions.
2478     LayoutRect rectInFrameCoords = LayoutRect(renderer->x() * -1, renderer->y() * -1,
2479                                               rectInPageCoords.width(), rectInPageCoords.height());
2480
2481     return rectInFrameCoords.contains(point);
2482 }
2483
2484 bool Editor::insideVisibleArea(Range* range) const
2485 {
2486     if (!range)
2487         return true;
2488
2489     if (m_frame->excludeFromTextSearch())
2490         return false;
2491     
2492     // Right now, we only check the visibility of a range for disconnected frames. For all other
2493     // frames, we assume visibility.
2494     Frame* frame = m_frame->isDisconnected() ? m_frame : m_frame->tree()->top(true);
2495     if (!frame->isDisconnected())
2496         return true;
2497     
2498     RenderPart* renderer = frame->ownerRenderer();
2499     if (!renderer)
2500         return false;
2501
2502     RenderBlock* container = renderer->containingBlock();
2503     if (!(container->style()->overflowX() == OHIDDEN || container->style()->overflowY() == OHIDDEN))
2504         return true;
2505
2506     LayoutRect rectInPageCoords = container->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
2507     LayoutRect rectInFrameCoords = LayoutRect(renderer->x() * -1, renderer->y() * -1,
2508                                     rectInPageCoords.width(), rectInPageCoords.height());
2509     LayoutRect resultRect = range->boundingBox();
2510     
2511     return rectInFrameCoords.contains(resultRect);
2512 }
2513
2514 PassRefPtr<Range> Editor::firstVisibleRange(const String& target, FindOptions options)
2515 {
2516     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2517     RefPtr<Range> resultRange = findPlainText(searchRange.get(), target, options & ~Backwards);
2518     ExceptionCode ec = 0;
2519
2520     while (!insideVisibleArea(resultRange.get())) {
2521         searchRange->setStartAfter(resultRange->endContainer(), ec);
2522         if (searchRange->startContainer() == searchRange->endContainer())
2523             return Range::create(m_frame->document());
2524         resultRange = findPlainText(searchRange.get(), target, options & ~Backwards);
2525     }
2526     
2527     return resultRange;
2528 }
2529
2530 PassRefPtr<Range> Editor::lastVisibleRange(const String& target, FindOptions options)
2531 {
2532     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2533     RefPtr<Range> resultRange = findPlainText(searchRange.get(), target, options | Backwards);
2534     ExceptionCode ec = 0;
2535
2536     while (!insideVisibleArea(resultRange.get())) {
2537         searchRange->setEndBefore(resultRange->startContainer(), ec);
2538         if (searchRange->startContainer() == searchRange->endContainer())
2539             return Range::create(m_frame->document());
2540         resultRange = findPlainText(searchRange.get(), target, options | Backwards);
2541     }
2542     
2543     return resultRange;
2544 }
2545
2546 PassRefPtr<Range> Editor::nextVisibleRange(Range* currentRange, const String& target, FindOptions options)
2547 {
2548     if (m_frame->excludeFromTextSearch())
2549         return Range::create(m_frame->document());
2550
2551     RefPtr<Range> resultRange = currentRange;
2552     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2553     ExceptionCode ec = 0;
2554     bool forward = !(options & Backwards);
2555     for ( ; !insideVisibleArea(resultRange.get()); resultRange = findPlainText(searchRange.get(), target, options)) {
2556         if (resultRange->collapsed(ec)) {
2557             if (!resultRange->startContainer()->isInShadowTree())
2558                 break;
2559             searchRange = rangeOfContents(m_frame->document());
2560             if (forward)
2561                 searchRange->setStartAfter(resultRange->startContainer()->shadowAncestorNode(), ec);
2562             else
2563                 searchRange->setEndBefore(resultRange->startContainer()->shadowAncestorNode(), ec);
2564             continue;
2565         }
2566
2567         if (forward)
2568             searchRange->setStartAfter(resultRange->endContainer(), ec);
2569         else
2570             searchRange->setEndBefore(resultRange->startContainer(), ec);
2571
2572         Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
2573         if (searchRange->collapsed(ec) && shadowTreeRoot) {
2574             if (forward)
2575                 searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec);
2576             else
2577                 searchRange->setStartBefore(shadowTreeRoot, ec);
2578         }
2579         
2580         if (searchRange->startContainer()->isDocumentNode() && searchRange->endContainer()->isDocumentNode())
2581             break;
2582     }
2583     
2584     if (insideVisibleArea(resultRange.get()))
2585         return resultRange;
2586     
2587     if (!(options & WrapAround))
2588         return Range::create(m_frame->document());
2589
2590     if (options & Backwards)
2591         return lastVisibleRange(target, options);
2592
2593     return firstVisibleRange(target, options);
2594 }
2595
2596 void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection, bool closeTyping, bool clearTypingStyle)
2597 {
2598     // If the new selection is orphaned, then don't update the selection.
2599     if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
2600         return;
2601
2602     // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
2603     // because there is work that it must do in this situation.
2604     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
2605     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
2606     bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection()->selection();
2607     if (selectionDidNotChangeDOMPosition || m_frame->selection()->shouldChangeSelection(newSelection)) {
2608         FrameSelection::SetSelectionOptions options = 0;
2609         if (closeTyping)
2610             options |= FrameSelection::CloseTyping;
2611         if (clearTypingStyle)
2612             options |= FrameSelection::ClearTypingStyle;
2613         m_frame->selection()->setSelection(newSelection, options);
2614     }
2615
2616     // Some editing operations change the selection visually without affecting its position within the DOM.
2617     // For example when you press return in the following (the caret is marked by ^):
2618     // <div contentEditable="true"><div>^Hello</div></div>
2619     // WebCore inserts <div><br></div> *before* the current block, which correctly moves the paragraph down but which doesn't
2620     // change the caret's DOM position (["hello", 0]). In these situations the above FrameSelection::setSelection call
2621     // does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
2622     // starts a new kill ring sequence, but we want to do these things (matches AppKit).
2623     if (selectionDidNotChangeDOMPosition)
2624         client()->respondToChangedSelection(m_frame);
2625 }
2626
2627 String Editor::selectedText() const
2628 {
2629     // We remove '\0' characters because they are not visibly rendered to the user.
2630     return plainText(m_frame->selection()->toNormalizedRange().get()).replace(0, "");
2631 }
2632
2633 IntRect Editor::firstRectForRange(Range* range) const
2634 {
2635     int extraWidthToEndOfLine = 0;
2636     ASSERT(range->startContainer());
2637     ASSERT(range->endContainer());
2638
2639     LayoutRect startCaretRect = RenderedPosition(VisiblePosition(range->startPosition()).deepEquivalent(), DOWNSTREAM).absoluteRect(extraWidthToEndOfLine);
2640     if (startCaretRect == LayoutRect())
2641         return IntRect();
2642
2643     LayoutRect endCaretRect = RenderedPosition(VisiblePosition(range->endPosition()).deepEquivalent(), UPSTREAM).absoluteRect();
2644     if (endCaretRect == LayoutRect())
2645         return IntRect();
2646
2647     if (startCaretRect.y() == endCaretRect.y()) {
2648         // start and end are on the same line
2649         return IntRect(min(startCaretRect.x(), endCaretRect.x()),
2650             startCaretRect.y(),
2651             abs(endCaretRect.x() - startCaretRect.x()),
2652             max(startCaretRect.height(), endCaretRect.height()));
2653     }
2654
2655     // start and end aren't on the same line, so go from start to the end of its line
2656     return IntRect(startCaretRect.x(),
2657         startCaretRect.y(),
2658         startCaretRect.width() + extraWidthToEndOfLine,
2659         startCaretRect.height());
2660 }
2661
2662 bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
2663 {
2664     return client() && client()->shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
2665 }
2666
2667 void Editor::computeAndSetTypingStyle(CSSStyleDeclaration* style, EditAction editingAction)
2668 {
2669     if (!style || !style->length()) {
2670         m_frame->selection()->clearTypingStyle();
2671         return;
2672     }
2673
2674     // Calculate the current typing style.
2675     RefPtr<EditingStyle> typingStyle;
2676     if (m_frame->selection()->typingStyle()) {
2677         typingStyle = m_frame->selection()->typingStyle()->copy();
2678         typingStyle->overrideWithStyle(style->makeMutable().get());
2679     } else
2680         typingStyle = EditingStyle::create(style);
2681
2682     typingStyle->prepareToApplyAt(m_frame->selection()->selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
2683
2684     // Handle block styles, substracting these from the typing style.
2685     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
2686     if (!blockStyle->isEmpty())
2687         applyCommand(ApplyStyleCommand::create(m_frame->document(), blockStyle.get(), editingAction));
2688
2689     // Set the remaining style as the typing style.
2690     m_frame->selection()->setTypingStyle(typingStyle);
2691 }
2692
2693 void Editor::textFieldDidBeginEditing(Element* e)
2694 {
2695     if (client())
2696         client()->textFieldDidBeginEditing(e);
2697 }
2698
2699 void Editor::textFieldDidEndEditing(Element* e)
2700 {
2701     dismissCorrectionPanelAsIgnored();
2702     if (client())
2703         client()->textFieldDidEndEditing(e);
2704 }
2705
2706 void Editor::textDidChangeInTextField(Element* e)
2707 {
2708     if (client())
2709         client()->textDidChangeInTextField(e);
2710 }
2711
2712 bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
2713 {
2714     if (client())
2715         return client()->doTextFieldCommandFromEvent(e, ke);
2716
2717     return false;
2718 }
2719
2720 void Editor::textWillBeDeletedInTextField(Element* input)
2721 {
2722     if (client())
2723         client()->textWillBeDeletedInTextField(input);
2724 }
2725
2726 void Editor::textDidChangeInTextArea(Element* e)
2727 {
2728     if (client())
2729         client()->textDidChangeInTextArea(e);
2730 }
2731
2732 void Editor::applyEditingStyleToBodyElement() const
2733 {
2734     RefPtr<NodeList> list = m_frame->document()->getElementsByTagName("body");
2735     unsigned len = list->length();
2736     for (unsigned i = 0; i < len; i++)
2737         applyEditingStyleToElement(static_cast<Element*>(list->item(i)));
2738 }
2739
2740 void Editor::applyEditingStyleToElement(Element* element) const
2741 {
2742     if (!element)
2743         return;
2744
2745     CSSStyleDeclaration* style = element->style();
2746     ASSERT(style);
2747     if (!style)
2748         return;
2749
2750     ExceptionCode ec = 0;
2751     style->setProperty(CSSPropertyWordWrap, "break-word", false, ec);
2752     ASSERT(!ec);
2753     style->setProperty(CSSPropertyWebkitNbspMode, "space", false, ec);
2754     ASSERT(!ec);
2755     style->setProperty(CSSPropertyWebkitLineBreak, "after-white-space", false, ec);
2756     ASSERT(!ec);
2757 }
2758
2759 // Searches from the beginning of the document if nothing is selected.
2760 bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
2761 {
2762     FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0);
2763     return findString(target, options);
2764 }
2765
2766 bool Editor::findString(const String& target, FindOptions options)
2767 {
2768     VisibleSelection selection = m_frame->selection()->selection();
2769
2770     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
2771
2772     if (!resultRange)
2773         return false;
2774
2775     m_frame->selection()->setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
2776     m_frame->selection()->revealSelection();
2777     return true;
2778 }
2779
2780 PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
2781 {
2782     if (target.isEmpty())
2783         return 0;
2784
2785     if (m_frame->excludeFromTextSearch())
2786         return 0;
2787
2788     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
2789     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
2790     RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
2791
2792     bool forward = !(options & Backwards);
2793     bool startInReferenceRange = referenceRange && (options & StartInSelection);
2794     if (referenceRange) {
2795         if (forward)
2796             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
2797         else
2798             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
2799     }
2800
2801     RefPtr<Node> shadowTreeRoot = referenceRange && referenceRange->startContainer() ? referenceRange->startContainer()->nonBoundaryShadowTreeRootNode() : 0;
2802     if (shadowTreeRoot) {
2803         if (forward)
2804             searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2805         else
2806             searchRange->setStart(shadowTreeRoot.get(), 0);
2807     }
2808
2809     RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options));
2810     // If we started in the reference range and the found range exactly matches the reference range, find again.
2811     // Build a selection with the found range to remove collapsed whitespace.
2812     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
2813     if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
2814         searchRange = rangeOfContents(m_frame->document());
2815         if (forward)
2816             searchRange->setStart(referenceRange->endPosition());
2817         else
2818             searchRange->setEnd(referenceRange->startPosition());
2819
2820         if (shadowTreeRoot) {
2821             if (forward)
2822                 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2823             else
2824                 searchRange->setStart(shadowTreeRoot.get(), 0);
2825         }
2826
2827         resultRange = findPlainText(searchRange.get(), target, options);
2828     }
2829
2830     // If nothing was found in the shadow tree, search in main content following the shadow tree.
2831     if (resultRange->collapsed() && shadowTreeRoot) {
2832         searchRange = rangeOfContents(m_frame->document());
2833         if (forward)
2834             searchRange->setStartAfter(shadowTreeRoot->shadowAncestorNode());
2835         else
2836             searchRange->setEndBefore(shadowTreeRoot->shadowAncestorNode());
2837
2838         resultRange = findPlainText(searchRange.get(), target, options);
2839     }
2840
2841     if (!insideVisibleArea(resultRange.get())) {
2842         resultRange = nextVisibleRange(resultRange.get(), target, options);
2843         if (!resultRange)
2844             return 0;
2845     }
2846
2847     // If we didn't find anything and we're wrapping, search again in the entire document (this will
2848     // redundantly re-search the area already searched in some cases).
2849     if (resultRange->collapsed() && options & WrapAround) {
2850         searchRange = rangeOfContents(m_frame->document());
2851         resultRange = findPlainText(searchRange.get(), target, options);
2852         // We used to return false here if we ended up with the same range that we started with
2853         // (e.g., the reference range was already the only instance of this text). But we decided that
2854         // this should be a success case instead, so we'll just fall through in that case.
2855     }
2856
2857     return resultRange->collapsed() ? 0 : resultRange.release();
2858 }
2859
2860 static bool isFrameInRange(Frame* frame, Range* range)
2861 {
2862     bool inRange = false;
2863     for (HTMLFrameOwnerElement* ownerElement = frame->ownerElement(); ownerElement; ownerElement = ownerElement->document()->ownerElement()) {
2864         if (ownerElement->document() == range->ownerDocument()) {
2865             ExceptionCode ec = 0;
2866             inRange = range->intersectsNode(ownerElement, ec);
2867             break;
2868         }
2869     }
2870     return inRange;
2871 }
2872
2873 unsigned Editor::countMatchesForText(const String& target, FindOptions options, unsigned limit, bool markMatches)
2874 {
2875     return countMatchesForText(target, 0, options, limit, markMatches);
2876 }
2877
2878 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches)
2879 {
2880     if (target.isEmpty())
2881         return 0;
2882
2883     RefPtr<Range> searchRange;
2884     if (range) {
2885         if (range->ownerDocument() == m_frame->document())
2886             searchRange = range;
2887         else if (!isFrameInRange(m_frame, range))
2888             return 0;
2889     }
2890     if (!searchRange)
2891         searchRange = rangeOfContents(m_frame->document());
2892
2893     Node* originalEndContainer = searchRange->endContainer();
2894     int originalEndOffset = searchRange->endOffset();
2895
2896     ExceptionCode exception = 0;
2897     unsigned matchCount = 0;
2898     do {
2899         RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options & ~Backwards));
2900         if (resultRange->collapsed(exception)) {
2901             if (!resultRange->startContainer()->isInShadowTree())
2902                 break;
2903
2904             searchRange->setStartAfter(resultRange->startContainer()->shadowAncestorNode(), exception);
2905             searchRange->setEnd(originalEndContainer, originalEndOffset, exception);
2906             continue;
2907         }
2908
2909         // Only treat the result as a match if it is visible
2910         if (insideVisibleArea(resultRange.get())) {
2911             ++matchCount;
2912             if (markMatches)
2913                 m_frame->document()->markers()->addMarker(resultRange.get(), DocumentMarker::TextMatch);
2914         }
2915
2916         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
2917         if (limit > 0 && matchCount >= limit)
2918             break;
2919
2920         // Set the new start for the search range to be the end of the previous
2921         // result range. There is no need to use a VisiblePosition here,
2922         // since findPlainText will use a TextIterator to go over the visible
2923         // text nodes. 
2924         searchRange->setStart(resultRange->endContainer(exception), resultRange->endOffset(exception), exception);
2925
2926         Node* shadowTreeRoot = searchRange->shadowTreeRootNode();
2927         if (searchRange->collapsed(exception) && shadowTreeRoot)
2928             searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), exception);
2929     } while (true);
2930
2931     if (markMatches) {
2932         // Do a "fake" paint in order to execute the code that computes the rendered rect for each text match.
2933         if (m_frame->view() && m_frame->contentRenderer()) {
2934             m_frame->document()->updateLayout(); // Ensure layout is up to date.
2935             LayoutRect visibleRect = m_frame->view()->visibleContentRect();
2936             if (!visibleRect.isEmpty()) {
2937                 GraphicsContext context((PlatformGraphicsContext*)0);
2938                 context.setPaintingDisabled(true);
2939
2940                 PaintBehavior oldBehavior = m_frame->view()->paintBehavior();
2941                 m_frame->view()->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
2942                 m_frame->view()->paintContents(&context, visibleRect);
2943                 m_frame->view()->setPaintBehavior(oldBehavior);
2944             }
2945         }
2946     }
2947
2948     return matchCount;
2949 }
2950
2951 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
2952 {
2953     if (flag == m_areMarkedTextMatchesHighlighted)
2954         return;
2955
2956     m_areMarkedTextMatchesHighlighted = flag;
2957     m_frame->document()->markers()->repaintMarkers(DocumentMarker::TextMatch);
2958 }
2959
2960 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
2961 {
2962     m_spellingCorrector->stopPendingCorrection(oldSelection);
2963
2964     bool closeTyping = options & FrameSelection::CloseTyping;
2965     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
2966     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
2967     if (isContinuousSpellCheckingEnabled) {
2968         VisibleSelection newAdjacentWords;
2969         VisibleSelection newSelectedSentence;
2970         bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
2971         if (m_frame->selection()->selection().isContentEditable() || caretBrowsing) {
2972             VisiblePosition newStart(m_frame->selection()->selection().visibleStart());
2973             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
2974             if (isContinuousGrammarCheckingEnabled)
2975                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
2976         }
2977
2978         // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
2979         bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
2980
2981         // When typing we check spelling elsewhere, so don't redo it here.
2982         // If this is a change in selection resulting from a delete operation,
2983         // oldSelection may no longer be in the document.
2984         if (shouldCheckSpellingAndGrammar && closeTyping && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
2985             VisiblePosition oldStart(oldSelection.visibleStart());
2986             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
2987             if (oldAdjacentWords != newAdjacentWords) {
2988                 if (isContinuousGrammarCheckingEnabled) {
2989                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
2990                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
2991                 } else
2992                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
2993             }
2994         }
2995
2996 #if !PLATFORM(MAC) || (PLATFORM(MAC) && (defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_SNOW_LEOPARD)))
2997         // This only erases markers that are in the first unit (word or sentence) of the selection.
2998         // Perhaps peculiar, but it matches AppKit on these Mac OS X versions.
2999         if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3000             m_frame->document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3001 #endif
3002         if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3003             m_frame->document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3004     }
3005
3006     // When continuous spell checking is off, existing markers disappear after the selection changes.
3007     if (!isContinuousSpellCheckingEnabled)
3008         m_frame->document()->markers()->removeMarkers(DocumentMarker::Spelling);
3009     if (!isContinuousGrammarCheckingEnabled)
3010         m_frame->document()->markers()->removeMarkers(DocumentMarker::Grammar);
3011
3012     respondToChangedSelection(oldSelection);
3013 }
3014
3015 static Node* findFirstMarkable(Node* node)
3016 {
3017     while (node) {
3018         if (!node->renderer())
3019             return 0;
3020         if (node->renderer()->isText())
3021             return node;
3022         if (node->renderer()->isTextControl())
3023             node = toRenderTextControl(node->renderer())->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3024         else if (node->firstChild())
3025             node = node->firstChild();
3026         else
3027             node = node->nextSibling();
3028     }
3029
3030     return 0;
3031 }
3032
3033 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3034 {
3035     Node* node = findFirstMarkable(m_frame->selection()->start().deprecatedNode());
3036     if (!node)
3037         return false;
3038
3039     unsigned int startOffset = static_cast<unsigned int>(from);
3040     unsigned int endOffset = static_cast<unsigned int>(from + length);
3041     Vector<DocumentMarker*> markers = m_frame->document()->markers()->markersFor(node);
3042     for (size_t i = 0; i < markers.size(); ++i) {
3043         DocumentMarker* marker = markers[i];
3044         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3045             return true;
3046     }
3047
3048     return false;
3049 }       
3050
3051 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
3052 {
3053     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3054     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3055     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3056     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3057
3058     TextCheckingTypeMask checkingTypes = 0;
3059     if (shouldMarkSpelling)
3060         checkingTypes |= TextCheckingTypeSpelling;
3061     if (shouldMarkGrammar)
3062         checkingTypes |= TextCheckingTypeGrammar;
3063     if (shouldCheckForCorrection)
3064         checkingTypes |= TextCheckingTypeCorrection;
3065
3066 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3067     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3068     if (shouldPerformReplacement) {
3069         if (isAutomaticLinkDetectionEnabled())
3070             checkingTypes |= TextCheckingTypeLink;
3071         if (isAutomaticQuoteSubstitutionEnabled())
3072             checkingTypes |= TextCheckingTypeQuote;
3073         if (isAutomaticDashSubstitutionEnabled())
3074             checkingTypes |= TextCheckingTypeDash;
3075         if (isAutomaticTextReplacementEnabled())
3076             checkingTypes |= TextCheckingTypeReplacement;
3077         if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3078             checkingTypes |= TextCheckingTypeCorrection;
3079     }
3080 #endif
3081
3082     return checkingTypes;
3083 }
3084
3085 void Editor::deviceScaleFactorChanged()
3086 {
3087     m_deleteButtonController->deviceScaleFactorChanged();
3088 }
3089
3090 bool Editor::unifiedTextCheckerEnabled() const
3091 {
3092     return WebCore::unifiedTextCheckerEnabled(m_frame);
3093 }
3094
3095 } // namespace WebCore