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