Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / android_webview / renderer / aw_render_view_ext.cc
1 // Copyright (c) 2012 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 "android_webview/renderer/aw_render_view_ext.h"
6
7 #include <string>
8
9 #include "android_webview/common/aw_hit_test_data.h"
10 #include "android_webview/common/render_view_messages.h"
11 #include "base/bind.h"
12 #include "base/strings/string_piece.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/time/time.h"
15 #include "content/public/common/url_constants.h"
16 #include "content/public/renderer/android_content_detection_prefixes.h"
17 #include "content/public/renderer/document_state.h"
18 #include "content/public/renderer/render_view.h"
19 #include "skia/ext/refptr.h"
20 #include "third_party/WebKit/public/platform/WebSize.h"
21 #include "third_party/WebKit/public/platform/WebURL.h"
22 #include "third_party/WebKit/public/platform/WebVector.h"
23 #include "third_party/WebKit/public/web/WebDataSource.h"
24 #include "third_party/WebKit/public/web/WebDocument.h"
25 #include "third_party/WebKit/public/web/WebElement.h"
26 #include "third_party/WebKit/public/web/WebElementCollection.h"
27 #include "third_party/WebKit/public/web/WebHitTestResult.h"
28 #include "third_party/WebKit/public/web/WebImageCache.h"
29 #include "third_party/WebKit/public/web/WebLocalFrame.h"
30 #include "third_party/WebKit/public/web/WebNode.h"
31 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
32 #include "third_party/WebKit/public/web/WebView.h"
33 #include "url/url_canon.h"
34 #include "url/url_util.h"
35
36 namespace android_webview {
37
38 namespace {
39
40 GURL GetAbsoluteUrl(const blink::WebNode& node,
41                     const base::string16& url_fragment) {
42   return GURL(node.document().completeURL(url_fragment));
43 }
44
45 base::string16 GetHref(const blink::WebElement& element) {
46   // Get the actual 'href' attribute, which might relative if valid or can
47   // possibly contain garbage otherwise, so not using absoluteLinkURL here.
48   return element.getAttribute("href");
49 }
50
51 GURL GetAbsoluteSrcUrl(const blink::WebElement& element) {
52   if (element.isNull())
53     return GURL();
54   return GetAbsoluteUrl(element, element.getAttribute("src"));
55 }
56
57 blink::WebElement GetImgChild(const blink::WebElement& element) {
58   // This implementation is incomplete (for example if is an area tag) but
59   // matches the original WebViewClassic implementation.
60
61   blink::WebElementCollection collection = element.getElementsByTagName("img");
62   DCHECK(!collection.isNull());
63   return collection.firstItem();
64 }
65
66 bool RemovePrefixAndAssignIfMatches(const base::StringPiece& prefix,
67                                     const GURL& url,
68                                     std::string* dest) {
69   const base::StringPiece spec(url.possibly_invalid_spec());
70
71   if (spec.starts_with(prefix)) {
72     url::RawCanonOutputW<1024> output;
73     url::DecodeURLEscapeSequences(spec.data() + prefix.length(),
74                                   spec.length() - prefix.length(),
75                                   &output);
76     std::string decoded_url = base::UTF16ToUTF8(
77         base::string16(output.data(), output.length()));
78     dest->assign(decoded_url.begin(), decoded_url.end());
79     return true;
80   }
81   return false;
82 }
83
84 void DistinguishAndAssignSrcLinkType(const GURL& url, AwHitTestData* data) {
85   if (RemovePrefixAndAssignIfMatches(
86       content::kAddressPrefix,
87       url,
88       &data->extra_data_for_type)) {
89     data->type = AwHitTestData::GEO_TYPE;
90   } else if (RemovePrefixAndAssignIfMatches(
91       content::kPhoneNumberPrefix,
92       url,
93       &data->extra_data_for_type)) {
94     data->type = AwHitTestData::PHONE_TYPE;
95   } else if (RemovePrefixAndAssignIfMatches(
96       content::kEmailPrefix,
97       url,
98       &data->extra_data_for_type)) {
99     data->type = AwHitTestData::EMAIL_TYPE;
100   } else {
101     data->type = AwHitTestData::SRC_LINK_TYPE;
102     data->extra_data_for_type = url.possibly_invalid_spec();
103     if (!data->extra_data_for_type.empty())
104       data->href = base::UTF8ToUTF16(data->extra_data_for_type);
105   }
106 }
107
108 void PopulateHitTestData(const GURL& absolute_link_url,
109                          const GURL& absolute_image_url,
110                          bool is_editable,
111                          AwHitTestData* data) {
112   // Note: Using GURL::is_empty instead of GURL:is_valid due to the
113   // WebViewClassic allowing any kind of protocol which GURL::is_valid
114   // disallows. Similar reasons for using GURL::possibly_invalid_spec instead of
115   // GURL::spec.
116   if (!absolute_image_url.is_empty())
117     data->img_src = absolute_image_url;
118
119   const bool is_javascript_scheme =
120       absolute_link_url.SchemeIs(content::kJavaScriptScheme);
121   const bool has_link_url = !absolute_link_url.is_empty();
122   const bool has_image_url = !absolute_image_url.is_empty();
123
124   if (has_link_url && !has_image_url && !is_javascript_scheme) {
125     DistinguishAndAssignSrcLinkType(absolute_link_url, data);
126   } else if (has_link_url && has_image_url && !is_javascript_scheme) {
127     data->type = AwHitTestData::SRC_IMAGE_LINK_TYPE;
128     data->extra_data_for_type = data->img_src.possibly_invalid_spec();
129     if (absolute_link_url.is_valid())
130       data->href = base::UTF8ToUTF16(absolute_link_url.possibly_invalid_spec());
131   } else if (!has_link_url && has_image_url) {
132     data->type = AwHitTestData::IMAGE_TYPE;
133     data->extra_data_for_type = data->img_src.possibly_invalid_spec();
134   } else if (is_editable) {
135     data->type = AwHitTestData::EDIT_TEXT_TYPE;
136     DCHECK(data->extra_data_for_type.length() == 0);
137   }
138 }
139
140 }  // namespace
141
142 AwRenderViewExt::AwRenderViewExt(content::RenderView* render_view)
143     : content::RenderViewObserver(render_view), page_scale_factor_(0.0f) {
144 }
145
146 AwRenderViewExt::~AwRenderViewExt() {
147 }
148
149 // static
150 void AwRenderViewExt::RenderViewCreated(content::RenderView* render_view) {
151   new AwRenderViewExt(render_view);  // |render_view| takes ownership.
152 }
153
154 bool AwRenderViewExt::OnMessageReceived(const IPC::Message& message) {
155   bool handled = true;
156   IPC_BEGIN_MESSAGE_MAP(AwRenderViewExt, message)
157     IPC_MESSAGE_HANDLER(AwViewMsg_DocumentHasImages, OnDocumentHasImagesRequest)
158     IPC_MESSAGE_HANDLER(AwViewMsg_DoHitTest, OnDoHitTest)
159     IPC_MESSAGE_HANDLER(AwViewMsg_SetTextZoomFactor, OnSetTextZoomFactor)
160     IPC_MESSAGE_HANDLER(AwViewMsg_ResetScrollAndScaleState,
161                         OnResetScrollAndScaleState)
162     IPC_MESSAGE_HANDLER(AwViewMsg_SetInitialPageScale, OnSetInitialPageScale)
163     IPC_MESSAGE_HANDLER(AwViewMsg_SetFixedLayoutSize, OnSetFixedLayoutSize)
164     IPC_MESSAGE_HANDLER(AwViewMsg_SetBackgroundColor, OnSetBackgroundColor)
165     IPC_MESSAGE_UNHANDLED(handled = false)
166   IPC_END_MESSAGE_MAP()
167   return handled;
168 }
169
170 void AwRenderViewExt::OnDocumentHasImagesRequest(int id) {
171   bool hasImages = false;
172   if (render_view()) {
173     blink::WebView* webview = render_view()->GetWebView();
174     if (webview) {
175       blink::WebVector<blink::WebElement> images;
176       webview->mainFrame()->document().images(images);
177       hasImages = !images.isEmpty();
178     }
179   }
180   Send(new AwViewHostMsg_DocumentHasImagesResponse(routing_id(), id,
181                                                    hasImages));
182 }
183
184 void AwRenderViewExt::DidCommitProvisionalLoad(blink::WebLocalFrame* frame,
185                                                bool is_new_navigation) {
186   content::DocumentState* document_state =
187       content::DocumentState::FromDataSource(frame->dataSource());
188   if (document_state->can_load_local_resources()) {
189     blink::WebSecurityOrigin origin = frame->document().securityOrigin();
190     origin.grantLoadLocalResources();
191   }
192 }
193
194 void AwRenderViewExt::DidCommitCompositorFrame() {
195   UpdatePageScaleFactor();
196 }
197
198 void AwRenderViewExt::DidUpdateLayout() {
199   if (check_contents_size_timer_.IsRunning())
200     return;
201
202   check_contents_size_timer_.Start(FROM_HERE,
203                                    base::TimeDelta::FromMilliseconds(0), this,
204                                    &AwRenderViewExt::CheckContentsSize);
205 }
206
207 void AwRenderViewExt::UpdatePageScaleFactor() {
208   if (page_scale_factor_ != render_view()->GetWebView()->pageScaleFactor()) {
209     page_scale_factor_ = render_view()->GetWebView()->pageScaleFactor();
210     Send(new AwViewHostMsg_PageScaleFactorChanged(routing_id(),
211                                                   page_scale_factor_));
212   }
213 }
214
215 void AwRenderViewExt::CheckContentsSize() {
216   if (!render_view()->GetWebView())
217     return;
218
219   gfx::Size contents_size;
220
221   blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
222   if (main_frame)
223     contents_size = main_frame->contentsSize();
224
225   // Fall back to contentsPreferredMinimumSize if the mainFrame is reporting a
226   // 0x0 size (this happens during initial load).
227   if (contents_size.IsEmpty()) {
228     contents_size = render_view()->GetWebView()->contentsPreferredMinimumSize();
229   }
230
231   if (contents_size == last_sent_contents_size_)
232     return;
233
234   last_sent_contents_size_ = contents_size;
235   Send(new AwViewHostMsg_OnContentsSizeChanged(routing_id(), contents_size));
236 }
237
238 void AwRenderViewExt::Navigate(const GURL& url) {
239   // Navigate is called only on NEW navigations, so WebImageCache won't be freed
240   // when the user just clicks on links, but only when a navigation is started,
241   // for instance via loadUrl. A better approach would be clearing the cache on
242   // cross-site boundaries, however this would require too many changes both on
243   // the browser side (in RenderViewHostManger), to the IPCmessages and to the
244   // RenderViewObserver. Thus, clearing decoding image cache on Navigate, seems
245   // a more acceptable compromise.
246   blink::WebImageCache::clear();
247 }
248
249 void AwRenderViewExt::FocusedNodeChanged(const blink::WebNode& node) {
250   if (node.isNull() || !node.isElementNode() || !render_view())
251     return;
252
253   // Note: element is not const due to innerText() is not const.
254   blink::WebElement element = node.toConst<blink::WebElement>();
255   AwHitTestData data;
256
257   data.href = GetHref(element);
258   data.anchor_text = element.innerText();
259
260   GURL absolute_link_url;
261   if (node.isLink())
262     absolute_link_url = GetAbsoluteUrl(node, data.href);
263
264   GURL absolute_image_url;
265   const blink::WebElement child_img = GetImgChild(element);
266   if (!child_img.isNull()) {
267     absolute_image_url =
268         GetAbsoluteSrcUrl(child_img);
269   }
270
271   PopulateHitTestData(absolute_link_url,
272                       absolute_image_url,
273                       render_view()->IsEditableNode(node),
274                       &data);
275   Send(new AwViewHostMsg_UpdateHitTestData(routing_id(), data));
276 }
277
278 void AwRenderViewExt::OnDoHitTest(int view_x, int view_y) {
279   if (!render_view() || !render_view()->GetWebView())
280     return;
281
282   const blink::WebHitTestResult result =
283       render_view()->GetWebView()->hitTestResultAt(
284           blink::WebPoint(view_x, view_y));
285   AwHitTestData data;
286
287   if (!result.urlElement().isNull()) {
288     data.anchor_text = result.urlElement().innerText();
289     data.href = GetHref(result.urlElement());
290   }
291
292   PopulateHitTestData(result.absoluteLinkURL(),
293                       result.absoluteImageURL(),
294                       result.isContentEditable(),
295                       &data);
296   Send(new AwViewHostMsg_UpdateHitTestData(routing_id(), data));
297 }
298
299 void AwRenderViewExt::OnSetTextZoomFactor(float zoom_factor) {
300   if (!render_view() || !render_view()->GetWebView())
301     return;
302   // Hide selection and autofill popups.
303   render_view()->GetWebView()->hidePopups();
304   render_view()->GetWebView()->setTextZoomFactor(zoom_factor);
305 }
306
307 void AwRenderViewExt::OnResetScrollAndScaleState() {
308   if (!render_view() || !render_view()->GetWebView())
309     return;
310   render_view()->GetWebView()->resetScrollAndScaleState();
311 }
312
313 void AwRenderViewExt::OnSetInitialPageScale(double page_scale_factor) {
314   if (!render_view() || !render_view()->GetWebView())
315     return;
316   render_view()->GetWebView()->setInitialPageScaleOverride(
317       page_scale_factor);
318 }
319
320 void AwRenderViewExt::OnSetFixedLayoutSize(const gfx::Size& size) {
321   if (!render_view() || !render_view()->GetWebView())
322     return;
323   render_view()->GetWebView()->setFixedLayoutSize(size);
324 }
325
326 void AwRenderViewExt::OnSetBackgroundColor(SkColor c) {
327   if (!render_view() || !render_view()->GetWebView())
328     return;
329   render_view()->GetWebView()->setBaseBackgroundColor(c);
330 }
331
332 }  // namespace android_webview