Bug 452317 - FeedConverter.js: QueryInterface should throw NS_ERROR_NO_INTERFACE...
[wine-gecko.git] / extensions / spellcheck / src / mozInlineSpellWordUtil.cpp
blob0246acea505b7fffafc454820a8190b51d7f2eaa
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is inline spellchecker code.
17 * The Initial Developer of the Original Code is Google Inc.
18 * Portions created by the Initial Developer are Copyright (C) 2004-2006
19 * the Initial Developer. All Rights Reserved.
21 * Contributor(s):
22 * Brett Wilson <brettw@gmail.com> (original author)
23 * Robert O'Callahan <rocallahan@novell.com>
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
39 #include "mozInlineSpellWordUtil.h"
40 #include "nsDebug.h"
41 #include "nsIAtom.h"
42 #include "nsComponentManagerUtils.h"
43 #include "nsIDOMCSSStyleDeclaration.h"
44 #include "nsIDOMDocumentView.h"
45 #include "nsIDOMElement.h"
46 #include "nsIDOMNSRange.h"
47 #include "nsIDOMRange.h"
48 #include "nsIEditor.h"
49 #include "nsIDOMNode.h"
50 #include "nsIDOMHTMLBRElement.h"
51 #include "nsUnicharUtilCIID.h"
52 #include "nsServiceManagerUtils.h"
54 // IsIgnorableCharacter
56 // These characters are ones that we should ignore in input.
58 inline PRBool IsIgnorableCharacter(PRUnichar ch)
60 return (ch == 0x200D || // ZERO-WIDTH JOINER
61 ch == 0xAD || // SOFT HYPHEN
62 ch == 0x1806); // MONGOLIAN TODO SOFT HYPHEN
65 // IsConditionalPunctuation
67 // Some characters (like apostrophes) require characters on each side to be
68 // part of a word, and are otherwise punctuation.
70 inline PRBool IsConditionalPunctuation(PRUnichar ch)
72 return (ch == '\'' ||
73 ch == 0x2019); // RIGHT SINGLE QUOTATION MARK
76 // mozInlineSpellWordUtil::Init
78 nsresult
79 mozInlineSpellWordUtil::Init(nsWeakPtr aWeakEditor)
81 nsresult rv;
83 mCategories = do_GetService(NS_UNICHARCATEGORY_CONTRACTID, &rv);
84 if (NS_FAILED(rv))
85 return rv;
87 // getting the editor can fail commonly because the editor was detached, so
88 // don't assert
89 nsCOMPtr<nsIEditor> editor = do_QueryReferent(aWeakEditor, &rv);
90 if (NS_FAILED(rv))
91 return rv;
93 nsCOMPtr<nsIDOMDocument> domDoc;
94 rv = editor->GetDocument(getter_AddRefs(domDoc));
95 NS_ENSURE_SUCCESS(rv, rv);
97 mDocument = do_QueryInterface(domDoc, &rv);
98 NS_ENSURE_SUCCESS(rv, rv);
100 mDOMDocumentRange = do_QueryInterface(domDoc, &rv);
101 NS_ENSURE_SUCCESS(rv, rv);
103 // view
104 nsCOMPtr<nsIDOMDocumentView> docView = do_QueryInterface(domDoc, &rv);
105 NS_ENSURE_SUCCESS(rv, rv);
106 nsCOMPtr<nsIDOMAbstractView> abstractView;
107 rv = docView->GetDefaultView(getter_AddRefs(abstractView));
108 NS_ENSURE_SUCCESS(rv, rv);
109 mCSSView = do_QueryInterface(abstractView, &rv);
110 NS_ENSURE_SUCCESS(rv, rv);
112 // Find the root node for the editor. For contenteditable we'll need something
113 // cleverer here.
114 nsCOMPtr<nsIDOMElement> rootElt;
115 rv = editor->GetRootElement(getter_AddRefs(rootElt));
116 NS_ENSURE_SUCCESS(rv, rv);
118 mRootNode = rootElt;
119 NS_ASSERTION(mRootNode, "GetRootElement returned null *and* claimed to suceed!");
120 return NS_OK;
123 static PRBool
124 IsTextNode(nsIDOMNode* aNode)
126 PRUint16 type = 0;
127 aNode->GetNodeType(&type);
128 return type == nsIDOMNode::TEXT_NODE;
131 typedef void (* OnLeaveNodeFunPtr)(nsIDOMNode* aNode, void* aClosure);
133 // Find the next node in the DOM tree in preorder. This isn't fast because
134 // one call to GetNextSibling can be O(N) in the number of siblings...
135 // Calls OnLeaveNodeFunPtr when the traversal leaves a node
136 static nsIDOMNode*
137 FindNextNode(nsIDOMNode* aNode, nsIDOMNode* aRoot,
138 OnLeaveNodeFunPtr aOnLeaveNode = nsnull, void* aClosure = nsnull)
140 NS_PRECONDITION(aNode, "Null starting node?");
142 nsCOMPtr<nsIDOMNode> next;
143 aNode->GetFirstChild(getter_AddRefs(next));
144 if (next)
145 return next;
147 // Don't look at siblings or otherwise outside of aRoot
148 if (aNode == aRoot)
149 return nsnull;
151 aNode->GetNextSibling(getter_AddRefs(next));
152 if (next)
153 return next;
155 // Go up
156 for (;;) {
157 if (aOnLeaveNode) {
158 aOnLeaveNode(aNode, aClosure);
161 aNode->GetParentNode(getter_AddRefs(next));
162 if (next == aRoot || ! next)
163 return nsnull;
164 aNode = next;
166 aNode->GetNextSibling(getter_AddRefs(next));
167 if (next)
168 return next;
172 // aNode is not a text node. Find the first text node starting at aNode/aOffset
173 // in a preorder DOM traversal.
174 static nsIDOMNode*
175 FindNextTextNode(nsIDOMNode* aNode, PRInt32 aOffset, nsIDOMNode* aRoot)
177 NS_PRECONDITION(aNode, "Null starting node?");
178 NS_ASSERTION(!IsTextNode(aNode), "FindNextTextNode should start with a non-text node");
180 nsIDOMNode* checkNode;
181 // Need to start at the aOffset'th child
182 nsCOMPtr<nsIDOMNode> child;
183 aNode->GetFirstChild(getter_AddRefs(child));
184 while (child && aOffset > 0) {
185 nsCOMPtr<nsIDOMNode> next;
186 child->GetNextSibling(getter_AddRefs(next));
187 child.swap(next);
188 --aOffset;
190 if (child) {
191 checkNode = child;
192 } else {
193 // aOffset was beyond the end of the child list. Start checking at the next
194 // node after the last child, or aNode if there are no children.
195 aNode->GetLastChild(getter_AddRefs(child));
196 if (child) {
197 checkNode = FindNextNode(child, aRoot);
198 } else {
199 checkNode = FindNextNode(aNode, aRoot);
203 while (checkNode && !IsTextNode(checkNode)) {
204 checkNode = FindNextNode(checkNode, aRoot);
206 return checkNode;
209 // mozInlineSpellWordUtil::SetEnd
211 // We have two ranges "hard" and "soft". The hard boundary is simply
212 // the scope of the root node. The soft boundary is that which is set
213 // by the caller of this class by calling this function. If this function is
214 // not called, the soft boundary is the same as the hard boundary.
216 // When we reach the soft boundary (mSoftEnd), we keep
217 // going until we reach the end of a word. This allows the caller to set the
218 // end of the range to anything, and we will always check whole multiples of
219 // words. When we reach the hard boundary we stop no matter what.
221 // There is no beginning soft boundary. This is because we only go to the
222 // previous node once, when finding the previous word boundary in
223 // SetPosition(). You might think of the soft boundary as being this initial
224 // position.
226 nsresult
227 mozInlineSpellWordUtil::SetEnd(nsIDOMNode* aEndNode, PRInt32 aEndOffset)
229 NS_PRECONDITION(aEndNode, "Null end node?");
231 NS_ASSERTION(mRootNode, "Not initialized");
233 InvalidateWords();
235 if (!IsTextNode(aEndNode)) {
236 // End at the start of the first text node after aEndNode/aEndOffset.
237 aEndNode = FindNextTextNode(aEndNode, aEndOffset, mRootNode);
238 aEndOffset = 0;
240 mSoftEnd = NodeOffset(aEndNode, aEndOffset);
241 return NS_OK;
244 nsresult
245 mozInlineSpellWordUtil::SetPosition(nsIDOMNode* aNode, PRInt32 aOffset)
247 InvalidateWords();
249 if (!IsTextNode(aNode)) {
250 // Start at the start of the first text node after aNode/aOffset.
251 aNode = FindNextTextNode(aNode, aOffset, mRootNode);
252 aOffset = 0;
254 mSoftBegin = NodeOffset(aNode, aOffset);
256 EnsureWords();
258 PRInt32 textOffset = MapDOMPositionToSoftTextOffset(mSoftBegin);
259 if (textOffset < 0)
260 return NS_OK;
261 mNextWordIndex = FindRealWordContaining(textOffset, HINT_END, PR_TRUE);
262 return NS_OK;
265 void
266 mozInlineSpellWordUtil::EnsureWords()
268 if (mSoftTextValid)
269 return;
270 BuildSoftText();
271 BuildRealWords();
272 mSoftTextValid = PR_TRUE;
275 nsresult
276 mozInlineSpellWordUtil::MakeRangeForWord(const RealWord& aWord, nsIDOMRange** aRange)
278 NodeOffset begin = MapSoftTextOffsetToDOMPosition(aWord.mSoftTextOffset, HINT_BEGIN);
279 NodeOffset end = MapSoftTextOffsetToDOMPosition(aWord.EndOffset(), HINT_END);
280 return MakeRange(begin, end, aRange);
283 // mozInlineSpellWordUtil::GetRangeForWord
285 nsresult
286 mozInlineSpellWordUtil::GetRangeForWord(nsIDOMNode* aWordNode,
287 PRInt32 aWordOffset,
288 nsIDOMRange** aRange)
290 // Set our soft end and start
291 NodeOffset pt = NodeOffset(aWordNode, aWordOffset);
293 InvalidateWords();
294 mSoftBegin = mSoftEnd = pt;
295 EnsureWords();
297 PRInt32 offset = MapDOMPositionToSoftTextOffset(pt);
298 if (offset < 0)
299 return MakeRange(pt, pt, aRange);
300 PRInt32 wordIndex = FindRealWordContaining(offset, HINT_BEGIN, PR_FALSE);
301 if (wordIndex < 0)
302 return MakeRange(pt, pt, aRange);
303 return MakeRangeForWord(mRealWords[wordIndex], aRange);
306 // This is to fix characters that the spellchecker may not like
307 static void
308 NormalizeWord(const nsSubstring& aInput, PRInt32 aPos, PRInt32 aLen, nsAString& aOutput)
310 aOutput.Truncate();
311 for (PRInt32 i = 0; i < aLen; i++) {
312 PRUnichar ch = aInput.CharAt(i + aPos);
314 // remove ignorable characters from the word
315 if (IsIgnorableCharacter(ch))
316 continue;
318 // the spellchecker doesn't handle curly apostrophes in all languages
319 if (ch == 0x2019) { // RIGHT SINGLE QUOTATION MARK
320 ch = '\'';
323 aOutput.Append(ch);
327 // mozInlineSpellWordUtil::GetNextWord
329 // FIXME-optimization: we shouldn't have to generate a range every single
330 // time. It would be better if the inline spellchecker didn't require a
331 // range unless the word was misspelled. This may or may not be possible.
333 nsresult
334 mozInlineSpellWordUtil::GetNextWord(nsAString& aText, nsIDOMRange** aRange,
335 PRBool* aSkipChecking)
337 #ifdef DEBUG_SPELLCHECK
338 printf("GetNextWord called; mNextWordIndex=%d\n", mNextWordIndex);
339 #endif
341 if (mNextWordIndex < 0 ||
342 mNextWordIndex >= PRInt32(mRealWords.Length())) {
343 mNextWordIndex = -1;
344 *aRange = nsnull;
345 *aSkipChecking = PR_TRUE;
346 return NS_OK;
349 const RealWord& word = mRealWords[mNextWordIndex];
350 nsresult rv = MakeRangeForWord(word, aRange);
351 NS_ENSURE_SUCCESS(rv, rv);
352 ++mNextWordIndex;
353 *aSkipChecking = !word.mCheckableWord;
354 ::NormalizeWord(mSoftText, word.mSoftTextOffset, word.mLength, aText);
356 #ifdef DEBUG_SPELLCHECK
357 printf("GetNextWord returning: %s (skip=%d)\n",
358 NS_ConvertUTF16toUTF8(aText).get(), *aSkipChecking);
359 #endif
361 return NS_OK;
364 // mozInlineSpellWordUtil::MakeRange
366 // Convenience function for creating a range over the current document.
368 nsresult
369 mozInlineSpellWordUtil::MakeRange(NodeOffset aBegin, NodeOffset aEnd,
370 nsIDOMRange** aRange)
372 if (! mDOMDocumentRange)
373 return NS_ERROR_NOT_INITIALIZED;
375 nsresult rv = mDOMDocumentRange->CreateRange(aRange);
376 NS_ENSURE_SUCCESS(rv, rv);
378 rv = (*aRange)->SetStart(aBegin.mNode, aBegin.mOffset);
379 NS_ENSURE_SUCCESS(rv, rv);
380 rv = (*aRange)->SetEnd(aEnd.mNode, aEnd.mOffset);
381 NS_ENSURE_SUCCESS(rv, rv);
383 return NS_OK;
386 /*********** DOM text extraction ************/
388 // IsDOMWordSeparator
390 // Determines if the given character should be considered as a DOM Word
391 // separator. Basically, this is whitespace, although it could also have
392 // certain punctuation that we know ALWAYS breaks words. This is important.
393 // For example, we can't have any punctuation that could appear in a URL
394 // or email address in this, because those need to always fit into a single
395 // DOM word.
397 static PRBool
398 IsDOMWordSeparator(PRUnichar ch)
400 // simple spaces
401 if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
402 return PR_TRUE;
404 // complex spaces - check only if char isn't ASCII (uncommon)
405 if (ch >= 0xA0 &&
406 (ch == 0x00A0 || // NO-BREAK SPACE
407 ch == 0x2002 || // EN SPACE
408 ch == 0x2003 || // EM SPACE
409 ch == 0x2009 || // THIN SPACE
410 ch == 0x200C || // ZERO WIDTH NON-JOINER
411 ch == 0x3000)) // IDEOGRAPHIC SPACE
412 return PR_TRUE;
414 // otherwise not a space
415 return PR_FALSE;
418 static PRBool
419 IsBRElement(nsIDOMNode* aNode)
421 nsresult rv;
422 nsCOMPtr<nsIDOMHTMLBRElement> elt = do_QueryInterface(aNode, &rv);
423 return NS_SUCCEEDED(rv);
426 static void
427 GetNodeText(nsIDOMNode* aNode, nsAutoString& aText)
429 nsresult rv = aNode->GetNodeValue(aText);
430 NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to get node text");
433 // Find the previous node in the DOM tree in preorder. This isn't fast because
434 // one call to GetPrevSibling can be O(N) in the number of siblings...
435 static nsIDOMNode*
436 FindPrevNode(nsIDOMNode* aNode, nsIDOMNode* aRoot)
438 if (aNode == aRoot)
439 return nsnull;
441 nsCOMPtr<nsIDOMNode> prev;
442 aNode->GetPreviousSibling(getter_AddRefs(prev));
443 if (prev) {
444 for (;;) {
445 nsCOMPtr<nsIDOMNode> lastChild;
446 prev->GetLastChild(getter_AddRefs(lastChild));
447 if (!lastChild)
448 return prev;
449 prev = lastChild;
453 // No prev sibling. So we are the first child of our parent, if any. Our
454 // parent is our previous node.
455 aNode->GetParentNode(getter_AddRefs(prev));
456 return prev;
460 * Check if there's a DOM word separator before aBeforeOffset in this node.
461 * Always returns PR_TRUE if it's a BR element.
462 * aSeparatorOffset is set to the index of the last separator if any is found
463 * (0 for BR elements).
465 static PRBool
466 ContainsDOMWordSeparator(nsIDOMNode* aNode, PRInt32 aBeforeOffset,
467 PRInt32* aSeparatorOffset)
469 if (IsBRElement(aNode)) {
470 *aSeparatorOffset = 0;
471 return PR_TRUE;
474 if (!IsTextNode(aNode))
475 return PR_FALSE;
477 nsAutoString str;
478 GetNodeText(aNode, str);
479 for (PRInt32 i = PR_MIN(aBeforeOffset, PRInt32(str.Length())) - 1; i >= 0; --i) {
480 if (IsDOMWordSeparator(str.CharAt(i))) {
481 *aSeparatorOffset = i;
482 return PR_TRUE;
485 return PR_FALSE;
488 static PRBool
489 IsBreakElement(nsIDOMViewCSS* aDocView, nsIDOMNode* aNode)
491 nsCOMPtr<nsIDOMElement> element = do_QueryInterface(aNode);
492 if (!element)
493 return PR_FALSE;
495 if (IsBRElement(aNode))
496 return PR_TRUE;
498 nsCOMPtr<nsIDOMCSSStyleDeclaration> style;
499 aDocView->GetComputedStyle(element, EmptyString(), getter_AddRefs(style));
500 if (!style)
501 return PR_FALSE;
503 #ifdef DEBUG_SPELLCHECK
504 printf(" searching element %p\n", (void*)aNode);
505 #endif
507 nsAutoString display;
508 style->GetPropertyValue(NS_LITERAL_STRING("display"), display);
509 #ifdef DEBUG_SPELLCHECK
510 printf(" display=\"%s\"\n", NS_ConvertUTF16toUTF8(display).get());
511 #endif
512 if (!display.EqualsLiteral("inline"))
513 return PR_TRUE;
515 nsAutoString position;
516 style->GetPropertyValue(NS_LITERAL_STRING("position"), position);
517 #ifdef DEBUG_SPELLCHECK
518 printf(" position=%s\n", NS_ConvertUTF16toUTF8(position).get());
519 #endif
520 if (!position.EqualsLiteral("static"))
521 return PR_TRUE;
523 // XXX What about floats? What else?
524 return PR_FALSE;
527 struct CheckLeavingBreakElementClosure {
528 nsIDOMViewCSS* mDocView;
529 PRPackedBool mLeftBreakElement;
532 static void
533 CheckLeavingBreakElement(nsIDOMNode* aNode, void* aClosure)
535 CheckLeavingBreakElementClosure* cl =
536 static_cast<CheckLeavingBreakElementClosure*>(aClosure);
537 if (!cl->mLeftBreakElement && IsBreakElement(cl->mDocView, aNode)) {
538 cl->mLeftBreakElement = PR_TRUE;
542 void
543 mozInlineSpellWordUtil::NormalizeWord(nsSubstring& aWord)
545 nsAutoString result;
546 ::NormalizeWord(aWord, 0, aWord.Length(), result);
547 aWord = result;
550 void
551 mozInlineSpellWordUtil::BuildSoftText()
553 // First we have to work backwards from mSoftStart to find a text node
554 // containing a DOM word separator, a non-inline-element
555 // boundary, or the hard start node. That's where we'll start building the
556 // soft string from.
557 nsIDOMNode* node = mSoftBegin.mNode;
558 PRInt32 firstOffsetInNode = 0;
559 PRInt32 checkBeforeOffset = mSoftBegin.mOffset;
560 while (node) {
561 if (ContainsDOMWordSeparator(node, checkBeforeOffset, &firstOffsetInNode))
562 break;
563 checkBeforeOffset = PR_INT32_MAX;
564 if (IsBreakElement(mCSSView, node)) {
565 // Since FindPrevNode follows tree *preorder*, we're about to traverse
566 // up out of 'node'. Since node induces breaks (e.g., it's a block),
567 // don't bother trying to look outside it, just stop now.
568 break;
570 node = FindPrevNode(node, mRootNode);
573 // Now build up the string moving forward through the DOM until we reach
574 // the soft end and *then* see a DOM word separator, a non-inline-element
575 // boundary, or the hard end node.
576 mSoftText.Truncate();
577 mSoftTextDOMMapping.Clear();
578 PRBool seenSoftEnd = PR_FALSE;
579 // Leave this outside the loop so large heap string allocations can be reused
580 // across iterations
581 nsAutoString str;
582 while (node) {
583 if (node == mSoftEnd.mNode) {
584 seenSoftEnd = PR_TRUE;
587 PRBool exit = PR_FALSE;
588 if (IsTextNode(node)) {
589 GetNodeText(node, str);
590 PRInt32 lastOffsetInNode = str.Length();
592 if (seenSoftEnd) {
593 // check whether we can stop after this
594 for (PRInt32 i = node == mSoftEnd.mNode ? mSoftEnd.mOffset : 0;
595 i < PRInt32(str.Length()); ++i) {
596 if (IsDOMWordSeparator(str.CharAt(i))) {
597 exit = PR_TRUE;
598 // stop at the first separator after the soft end point
599 lastOffsetInNode = i;
600 break;
605 if (firstOffsetInNode < lastOffsetInNode) {
606 PRInt32 len = lastOffsetInNode - firstOffsetInNode;
607 mSoftTextDOMMapping.AppendElement(
608 DOMTextMapping(NodeOffset(node, firstOffsetInNode), mSoftText.Length(), len));
609 mSoftText.Append(Substring(str, firstOffsetInNode, len));
612 firstOffsetInNode = 0;
615 if (exit)
616 break;
618 CheckLeavingBreakElementClosure closure = { mCSSView, PR_FALSE };
619 node = FindNextNode(node, mRootNode, CheckLeavingBreakElement, &closure);
620 if (closure.mLeftBreakElement || (node && IsBreakElement(mCSSView, node))) {
621 // We left, or are entering, a break element (e.g., block). Maybe we can
622 // stop now.
623 if (seenSoftEnd)
624 break;
625 // Record the break
626 mSoftText.Append(' ');
630 #ifdef DEBUG_SPELLCHECK
631 printf("Got DOM string: %s\n", NS_ConvertUTF16toUTF8(mSoftText).get());
632 #endif
635 void
636 mozInlineSpellWordUtil::BuildRealWords()
638 // This is pretty simple. We just have to walk mSoftText, tokenizing it
639 // into "real words".
640 // We do an outer traversal of words delimited by IsDOMWordSeparator, calling
641 // SplitDOMWord on each of those DOM words
642 PRInt32 wordStart = -1;
643 mRealWords.Clear();
644 for (PRInt32 i = 0; i < PRInt32(mSoftText.Length()); ++i) {
645 if (IsDOMWordSeparator(mSoftText.CharAt(i))) {
646 if (wordStart >= 0) {
647 SplitDOMWord(wordStart, i);
648 wordStart = -1;
650 } else {
651 if (wordStart < 0) {
652 wordStart = i;
656 if (wordStart >= 0) {
657 SplitDOMWord(wordStart, mSoftText.Length());
661 /*********** DOM/realwords<->mSoftText mapping functions ************/
663 PRInt32
664 mozInlineSpellWordUtil::MapDOMPositionToSoftTextOffset(NodeOffset aNodeOffset)
666 if (!mSoftTextValid) {
667 NS_ERROR("Soft text must be valid if we're to map into it");
668 return -1;
671 for (PRInt32 i = 0; i < PRInt32(mSoftTextDOMMapping.Length()); ++i) {
672 const DOMTextMapping& map = mSoftTextDOMMapping[i];
673 if (map.mNodeOffset.mNode == aNodeOffset.mNode) {
674 // Allow offsets at either end of the string, in particular, allow the
675 // offset that's at the end of the contributed string
676 PRInt32 offsetInContributedString =
677 aNodeOffset.mOffset - map.mNodeOffset.mOffset;
678 if (offsetInContributedString >= 0 &&
679 offsetInContributedString <= map.mLength)
680 return map.mSoftTextOffset + offsetInContributedString;
681 return -1;
684 return -1;
687 mozInlineSpellWordUtil::NodeOffset
688 mozInlineSpellWordUtil::MapSoftTextOffsetToDOMPosition(PRInt32 aSoftTextOffset,
689 DOMMapHint aHint)
691 NS_ASSERTION(mSoftTextValid, "Soft text must be valid if we're to map out of it");
692 if (!mSoftTextValid)
693 return NodeOffset(nsnull, -1);
695 // The invariant is that the range start..end includes the last mapping,
696 // if any, such that mSoftTextOffset <= aSoftTextOffset
697 PRInt32 start = 0;
698 PRInt32 end = mSoftTextDOMMapping.Length();
699 while (end - start >= 2) {
700 PRInt32 mid = (start + end)/2;
701 const DOMTextMapping& map = mSoftTextDOMMapping[mid];
702 if (map.mSoftTextOffset > aSoftTextOffset) {
703 end = mid;
704 } else {
705 start = mid;
709 if (start >= end)
710 return NodeOffset(nsnull, -1);
712 // 'start' is now the last mapping, if any, such that
713 // mSoftTextOffset <= aSoftTextOffset.
714 // If we're doing HINT_END, then we may want to return the end of the
715 // the previous mapping instead of the start of this mapping
716 if (aHint == HINT_END && start > 0) {
717 const DOMTextMapping& map = mSoftTextDOMMapping[start - 1];
718 if (map.mSoftTextOffset + map.mLength == aSoftTextOffset)
719 return NodeOffset(map.mNodeOffset.mNode, map.mNodeOffset.mOffset + map.mLength);
722 // We allow ourselves to return the end of this mapping even if we're
723 // doing HINT_START. This will only happen if there is no mapping which this
724 // point is the start of. I'm not 100% sure this is OK...
725 const DOMTextMapping& map = mSoftTextDOMMapping[start];
726 PRInt32 offset = aSoftTextOffset - map.mSoftTextOffset;
727 if (offset >= 0 && offset <= map.mLength)
728 return NodeOffset(map.mNodeOffset.mNode, map.mNodeOffset.mOffset + offset);
730 return NodeOffset(nsnull, -1);
733 PRInt32
734 mozInlineSpellWordUtil::FindRealWordContaining(PRInt32 aSoftTextOffset,
735 DOMMapHint aHint, PRBool aSearchForward)
737 NS_ASSERTION(mSoftTextValid, "Soft text must be valid if we're to map out of it");
738 if (!mSoftTextValid)
739 return -1;
741 // The invariant is that the range start..end includes the last word,
742 // if any, such that mSoftTextOffset <= aSoftTextOffset
743 PRInt32 start = 0;
744 PRInt32 end = mRealWords.Length();
745 while (end - start >= 2) {
746 PRInt32 mid = (start + end)/2;
747 const RealWord& word = mRealWords[mid];
748 if (word.mSoftTextOffset > aSoftTextOffset) {
749 end = mid;
750 } else {
751 start = mid;
755 if (start >= end)
756 return -1;
758 // 'start' is now the last word, if any, such that
759 // mSoftTextOffset <= aSoftTextOffset.
760 // If we're doing HINT_END, then we may want to return the end of the
761 // the previous word instead of the start of this word
762 if (aHint == HINT_END && start > 0) {
763 const RealWord& word = mRealWords[start - 1];
764 if (word.mSoftTextOffset + word.mLength == aSoftTextOffset)
765 return start - 1;
768 // We allow ourselves to return the end of this word even if we're
769 // doing HINT_START. This will only happen if there is no word which this
770 // point is the start of. I'm not 100% sure this is OK...
771 const RealWord& word = mRealWords[start];
772 PRInt32 offset = aSoftTextOffset - word.mSoftTextOffset;
773 if (offset >= 0 && offset <= word.mLength)
774 return start;
776 if (aSearchForward) {
777 if (mRealWords[0].mSoftTextOffset > aSoftTextOffset) {
778 // All words have mSoftTextOffset > aSoftTextOffset
779 return 0;
781 // 'start' is the last word such that mSoftTextOffset <= aSoftTextOffset.
782 // Word start+1, if it exists, will be the first with
783 // mSoftTextOffset > aSoftTextOffset.
784 if (start + 1 < PRInt32(mRealWords.Length()))
785 return start + 1;
788 return -1;
791 /*********** Word Splitting ************/
793 // classifies a given character in the DOM word
794 enum CharClass {
795 CHAR_CLASS_WORD,
796 CHAR_CLASS_SEPARATOR,
797 CHAR_CLASS_END_OF_INPUT };
799 // Encapsulates DOM-word to real-word splitting
800 struct WordSplitState
802 mozInlineSpellWordUtil* mWordUtil;
803 const nsDependentSubstring mDOMWordText;
804 PRInt32 mDOMWordOffset;
805 CharClass mCurCharClass;
807 WordSplitState(mozInlineSpellWordUtil* aWordUtil,
808 const nsString& aString, PRInt32 aStart, PRInt32 aLen)
809 : mWordUtil(aWordUtil), mDOMWordText(aString, aStart, aLen),
810 mDOMWordOffset(0), mCurCharClass(CHAR_CLASS_END_OF_INPUT) {}
812 CharClass ClassifyCharacter(PRInt32 aIndex, PRBool aRecurse) const;
813 void Advance();
814 void AdvanceThroughSeparators();
815 void AdvanceThroughWord();
817 // Finds special words like email addresses and URLs that may start at the
818 // current position, and returns their length, or 0 if not found. This allows
819 // arbitrary word breaking rules to be used for these special entities, as
820 // long as they can not contain whitespace.
821 PRInt32 FindSpecialWord();
823 // Similar to FindSpecialWord except that this takes a split word as
824 // input. This checks for things that do not require special word-breaking
825 // rules.
826 PRBool ShouldSkipWord(PRInt32 aStart, PRInt32 aLength);
829 // WordSplitState::ClassifyCharacter
831 CharClass
832 WordSplitState::ClassifyCharacter(PRInt32 aIndex, PRBool aRecurse) const
834 NS_ASSERTION(aIndex >= 0 && aIndex <= PRInt32(mDOMWordText.Length()),
835 "Index out of range");
836 if (aIndex == PRInt32(mDOMWordText.Length()))
837 return CHAR_CLASS_SEPARATOR;
839 // this will classify the character, we want to treat "ignorable" characters
840 // such as soft hyphens as word characters.
841 nsIUGenCategory::nsUGenCategory
842 charCategory = mWordUtil->GetCategories()->Get(PRUint32(mDOMWordText[aIndex]));
843 if (charCategory == nsIUGenCategory::kLetter ||
844 IsIgnorableCharacter(mDOMWordText[aIndex]))
845 return CHAR_CLASS_WORD;
847 // If conditional punctuation is surrounded immediately on both sides by word
848 // characters it also counts as a word character.
849 if (IsConditionalPunctuation(mDOMWordText[aIndex])) {
850 if (!aRecurse) {
851 // not allowed to look around, this punctuation counts like a separator
852 return CHAR_CLASS_SEPARATOR;
855 // check the left-hand character
856 if (aIndex == 0)
857 return CHAR_CLASS_SEPARATOR;
858 if (ClassifyCharacter(aIndex - 1, false) != CHAR_CLASS_WORD)
859 return CHAR_CLASS_SEPARATOR;
861 // now we know left char is a word-char, check the right-hand character
862 if (aIndex == PRInt32(mDOMWordText.Length()) - 1)
863 return CHAR_CLASS_SEPARATOR;
864 if (ClassifyCharacter(aIndex + 1, false) != CHAR_CLASS_WORD)
865 return CHAR_CLASS_SEPARATOR;
867 // char on either side is a word, this counts as a word
868 return CHAR_CLASS_WORD;
871 // all other punctuation
872 if (charCategory == nsIUGenCategory::kSeparator ||
873 charCategory == nsIUGenCategory::kOther ||
874 charCategory == nsIUGenCategory::kPunctuation ||
875 charCategory == nsIUGenCategory::kSymbol)
876 return CHAR_CLASS_SEPARATOR;
878 // any other character counts as a word
879 return CHAR_CLASS_WORD;
883 // WordSplitState::Advance
885 void
886 WordSplitState::Advance()
888 NS_ASSERTION(mDOMWordOffset >= 0, "Negative word index");
889 NS_ASSERTION(mDOMWordOffset < (PRInt32)mDOMWordText.Length(),
890 "Length beyond end");
892 mDOMWordOffset ++;
893 if (mDOMWordOffset >= (PRInt32)mDOMWordText.Length())
894 mCurCharClass = CHAR_CLASS_END_OF_INPUT;
895 else
896 mCurCharClass = ClassifyCharacter(mDOMWordOffset, PR_TRUE);
900 // WordSplitState::AdvanceThroughSeparators
902 void
903 WordSplitState::AdvanceThroughSeparators()
905 while (mCurCharClass == CHAR_CLASS_SEPARATOR)
906 Advance();
909 // WordSplitState::AdvanceThroughWord
911 void
912 WordSplitState::AdvanceThroughWord()
914 while (mCurCharClass == CHAR_CLASS_WORD)
915 Advance();
919 // WordSplitState::FindSpecialWord
921 PRInt32
922 WordSplitState::FindSpecialWord()
924 PRInt32 i;
926 // Search for email addresses. We simply define these as any sequence of
927 // characters with an '@' character in the middle. The DOM word is already
928 // split on whitepace, so we know that everything to the end is the address
930 // Also look for periods, this tells us if we want to run the URL finder.
931 PRBool foundDot = PR_FALSE;
932 PRInt32 firstColon = -1;
933 for (i = mDOMWordOffset;
934 i < PRInt32(mDOMWordText.Length()); i ++) {
935 if (mDOMWordText[i] == '@') {
936 // only accept this if there are unambiguous word characters (don't bother
937 // recursing to disambiguate apostrophes) on each side. This prevents
938 // classifying, e.g. "@home" as an email address
940 // Use this condition to only accept words with '@' in the middle of
941 // them. It works, but the inlinespellcker doesn't like this. The problem
942 // is that you type "fhsgfh@" that's a misspelled word followed by a
943 // symbol, but when you type another letter "fhsgfh@g" that first word
944 // need to be unmarked misspelled. It doesn't do this. it only checks the
945 // current position for potentially removing a spelling range.
946 if (i > 0 && ClassifyCharacter(i - 1, PR_FALSE) == CHAR_CLASS_WORD &&
947 i < (PRInt32)mDOMWordText.Length() - 1 &&
948 ClassifyCharacter(i + 1, PR_FALSE) == CHAR_CLASS_WORD)
950 return mDOMWordText.Length() - mDOMWordOffset;
951 } else if (mDOMWordText[i] == '.' && ! foundDot &&
952 i > 0 && i < (PRInt32)mDOMWordText.Length() - 1) {
953 // we found a period not at the end, we should check harder for URLs
954 foundDot = PR_TRUE;
955 } else if (mDOMWordText[i] == ':' && firstColon < 0) {
956 firstColon = i;
960 // If the first colon is followed by a slash, consider it a URL
961 // This will catch things like asdf://foo.com
962 if (firstColon >= 0 && firstColon < (PRInt32)mDOMWordText.Length() - 1 &&
963 mDOMWordText[firstColon + 1] == '/') {
964 return mDOMWordText.Length() - mDOMWordOffset;
967 // Check the text before the first colon against some known protocols. It
968 // is impossible to check against all protocols, especially since you can
969 // plug in new protocols. We also don't want to waste time here checking
970 // against a lot of obscure protocols.
971 if (firstColon > mDOMWordOffset) {
972 nsString protocol(Substring(mDOMWordText, mDOMWordOffset,
973 firstColon - mDOMWordOffset));
974 if (protocol.EqualsIgnoreCase("http") ||
975 protocol.EqualsIgnoreCase("https") ||
976 protocol.EqualsIgnoreCase("news") ||
977 protocol.EqualsIgnoreCase("ftp") ||
978 protocol.EqualsIgnoreCase("file") ||
979 protocol.EqualsIgnoreCase("javascript") ||
980 protocol.EqualsIgnoreCase("ftp")) {
981 return mDOMWordText.Length() - mDOMWordOffset;
985 // not anything special
986 return -1;
989 // WordSplitState::ShouldSkipWord
991 PRBool
992 WordSplitState::ShouldSkipWord(PRInt32 aStart, PRInt32 aLength)
994 PRInt32 last = aStart + aLength;
996 // check to see if the word contains a digit
997 for (PRInt32 i = aStart; i < last; i ++) {
998 PRUnichar ch = mDOMWordText[i];
999 // XXX Shouldn't this be something a lot more complex, Unicode-based?
1000 if (ch >= '0' && ch <= '9')
1001 return PR_TRUE;
1004 // not special
1005 return PR_FALSE;
1008 // mozInlineSpellWordUtil::SplitDOMWord
1010 void
1011 mozInlineSpellWordUtil::SplitDOMWord(PRInt32 aStart, PRInt32 aEnd)
1013 WordSplitState state(this, mSoftText, aStart, aEnd - aStart);
1014 state.mCurCharClass = state.ClassifyCharacter(0, PR_TRUE);
1016 while (state.mCurCharClass != CHAR_CLASS_END_OF_INPUT) {
1017 state.AdvanceThroughSeparators();
1018 if (state.mCurCharClass == CHAR_CLASS_END_OF_INPUT)
1019 break;
1021 PRInt32 specialWordLength = state.FindSpecialWord();
1022 if (specialWordLength > 0) {
1023 mRealWords.AppendElement(
1024 RealWord(aStart + state.mDOMWordOffset, specialWordLength, PR_FALSE));
1026 // skip the special word
1027 state.mDOMWordOffset += specialWordLength;
1028 if (state.mDOMWordOffset + aStart >= aEnd)
1029 state.mCurCharClass = CHAR_CLASS_END_OF_INPUT;
1030 else
1031 state.mCurCharClass = state.ClassifyCharacter(state.mDOMWordOffset, PR_TRUE);
1032 continue;
1035 // save the beginning of the word
1036 PRInt32 wordOffset = state.mDOMWordOffset;
1038 // find the end of the word
1039 state.AdvanceThroughWord();
1040 PRInt32 wordLen = state.mDOMWordOffset - wordOffset;
1041 mRealWords.AppendElement(
1042 RealWord(aStart + wordOffset, wordLen,
1043 !state.ShouldSkipWord(wordOffset, wordLen)));