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