c713b1be3a59b2a1951c36735abb1e28d1228c16
[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 "StyleProperties.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 HTMLNames;
101 using namespace WTF;
102 using namespace Unicode;
103
104 #if ENABLE(DELETION_UI)
105
106 PassRefPtr<Range> Editor::avoidIntersectionWithDeleteButtonController(const Range* range) const
107 {
108     if (!range)
109         return 0;
110
111     Node* startContainer = range->startContainer();
112     int startOffset = range->startOffset();
113     Node* endContainer = range->endContainer();
114     int endOffset = range->endOffset();
115
116     if (!startContainer)
117         return 0;
118
119     ASSERT(endContainer);
120
121     Element* element = m_deleteButtonController->containerElement();
122     if (startContainer == element || startContainer->isDescendantOf(element)) {
123         ASSERT(element->parentNode());
124         startContainer = element->parentNode();
125         startOffset = element->nodeIndex();
126     }
127     if (endContainer == element || endContainer->isDescendantOf(element)) {
128         ASSERT(element->parentNode());
129         endContainer = element->parentNode();
130         endOffset = element->nodeIndex();
131     }
132
133     return Range::create(range->ownerDocument(), startContainer, startOffset, endContainer, endOffset);
134 }
135
136 VisibleSelection Editor::avoidIntersectionWithDeleteButtonController(const VisibleSelection& selection) const
137 {
138     if (selection.isNone())
139         return selection;
140
141     Element* element = m_deleteButtonController->containerElement();
142     if (!element)
143         return selection;
144     VisibleSelection updatedSelection = selection;
145
146     Position updatedBase = selection.base();
147     updatePositionForNodeRemoval(updatedBase, element);
148     if (updatedBase != selection.base())
149         updatedSelection.setBase(updatedBase);
150
151     Position updatedExtent = selection.extent();
152     updatePositionForNodeRemoval(updatedExtent, element);
153     if (updatedExtent != selection.extent())
154         updatedSelection.setExtent(updatedExtent);
155
156     return updatedSelection;
157 }
158
159 #endif
160
161 // When an event handler has moved the selection outside of a text control
162 // we should use the target control's selection for this editing operation.
163 VisibleSelection Editor::selectionForCommand(Event* event)
164 {
165     VisibleSelection selection = m_frame.selection().selection();
166     if (!event)
167         return selection;
168     // If the target is a text control, and the current selection is outside of its shadow tree,
169     // then use the saved selection for that text control.
170     HTMLTextFormControlElement* textFormControlOfSelectionStart = enclosingTextFormControl(selection.start());
171     HTMLTextFormControlElement* textFromControlOfTarget = isHTMLTextFormControlElement(*event->target()->toNode()) ? toHTMLTextFormControlElement(event->target()->toNode()) : nullptr;
172     if (textFromControlOfTarget && (selection.start().isNull() || textFromControlOfTarget != textFormControlOfSelectionStart)) {
173         if (RefPtr<Range> range = textFromControlOfTarget->selection())
174             return VisibleSelection(range.get(), DOWNSTREAM, selection.isDirectional());
175     }
176     return selection;
177 }
178
179 // Function considers Mac editing behavior a fallback when Page or Settings is not available.
180 EditingBehavior Editor::behavior() const
181 {
182     return EditingBehavior(m_frame.settings().editingBehaviorType());
183 }
184
185 EditorClient* Editor::client() const
186 {
187     if (Page* page = m_frame.page())
188         return page->editorClient();
189     return 0;
190 }
191
192
193 TextCheckerClient* Editor::textChecker() const
194 {
195     if (EditorClient* owner = client())
196         return owner->textChecker();
197     return 0;
198 }
199
200 void Editor::handleKeyboardEvent(KeyboardEvent* event)
201 {
202     if (EditorClient* c = client())
203         c->handleKeyboardEvent(event);
204 }
205
206 void Editor::handleInputMethodKeydown(KeyboardEvent* event)
207 {
208     if (EditorClient* c = client())
209         c->handleInputMethodKeydown(event);
210 }
211
212 bool Editor::handleTextEvent(TextEvent* event)
213 {
214     // Default event handling for Drag and Drop will be handled by DragController
215     // so we leave the event for it.
216     if (event->isDrop())
217         return false;
218
219     if (event->isPaste()) {
220         if (event->pastingFragment())
221             replaceSelectionWithFragment(event->pastingFragment(), false, event->shouldSmartReplace(), event->shouldMatchStyle());
222         else 
223             replaceSelectionWithText(event->data(), false, event->shouldSmartReplace());
224         return true;
225     }
226
227     String data = event->data();
228     if (data == "\n") {
229         if (event->isLineBreak())
230             return insertLineBreak();
231         return insertParagraphSeparator();
232     }
233
234     return insertTextWithoutSendingTextEvent(data, false, event);
235 }
236
237 bool Editor::canEdit() const
238 {
239     return m_frame.selection().rootEditableElement();
240 }
241
242 bool Editor::canEditRichly() const
243 {
244     return m_frame.selection().isContentRichlyEditable();
245 }
246
247 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
248 // also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
249 // We need to use onbeforecopy as a real menu enabler because we allow elements that are not
250 // normally selectable to implement copy/paste (like divs, or a document body).
251
252 bool Editor::canDHTMLCut()
253 {
254     return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
255 }
256
257 bool Editor::canDHTMLCopy()
258 {
259     return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
260 }
261
262 bool Editor::canDHTMLPaste()
263 {
264     return !dispatchCPPEvent(eventNames().beforepasteEvent, ClipboardNumb);
265 }
266
267 bool Editor::canCut() const
268 {
269     return canCopy() && canDelete();
270 }
271
272 static HTMLImageElement* imageElementFromImageDocument(Document& document)
273 {
274     if (!document.isImageDocument())
275         return 0;
276     
277     HTMLElement* body = document.body();
278     if (!body)
279         return 0;
280     
281     Node* node = body->firstChild();
282     if (!node)
283         return 0;
284     if (!isHTMLImageElement(node))
285         return 0;
286     return toHTMLImageElement(node);
287 }
288
289 bool Editor::canCopy() const
290 {
291     if (imageElementFromImageDocument(document()))
292         return true;
293     FrameSelection& selection = m_frame.selection();
294     return selection.isRange() && !selection.isInPasswordField();
295 }
296
297 bool Editor::canPaste() const
298 {
299     return canEdit();
300 }
301
302 bool Editor::canDelete() const
303 {
304     FrameSelection& selection = m_frame.selection();
305     return selection.isRange() && selection.rootEditableElement();
306 }
307
308 bool Editor::canDeleteRange(Range* range) const
309 {
310     Node* startContainer = range->startContainer();
311     Node* endContainer = range->endContainer();
312     if (!startContainer || !endContainer)
313         return false;
314     
315     if (!startContainer->hasEditableStyle() || !endContainer->hasEditableStyle())
316         return false;
317
318     if (range->collapsed(IGNORE_EXCEPTION)) {
319         VisiblePosition start(range->startPosition(), DOWNSTREAM);
320         VisiblePosition previous = start.previous();
321         // FIXME: We sometimes allow deletions at the start of editable roots, like when the caret is in an empty list item.
322         if (previous.isNull() || previous.deepEquivalent().deprecatedNode()->rootEditableElement() != startContainer->rootEditableElement())
323             return false;
324     }
325     return true;
326 }
327
328 bool Editor::smartInsertDeleteEnabled()
329 {   
330     return client() && client()->smartInsertDeleteEnabled();
331 }
332     
333 bool Editor::canSmartCopyOrDelete()
334 {
335     return client() && client()->smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
336 }
337
338 bool Editor::isSelectTrailingWhitespaceEnabled()
339 {
340     return client() && client()->isSelectTrailingWhitespaceEnabled();
341 }
342
343 bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
344 {
345     if (!canEdit())
346         return false;
347
348     if (m_frame.selection().isRange()) {
349         if (isTypingAction) {
350             TypingCommand::deleteKeyPressed(document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
351             revealSelectionAfterEditingOperation();
352         } else {
353             if (killRing)
354                 addToKillRing(selectedRange().get(), false);
355             deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
356             // Implicitly calls revealSelectionAfterEditingOperation().
357         }
358     } else {
359         TypingCommand::Options options = 0;
360         if (canSmartCopyOrDelete())
361             options |= TypingCommand::SmartDelete;
362         if (killRing)
363             options |= TypingCommand::KillRing;
364         switch (direction) {
365         case DirectionForward:
366         case DirectionRight:
367             TypingCommand::forwardDeleteKeyPressed(document(), options, granularity);
368             break;
369         case DirectionBackward:
370         case DirectionLeft:
371             TypingCommand::deleteKeyPressed(document(), options, granularity);
372             break;
373         }
374         revealSelectionAfterEditingOperation();
375     }
376
377     // FIXME: We should to move this down into deleteKeyPressed.
378     // clear the "start new kill ring sequence" setting, because it was set to true
379     // when the selection was updated by deleting the range
380     if (killRing)
381         setStartNewKillRingSequence(false);
382
383     return true;
384 }
385
386 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
387 {
388     if (m_frame.selection().isNone())
389         return;
390
391     applyCommand(DeleteSelectionCommand::create(document(), smartDelete));
392 }
393
394 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
395 {
396     Node* target = findEventTargetFromSelection();
397     if (!target)
398         return;
399     target->dispatchEvent(TextEvent::createForPlainTextPaste(document().domWindow(), pastingText, smartReplace), IGNORE_EXCEPTION);
400 }
401
402 void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool smartReplace, bool matchStyle)
403 {
404     Node* target = findEventTargetFromSelection();
405     if (!target)
406         return;
407     target->dispatchEvent(TextEvent::createForFragmentPaste(document().domWindow(), pastingFragment, smartReplace, matchStyle), IGNORE_EXCEPTION);
408 }
409
410 void Editor::pasteAsPlainTextBypassingDHTML()
411 {
412     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
413 }
414
415 void Editor::pasteAsPlainTextWithPasteboard(Pasteboard& pasteboard)
416 {
417     String text = readPlainTextFromPasteboard(pasteboard);
418     if (client() && client()->shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
419         pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
420 }
421
422 String Editor::readPlainTextFromPasteboard(Pasteboard& pasteboard)
423 {
424     PasteboardPlainText text;
425     pasteboard.read(text);
426     return plainTextFromPasteboard(text);
427 }
428
429 #if !(PLATFORM(MAC) && !PLATFORM(IOS))
430
431 String Editor::plainTextFromPasteboard(const PasteboardPlainText& text)
432 {
433     return text.text;
434 }
435
436 #endif
437
438 #if !PLATFORM(MAC) && !PLATFORM(EFL) && !PLATFORM(NIX)
439 void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
440 {
441     RefPtr<Range> range = selectedRange();
442     if (!range)
443         return;
444
445     bool chosePlainText;
446     RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, *range, allowPlainText, chosePlainText);
447     if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
448         pasteAsFragment(fragment, canSmartReplaceWithPasteboard(*pasteboard), chosePlainText);
449 }
450 #endif
451
452 bool Editor::canSmartReplaceWithPasteboard(Pasteboard& pasteboard)
453 {
454     return client() && client()->smartInsertDeleteEnabled() && pasteboard.canSmartReplace();
455 }
456
457 bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
458 {
459     if (!client())
460         return false;
461     
462     if (fragment) {
463         Node* child = fragment->firstChild();
464         if (child && fragment->lastChild() == child && child->isCharacterDataNode())
465             return client()->shouldInsertText(toCharacterData(child)->data(), replacingDOMRange.get(), givenAction);
466     }
467
468     return client()->shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
469 }
470
471 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
472 {
473     if (m_frame.selection().isNone() || !m_frame.selection().isContentEditable() || !fragment)
474         return;
475
476     ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
477     if (selectReplacement)
478         options |= ReplaceSelectionCommand::SelectReplacement;
479     if (smartReplace)
480         options |= ReplaceSelectionCommand::SmartReplace;
481     if (matchStyle)
482         options |= ReplaceSelectionCommand::MatchStyle;
483     applyCommand(ReplaceSelectionCommand::create(document(), fragment, options, EditActionPaste));
484     revealSelectionAfterEditingOperation();
485
486     if (m_frame.selection().isInPasswordField() || !isContinuousSpellCheckingEnabled())
487         return;
488     Node* nodeToCheck = m_frame.selection().rootEditableElement();
489     if (!nodeToCheck)
490         return;
491
492     RefPtr<Range> rangeToCheck = Range::create(document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
493     m_spellChecker->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
494 }
495
496 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
497 {
498     RefPtr<Range> range = selectedRange();
499     if (!range)
500         return;
501
502     replaceSelectionWithFragment(createFragmentFromText(*range, text), selectReplacement, smartReplace, true);
503 }
504
505 PassRefPtr<Range> Editor::selectedRange()
506 {
507     return m_frame.selection().toNormalizedRange();
508 }
509
510 bool Editor::shouldDeleteRange(Range* range) const
511 {
512     if (!range || range->collapsed(IGNORE_EXCEPTION))
513         return false;
514     
515     if (!canDeleteRange(range))
516         return false;
517
518     return client() && client()->shouldDeleteRange(range);
519 }
520
521 bool Editor::tryDHTMLCopy()
522 {   
523     if (m_frame.selection().isInPasswordField())
524         return false;
525
526     return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
527 }
528
529 bool Editor::tryDHTMLCut()
530 {
531     if (m_frame.selection().isInPasswordField())
532         return false;
533     
534     return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
535 }
536
537 bool Editor::tryDHTMLPaste()
538 {
539     return !dispatchCPPEvent(eventNames().pasteEvent, ClipboardReadable);
540 }
541
542 bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
543 {
544     return client() && client()->shouldInsertText(text, range, action);
545 }
546
547 void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
548 {
549     if (client())
550         client()->respondToChangedSelection(&m_frame);
551     setStartNewKillRingSequence(true);
552 #if ENABLE(DELETION_UI)
553     m_deleteButtonController->respondToChangedSelection(oldSelection);
554 #endif
555     m_alternativeTextController->respondToChangedSelection(oldSelection, options);
556 }
557
558 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
559 {
560     if (AXObjectCache::accessibilityEnabled()) {
561         Node* node = endingSelection.start().deprecatedNode();
562         if (AXObjectCache* cache = document().existingAXObjectCache())
563             cache->postNotification(node, AXObjectCache::AXValueChanged, TargetObservableParent);
564     }
565
566     updateMarkersForWordsAffectedByEditing(true);
567
568     if (client())
569         client()->respondToChangedContents();
570 }
571
572 bool Editor::hasBidiSelection() const
573 {
574     if (m_frame.selection().isNone())
575         return false;
576
577     Node* startNode;
578     if (m_frame.selection().isRange()) {
579         startNode = m_frame.selection().selection().start().downstream().deprecatedNode();
580         Node* endNode = m_frame.selection().selection().end().upstream().deprecatedNode();
581         if (enclosingBlock(startNode) != enclosingBlock(endNode))
582             return false;
583     } else
584         startNode = m_frame.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
585
586     auto renderer = startNode->renderer();
587     while (renderer && !renderer->isRenderBlockFlow())
588         renderer = renderer->parent();
589
590     if (!renderer)
591         return false;
592
593     if (!renderer->style().isLeftToRightDirection())
594         return true;
595
596     return toRenderBlockFlow(renderer)->containsNonZeroBidiLevel();
597 }
598
599 TriState Editor::selectionUnorderedListState() const
600 {
601     if (m_frame.selection().isCaret()) {
602         if (enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag))
603             return TrueTriState;
604     } else if (m_frame.selection().isRange()) {
605         Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag);
606         Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), ulTag);
607         if (startNode && endNode && startNode == endNode)
608             return TrueTriState;
609     }
610
611     return FalseTriState;
612 }
613
614 TriState Editor::selectionOrderedListState() const
615 {
616     if (m_frame.selection().isCaret()) {
617         if (enclosingNodeWithTag(m_frame.selection().selection().start(), olTag))
618             return TrueTriState;
619     } else if (m_frame.selection().isRange()) {
620         Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), olTag);
621         Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), olTag);
622         if (startNode && endNode && startNode == endNode)
623             return TrueTriState;
624     }
625
626     return FalseTriState;
627 }
628
629 PassRefPtr<Node> Editor::insertOrderedList()
630 {
631     if (!canEditRichly())
632         return 0;
633         
634     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::OrderedList);
635     revealSelectionAfterEditingOperation();
636     return newList;
637 }
638
639 PassRefPtr<Node> Editor::insertUnorderedList()
640 {
641     if (!canEditRichly())
642         return 0;
643         
644     RefPtr<Node> newList = InsertListCommand::insertList(document(), InsertListCommand::UnorderedList);
645     revealSelectionAfterEditingOperation();
646     return newList;
647 }
648
649 bool Editor::canIncreaseSelectionListLevel()
650 {
651     return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(&document());
652 }
653
654 bool Editor::canDecreaseSelectionListLevel()
655 {
656     return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(&document());
657 }
658
659 PassRefPtr<Node> Editor::increaseSelectionListLevel()
660 {
661     if (!canEditRichly() || m_frame.selection().isNone())
662         return 0;
663     
664     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(&document());
665     revealSelectionAfterEditingOperation();
666     return newList;
667 }
668
669 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
670 {
671     if (!canEditRichly() || m_frame.selection().isNone())
672         return 0;
673     
674     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(&document());
675     revealSelectionAfterEditingOperation();
676     return newList.release();
677 }
678
679 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
680 {
681     if (!canEditRichly() || m_frame.selection().isNone())
682         return 0;
683     
684     RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(&document());
685     revealSelectionAfterEditingOperation();
686     return newList.release();
687 }
688
689 void Editor::decreaseSelectionListLevel()
690 {
691     if (!canEditRichly() || m_frame.selection().isNone())
692         return;
693     
694     DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(&document());
695     revealSelectionAfterEditingOperation();
696 }
697
698 void Editor::removeFormattingAndStyle()
699 {
700     applyCommand(RemoveFormatCommand::create(document()));
701 }
702
703 void Editor::clearLastEditCommand() 
704 {
705     m_lastEditCommand.clear();
706 }
707
708 // Returns whether caller should continue with "the default processing", which is the same as 
709 // the event handler NOT setting the return value to false
710 bool Editor::dispatchCPPEvent(const AtomicString& eventType, ClipboardAccessPolicy policy)
711 {
712     Node* target = findEventTargetFromSelection();
713     if (!target)
714         return true;
715
716     RefPtr<Clipboard> clipboard = Clipboard::createForCopyAndPaste(policy);
717
718     RefPtr<Event> event = ClipboardEvent::create(eventType, true, true, clipboard);
719     target->dispatchEvent(event, IGNORE_EXCEPTION);
720     bool noDefaultProcessing = event->defaultPrevented();
721     if (noDefaultProcessing && policy == ClipboardWritable) {
722         OwnPtr<Pasteboard> pasteboard = Pasteboard::createForCopyAndPaste();
723         pasteboard->clear();
724         pasteboard->writePasteboard(clipboard->pasteboard());
725     }
726
727     // invalidate clipboard here for security
728     clipboard->setAccessPolicy(ClipboardNumb);
729     
730     return !noDefaultProcessing;
731 }
732
733 Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
734 {
735     Node* target = selection.start().element();
736     if (!target)
737         target = document().body();
738     if (!target)
739         return 0;
740
741     return target;
742 }
743
744 Node* Editor::findEventTargetFromSelection() const
745 {
746     return findEventTargetFrom(m_frame.selection().selection());
747 }
748
749 void Editor::applyStyle(StyleProperties* style, EditAction editingAction)
750 {
751     switch (m_frame.selection().selectionType()) {
752     case VisibleSelection::NoSelection:
753         // do nothing
754         break;
755     case VisibleSelection::CaretSelection:
756         computeAndSetTypingStyle(style, editingAction);
757         break;
758     case VisibleSelection::RangeSelection:
759         if (style)
760             applyCommand(ApplyStyleCommand::create(document(), EditingStyle::create(style).get(), editingAction));
761         break;
762     }
763 }
764     
765 bool Editor::shouldApplyStyle(StyleProperties* style, Range* range)
766 {   
767     return client()->shouldApplyStyle(style, range);
768 }
769     
770 void Editor::applyParagraphStyle(StyleProperties* style, EditAction editingAction)
771 {
772     switch (m_frame.selection().selectionType()) {
773     case VisibleSelection::NoSelection:
774         // do nothing
775         break;
776     case VisibleSelection::CaretSelection:
777     case VisibleSelection::RangeSelection:
778         if (style)
779             applyCommand(ApplyStyleCommand::create(document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties));
780         break;
781     }
782 }
783
784 void Editor::applyStyleToSelection(StyleProperties* style, EditAction editingAction)
785 {
786     if (!style || style->isEmpty() || !canEditRichly())
787         return;
788
789     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
790         applyStyle(style, editingAction);
791 }
792
793 void Editor::applyParagraphStyleToSelection(StyleProperties* style, EditAction editingAction)
794 {
795     if (!style || style->isEmpty() || !canEditRichly())
796         return;
797     
798     if (client() && client()->shouldApplyStyle(style, m_frame.selection().toNormalizedRange().get()))
799         applyParagraphStyle(style, editingAction);
800 }
801
802 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
803 {
804     return EditingStyle::create(propertyID, value)->triStateOfStyle(
805         EditingStyle::styleAtSelectionStart(m_frame.selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
806 }
807
808 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
809 {
810     return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame.selection().selection());
811 }
812
813 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
814 {
815     RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(),
816         propertyID == CSSPropertyBackgroundColor);
817     if (!selectionStyle || !selectionStyle->style())
818         return String();
819
820     if (propertyID == CSSPropertyFontSize)
821         return String::number(selectionStyle->legacyFontSize(&document()));
822     return selectionStyle->style()->getPropertyValue(propertyID);
823 }
824
825 void Editor::indent()
826 {
827     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Indent));
828 }
829
830 void Editor::outdent()
831 {
832     applyCommand(IndentOutdentCommand::create(document(), IndentOutdentCommand::Outdent));
833 }
834
835 static void dispatchEditableContentChangedEvents(PassRefPtr<Element> prpStartRoot, PassRefPtr<Element> prpEndRoot)
836 {
837     RefPtr<Element> startRoot = prpStartRoot;
838     RefPtr<Element> endRoot = prpEndRoot;
839     if (startRoot)
840         startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
841     if (endRoot && endRoot != startRoot)
842         endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent, false, false), IGNORE_EXCEPTION);
843 }
844
845 void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
846 {
847     document().updateLayout();
848
849     EditCommandComposition* composition = cmd->composition();
850     ASSERT(composition);
851     VisibleSelection newSelection(cmd->endingSelection());
852
853     m_alternativeTextController->respondToAppliedEditing(cmd.get());
854
855     // Don't clear the typing style with this selection change.  We do those things elsewhere if necessary.
856     FrameSelection::SetSelectionOptions options = cmd->isDictationCommand() ? FrameSelection::DictationTriggered : 0;
857     changeSelectionAfterCommand(newSelection, options);
858     dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
859
860     if (!cmd->preservesTypingStyle())
861         m_frame.selection().clearTypingStyle();
862
863     // Command will be equal to last edit command only in the case of typing
864     if (m_lastEditCommand.get() == cmd)
865         ASSERT(cmd->isTypingCommand());
866     else {
867         // Only register a new undo command if the command passed in is
868         // different from the last command
869         m_lastEditCommand = cmd;
870         if (client())
871             client()->registerUndoStep(m_lastEditCommand->ensureComposition());
872     }
873
874     respondToChangedContents(newSelection);
875 }
876
877 void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
878 {
879     document().updateLayout();
880
881     VisibleSelection newSelection(cmd->startingSelection());
882     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
883     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
884
885     m_alternativeTextController->respondToUnappliedEditing(cmd.get());
886
887     m_lastEditCommand = 0;
888     if (client())
889         client()->registerRedoStep(cmd);
890     respondToChangedContents(newSelection);
891 }
892
893 void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
894 {
895     document().updateLayout();
896
897     VisibleSelection newSelection(cmd->endingSelection());
898     changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
899     dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
900
901     m_lastEditCommand = 0;
902     if (client())
903         client()->registerUndoStep(cmd);
904     respondToChangedContents(newSelection);
905 }
906
907 Editor::Editor(Frame& frame)
908     : m_frame(frame)
909 #if ENABLE(DELETION_UI)
910     , m_deleteButtonController(adoptPtr(new DeleteButtonController(frame)))
911 #endif
912     , m_ignoreCompositionSelectionChange(false)
913     , m_shouldStartNewKillRingSequence(false)
914     // This is off by default, since most editors want this behavior (this matches IE but not FF).
915     , m_shouldStyleWithCSS(false)
916     , m_killRing(adoptPtr(new KillRing))
917     , m_spellChecker(adoptPtr(new SpellChecker(frame)))
918     , m_alternativeTextController(adoptPtr(new AlternativeTextController(frame)))
919     , m_areMarkedTextMatchesHighlighted(false)
920     , m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv)
921     , m_overwriteModeEnabled(false)
922 {
923 }
924
925 Editor::~Editor()
926 {
927 }
928
929 void Editor::clear()
930 {
931     m_compositionNode = 0;
932     m_customCompositionUnderlines.clear();
933     m_shouldStyleWithCSS = false;
934     m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
935
936 #if ENABLE(DELETION_UI)
937     m_deleteButtonController = adoptPtr(new DeleteButtonController(m_frame));
938 #endif
939 }
940
941 bool Editor::insertText(const String& text, Event* triggeringEvent)
942 {
943     return m_frame.eventHandler().handleTextInputEvent(text, triggeringEvent);
944 }
945
946 bool Editor::insertTextForConfirmedComposition(const String& text)
947 {
948     return m_frame.eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
949 }
950
951 bool Editor::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent)
952 {
953     return m_alternativeTextController->insertDictatedText(text, dictationAlternatives, triggeringEvent);
954 }
955
956 bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
957 {
958     if (text.isEmpty())
959         return false;
960
961     VisibleSelection selection = selectionForCommand(triggeringEvent);
962     if (!selection.isContentEditable())
963         return false;
964     RefPtr<Range> range = selection.toNormalizedRange();
965
966     if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
967         return true;
968
969     updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
970
971     bool shouldConsiderApplyingAutocorrection = false;
972     if (text == " " || text == "\t")
973         shouldConsiderApplyingAutocorrection = true;
974
975     if (text.length() == 1 && u_ispunct(text[0]) && !isAmbiguousBoundaryCharacter(text[0]))
976         shouldConsiderApplyingAutocorrection = true;
977
978     bool autocorrectionWasApplied = shouldConsiderApplyingAutocorrection && m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
979
980     // Get the selection to use for the event that triggered this insertText.
981     // If the event handler changed the selection, we may want to use a different selection
982     // that is contained in the event target.
983     selection = selectionForCommand(triggeringEvent);
984     if (selection.isContentEditable()) {
985         if (Node* selectionStart = selection.start().deprecatedNode()) {
986             Ref<Document> document(selectionStart->document());
987
988             // Insert the text
989             if (triggeringEvent && triggeringEvent->isDictation())
990                 DictationCommand::insertText(&document.get(), text, triggeringEvent->dictationAlternatives(), selection);
991             else {
992                 TypingCommand::Options options = 0;
993                 if (selectInsertedText)
994                     options |= TypingCommand::SelectInsertedText;
995                 if (autocorrectionWasApplied)
996                     options |= TypingCommand::RetainAutocorrectionIndicator;
997                 TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
998             }
999
1000             // Reveal the current selection
1001             if (Frame* editedFrame = document->frame())
1002                 if (Page* page = editedFrame->page())
1003                     page->focusController().focusedOrMainFrame().selection().revealSelection(ScrollAlignment::alignCenterIfNeeded);
1004         }
1005     }
1006
1007     return true;
1008 }
1009
1010 bool Editor::insertLineBreak()
1011 {
1012     if (!canEdit())
1013         return false;
1014
1015     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1016         return true;
1017
1018     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1019     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1020     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1021     TypingCommand::insertLineBreak(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1022     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1023
1024     return true;
1025 }
1026
1027 bool Editor::insertParagraphSeparator()
1028 {
1029     if (!canEdit())
1030         return false;
1031
1032     if (!canEditRichly())
1033         return insertLineBreak();
1034
1035     if (!shouldInsertText("\n", m_frame.selection().toNormalizedRange().get(), EditorInsertActionTyped))
1036         return true;
1037
1038     VisiblePosition caret = m_frame.selection().selection().visibleStart();
1039     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
1040     bool autocorrectionIsApplied = m_alternativeTextController->applyAutocorrectionBeforeTypingIfAppropriate();
1041     TypingCommand::insertParagraphSeparator(document(), autocorrectionIsApplied ? TypingCommand::RetainAutocorrectionIndicator : 0);
1042     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
1043
1044     return true;
1045 }
1046
1047 void Editor::cut()
1048 {
1049     if (tryDHTMLCut())
1050         return; // DHTML did the whole operation
1051     if (!canCut()) {
1052         systemBeep();
1053         return;
1054     }
1055
1056     // FIXME: This should share more code with the copy function; there is a lot of overlap.
1057     RefPtr<Range> selection = selectedRange();
1058     willWriteSelectionToPasteboard(selection);
1059     if (shouldDeleteRange(selection.get())) {
1060         updateMarkersForWordsAffectedByEditing(true);
1061         if (enclosingTextFormControl(m_frame.selection().start()))
1062             Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForClipboard(), canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1063         else {
1064 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1065             writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
1066 #else
1067             // FIXME: Convert all other platforms to match Mac and delete this.
1068             Pasteboard::createForCopyAndPaste()->writeSelection(*selection, canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1069 #endif
1070         }
1071         didWriteSelectionToPasteboard();
1072         deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1073     }
1074 }
1075
1076 void Editor::copy()
1077 {
1078     if (tryDHTMLCopy())
1079         return; // DHTML did the whole operation
1080     if (!canCopy()) {
1081         systemBeep();
1082         return;
1083     }
1084
1085     willWriteSelectionToPasteboard(selectedRange());
1086     if (enclosingTextFormControl(m_frame.selection().start())) {
1087         Pasteboard::createForCopyAndPaste()->writePlainText(selectedTextForClipboard(),
1088             canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
1089     } else {
1090         if (HTMLImageElement* imageElement = imageElementFromImageDocument(document())) {
1091 #if (PLATFORM(MAC) && !PLATFORM(IOS)) || PLATFORM(EFL) || PLATFORM(NIX)
1092             writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *imageElement, document().url(), document().title());
1093 #else
1094             Pasteboard::createForCopyAndPaste()->writeImage(*imageElement, document().url(), document().title());
1095 #endif
1096         } else {
1097 #if (PLATFORM(MAC) && !PLATFORM(IOS)) || PLATFORM(EFL) || PLATFORM(NIX)
1098             writeSelectionToPasteboard(*Pasteboard::createForCopyAndPaste());
1099 #else
1100             // FIXME: Convert all other platforms to match Mac and delete this.
1101             Pasteboard::createForCopyAndPaste()->writeSelection(*selectedRange(), canSmartCopyOrDelete(), m_frame, IncludeImageAltTextForClipboard);
1102 #endif
1103         }
1104     }
1105
1106     didWriteSelectionToPasteboard();
1107 }
1108
1109 void Editor::paste()
1110 {
1111     paste(*Pasteboard::createForCopyAndPaste());
1112 }
1113
1114 void Editor::paste(Pasteboard& pasteboard)
1115 {
1116     if (tryDHTMLPaste())
1117         return; // DHTML did the whole operation
1118     if (!canPaste())
1119         return;
1120     updateMarkersForWordsAffectedByEditing(false);
1121     CachedResourceLoader* loader = document().cachedResourceLoader();
1122     ResourceCacheValidationSuppressor validationSuppressor(loader);
1123     if (m_frame.selection().isContentRichlyEditable())
1124         pasteWithPasteboard(&pasteboard, true);
1125     else
1126         pasteAsPlainTextWithPasteboard(pasteboard);
1127 }
1128
1129 void Editor::pasteAsPlainText()
1130 {
1131     if (tryDHTMLPaste())
1132         return;
1133     if (!canPaste())
1134         return;
1135     updateMarkersForWordsAffectedByEditing(false);
1136     pasteAsPlainTextWithPasteboard(*Pasteboard::createForCopyAndPaste());
1137 }
1138
1139 void Editor::performDelete()
1140 {
1141     if (!canDelete()) {
1142         systemBeep();
1143         return;
1144     }
1145
1146     addToKillRing(selectedRange().get(), false);
1147     deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
1148
1149     // clear the "start new kill ring sequence" setting, because it was set to true
1150     // when the selection was updated by deleting the range
1151     setStartNewKillRingSequence(false);
1152 }
1153
1154 void Editor::simplifyMarkup(Node* startNode, Node* endNode)
1155 {
1156     if (!startNode)
1157         return;
1158     if (endNode) {
1159         if (&startNode->document() != &endNode->document())
1160             return;
1161         // check if start node is before endNode
1162         Node* node = startNode;
1163         while (node && node != endNode)
1164             node = NodeTraversal::next(node);
1165         if (!node)
1166             return;
1167     }
1168     
1169     applyCommand(SimplifyMarkupCommand::create(document(), startNode, (endNode) ? NodeTraversal::next(endNode) : 0));
1170 }
1171
1172 void Editor::copyURL(const URL& url, const String& title)
1173 {
1174     copyURL(url, title, *Pasteboard::createForCopyAndPaste());
1175 }
1176
1177 void Editor::copyURL(const URL& url, const String& title, Pasteboard& pasteboard)
1178 {
1179     PasteboardURL pasteboardURL;
1180     pasteboardURL.url = url;
1181     pasteboardURL.title = title;
1182
1183 #if PLATFORM(MAC) && !PLATFORM(IOS)
1184     fillInUserVisibleForm(pasteboardURL);
1185 #endif
1186
1187     pasteboard.write(pasteboardURL);
1188 }
1189
1190 void Editor::copyImage(const HitTestResult& result)
1191 {
1192     Element* element = result.innerNonSharedElement();
1193     if (!element)
1194         return;
1195
1196     URL url = result.absoluteLinkURL();
1197     if (url.isEmpty())
1198         url = result.absoluteImageURL();
1199
1200 #if PLATFORM(MAC) || PLATFORM(EFL) || PLATFORM(NIX)
1201     writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), *element, url, result.altDisplayString());
1202 #else
1203     Pasteboard::createForCopyAndPaste()->writeImage(*element, url, result.altDisplayString());
1204 #endif
1205 }
1206
1207 bool Editor::isContinuousSpellCheckingEnabled() const
1208 {
1209     return client() && client()->isContinuousSpellCheckingEnabled();
1210 }
1211
1212 void Editor::toggleContinuousSpellChecking()
1213 {
1214     if (client())
1215         client()->toggleContinuousSpellChecking();
1216 }
1217
1218 bool Editor::isGrammarCheckingEnabled()
1219 {
1220     return client() && client()->isGrammarCheckingEnabled();
1221 }
1222
1223 void Editor::toggleGrammarChecking()
1224 {
1225     if (client())
1226         client()->toggleGrammarChecking();
1227 }
1228
1229 int Editor::spellCheckerDocumentTag()
1230 {
1231     return client() ? client()->spellCheckerDocumentTag() : 0;
1232 }
1233
1234 #if USE(APPKIT)
1235
1236 void Editor::uppercaseWord()
1237 {
1238     if (client())
1239         client()->uppercaseWord();
1240 }
1241
1242 void Editor::lowercaseWord()
1243 {
1244     if (client())
1245         client()->lowercaseWord();
1246 }
1247
1248 void Editor::capitalizeWord()
1249 {
1250     if (client())
1251         client()->capitalizeWord();
1252 }
1253     
1254 #endif
1255
1256 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1257
1258 void Editor::showSubstitutionsPanel()
1259 {
1260     if (!client()) {
1261         LOG_ERROR("No NSSpellChecker");
1262         return;
1263     }
1264
1265     if (client()->substitutionsPanelIsShowing()) {
1266         client()->showSubstitutionsPanel(false);
1267         return;
1268     }
1269     client()->showSubstitutionsPanel(true);
1270 }
1271
1272 bool Editor::substitutionsPanelIsShowing()
1273 {
1274     if (!client())
1275         return false;
1276     return client()->substitutionsPanelIsShowing();
1277 }
1278
1279 void Editor::toggleSmartInsertDelete()
1280 {
1281     if (client())
1282         client()->toggleSmartInsertDelete();
1283 }
1284
1285 bool Editor::isAutomaticQuoteSubstitutionEnabled()
1286 {
1287     return client() && client()->isAutomaticQuoteSubstitutionEnabled();
1288 }
1289
1290 void Editor::toggleAutomaticQuoteSubstitution()
1291 {
1292     if (client())
1293         client()->toggleAutomaticQuoteSubstitution();
1294 }
1295
1296 bool Editor::isAutomaticLinkDetectionEnabled()
1297 {
1298     return client() && client()->isAutomaticLinkDetectionEnabled();
1299 }
1300
1301 void Editor::toggleAutomaticLinkDetection()
1302 {
1303     if (client())
1304         client()->toggleAutomaticLinkDetection();
1305 }
1306
1307 bool Editor::isAutomaticDashSubstitutionEnabled()
1308 {
1309     return client() && client()->isAutomaticDashSubstitutionEnabled();
1310 }
1311
1312 void Editor::toggleAutomaticDashSubstitution()
1313 {
1314     if (client())
1315         client()->toggleAutomaticDashSubstitution();
1316 }
1317
1318 bool Editor::isAutomaticTextReplacementEnabled()
1319 {
1320     return client() && client()->isAutomaticTextReplacementEnabled();
1321 }
1322
1323 void Editor::toggleAutomaticTextReplacement()
1324 {
1325     if (client())
1326         client()->toggleAutomaticTextReplacement();
1327 }
1328
1329 bool Editor::isAutomaticSpellingCorrectionEnabled()
1330 {
1331     return m_alternativeTextController->isAutomaticSpellingCorrectionEnabled();
1332 }
1333
1334 void Editor::toggleAutomaticSpellingCorrection()
1335 {
1336     if (client())
1337         client()->toggleAutomaticSpellingCorrection();
1338 }
1339
1340 #endif
1341
1342 bool Editor::shouldEndEditing(Range* range)
1343 {
1344     return client() && client()->shouldEndEditing(range);
1345 }
1346
1347 bool Editor::shouldBeginEditing(Range* range)
1348 {
1349     return client() && client()->shouldBeginEditing(range);
1350 }
1351
1352 void Editor::clearUndoRedoOperations()
1353 {
1354     if (client())
1355         client()->clearUndoRedoOperations();
1356 }
1357
1358 bool Editor::canUndo()
1359 {
1360     return client() && client()->canUndo();
1361 }
1362
1363 void Editor::undo()
1364 {
1365     if (client())
1366         client()->undo();
1367 }
1368
1369 bool Editor::canRedo()
1370 {
1371     return client() && client()->canRedo();
1372 }
1373
1374 void Editor::redo()
1375 {
1376     if (client())
1377         client()->redo();
1378 }
1379
1380 void Editor::didBeginEditing()
1381 {
1382     if (client())
1383         client()->didBeginEditing();
1384 }
1385
1386 void Editor::didEndEditing()
1387 {
1388     if (client())
1389         client()->didEndEditing();
1390 }
1391
1392 void Editor::willWriteSelectionToPasteboard(PassRefPtr<Range> range)
1393 {
1394     if (client())
1395         client()->willWriteSelectionToPasteboard(range.get());
1396 }
1397
1398 void Editor::didWriteSelectionToPasteboard()
1399 {
1400     if (client())
1401         client()->didWriteSelectionToPasteboard();
1402 }
1403
1404 void Editor::toggleBold()
1405 {
1406     command("ToggleBold").execute();
1407 }
1408
1409 void Editor::toggleUnderline()
1410 {
1411     command("ToggleUnderline").execute();
1412 }
1413
1414 void Editor::setBaseWritingDirection(WritingDirection direction)
1415 {
1416     Element* focusedElement = document().focusedElement();
1417     if (focusedElement && isHTMLTextFormControlElement(*focusedElement)) {
1418         if (direction == NaturalWritingDirection)
1419             return;
1420         toHTMLElement(focusedElement)->setAttribute(dirAttr, direction == LeftToRightWritingDirection ? "ltr" : "rtl");
1421         focusedElement->dispatchInputEvent();
1422         document().updateStyleIfNeeded();
1423         return;
1424     }
1425
1426     RefPtr<MutableStyleProperties> style = MutableStyleProperties::create();
1427     style->setProperty(CSSPropertyDirection, direction == LeftToRightWritingDirection ? "ltr" : direction == RightToLeftWritingDirection ? "rtl" : "inherit", false);
1428     applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
1429 }
1430
1431 WritingDirection Editor::baseWritingDirectionForSelectionStart() const
1432 {
1433     WritingDirection result = LeftToRightWritingDirection;
1434
1435     Position pos = m_frame.selection().selection().visibleStart().deepEquivalent();
1436     Node* node = pos.deprecatedNode();
1437     if (!node)
1438         return result;
1439
1440     auto renderer = node->renderer();
1441     if (!renderer)
1442         return result;
1443
1444     if (!renderer->isRenderBlockFlow()) {
1445         renderer = renderer->containingBlock();
1446         if (!renderer)
1447             return result;
1448     }
1449
1450     switch (renderer->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 = std::min(baseOffset + selectionStart, extentOffset);
1632             unsigned end = std::min(std::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->hasEditableStyle())
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->hasEditableStyle())
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 = std::min(m_compositionStart, length);
2540     unsigned end = std::min(std::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(StyleProperties* 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 = toStyledElement(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 bool Editor::findString(const String& target, FindOptions options)
2822 {
2823     VisibleSelection selection = m_frame.selection().selection();
2824
2825     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
2826
2827     if (!resultRange)
2828         return false;
2829
2830     m_frame.selection().setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
2831     m_frame.selection().revealSelection();
2832     return true;
2833 }
2834
2835 PassRefPtr<Range> Editor::findStringAndScrollToVisible(const String& target, Range* previousMatch, FindOptions options)
2836 {
2837     RefPtr<Range> nextMatch = rangeOfString(target, previousMatch, options);
2838     if (!nextMatch)
2839         return 0;
2840
2841     nextMatch->firstNode()->renderer()->scrollRectToVisible(nextMatch->boundingBox(),
2842         ScrollAlignment::alignCenterIfNeeded, ScrollAlignment::alignCenterIfNeeded);
2843
2844     return nextMatch.release();
2845 }
2846
2847 PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRange, FindOptions options)
2848 {
2849     if (target.isEmpty())
2850         return 0;
2851
2852     // Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
2853     // is used depends on whether we're searching forward or backward, and whether startInSelection is set.
2854     RefPtr<Range> searchRange(rangeOfContents(document()));
2855
2856     bool forward = !(options & Backwards);
2857     bool startInReferenceRange = referenceRange && (options & StartInSelection);
2858     if (referenceRange) {
2859         if (forward)
2860             searchRange->setStart(startInReferenceRange ? referenceRange->startPosition() : referenceRange->endPosition());
2861         else
2862             searchRange->setEnd(startInReferenceRange ? referenceRange->endPosition() : referenceRange->startPosition());
2863     }
2864
2865     RefPtr<Node> shadowTreeRoot = referenceRange && referenceRange->startContainer() ? referenceRange->startContainer()->nonBoundaryShadowTreeRootNode() : 0;
2866     if (shadowTreeRoot) {
2867         if (forward)
2868             searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2869         else
2870             searchRange->setStart(shadowTreeRoot.get(), 0);
2871     }
2872
2873     RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options));
2874     // If we started in the reference range and the found range exactly matches the reference range, find again.
2875     // Build a selection with the found range to remove collapsed whitespace.
2876     // Compare ranges instead of selection objects to ignore the way that the current selection was made.
2877     if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
2878         searchRange = rangeOfContents(document());
2879         if (forward)
2880             searchRange->setStart(referenceRange->endPosition());
2881         else
2882             searchRange->setEnd(referenceRange->startPosition());
2883
2884         if (shadowTreeRoot) {
2885             if (forward)
2886                 searchRange->setEnd(shadowTreeRoot.get(), shadowTreeRoot->childNodeCount());
2887             else
2888                 searchRange->setStart(shadowTreeRoot.get(), 0);
2889         }
2890
2891         resultRange = findPlainText(searchRange.get(), target, options);
2892     }
2893
2894     // If nothing was found in the shadow tree, search in main content following the shadow tree.
2895     if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && shadowTreeRoot) {
2896         searchRange = rangeOfContents(document());
2897         if (forward)
2898             searchRange->setStartAfter(shadowTreeRoot->shadowHost());
2899         else
2900             searchRange->setEndBefore(shadowTreeRoot->shadowHost());
2901
2902         resultRange = findPlainText(searchRange.get(), target, options);
2903     }
2904
2905     // If we didn't find anything and we're wrapping, search again in the entire document (this will
2906     // redundantly re-search the area already searched in some cases).
2907     if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && options & WrapAround) {
2908         searchRange = rangeOfContents(document());
2909         resultRange = findPlainText(searchRange.get(), target, options);
2910         // We used to return false here if we ended up with the same range that we started with
2911         // (e.g., the reference range was already the only instance of this text). But we decided that
2912         // this should be a success case instead, so we'll just fall through in that case.
2913     }
2914
2915     return resultRange->collapsed(ASSERT_NO_EXCEPTION) ? 0 : resultRange.release();
2916 }
2917
2918 static bool isFrameInRange(Frame* frame, Range* range)
2919 {
2920     bool inRange = false;
2921     for (HTMLFrameOwnerElement* ownerElement = frame->ownerElement(); ownerElement; ownerElement = ownerElement->document().ownerElement()) {
2922         if (&ownerElement->document() == &range->ownerDocument()) {
2923             inRange = range->intersectsNode(ownerElement, IGNORE_EXCEPTION);
2924             break;
2925         }
2926     }
2927     return inRange;
2928 }
2929
2930 unsigned Editor::countMatchesForText(const String& target, Range* range, FindOptions options, unsigned limit, bool markMatches, Vector<RefPtr<Range>>* matches)
2931 {
2932     if (target.isEmpty())
2933         return 0;
2934
2935     RefPtr<Range> searchRange;
2936     if (range) {
2937         if (&range->ownerDocument() == &document())
2938             searchRange = range;
2939         else if (!isFrameInRange(&m_frame, range))
2940             return 0;
2941     }
2942     if (!searchRange)
2943         searchRange = rangeOfContents(document());
2944
2945     Node* originalEndContainer = searchRange->endContainer();
2946     int originalEndOffset = searchRange->endOffset();
2947
2948     unsigned matchCount = 0;
2949     do {
2950         RefPtr<Range> resultRange(findPlainText(searchRange.get(), target, options & ~Backwards));
2951         if (resultRange->collapsed(IGNORE_EXCEPTION)) {
2952             if (!resultRange->startContainer()->isInShadowTree())
2953                 break;
2954
2955             searchRange->setStartAfter(resultRange->startContainer()->shadowHost(), IGNORE_EXCEPTION);
2956             searchRange->setEnd(originalEndContainer, originalEndOffset, IGNORE_EXCEPTION);
2957             continue;
2958         }
2959
2960         ++matchCount;
2961         if (matches)
2962             matches->append(resultRange);
2963         
2964         if (markMatches)
2965             document().markers().addMarker(resultRange.get(), DocumentMarker::TextMatch);
2966
2967         // Stop looking if we hit the specified limit. A limit of 0 means no limit.
2968         if (limit > 0 && matchCount >= limit)
2969             break;
2970
2971         // Set the new start for the search range to be the end of the previous
2972         // result range. There is no need to use a VisiblePosition here,
2973         // since findPlainText will use a TextIterator to go over the visible
2974         // text nodes. 
2975         searchRange->setStart(resultRange->endContainer(IGNORE_EXCEPTION), resultRange->endOffset(IGNORE_EXCEPTION), IGNORE_EXCEPTION);
2976
2977         Node* shadowTreeRoot = searchRange->shadowRoot();
2978         if (searchRange->collapsed(IGNORE_EXCEPTION) && shadowTreeRoot)
2979             searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), IGNORE_EXCEPTION);
2980     } while (true);
2981
2982     if (markMatches || matches) {
2983         // Do a "fake" paint in order to execute the code that computes the rendered rect for each text match.
2984         if (m_frame.view() && m_frame.contentRenderer()) {
2985             document().updateLayout(); // Ensure layout is up to date.
2986             LayoutRect visibleRect = m_frame.view()->visibleContentRect();
2987             if (!visibleRect.isEmpty()) {
2988                 GraphicsContext context((PlatformGraphicsContext*)0);
2989                 context.setPaintingDisabled(true);
2990
2991                 PaintBehavior oldBehavior = m_frame.view()->paintBehavior();
2992                 m_frame.view()->setPaintBehavior(oldBehavior | PaintBehaviorFlattenCompositingLayers);
2993                 m_frame.view()->paintContents(&context, enclosingIntRect(visibleRect));
2994                 m_frame.view()->setPaintBehavior(oldBehavior);
2995             }
2996         }
2997     }
2998
2999     return matchCount;
3000 }
3001
3002 void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
3003 {
3004     if (flag == m_areMarkedTextMatchesHighlighted)
3005         return;
3006
3007     m_areMarkedTextMatchesHighlighted = flag;
3008     document().markers().repaintMarkers(DocumentMarker::TextMatch);
3009 }
3010
3011 void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
3012 {
3013     m_alternativeTextController->stopPendingCorrection(oldSelection);
3014
3015     bool closeTyping = options & FrameSelection::CloseTyping;
3016     bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
3017     bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
3018     if (isContinuousSpellCheckingEnabled) {
3019         VisibleSelection newAdjacentWords;
3020         VisibleSelection newSelectedSentence;
3021         bool caretBrowsing = m_frame.settings().caretBrowsingEnabled();
3022         if (m_frame.selection().selection().isContentEditable() || caretBrowsing) {
3023             VisiblePosition newStart(m_frame.selection().selection().visibleStart());
3024             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
3025             if (isContinuousGrammarCheckingEnabled)
3026                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
3027         }
3028
3029         // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
3030         bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
3031
3032         // When typing we check spelling elsewhere, so don't redo it here.
3033         // If this is a change in selection resulting from a delete operation,
3034         // oldSelection may no longer be in the document.
3035         if (shouldCheckSpellingAndGrammar && closeTyping && oldSelection.isContentEditable() && oldSelection.start().deprecatedNode() && oldSelection.start().anchorNode()->inDocument()) {
3036             VisiblePosition oldStart(oldSelection.visibleStart());
3037             VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
3038             if (oldAdjacentWords != newAdjacentWords) {
3039                 if (isContinuousGrammarCheckingEnabled) {
3040                     VisibleSelection oldSelectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
3041                     markMisspellingsAndBadGrammar(oldAdjacentWords, oldSelectedSentence != newSelectedSentence, oldSelectedSentence);
3042                 } else
3043                     markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
3044             }
3045         }
3046
3047         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
3048             if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
3049                 document().markers().removeMarkers(wordRange.get(), DocumentMarker::Spelling);
3050         }
3051         if (!textChecker() || textChecker()->shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
3052             if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
3053                 document().markers().removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
3054         }
3055     }
3056
3057     // When continuous spell checking is off, existing markers disappear after the selection changes.
3058     if (!isContinuousSpellCheckingEnabled)
3059         document().markers().removeMarkers(DocumentMarker::Spelling);
3060     if (!isContinuousGrammarCheckingEnabled)
3061         document().markers().removeMarkers(DocumentMarker::Grammar);
3062
3063     notifyComponentsOnChangedSelection(oldSelection, options);
3064 }
3065
3066 static Node* findFirstMarkable(Node* node)
3067 {
3068     while (node) {
3069         if (!node->renderer())
3070             return 0;
3071         if (node->renderer()->isTextOrLineBreak())
3072             return node;
3073         if (isHTMLTextFormControlElement(*node))
3074             node = toHTMLTextFormControlElement(node)->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
3075         else if (node->firstChild())
3076             node = node->firstChild();
3077         else
3078             node = node->nextSibling();
3079     }
3080
3081     return 0;
3082 }
3083
3084 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
3085 {
3086     Node* node = findFirstMarkable(m_frame.selection().start().deprecatedNode());
3087     if (!node)
3088         return false;
3089
3090     unsigned int startOffset = static_cast<unsigned int>(from);
3091     unsigned int endOffset = static_cast<unsigned int>(from + length);
3092     Vector<DocumentMarker*> markers = document().markers().markersFor(node);
3093     for (size_t i = 0; i < markers.size(); ++i) {
3094         DocumentMarker* marker = markers[i];
3095         if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
3096             return true;
3097     }
3098
3099     return false;
3100 }       
3101
3102 TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
3103 {
3104     bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
3105     bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
3106     bool shouldShowCorrectionPanel = textCheckingOptions & TextCheckingTypeShowCorrectionPanel;
3107     bool shouldCheckForCorrection = shouldShowCorrectionPanel || (textCheckingOptions & TextCheckingTypeCorrection);
3108
3109     TextCheckingTypeMask checkingTypes = 0;
3110     if (shouldMarkSpelling)
3111         checkingTypes |= TextCheckingTypeSpelling;
3112     if (shouldMarkGrammar)
3113         checkingTypes |= TextCheckingTypeGrammar;
3114     if (shouldCheckForCorrection)
3115         checkingTypes |= TextCheckingTypeCorrection;
3116     if (shouldShowCorrectionPanel)
3117         checkingTypes |= TextCheckingTypeShowCorrectionPanel;
3118
3119 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
3120     bool shouldPerformReplacement = textCheckingOptions & TextCheckingTypeReplacement;
3121     if (shouldPerformReplacement) {
3122         if (isAutomaticLinkDetectionEnabled())
3123             checkingTypes |= TextCheckingTypeLink;
3124         if (isAutomaticQuoteSubstitutionEnabled())
3125             checkingTypes |= TextCheckingTypeQuote;
3126         if (isAutomaticDashSubstitutionEnabled())
3127             checkingTypes |= TextCheckingTypeDash;
3128         if (isAutomaticTextReplacementEnabled())
3129             checkingTypes |= TextCheckingTypeReplacement;
3130         if (shouldMarkSpelling && isAutomaticSpellingCorrectionEnabled())
3131             checkingTypes |= TextCheckingTypeCorrection;
3132     }
3133 #endif
3134
3135     return checkingTypes;
3136 }
3137
3138 void Editor::deviceScaleFactorChanged()
3139 {
3140 #if ENABLE(DELETION_UI)
3141     m_deleteButtonController->deviceScaleFactorChanged();
3142 #endif
3143 }
3144
3145 bool Editor::unifiedTextCheckerEnabled() const
3146 {
3147     return WebCore::unifiedTextCheckerEnabled(&m_frame);
3148 }
3149
3150 Vector<String> Editor::dictationAlternativesForMarker(const DocumentMarker* marker)
3151 {
3152     return m_alternativeTextController->dictationAlternativesForMarker(marker);
3153 }
3154
3155 void Editor::applyDictationAlternativelternative(const String& alternativeString)
3156 {
3157     m_alternativeTextController->applyDictationAlternative(alternativeString);
3158 }
3159
3160 void Editor::toggleOverwriteModeEnabled()
3161 {
3162     m_overwriteModeEnabled = !m_overwriteModeEnabled;
3163     m_frame.selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
3164 }
3165
3166 Document& Editor::document() const
3167 {
3168     ASSERT(m_frame.document());
3169     return *m_frame.document();
3170 }
3171
3172 } // namespace WebCore