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 #ifndef ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_
6 #define ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_
7 
8 #include <list>
9 #include <memory>
10 #include <string>
11 #include <utility>
12 
13 #include "android_webview/browser/aw_browser_permission_request_delegate.h"
14 #include "android_webview/browser/aw_render_process_gone_delegate.h"
15 #include "android_webview/browser/find_helper.h"
16 #include "android_webview/browser/gfx/browser_view_renderer.h"
17 #include "android_webview/browser/gfx/browser_view_renderer_client.h"
18 #include "android_webview/browser/icon_helper.h"
19 #include "android_webview/browser/metrics/visibility_metrics_logger.h"
20 #include "android_webview/browser/permission/permission_request_handler_client.h"
21 #include "android_webview/browser/renderer_host/aw_render_view_host_ext.h"
22 #include "android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.h"
23 #include "base/android/jni_weak_ref.h"
24 #include "base/android/scoped_java_ref.h"
25 #include "base/callback_forward.h"
26 #include "base/macros.h"
27 #include "components/js_injection/browser/js_communication_host.h"
28 #include "content/public/browser/web_contents_observer.h"
29 
30 class SkBitmap;
31 
32 namespace autofill {
33 class AutofillProvider;
34 }
35 
36 namespace content {
37 class WebContents;
38 }
39 
40 namespace android_webview {
41 
42 class AwContentsClientBridge;
43 class AwPdfExporter;
44 class AwWebContentsDelegate;
45 class PermissionRequestHandler;
46 
47 // Native side of java-class of same name.
48 //
49 // Object lifetime:
50 // For most purposes the java and native objects can be considered to have
51 // 1:1 lifetime and relationship. The exception is the java instance that
52 // hosts a popup will be rebound to a second native instance (carrying the
53 // popup content) and discard the 'default' native instance it made on
54 // construction. A native instance is only bound to at most one Java peer over
55 // its entire lifetime - see Init() and SetPendingWebContentsForPopup() for the
56 // construction points, and SetJavaPeers() where these paths join.
57 class AwContents : public FindHelper::Listener,
58                    public IconHelper::Listener,
59                    public AwRenderViewHostExtClient,
60                    public BrowserViewRendererClient,
61                    public PermissionRequestHandlerClient,
62                    public AwBrowserPermissionRequestDelegate,
63                    public AwRenderProcessGoneDelegate,
64                    public content::WebContentsObserver,
65                    public AwSafeBrowsingUIManager::UIManagerClient,
66                    public VisibilityMetricsLogger::Client {
67  public:
68   // Returns the AwContents instance associated with |web_contents|, or NULL.
69   static AwContents* FromWebContents(content::WebContents* web_contents);
70 
71   static std::string GetLocale();
72 
73   static std::string GetLocaleList();
74 
75   AwContents(std::unique_ptr<content::WebContents> web_contents);
76   ~AwContents() override;
77 
render_view_host_ext()78   AwRenderViewHostExt* render_view_host_ext() {
79     return render_view_host_ext_.get();
80   }
81 
82   // |handler| is an instance of
83   // org.chromium.android_webview.AwHttpAuthHandler.
84   bool OnReceivedHttpAuthRequest(const base::android::JavaRef<jobject>& handler,
85                                  const std::string& host,
86                                  const std::string& realm);
87 
88   void SetOffscreenPreRaster(bool enabled);
89 
90   // Methods called from Java.
91   void SetJavaPeers(
92       JNIEnv* env,
93       const base::android::JavaParamRef<jobject>& obj,
94       const base::android::JavaParamRef<jobject>& aw_contents,
95       const base::android::JavaParamRef<jobject>& web_contents_delegate,
96       const base::android::JavaParamRef<jobject>& contents_client_bridge,
97       const base::android::JavaParamRef<jobject>& io_thread_client,
98       const base::android::JavaParamRef<jobject>& intercept_navigation_delegate,
99       const base::android::JavaParamRef<jobject>& autofill_provider);
100   base::android::ScopedJavaLocalRef<jobject> GetWebContents(
101       JNIEnv* env,
102       const base::android::JavaParamRef<jobject>& obj);
103   base::android::ScopedJavaLocalRef<jobject> GetBrowserContext(
104       JNIEnv* env,
105       const base::android::JavaParamRef<jobject>& obj);
106   void SetCompositorFrameConsumer(
107       JNIEnv* env,
108       const base::android::JavaParamRef<jobject>& obj,
109       jlong compositor_frame_consumer);
110   base::android::ScopedJavaLocalRef<jobject> GetRenderProcess(
111       JNIEnv* env,
112       const base::android::JavaParamRef<jobject>& obj);
113 
114   void Destroy(JNIEnv* env);
115   void DocumentHasImages(JNIEnv* env,
116                          const base::android::JavaParamRef<jobject>& obj,
117                          const base::android::JavaParamRef<jobject>& message);
118   void GenerateMHTML(JNIEnv* env,
119                      const base::android::JavaParamRef<jobject>& obj,
120                      const base::android::JavaParamRef<jstring>& jpath,
121                      const base::android::JavaParamRef<jobject>& callback);
122   void CreatePdfExporter(
123       JNIEnv* env,
124       const base::android::JavaParamRef<jobject>& obj,
125       const base::android::JavaParamRef<jobject>& pdfExporter);
126   void AddVisitedLinks(
127       JNIEnv* env,
128       const base::android::JavaParamRef<jobject>& obj,
129       const base::android::JavaParamRef<jobjectArray>& jvisited_links);
130   base::android::ScopedJavaLocalRef<jbyteArray> GetCertificate(
131       JNIEnv* env,
132       const base::android::JavaParamRef<jobject>& obj);
133   void RequestNewHitTestDataAt(JNIEnv* env,
134                                const base::android::JavaParamRef<jobject>& obj,
135                                jfloat x,
136                                jfloat y,
137                                jfloat touch_major);
138   void UpdateLastHitTestData(JNIEnv* env,
139                              const base::android::JavaParamRef<jobject>& obj);
140   void OnSizeChanged(JNIEnv* env,
141                      const base::android::JavaParamRef<jobject>& obj,
142                      int w,
143                      int h,
144                      int ow,
145                      int oh);
146   void SetViewVisibility(JNIEnv* env,
147                          const base::android::JavaParamRef<jobject>& obj,
148                          bool visible);
149   void SetWindowVisibility(JNIEnv* env,
150                            const base::android::JavaParamRef<jobject>& obj,
151                            bool visible);
152   void SetIsPaused(JNIEnv* env,
153                    const base::android::JavaParamRef<jobject>& obj,
154                    bool paused);
155   void OnAttachedToWindow(JNIEnv* env,
156                           const base::android::JavaParamRef<jobject>& obj,
157                           int w,
158                           int h);
159   void OnDetachedFromWindow(JNIEnv* env,
160                             const base::android::JavaParamRef<jobject>& obj);
161   bool IsVisible(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
162   bool IsDisplayingInterstitialForTesting(
163       JNIEnv* env,
164       const base::android::JavaParamRef<jobject>& obj);
165   base::android::ScopedJavaLocalRef<jbyteArray> GetOpaqueState(
166       JNIEnv* env,
167       const base::android::JavaParamRef<jobject>& obj);
168   jboolean RestoreFromOpaqueState(
169       JNIEnv* env,
170       const base::android::JavaParamRef<jobject>& obj,
171       const base::android::JavaParamRef<jbyteArray>& state);
172   void FocusFirstNode(JNIEnv* env,
173                       const base::android::JavaParamRef<jobject>& obj);
174   void SetBackgroundColor(JNIEnv* env,
175                           const base::android::JavaParamRef<jobject>& obj,
176                           jint color);
177   void ZoomBy(JNIEnv* env,
178               const base::android::JavaParamRef<jobject>& obj,
179               jfloat delta);
180   void OnComputeScroll(JNIEnv* env,
181                        const base::android::JavaParamRef<jobject>& obj,
182                        jlong animation_time_millis);
183   bool OnDraw(JNIEnv* env,
184               const base::android::JavaParamRef<jobject>& obj,
185               const base::android::JavaParamRef<jobject>& canvas,
186               jboolean is_hardware_accelerated,
187               jint scroll_x,
188               jint scroll_y,
189               jint visible_left,
190               jint visible_top,
191               jint visible_right,
192               jint visible_bottom,
193               jboolean force_auxiliary_bitmap_rendering);
194   bool NeedToDrawBackgroundColor(JNIEnv* env,
195                                const base::android::JavaParamRef<jobject>& obj);
196   jlong CapturePicture(JNIEnv* env,
197                        const base::android::JavaParamRef<jobject>& obj,
198                        int width,
199                        int height);
200   void EnableOnNewPicture(JNIEnv* env,
201                           const base::android::JavaParamRef<jobject>& obj,
202                           jboolean enabled);
203   void InsertVisualStateCallback(
204       JNIEnv* env,
205       const base::android::JavaParamRef<jobject>& obj,
206       jlong request_id,
207       const base::android::JavaParamRef<jobject>& callback);
208   void ClearView(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
209   void SetExtraHeadersForUrl(
210       JNIEnv* env,
211       const base::android::JavaParamRef<jobject>& obj,
212       const base::android::JavaParamRef<jstring>& url,
213       const base::android::JavaParamRef<jstring>& extra_headers);
214 
215   void InvokeGeolocationCallback(
216       JNIEnv* env,
217       const base::android::JavaParamRef<jobject>& obj,
218       jboolean value,
219       const base::android::JavaParamRef<jstring>& origin);
220 
221   jint GetEffectivePriority(JNIEnv* env,
222                             const base::android::JavaParamRef<jobject>& obj);
223 
224   js_injection::JsCommunicationHost* GetJsCommunicationHost();
225 
226   jint AddDocumentStartJavaScript(
227       JNIEnv* env,
228       const base::android::JavaParamRef<jobject>& obj,
229       const base::android::JavaParamRef<jstring>& script,
230       const base::android::JavaParamRef<jobjectArray>& allowed_origin_rules);
231 
232   void RemoveDocumentStartJavaScript(
233       JNIEnv* env,
234       const base::android::JavaParamRef<jobject>& obj,
235       jint script_id);
236 
237   base::android::ScopedJavaLocalRef<jstring> AddWebMessageListener(
238       JNIEnv* env,
239       const base::android::JavaParamRef<jobject>& obj,
240       const base::android::JavaParamRef<jobject>& listener,
241       const base::android::JavaParamRef<jstring>& js_object_name,
242       const base::android::JavaParamRef<jobjectArray>& allowed_origins);
243 
244   void RemoveWebMessageListener(
245       JNIEnv* env,
246       const base::android::JavaParamRef<jobject>& obj,
247       const base::android::JavaParamRef<jstring>& js_object_name);
248 
249   base::android::ScopedJavaLocalRef<jobjectArray> GetJsObjectsInfo(
250       JNIEnv* env,
251       const base::android::JavaParamRef<jobject>& obj,
252       const base::android::JavaParamRef<jclass>& clazz);
253 
GetViewTreeForceDarkState()254   bool GetViewTreeForceDarkState() { return view_tree_force_dark_state_; }
255 
256   // PermissionRequestHandlerClient implementation.
257   void OnPermissionRequest(base::android::ScopedJavaLocalRef<jobject> j_request,
258                            AwPermissionRequest* request) override;
259   void OnPermissionRequestCanceled(AwPermissionRequest* request) override;
260 
GetPermissionRequestHandler()261   PermissionRequestHandler* GetPermissionRequestHandler() {
262     return permission_request_handler_.get();
263   }
264 
265   void PreauthorizePermission(
266       JNIEnv* env,
267       const base::android::JavaParamRef<jobject>& obj,
268       const base::android::JavaParamRef<jstring>& origin,
269       jlong resources);
270 
271   // AwBrowserPermissionRequestDelegate implementation.
272   void RequestProtectedMediaIdentifierPermission(
273       const GURL& origin,
274       base::OnceCallback<void(bool)> callback) override;
275   void CancelProtectedMediaIdentifierPermissionRequests(
276       const GURL& origin) override;
277   void RequestGeolocationPermission(
278       const GURL& origin,
279       base::OnceCallback<void(bool)> callback) override;
280   void CancelGeolocationPermissionRequests(const GURL& origin) override;
281   void RequestMIDISysexPermission(
282       const GURL& origin,
283       base::OnceCallback<void(bool)> callback) override;
284   void CancelMIDISysexPermissionRequests(const GURL& origin) override;
285 
286   // Find-in-page API and related methods.
287   void FindAllAsync(JNIEnv* env,
288                     const base::android::JavaParamRef<jobject>& obj,
289                     const base::android::JavaParamRef<jstring>& search_string);
290   void FindNext(JNIEnv* env,
291                 const base::android::JavaParamRef<jobject>& obj,
292                 jboolean forward);
293   void ClearMatches(JNIEnv* env,
294                     const base::android::JavaParamRef<jobject>& obj);
295   FindHelper* GetFindHelper();
296 
297   // Per WebView Cookie Policy
298   bool AllowThirdPartyCookies();
299 
300   // FindHelper::Listener implementation.
301   void OnFindResultReceived(int active_ordinal,
302                             int match_count,
303                             bool finished) override;
304   // IconHelper::Listener implementation.
305   bool ShouldDownloadFavicon(const GURL& icon_url) override;
306   void OnReceivedIcon(const GURL& icon_url, const SkBitmap& bitmap) override;
307   void OnReceivedTouchIconUrl(const std::string& url,
308                               const bool precomposed) override;
309 
310   // AwRenderViewHostExtClient implementation.
311   void OnWebLayoutPageScaleFactorChanged(float page_scale_factor) override;
312   void OnWebLayoutContentsSizeChanged(const gfx::Size& contents_size) override;
313 
314   // BrowserViewRendererClient implementation.
315   void PostInvalidate() override;
316   void OnNewPicture() override;
317   gfx::Point GetLocationOnScreen() override;
318   void OnViewTreeForceDarkStateChanged(
319       bool view_tree_force_dark_state) override;
320 
321   // |new_value| is in physical pixel scale.
322   void ScrollContainerViewTo(const gfx::Vector2d& new_value) override;
323 
324   void UpdateScrollState(const gfx::Vector2d& max_scroll_offset,
325                          const gfx::SizeF& contents_size_dip,
326                          float page_scale_factor,
327                          float min_page_scale_factor,
328                          float max_page_scale_factor) override;
329   void DidOverscroll(const gfx::Vector2d& overscroll_delta,
330                      const gfx::Vector2dF& overscroll_velocity) override;
331   ui::TouchHandleDrawable* CreateDrawable() override;
332 
333   void ClearCache(JNIEnv* env,
334                   const base::android::JavaParamRef<jobject>& obj,
335                   jboolean include_disk_files);
336   // See //android_webview/docs/how-does-on-create-window-work.md for more
337   // details.
338   void SetPendingWebContentsForPopup(
339       std::unique_ptr<content::WebContents> pending);
340   jlong ReleasePopupAwContents(JNIEnv* env,
341                                const base::android::JavaParamRef<jobject>& obj);
342 
343   void ScrollTo(JNIEnv* env,
344                 const base::android::JavaParamRef<jobject>& obj,
345                 jint x,
346                 jint y);
347   void RestoreScrollAfterTransition(
348       JNIEnv* env,
349       const base::android::JavaParamRef<jobject>& obj,
350       jint x,
351       jint y);
352   void SmoothScroll(JNIEnv* env,
353                     const base::android::JavaParamRef<jobject>& obj,
354                     jint target_x,
355                     jint target_y,
356                     jlong duration_ms);
357   void SetDipScale(JNIEnv* env,
358                    const base::android::JavaParamRef<jobject>& obj,
359                    jfloat dip_scale);
360   jboolean IsDisplayingOpenWebContent(
361       JNIEnv* env,
362       const base::android::JavaParamRef<jobject>& obj);
363   void OnInputEvent(JNIEnv* env,
364                     const base::android::JavaParamRef<jobject>& obj);
365   void SetSaveFormData(bool enabled);
366 
367   // Sets the java client
368   void SetAwAutofillClient(const base::android::JavaRef<jobject>& client);
369 
370   void SetJsOnlineProperty(JNIEnv* env,
371                            const base::android::JavaParamRef<jobject>& obj,
372                            jboolean network_up);
373   void TrimMemory(JNIEnv* env,
374                   const base::android::JavaParamRef<jobject>& obj,
375                   jint level,
376                   jboolean visible);
377 
378   void GrantFileSchemeAccesstoChildProcess(
379       JNIEnv* env,
380       const base::android::JavaParamRef<jobject>& obj);
381 
382   void ResumeLoadingCreatedPopupWebContents(
383       JNIEnv* env,
384       const base::android::JavaParamRef<jobject>& obj);
385 
386   jlong GetAutofillProvider(JNIEnv* env,
387                             const base::android::JavaParamRef<jobject>& obj);
388 
389   void RendererUnresponsive(content::RenderProcessHost* render_process_host);
390   void RendererResponsive(content::RenderProcessHost* render_process_host);
391 
392   // content::WebContentsObserver overrides
393   void RenderViewHostChanged(content::RenderViewHost* old_host,
394                              content::RenderViewHost* new_host) override;
395   void DidFinishNavigation(
396       content::NavigationHandle* navigation_handle) override;
397 
398   // AwSafeBrowsingUIManager::UIManagerClient implementation
399   bool CanShowInterstitial() override;
400   int GetErrorUiType() override;
401 
402   // VisibilityMetricsLogger::Client implementation
403   VisibilityMetricsLogger::VisibilityInfo GetVisibilityInfo() override;
404 
405   // AwRenderProcessGoneDelegate overrides
406   RenderProcessGoneResult OnRenderProcessGone(int child_process_id,
407                                               bool crashed) override;
408 
409  private:
410   void InitAutofillIfNecessary(bool autocomplete_enabled);
411 
412   // Geolocation API support
413   void ShowGeolocationPrompt(const GURL& origin,
414                              base::OnceCallback<void(bool)>);
415   void HideGeolocationPrompt(const GURL& origin);
416 
417   void SetDipScaleInternal(float dip_scale);
418 
419   JavaObjectWeakGlobalRef java_ref_;
420   BrowserViewRenderer browser_view_renderer_;  // Must outlive |web_contents_|.
421   std::unique_ptr<content::WebContents> web_contents_;
422   std::unique_ptr<AwWebContentsDelegate> web_contents_delegate_;
423   std::unique_ptr<AwContentsClientBridge> contents_client_bridge_;
424   std::unique_ptr<AwRenderViewHostExt> render_view_host_ext_;
425   std::unique_ptr<FindHelper> find_helper_;
426   std::unique_ptr<IconHelper> icon_helper_;
427   // See //android_webview/docs/how-does-on-create-window-work.md for more
428   // details for |pending_contents_|.
429   std::unique_ptr<AwContents> pending_contents_;
430   std::unique_ptr<AwPdfExporter> pdf_exporter_;
431   std::unique_ptr<PermissionRequestHandler> permission_request_handler_;
432   std::unique_ptr<autofill::AutofillProvider> autofill_provider_;
433   std::unique_ptr<js_injection::JsCommunicationHost> js_communication_host_;
434 
435   bool view_tree_force_dark_state_ = false;
436   bool scheme_http_or_https_ = false;
437 
438   // GURL is supplied by the content layer as requesting frame.
439   // Callback is supplied by the content layer, and is invoked with the result
440   // from the permission prompt.
441   typedef std::pair<const GURL, base::OnceCallback<void(bool)>> OriginCallback;
442   // The first element in the list is always the currently pending request.
443   std::list<OriginCallback> pending_geolocation_prompts_;
444 
445   DISALLOW_COPY_AND_ASSIGN(AwContents);
446 };
447 
448 }  // namespace android_webview
449 
450 #endif  // ANDROID_WEBVIEW_BROWSER_AW_CONTENTS_H_
451