6e50c37ca0a601fd9881533b4e003504817e1069
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / web / mac / WebSubstringUtil.mm
1 /*
2  * Copyright (C) 2005, 2007, 2008 Apple Inc. All rights reserved.
3  * Copyright (C) 2011 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include "config.h"
33 #include "WebSubstringUtil.h"
34
35 #import <Cocoa/Cocoa.h>
36
37 #include "WebFrameImpl.h"
38 #include "bindings/v8/ExceptionStatePlaceholder.h"
39 #include "core/dom/Document.h"
40 #include "core/dom/Element.h"
41 #include "core/dom/Node.h"
42 #include "core/dom/Range.h"
43 #include "core/editing/FrameSelection.h"
44 #include "core/editing/PlainTextRange.h"
45 #include "core/editing/TextIterator.h"
46 #include "core/html/HTMLElement.h"
47 #include "core/frame/LocalFrame.h"
48 #include "core/frame/FrameView.h"
49 #include "core/rendering/RenderObject.h"
50 #include "core/rendering/style/RenderStyle.h"
51 #include "core/rendering/HitTestResult.h"
52 #include "platform/fonts/Font.h"
53 #include "platform/mac/ColorMac.h"
54 #include "public/platform/WebRect.h"
55 #include "public/web/WebHitTestResult.h"
56 #include "public/web/WebRange.h"
57 #include "public/web/WebView.h"
58
59 using namespace WebCore;
60
61 static NSAttributedString* attributedSubstringFromRange(const Range* range)
62 {
63     NSMutableAttributedString* string = [[NSMutableAttributedString alloc] init];
64     NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
65     size_t length = range->endOffset() - range->startOffset();
66
67     unsigned position = 0;
68     for (TextIterator it(range); !it.atEnd() && [string length] < length; it.advance()) {
69         unsigned numCharacters = it.length();
70         if (!numCharacters)
71             continue;
72
73         Node* container = it.range()->startContainer(IGNORE_EXCEPTION);
74         RenderObject* renderer = container->renderer();
75         ASSERT(renderer);
76         if (!renderer)
77             continue;
78
79         RenderStyle* style = renderer->style();
80         NSFont* font = style->font().primaryFont()->getNSFont();
81         // If the platform font can't be loaded, it's likely that the site is
82         // using a web font. For now, just use the default font instead.
83         // TODO(rsesek): Change the font activation flags to allow other processes
84         // to use the font.
85         if (!font)
86           font = [NSFont systemFontOfSize:style->font().fontDescription().computedSize()];
87         [attrs setObject:font forKey:NSFontAttributeName];
88
89         if (style->visitedDependentColor(CSSPropertyColor).alpha())
90             [attrs setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
91         else
92             [attrs removeObjectForKey:NSForegroundColorAttributeName];
93         if (style->visitedDependentColor(CSSPropertyBackgroundColor).alpha())
94             [attrs setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
95         else
96             [attrs removeObjectForKey:NSBackgroundColorAttributeName];
97
98         Vector<UChar> characters;
99         it.appendTextTo(characters);
100         NSString* substring =
101             [[[NSString alloc] initWithCharacters:characters.data()
102                                            length:characters.size()] autorelease];
103         [string replaceCharactersInRange:NSMakeRange(position, 0)
104                               withString:substring];
105         [string setAttributes:attrs range:NSMakeRange(position, numCharacters)];
106         position += numCharacters;
107     }
108     return [string autorelease];
109 }
110
111 namespace blink {
112
113 NSAttributedString* WebSubstringUtil::attributedWordAtPoint(WebView* view, WebPoint point, WebPoint& baselinePoint)
114 {
115     HitTestResult result = view->hitTestResultAt(point);
116     LocalFrame* frame = result.targetNode()->document().frame();
117     FrameView* frameView = frame->view();
118
119     RefPtr<Range> range = frame->rangeForPoint(result.roundedPointInInnerNodeFrame());
120     if (!range)
121         return nil;
122
123     // Expand to word under point.
124     VisibleSelection selection(range.get());
125     selection.expandUsingGranularity(WordGranularity);
126     RefPtr<Range> wordRange = selection.toNormalizedRange();
127
128     // Convert to NSAttributedString.
129     NSAttributedString* string = attributedSubstringFromRange(wordRange.get());
130
131     // Compute bottom left corner and convert to AppKit coordinates.
132     IntRect stringRect = enclosingIntRect(wordRange->boundingRect());
133     IntPoint stringPoint = frameView->contentsToWindow(stringRect).minXMaxYCorner();
134     stringPoint.setY(frameView->height() - stringPoint.y());
135
136     // Adjust for the font's descender. AppKit wants the baseline point.
137     if ([string length]) {
138         NSDictionary* attributes = [string attributesAtIndex:0 effectiveRange:NULL];
139         NSFont* font = [attributes objectForKey:NSFontAttributeName];
140         if (font)
141             stringPoint.move(0, ceil(-[font descender]));
142     }
143
144     baselinePoint = stringPoint;
145     return string;
146 }
147
148 NSAttributedString* WebSubstringUtil::attributedSubstringInRange(WebFrame* webFrame, size_t location, size_t length)
149 {
150     LocalFrame* frame = toWebFrameImpl(webFrame)->frame();
151     if (frame->view()->needsLayout())
152         frame->view()->layout();
153
154     Element* editable = frame->selection().rootEditableElementOrDocumentElement();
155     ASSERT(editable);
156     RefPtr<Range> range(PlainTextRange(location, location + length).createRange(*editable));
157     if (!range)
158         return nil;
159
160     return attributedSubstringFromRange(range.get());
161 }
162
163 } // namespace blink