Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / WebKit / Source / web / mac / WebSubstringUtil.mm
blob92121facd292eacd2de662288b309858ff00e434
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  */
32 #include "config.h"
33 #include "public/web/mac/WebSubstringUtil.h"
35 #import <Cocoa/Cocoa.h>
37 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
38 #include "core/dom/Document.h"
39 #include "core/dom/Element.h"
40 #include "core/dom/Node.h"
41 #include "core/dom/Range.h"
42 #include "core/editing/FrameSelection.h"
43 #include "core/editing/PlainTextRange.h"
44 #include "core/editing/iterators/TextIterator.h"
45 #include "core/frame/FrameView.h"
46 #include "core/frame/LocalFrame.h"
47 #include "core/html/HTMLElement.h"
48 #include "core/layout/HitTestResult.h"
49 #include "core/layout/LayoutObject.h"
50 #include "core/style/ComputedStyle.h"
51 #include "platform/fonts/Font.h"
52 #include "platform/mac/ColorMac.h"
53 #include "public/platform/WebRect.h"
54 #include "public/web/WebHitTestResult.h"
55 #include "public/web/WebRange.h"
56 #include "public/web/WebView.h"
57 #include "web/WebLocalFrameImpl.h"
58 #include "web/WebViewImpl.h"
60 using namespace blink;
62 static NSAttributedString* attributedSubstringFromRange(const EphemeralRange& range)
64     NSMutableAttributedString* string = [[NSMutableAttributedString alloc] init];
65     NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
66     size_t length = range.endPosition().computeOffsetInContainerNode() - range.startPosition().computeOffsetInContainerNode();
68     unsigned position = 0;
69     for (TextIterator it(range.startPosition(), range.endPosition()); !it.atEnd() && [string length] < length; it.advance()) {
70         unsigned numCharacters = it.length();
71         if (!numCharacters)
72             continue;
74         Node* container = it.currentContainer();
75         LayoutObject* layoutObject = container->layoutObject();
76         ASSERT(layoutObject);
77         if (!layoutObject)
78             continue;
80         const ComputedStyle* style = layoutObject->style();
81         const FontPlatformData& fontPlatformData = style->font().primaryFont()->platformData();
82         NSFont* font = toNSFont(fontPlatformData.ctFont());
83         // If the platform font can't be loaded, it's likely that the site is
84         // using a web font. For now, just use the default font instead.
85         // TODO(rsesek): Change the font activation flags to allow other processes
86         // to use the font.
87         if (!font)
88           font = [NSFont systemFontOfSize:style->font().fontDescription().computedSize()];
89         [attrs setObject:font forKey:NSFontAttributeName];
91         if (style->visitedDependentColor(CSSPropertyColor).alpha())
92             [attrs setObject:nsColor(style->visitedDependentColor(CSSPropertyColor)) forKey:NSForegroundColorAttributeName];
93         else
94             [attrs removeObjectForKey:NSForegroundColorAttributeName];
95         if (style->visitedDependentColor(CSSPropertyBackgroundColor).alpha())
96             [attrs setObject:nsColor(style->visitedDependentColor(CSSPropertyBackgroundColor)) forKey:NSBackgroundColorAttributeName];
97         else
98             [attrs removeObjectForKey:NSBackgroundColorAttributeName];
100         Vector<UChar> characters;
101         it.text().appendTextTo(characters);
102         NSString* substring =
103             [[[NSString alloc] initWithCharacters:characters.data()
104                                            length:characters.size()] autorelease];
105         [string replaceCharactersInRange:NSMakeRange(position, 0)
106                               withString:substring];
107         [string setAttributes:attrs range:NSMakeRange(position, numCharacters)];
108         position += numCharacters;
109     }
110     return [string autorelease];
113 WebPoint getBaselinePoint(FrameView* frameView, const EphemeralRange& range, NSAttributedString* string)
115     // Compute bottom left corner and convert to AppKit coordinates.
116     // TODO(yosin) We shold avoid to create |Range| object. See crbug.com/529985.
117     IntRect stringRect = enclosingIntRect(createRange(range)->boundingRect());
118     IntPoint stringPoint = stringRect.minXMaxYCorner();
119     stringPoint.setY(frameView->height() - stringPoint.y());
121     // Adjust for the font's descender. AppKit wants the baseline point.
122     if ([string length]) {
123         NSDictionary* attributes = [string attributesAtIndex:0 effectiveRange:NULL];
124         if (NSFont* font = [attributes objectForKey:NSFontAttributeName])
125             stringPoint.move(0, ceil(-[font descender]));
126     }
127     return stringPoint;
130 namespace blink {
132 NSAttributedString* WebSubstringUtil::attributedWordAtPoint(WebView* view, WebPoint point, WebPoint& baselinePoint)
134     HitTestResult result = static_cast<WebViewImpl*>(view)->coreHitTestResultAt(point);
135     if (!result.innerNode())
136         return nil;
137     LocalFrame* frame = result.innerNode()->document().frame();
138     EphemeralRange range = frame->rangeForPoint(result.roundedPointInInnerNodeFrame());
139     if (range.isNull())
140         return nil;
142     // Expand to word under point.
143     VisibleSelection selection(range);
144     selection.expandUsingGranularity(WordGranularity);
145     const EphemeralRange wordRange = selection.toNormalizedEphemeralRange();
147     // Convert to NSAttributedString.
148     NSAttributedString* string = attributedSubstringFromRange(wordRange);
149     baselinePoint = getBaselinePoint(frame->view(), wordRange, string);
150     return string;
153 NSAttributedString* WebSubstringUtil::attributedSubstringInRange(WebLocalFrame* webFrame, size_t location, size_t length)
155     return WebSubstringUtil::attributedSubstringInRange(webFrame, location, length, nil);
158 NSAttributedString* WebSubstringUtil::attributedSubstringInRange(WebLocalFrame* webFrame, size_t location, size_t length, WebPoint* baselinePoint)
160     LocalFrame* frame = toWebLocalFrameImpl(webFrame)->frame();
161     if (frame->view()->needsLayout())
162         frame->view()->layout();
164     Element* editable = frame->selection().rootEditableElementOrDocumentElement();
165     if (!editable)
166         return nil;
167     const EphemeralRange ephemeralRange(PlainTextRange(location, location + length).createRange(*editable));
168     if (ephemeralRange.isNull())
169         return nil;
171     NSAttributedString* result = attributedSubstringFromRange(ephemeralRange);
172     if (baselinePoint)
173         *baselinePoint = getBaselinePoint(frame->view(), ephemeralRange, result);
174     return result;
177 } // namespace blink