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