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