1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/strings/sys_string_conversions.h"
6#import "content/browser/renderer_host/render_widget_host_view_mac_dictionary_helper.h"
7#import "content/browser/renderer_host/render_widget_host_view_mac.h"
8
9namespace content {
10
11RenderWidgetHostViewMacDictionaryHelper::
12    RenderWidgetHostViewMacDictionaryHelper(RenderWidgetHostView* view)
13    : view_(static_cast<RenderWidgetHostViewMac*>(view)),
14      target_view_(static_cast<RenderWidgetHostViewMac*>(view)) {
15}
16
17void RenderWidgetHostViewMacDictionaryHelper::SetTargetView(
18    RenderWidgetHostView* target_view) {
19  target_view_ = static_cast<RenderWidgetHostViewMac*>(target_view);
20}
21
22void RenderWidgetHostViewMacDictionaryHelper::ShowDefinitionForSelection() {
23  NSRange selection_range = [view_->cocoa_view() selectedRange];
24  NSAttributedString* attr_string =
25      [view_->cocoa_view() attributedSubstringForProposedRange:selection_range
26                                           actualRange:nil];
27  if (!attr_string) {
28    if (view_->selected_text().empty())
29      return;
30    // The PDF plugin does not support getting the attributed string. Until it
31    // does, use NSPerformService(), which opens Dictionary.app.
32    // http://crbug.com/152438
33    // TODO(asvitkine): This should be removed after the above support is added.
34    NSString* text = base::SysUTF8ToNSString(view_->selected_text());
35    NSPasteboard* pasteboard = [NSPasteboard pasteboardWithUniqueName];
36    NSArray* types = [NSArray arrayWithObject:NSStringPboardType];
37    [pasteboard declareTypes:types owner:nil];
38    if ([pasteboard setString:text forType:NSStringPboardType])
39      NSPerformService(@"Look Up in Dictionary", pasteboard);
40    return;
41  }
42
43  NSRect rect =
44      [view_->cocoa_view() firstViewRectForCharacterRange:selection_range
45                                              actualRange:nil];
46
47  NSDictionary* attrs = [attr_string attributesAtIndex:0 effectiveRange:nil];
48  NSFont* font = [attrs objectForKey:NSFontAttributeName];
49  rect.origin.y += NSHeight(rect) - [font ascender];
50
51  rect.origin.x += offset_.x();
52  rect.origin.y += offset_.y();
53
54  [target_view_->cocoa_view() showDefinitionForAttributedString:attr_string
55                                                        atPoint:rect.origin];
56}
57
58}  // namespace content
59