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