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