Merge pull request #9180 from runinspring/patch-1
[platform/framework/web/crosswalk-tizen.git] / atom / browser / api / atom_api_web_contents.cc
1 // Copyright (c) 2014 GitHub, Inc.
2 // Use of this source code is governed by the MIT license that can be
3 // found in the LICENSE file.
4
5 #include "atom/browser/api/atom_api_web_contents.h"
6
7 #include <set>
8 #include <string>
9
10 #include "atom/browser/api/atom_api_debugger.h"
11 #include "atom/browser/api/atom_api_session.h"
12 #include "atom/browser/api/atom_api_window.h"
13 #include "atom/browser/atom_browser_client.h"
14 #include "atom/browser/atom_browser_context.h"
15 #include "atom/browser/atom_browser_main_parts.h"
16 #include "atom/browser/lib/bluetooth_chooser.h"
17 #include "atom/browser/native_window.h"
18 #include "atom/browser/net/atom_network_delegate.h"
19 #include "atom/browser/osr/osr_output_device.h"
20 #include "atom/browser/osr/osr_render_widget_host_view.h"
21 #include "atom/browser/osr/osr_web_contents_view.h"
22 #include "atom/browser/ui/drag_util.h"
23 #include "atom/browser/web_contents_permission_helper.h"
24 #include "atom/browser/web_contents_preferences.h"
25 #include "atom/browser/web_contents_zoom_controller.h"
26 #include "atom/browser/web_view_guest_delegate.h"
27 #include "atom/common/api/api_messages.h"
28 #include "atom/common/api/event_emitter_caller.h"
29 #include "atom/common/color_util.h"
30 #include "atom/common/mouse_util.h"
31 #include "atom/common/native_mate_converters/blink_converter.h"
32 #include "atom/common/native_mate_converters/callback.h"
33 #include "atom/common/native_mate_converters/content_converter.h"
34 #include "atom/common/native_mate_converters/file_path_converter.h"
35 #include "atom/common/native_mate_converters/gfx_converter.h"
36 #include "atom/common/native_mate_converters/gurl_converter.h"
37 #include "atom/common/native_mate_converters/image_converter.h"
38 #include "atom/common/native_mate_converters/net_converter.h"
39 #include "atom/common/native_mate_converters/string16_converter.h"
40 #include "atom/common/native_mate_converters/value_converter.h"
41 #include "atom/common/options_switches.h"
42 #include "base/strings/utf_string_conversions.h"
43 #include "base/threading/thread_task_runner_handle.h"
44 #include "brightray/browser/inspectable_web_contents.h"
45 #include "brightray/browser/inspectable_web_contents_view.h"
46 #include "chrome/browser/printing/print_preview_message_handler.h"
47 #include "chrome/browser/printing/print_view_manager_basic.h"
48 #include "chrome/browser/ssl/security_state_tab_helper.h"
49 #include "content/browser/frame_host/navigation_entry_impl.h"
50 #include "content/browser/renderer_host/render_widget_host_impl.h"
51 #include "content/browser/web_contents/web_contents_impl.h"
52 #include "content/common/view_messages.h"
53 #include "content/public/browser/favicon_status.h"
54 #include "content/public/browser/native_web_keyboard_event.h"
55 #include "content/public/browser/navigation_details.h"
56 #include "content/public/browser/navigation_entry.h"
57 #include "content/public/browser/navigation_handle.h"
58 #include "content/public/browser/notification_details.h"
59 #include "content/public/browser/notification_source.h"
60 #include "content/public/browser/notification_types.h"
61 #include "content/public/browser/plugin_service.h"
62 #include "content/public/browser/render_frame_host.h"
63 #include "content/public/browser/render_process_host.h"
64 #include "content/public/browser/render_view_host.h"
65 #include "content/public/browser/render_widget_host.h"
66 #include "content/public/browser/render_widget_host_view.h"
67 #include "content/public/browser/resource_request_details.h"
68 #include "content/public/browser/service_worker_context.h"
69 #include "content/public/browser/site_instance.h"
70 #include "content/public/browser/storage_partition.h"
71 #include "content/public/browser/web_contents.h"
72 #include "content/public/common/context_menu_params.h"
73 #include "native_mate/dictionary.h"
74 #include "native_mate/object_template_builder.h"
75 #include "net/url_request/url_request_context.h"
76 #include "third_party/WebKit/public/platform/WebInputEvent.h"
77 #include "third_party/WebKit/public/web/WebFindOptions.h"
78 #include "ui/display/screen.h"
79
80 #if !defined(OS_MACOSX)
81 #include "ui/aura/window.h"
82 #endif
83
84 #include "atom/common/node_includes.h"
85
86 namespace {
87
88 struct PrintSettings {
89   bool silent;
90   bool print_background;
91 };
92
93 }  // namespace
94
95 namespace mate {
96
97 template<>
98 struct Converter<atom::SetSizeParams> {
99   static bool FromV8(v8::Isolate* isolate,
100                      v8::Local<v8::Value> val,
101                      atom::SetSizeParams* out) {
102     mate::Dictionary params;
103     if (!ConvertFromV8(isolate, val, &params))
104       return false;
105     bool autosize;
106     if (params.Get("enableAutoSize", &autosize))
107       out->enable_auto_size.reset(new bool(true));
108     gfx::Size size;
109     if (params.Get("min", &size))
110       out->min_size.reset(new gfx::Size(size));
111     if (params.Get("max", &size))
112       out->max_size.reset(new gfx::Size(size));
113     if (params.Get("normal", &size))
114       out->normal_size.reset(new gfx::Size(size));
115     return true;
116   }
117 };
118
119 template<>
120 struct Converter<PrintSettings> {
121   static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
122                      PrintSettings* out) {
123     mate::Dictionary dict;
124     if (!ConvertFromV8(isolate, val, &dict))
125       return false;
126     dict.Get("silent", &(out->silent));
127     dict.Get("printBackground", &(out->print_background));
128     return true;
129   }
130 };
131
132 template<>
133 struct Converter<WindowOpenDisposition> {
134   static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
135                                    WindowOpenDisposition val) {
136     std::string disposition = "other";
137     switch (val) {
138       case WindowOpenDisposition::CURRENT_TAB:
139         disposition = "default";
140         break;
141       case WindowOpenDisposition::NEW_FOREGROUND_TAB:
142         disposition = "foreground-tab";
143         break;
144       case WindowOpenDisposition::NEW_BACKGROUND_TAB:
145         disposition = "background-tab";
146         break;
147       case WindowOpenDisposition::NEW_POPUP:
148       case WindowOpenDisposition::NEW_WINDOW:
149         disposition = "new-window";
150         break;
151       case WindowOpenDisposition::SAVE_TO_DISK:
152         disposition = "save-to-disk";
153         break;
154       default:
155         break;
156     }
157     return mate::ConvertToV8(isolate, disposition);
158   }
159 };
160
161 template<>
162 struct Converter<content::SavePageType> {
163   static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
164                      content::SavePageType* out) {
165     std::string save_type;
166     if (!ConvertFromV8(isolate, val, &save_type))
167       return false;
168     save_type = base::ToLowerASCII(save_type);
169     if (save_type == "htmlonly") {
170       *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
171     } else if (save_type == "htmlcomplete") {
172       *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
173     } else if (save_type == "mhtml") {
174       *out = content::SAVE_PAGE_TYPE_AS_MHTML;
175     } else {
176       return false;
177     }
178     return true;
179   }
180 };
181
182 template<>
183 struct Converter<atom::api::WebContents::Type> {
184   static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
185                                    atom::api::WebContents::Type val) {
186     using Type = atom::api::WebContents::Type;
187     std::string type = "";
188     switch (val) {
189       case Type::BACKGROUND_PAGE: type = "backgroundPage"; break;
190       case Type::BROWSER_WINDOW: type = "window"; break;
191       case Type::BROWSER_VIEW: type = "browserView"; break;
192       case Type::REMOTE: type = "remote"; break;
193       case Type::WEB_VIEW: type = "webview"; break;
194       case Type::OFF_SCREEN: type = "offscreen"; break;
195       default: break;
196     }
197     return mate::ConvertToV8(isolate, type);
198   }
199
200   static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
201                      atom::api::WebContents::Type* out) {
202     using Type = atom::api::WebContents::Type;
203     std::string type;
204     if (!ConvertFromV8(isolate, val, &type))
205       return false;
206     if (type == "backgroundPage") {
207       *out = Type::BACKGROUND_PAGE;
208     } else if (type == "browserView") {
209       *out = Type::BROWSER_VIEW;
210     } else if (type == "webview") {
211       *out = Type::WEB_VIEW;
212     } else if (type == "offscreen") {
213       *out = Type::OFF_SCREEN;
214     } else {
215       return false;
216     }
217     return true;
218   }
219 };
220
221 }  // namespace mate
222
223
224 namespace atom {
225
226 namespace api {
227
228 namespace {
229
230 content::ServiceWorkerContext* GetServiceWorkerContext(
231     const content::WebContents* web_contents) {
232   auto context = web_contents->GetBrowserContext();
233   auto site_instance = web_contents->GetSiteInstance();
234   if (!context || !site_instance)
235     return nullptr;
236
237   auto storage_partition =
238       content::BrowserContext::GetStoragePartition(context, site_instance);
239   if (!storage_partition)
240     return nullptr;
241
242   return storage_partition->GetServiceWorkerContext();
243 }
244
245 // Called when CapturePage is done.
246 void OnCapturePageDone(const base::Callback<void(const gfx::Image&)>& callback,
247                        const SkBitmap& bitmap,
248                        content::ReadbackResponse response) {
249   callback.Run(gfx::Image::CreateFrom1xBitmap(bitmap));
250 }
251
252 // Set the background color of RenderWidgetHostView.
253 void SetBackgroundColor(content::WebContents* web_contents) {
254   const auto view = web_contents->GetRenderWidgetHostView();
255   if (view) {
256     WebContentsPreferences* web_preferences =
257         WebContentsPreferences::FromWebContents(web_contents);
258     std::string color_name;
259     if (web_preferences->web_preferences()->GetString(options::kBackgroundColor,
260                                                       &color_name)) {
261       view->SetBackgroundColor(ParseHexColor(color_name));
262     } else {
263       view->SetBackgroundColor(SK_ColorTRANSPARENT);
264     }
265   }
266 }
267
268 }  // namespace
269
270 WebContents::WebContents(v8::Isolate* isolate,
271                          content::WebContents* web_contents,
272                          Type type)
273     : content::WebContentsObserver(web_contents),
274       embedder_(nullptr),
275       zoom_controller_(nullptr),
276       type_(type),
277       request_id_(0),
278       background_throttling_(true),
279       enable_devtools_(true) {
280   if (type == REMOTE) {
281     web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
282     Init(isolate);
283     AttachAsUserData(web_contents);
284   } else {
285     const mate::Dictionary options = mate::Dictionary::CreateEmpty(isolate);
286     auto session = Session::CreateFrom(isolate, GetBrowserContext());
287     session_.Reset(isolate, session.ToV8());
288     InitWithSessionAndOptions(isolate, web_contents, session, options);
289   }
290 }
291
292 WebContents::WebContents(v8::Isolate* isolate, const mate::Dictionary& options)
293     : embedder_(nullptr),
294       zoom_controller_(nullptr),
295       type_(BROWSER_WINDOW),
296       request_id_(0),
297       background_throttling_(true),
298       enable_devtools_(true) {
299   // Read options.
300   options.Get("backgroundThrottling", &background_throttling_);
301
302   // FIXME(zcbenz): We should read "type" parameter for better design, but
303   // on Windows we have encountered a compiler bug that if we read "type"
304   // from |options| and then set |type_|, a memory corruption will happen
305   // and Electron will soon crash.
306   // Remvoe this after we upgraded to use VS 2015 Update 3.
307   bool b = false;
308   if (options.Get("isGuest", &b) && b)
309     type_ = WEB_VIEW;
310   else if (options.Get("isBackgroundPage", &b) && b)
311     type_ = BACKGROUND_PAGE;
312   else if (options.Get("isBrowserView", &b) && b)
313     type_ = BROWSER_VIEW;
314   else if (options.Get("offscreen", &b) && b)
315     type_ = OFF_SCREEN;
316
317   // Whether to enable DevTools.
318   options.Get("devTools", &enable_devtools_);
319
320   // Obtain the session.
321   std::string partition;
322   mate::Handle<api::Session> session;
323   if (options.Get("session", &session)) {
324   } else if (options.Get("partition", &partition)) {
325     session = Session::FromPartition(isolate, partition);
326   } else {
327     // Use the default session if not specified.
328     session = Session::FromPartition(isolate, "");
329   }
330   session_.Reset(isolate, session.ToV8());
331
332   content::WebContents* web_contents;
333   if (IsGuest()) {
334     scoped_refptr<content::SiteInstance> site_instance =
335         content::SiteInstance::CreateForURL(
336             session->browser_context(), GURL("chrome-guest://fake-host"));
337     content::WebContents::CreateParams params(
338         session->browser_context(), site_instance);
339     guest_delegate_.reset(new WebViewGuestDelegate);
340     params.guest_delegate = guest_delegate_.get();
341     web_contents = content::WebContents::Create(params);
342   } else if (IsOffScreen()) {
343     bool transparent = false;
344     options.Get("transparent", &transparent);
345
346     content::WebContents::CreateParams params(session->browser_context());
347     auto* view = new OffScreenWebContentsView(
348         transparent, base::Bind(&WebContents::OnPaint, base::Unretained(this)));
349     params.view = view;
350     params.delegate_view = view;
351
352     web_contents = content::WebContents::Create(params);
353     view->SetWebContents(web_contents);
354   } else {
355     content::WebContents::CreateParams params(session->browser_context());
356     web_contents = content::WebContents::Create(params);
357   }
358
359   InitWithSessionAndOptions(isolate, web_contents, session, options);
360 }
361
362 void WebContents::InitWithSessionAndOptions(v8::Isolate* isolate,
363                                             content::WebContents *web_contents,
364                                             mate::Handle<api::Session> session,
365                                             const mate::Dictionary& options) {
366   content::WebContentsObserver::Observe(web_contents);
367   InitWithWebContents(web_contents, session->browser_context());
368
369   managed_web_contents()->GetView()->SetDelegate(this);
370
371   // Save the preferences in C++.
372   new WebContentsPreferences(web_contents, options);
373
374   // Initialize permission helper.
375   WebContentsPermissionHelper::CreateForWebContents(web_contents);
376   // Initialize security state client.
377   SecurityStateTabHelper::CreateForWebContents(web_contents);
378   // Initialize zoom controller.
379   WebContentsZoomController::CreateForWebContents(web_contents);
380   zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
381   double zoom_factor;
382   if (options.Get(options::kZoomFactor, &zoom_factor))
383     zoom_controller_->SetDefaultZoomFactor(zoom_factor);
384
385   web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
386
387   if (IsGuest()) {
388     guest_delegate_->Initialize(this);
389
390     NativeWindow* owner_window = nullptr;
391     if (options.Get("embedder", &embedder_) && embedder_) {
392       // New WebContents's owner_window is the embedder's owner_window.
393       auto relay =
394           NativeWindowRelay::FromWebContents(embedder_->web_contents());
395       if (relay)
396         owner_window = relay->window.get();
397     }
398     if (owner_window)
399       SetOwnerWindow(owner_window);
400   }
401
402   const content::NavigationController* controller =
403       &web_contents->GetController();
404   registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_PENDING,
405                  content::Source<content::NavigationController>(controller));
406
407   Init(isolate);
408   AttachAsUserData(web_contents);
409 }
410
411 WebContents::~WebContents() {
412   // The destroy() is called.
413   if (managed_web_contents()) {
414     // For webview we need to tell content module to do some cleanup work before
415     // destroying it.
416     if (type_ == WEB_VIEW)
417       guest_delegate_->Destroy();
418
419     RenderViewDeleted(web_contents()->GetRenderViewHost());
420     DestroyWebContents();
421   }
422 }
423
424 void WebContents::DestroyWebContents() {
425   // This event is only for internal use, which is emitted when WebContents is
426   // being destroyed.
427   Emit("will-destroy");
428   ResetManagedWebContents();
429 }
430
431 bool WebContents::DidAddMessageToConsole(content::WebContents* source,
432                                          int32_t level,
433                                          const base::string16& message,
434                                          int32_t line_no,
435                                          const base::string16& source_id) {
436   if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) {
437     return false;
438   } else {
439     Emit("console-message", level, message, line_no, source_id);
440     return true;
441   }
442 }
443
444 void WebContents::OnCreateWindow(
445     const GURL& target_url,
446     const std::string& frame_name,
447     WindowOpenDisposition disposition,
448     const std::vector<std::string>& features,
449     const scoped_refptr<content::ResourceRequestBodyImpl>& body) {
450   if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
451     Emit("-new-window", target_url, frame_name, disposition, features, body);
452   else
453     Emit("new-window", target_url, frame_name, disposition, features);
454 }
455
456 void WebContents::WebContentsCreated(content::WebContents* source_contents,
457                                      int opener_render_process_id,
458                                      int opener_render_frame_id,
459                                      const std::string& frame_name,
460                                      const GURL& target_url,
461                                      content::WebContents* new_contents) {
462   v8::Locker locker(isolate());
463   v8::HandleScope handle_scope(isolate());
464   auto api_web_contents = CreateFrom(isolate(), new_contents, BROWSER_WINDOW);
465   Emit("-web-contents-created", api_web_contents, target_url, frame_name);
466 }
467
468 void WebContents::AddNewContents(content::WebContents* source,
469                                  content::WebContents* new_contents,
470                                  WindowOpenDisposition disposition,
471                                  const gfx::Rect& initial_rect,
472                                  bool user_gesture,
473                                  bool* was_blocked) {
474   v8::Locker locker(isolate());
475   v8::HandleScope handle_scope(isolate());
476   auto api_web_contents = CreateFrom(isolate(), new_contents);
477   if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
478       initial_rect.x(), initial_rect.y(), initial_rect.width(),
479       initial_rect.height())) {
480     api_web_contents->DestroyWebContents();
481   }
482 }
483
484 content::WebContents* WebContents::OpenURLFromTab(
485     content::WebContents* source,
486     const content::OpenURLParams& params) {
487   if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
488     if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
489       Emit("-new-window", params.url, "", params.disposition);
490     else
491       Emit("new-window", params.url, "", params.disposition);
492     return nullptr;
493   }
494
495   // Give user a chance to cancel navigation.
496   if (Emit("will-navigate", params.url))
497     return nullptr;
498
499   // Don't load the URL if the web contents was marked as destroyed from a
500   // will-navigate event listener
501   if (IsDestroyed())
502     return nullptr;
503
504   return CommonWebContentsDelegate::OpenURLFromTab(source, params);
505 }
506
507 void WebContents::BeforeUnloadFired(content::WebContents* tab,
508                                     bool proceed,
509                                     bool* proceed_to_fire_unload) {
510   if (type_ == BROWSER_WINDOW || type_ == OFF_SCREEN)
511     *proceed_to_fire_unload = proceed;
512   else
513     *proceed_to_fire_unload = true;
514 }
515
516 void WebContents::MoveContents(content::WebContents* source,
517                                const gfx::Rect& pos) {
518   Emit("move", pos);
519 }
520
521 void WebContents::CloseContents(content::WebContents* source) {
522   Emit("close");
523
524   if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
525     owner_window()->CloseContents(source);
526 }
527
528 void WebContents::ActivateContents(content::WebContents* source) {
529   Emit("activate");
530 }
531
532 void WebContents::UpdateTargetURL(content::WebContents* source,
533                                   const GURL& url) {
534   Emit("update-target-url", url);
535 }
536
537 bool WebContents::IsPopupOrPanel(const content::WebContents* source) const {
538   return type_ == BROWSER_WINDOW;
539 }
540
541 void WebContents::HandleKeyboardEvent(
542     content::WebContents* source,
543     const content::NativeWebKeyboardEvent& event) {
544   if (type_ == WEB_VIEW && embedder_) {
545     // Send the unhandled keyboard events back to the embedder.
546     embedder_->HandleKeyboardEvent(source, event);
547   } else {
548     // Go to the default keyboard handling.
549     CommonWebContentsDelegate::HandleKeyboardEvent(source, event);
550   }
551 }
552
553 bool WebContents::PreHandleKeyboardEvent(
554     content::WebContents* source,
555     const content::NativeWebKeyboardEvent& event,
556     bool* is_keyboard_shortcut) {
557   if (event.type == blink::WebInputEvent::Type::RawKeyDown
558       || event.type == blink::WebInputEvent::Type::KeyUp)
559     return Emit("before-input-event", event);
560   else
561     return false;
562 }
563
564 void WebContents::EnterFullscreenModeForTab(content::WebContents* source,
565                                             const GURL& origin) {
566   auto permission_helper =
567       WebContentsPermissionHelper::FromWebContents(source);
568   auto callback = base::Bind(&WebContents::OnEnterFullscreenModeForTab,
569                              base::Unretained(this), source, origin);
570   permission_helper->RequestFullscreenPermission(callback);
571 }
572
573 void WebContents::OnEnterFullscreenModeForTab(content::WebContents* source,
574                                               const GURL& origin,
575                                               bool allowed) {
576   if (!allowed)
577     return;
578   CommonWebContentsDelegate::EnterFullscreenModeForTab(source, origin);
579   Emit("enter-html-full-screen");
580 }
581
582 void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
583   CommonWebContentsDelegate::ExitFullscreenModeForTab(source);
584   Emit("leave-html-full-screen");
585 }
586
587 void WebContents::RendererUnresponsive(
588     content::WebContents* source,
589     const content::WebContentsUnresponsiveState& unresponsive_state) {
590   Emit("unresponsive");
591   if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
592     owner_window()->RendererUnresponsive(source);
593 }
594
595 void WebContents::RendererResponsive(content::WebContents* source) {
596   Emit("responsive");
597   if ((type_ == BROWSER_WINDOW || type_ == OFF_SCREEN) && owner_window())
598     owner_window()->RendererResponsive(source);
599 }
600
601 bool WebContents::HandleContextMenu(const content::ContextMenuParams& params) {
602   if (params.custom_context.is_pepper_menu) {
603     Emit("pepper-context-menu", std::make_pair(params, web_contents()));
604     web_contents()->NotifyContextMenuClosed(params.custom_context);
605   } else {
606     Emit("context-menu", std::make_pair(params, web_contents()));
607   }
608
609   return true;
610 }
611
612 bool WebContents::OnGoToEntryOffset(int offset) {
613   GoToOffset(offset);
614   return false;
615 }
616
617 void WebContents::FindReply(content::WebContents* web_contents,
618                             int request_id,
619                             int number_of_matches,
620                             const gfx::Rect& selection_rect,
621                             int active_match_ordinal,
622                             bool final_update) {
623   if (!final_update)
624     return;
625
626   v8::Locker locker(isolate());
627   v8::HandleScope handle_scope(isolate());
628   mate::Dictionary result = mate::Dictionary::CreateEmpty(isolate());
629   result.Set("requestId", request_id);
630   result.Set("matches", number_of_matches);
631   result.Set("selectionArea", selection_rect);
632   result.Set("activeMatchOrdinal", active_match_ordinal);
633   result.Set("finalUpdate", final_update);  // Deprecate after 2.0
634   Emit("found-in-page", result);
635 }
636
637 bool WebContents::CheckMediaAccessPermission(
638     content::WebContents* web_contents,
639     const GURL& security_origin,
640     content::MediaStreamType type) {
641   return true;
642 }
643
644 void WebContents::RequestMediaAccessPermission(
645     content::WebContents* web_contents,
646     const content::MediaStreamRequest& request,
647     const content::MediaResponseCallback& callback) {
648   auto permission_helper =
649       WebContentsPermissionHelper::FromWebContents(web_contents);
650   permission_helper->RequestMediaAccessPermission(request, callback);
651 }
652
653 void WebContents::RequestToLockMouse(
654     content::WebContents* web_contents,
655     bool user_gesture,
656     bool last_unlocked_by_target) {
657   auto permission_helper =
658       WebContentsPermissionHelper::FromWebContents(web_contents);
659   permission_helper->RequestPointerLockPermission(user_gesture);
660 }
661
662 std::unique_ptr<content::BluetoothChooser> WebContents::RunBluetoothChooser(
663     content::RenderFrameHost* frame,
664     const content::BluetoothChooser::EventHandler& event_handler) {
665   std::unique_ptr<BluetoothChooser> bluetooth_chooser(
666       new BluetoothChooser(this, event_handler));
667   return std::move(bluetooth_chooser);
668 }
669
670 void WebContents::BeforeUnloadFired(const base::TimeTicks& proceed_time) {
671   // Do nothing, we override this method just to avoid compilation error since
672   // there are two virtual functions named BeforeUnloadFired.
673 }
674
675 void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) {
676   const auto impl = content::RenderWidgetHostImpl::FromID(
677       render_view_host->GetProcess()->GetID(),
678       render_view_host->GetRoutingID());
679   if (impl)
680     impl->disable_hidden_ = !background_throttling_;
681 }
682
683 void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
684   Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
685 }
686
687 void WebContents::RenderProcessGone(base::TerminationStatus status) {
688   Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
689 }
690
691 void WebContents::PluginCrashed(const base::FilePath& plugin_path,
692                                 base::ProcessId plugin_pid) {
693   content::WebPluginInfo info;
694   auto plugin_service = content::PluginService::GetInstance();
695   plugin_service->GetPluginInfoByPath(plugin_path, &info);
696   Emit("plugin-crashed", info.name, info.version);
697 }
698
699 void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
700                                       const MediaPlayerId& id) {
701   Emit("media-started-playing");
702 }
703
704 void WebContents::MediaStoppedPlaying(const MediaPlayerInfo& video_type,
705                                       const MediaPlayerId& id) {
706   Emit("media-paused");
707 }
708
709 void WebContents::DidChangeThemeColor(SkColor theme_color) {
710   Emit("did-change-theme-color", atom::ToRGBHex(theme_color));
711 }
712
713 void WebContents::DocumentLoadedInFrame(
714     content::RenderFrameHost* render_frame_host) {
715   if (!render_frame_host->GetParent())
716     Emit("dom-ready");
717 }
718
719 void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
720                                 const GURL& validated_url) {
721   bool is_main_frame = !render_frame_host->GetParent();
722   Emit("did-frame-finish-load", is_main_frame);
723
724   if (is_main_frame)
725     Emit("did-finish-load");
726 }
727
728 void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
729                               const GURL& url,
730                               int error_code,
731                               const base::string16& error_description,
732                               bool was_ignored_by_handler) {
733   bool is_main_frame = !render_frame_host->GetParent();
734   Emit("did-fail-load", error_code, error_description, url, is_main_frame);
735 }
736
737 void WebContents::DidStartLoading() {
738   Emit("did-start-loading");
739 }
740
741 void WebContents::DidStopLoading() {
742   Emit("did-stop-loading");
743 }
744
745 void WebContents::DidGetResourceResponseStart(
746     const content::ResourceRequestDetails& details) {
747   Emit("did-get-response-details",
748        details.socket_address.IsEmpty(),
749        details.url,
750        details.original_url,
751        details.http_response_code,
752        details.method,
753        details.referrer,
754        details.headers.get(),
755        ResourceTypeToString(details.resource_type));
756 }
757
758 void WebContents::DidGetRedirectForResourceRequest(
759     const content::ResourceRedirectDetails& details) {
760   Emit("did-get-redirect-request",
761        details.url,
762        details.new_url,
763        (details.resource_type == content::RESOURCE_TYPE_MAIN_FRAME),
764        details.http_response_code,
765        details.method,
766        details.referrer,
767        details.headers.get());
768 }
769
770 void WebContents::DidStartNavigation(
771     content::NavigationHandle* navigation_handle) {
772   if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSamePage())
773     return;
774
775   if (deferred_load_url_.id) {
776     auto web_contents = navigation_handle->GetWebContents();
777     auto& controller = web_contents->GetController();
778     int id = controller.GetPendingEntry()->GetUniqueID();
779     if (id == deferred_load_url_.id) {
780       if (!deferred_load_url_.params.url.is_empty()) {
781         auto params = deferred_load_url_.params;
782         deferred_load_url_.id = 0;
783         deferred_load_url_.params =
784             content::NavigationController::LoadURLParams(GURL());
785         controller.LoadURLWithParams(params);
786         SetBackgroundColor(web_contents);
787       } else {
788         deferred_load_url_.id = 0;
789       }
790     }
791   }
792 }
793
794 void WebContents::DidFinishNavigation(
795     content::NavigationHandle* navigation_handle) {
796   bool is_main_frame = navigation_handle->IsInMainFrame();
797   if (navigation_handle->HasCommitted() && !navigation_handle->IsErrorPage()) {
798     auto url = navigation_handle->GetURL();
799     bool is_in_page = navigation_handle->IsSamePage();
800     if (is_main_frame && !is_in_page) {
801       Emit("did-navigate", url);
802     } else if (is_in_page) {
803       Emit("did-navigate-in-page", url, is_main_frame);
804     }
805   } else {
806     auto url = navigation_handle->GetURL();
807     int code = navigation_handle->GetNetErrorCode();
808     auto description = net::ErrorToShortString(code);
809     Emit("did-fail-provisional-load", code, description, url, is_main_frame);
810
811     // Do not emit "did-fail-load" for canceled requests.
812     if (code != net::ERR_ABORTED)
813       Emit("did-fail-load", code, description, url, is_main_frame);
814   }
815 }
816
817 void WebContents::TitleWasSet(content::NavigationEntry* entry,
818                               bool explicit_set) {
819   if (entry)
820     Emit("-page-title-updated", entry->GetTitle(), explicit_set);
821   else
822     Emit("-page-title-updated", "", explicit_set);
823 }
824
825 void WebContents::DidUpdateFaviconURL(
826     const std::vector<content::FaviconURL>& urls) {
827   std::set<GURL> unique_urls;
828   for (const auto& iter : urls) {
829     if (iter.icon_type != content::FaviconURL::FAVICON)
830       continue;
831     const GURL& url = iter.icon_url;
832     if (url.is_valid())
833       unique_urls.insert(url);
834   }
835   Emit("page-favicon-updated", unique_urls);
836 }
837
838 void WebContents::Observe(int type,
839                           const content::NotificationSource& source,
840                           const content::NotificationDetails& details) {
841   switch (type) {
842     case content::NOTIFICATION_NAV_ENTRY_PENDING: {
843       content::NavigationEntry* entry =
844           content::Details<content::NavigationEntry>(details).ptr();
845       content::NavigationEntryImpl* entry_impl =
846           static_cast<content::NavigationEntryImpl*>(entry);
847       // In NavigatorImpl::DidStartMainFrameNavigation when there is no
848       // browser side pending entry available it creates a new one based
849       // on existing pending entry, hence we track the unique id here
850       // instead in WebContents::LoadURL with controller.GetPendingEntry()
851       // TODO(deepak1556): Remove once we have
852       // https://codereview.chromium.org/2661743002.
853       if (entry_impl->frame_tree_node_id() == -1) {
854         deferred_load_url_.id = entry->GetUniqueID();
855       }
856       break;
857     }
858     default:
859       NOTREACHED();
860       break;
861   }
862 }
863
864 void WebContents::DevToolsReloadPage() {
865   Emit("devtools-reload-page");
866 }
867
868 void WebContents::DevToolsFocused() {
869   Emit("devtools-focused");
870 }
871
872 void WebContents::DevToolsOpened() {
873   v8::Locker locker(isolate());
874   v8::HandleScope handle_scope(isolate());
875   auto handle = WebContents::CreateFrom(
876       isolate(), managed_web_contents()->GetDevToolsWebContents());
877   devtools_web_contents_.Reset(isolate(), handle.ToV8());
878
879   // Set inspected tabID.
880   base::FundamentalValue tab_id(ID());
881   managed_web_contents()->CallClientFunction(
882       "DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr);
883
884   // Inherit owner window in devtools.
885   if (owner_window())
886     handle->SetOwnerWindow(managed_web_contents()->GetDevToolsWebContents(),
887                            owner_window());
888
889   Emit("devtools-opened");
890 }
891
892 void WebContents::DevToolsClosed() {
893   v8::Locker locker(isolate());
894   v8::HandleScope handle_scope(isolate());
895   devtools_web_contents_.Reset();
896
897   Emit("devtools-closed");
898 }
899
900 bool WebContents::OnMessageReceived(const IPC::Message& message) {
901   bool handled = true;
902   IPC_BEGIN_MESSAGE_MAP(WebContents, message)
903     IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
904     IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_Message_Sync,
905                                     OnRendererMessageSync)
906     IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_SetTemporaryZoomLevel,
907                                     OnSetTemporaryZoomLevel)
908     IPC_MESSAGE_HANDLER_DELAY_REPLY(AtomViewHostMsg_GetZoomLevel,
909                                     OnGetZoomLevel)
910     IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
911       handled = false)
912     IPC_MESSAGE_UNHANDLED(handled = false)
913   IPC_END_MESSAGE_MAP()
914
915   return handled;
916 }
917
918 // There are three ways of destroying a webContents:
919 // 1. call webContents.destroy();
920 // 2. garbage collection;
921 // 3. user closes the window of webContents;
922 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
923 // happen. The #2 should never happen for webContents, because webview is
924 // managed by GuestViewManager, and BrowserWindow's webContents is managed
925 // by api::Window.
926 // For #1, the destructor will do the cleanup work and we only need to make
927 // sure "destroyed" event is emitted. For #3, the content::WebContents will
928 // be destroyed on close, and WebContentsDestroyed would be called for it, so
929 // we need to make sure the api::WebContents is also deleted.
930 void WebContents::WebContentsDestroyed() {
931   // Cleanup relationships with other parts.
932   RemoveFromWeakMap();
933
934   // We can not call Destroy here because we need to call Emit first, but we
935   // also do not want any method to be used, so just mark as destroyed here.
936   MarkDestroyed();
937
938   Emit("destroyed");
939
940   // Destroy the native class in next tick.
941   base::ThreadTaskRunnerHandle::Get()->PostTask(
942       FROM_HERE, GetDestroyClosure());
943 }
944
945 void WebContents::NavigationEntryCommitted(
946     const content::LoadCommittedDetails& details) {
947   Emit("navigation-entry-commited", details.entry->GetURL(),
948        details.is_in_page, details.did_replace_entry);
949 }
950
951 int64_t WebContents::GetID() const {
952   int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
953   int64_t routing_id = web_contents()->GetRoutingID();
954   int64_t rv = (process_id << 32) + routing_id;
955   return rv;
956 }
957
958 int WebContents::GetProcessID() const {
959   return web_contents()->GetRenderProcessHost()->GetID();
960 }
961
962 WebContents::Type WebContents::GetType() const {
963   return type_;
964 }
965
966 bool WebContents::Equal(const WebContents* web_contents) const {
967   return GetID() == web_contents->GetID();
968 }
969
970 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
971   if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
972     Emit("did-fail-load",
973          static_cast<int>(net::ERR_INVALID_URL),
974          net::ErrorToShortString(net::ERR_INVALID_URL),
975          url.possibly_invalid_spec(),
976          true);
977     return;
978   }
979
980   content::NavigationController::LoadURLParams params(url);
981
982   GURL http_referrer;
983   if (options.Get("httpReferrer", &http_referrer))
984     params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
985                                         blink::WebReferrerPolicyDefault);
986
987   std::string user_agent;
988   if (options.Get("userAgent", &user_agent))
989     web_contents()->SetUserAgentOverride(user_agent);
990
991   std::string extra_headers;
992   if (options.Get("extraHeaders", &extra_headers))
993     params.extra_headers = extra_headers;
994
995   scoped_refptr<content::ResourceRequestBodyImpl> body;
996   if (options.Get("postData", &body)) {
997     params.post_data = body;
998     params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
999   }
1000
1001   GURL base_url_for_data_url;
1002   if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1003     params.base_url_for_data_url = base_url_for_data_url;
1004     params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1005   }
1006
1007   params.transition_type = ui::PAGE_TRANSITION_TYPED;
1008   params.should_clear_history_list = true;
1009   params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1010
1011   if (deferred_load_url_.id) {
1012     deferred_load_url_.params = params;
1013     return;
1014   }
1015
1016   web_contents()->GetController().LoadURLWithParams(params);
1017   // We have to call it right after LoadURL because the RenderViewHost is only
1018   // created after loading a page.
1019   SetBackgroundColor(web_contents());
1020 }
1021
1022 void WebContents::DownloadURL(const GURL& url) {
1023   auto browser_context = web_contents()->GetBrowserContext();
1024   auto download_manager =
1025     content::BrowserContext::GetDownloadManager(browser_context);
1026
1027   download_manager->DownloadUrl(
1028       content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1029           web_contents(), url));
1030 }
1031
1032 GURL WebContents::GetURL() const {
1033   return web_contents()->GetURL();
1034 }
1035
1036 base::string16 WebContents::GetTitle() const {
1037   return web_contents()->GetTitle();
1038 }
1039
1040 bool WebContents::IsLoading() const {
1041   return web_contents()->IsLoading();
1042 }
1043
1044 bool WebContents::IsLoadingMainFrame() const {
1045   // Comparing site instances works because Electron always creates a new site
1046   // instance when navigating, regardless of origin. See AtomBrowserClient.
1047   return (web_contents()->GetLastCommittedURL().is_empty() ||
1048           web_contents()->GetSiteInstance() !=
1049           web_contents()->GetPendingSiteInstance()) && IsLoading();
1050 }
1051
1052 bool WebContents::IsWaitingForResponse() const {
1053   return web_contents()->IsWaitingForResponse();
1054 }
1055
1056 void WebContents::Stop() {
1057   web_contents()->Stop();
1058 }
1059
1060 void WebContents::GoBack() {
1061   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1062   web_contents()->GetController().GoBack();
1063 }
1064
1065 void WebContents::GoForward() {
1066   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1067   web_contents()->GetController().GoForward();
1068 }
1069
1070 void WebContents::GoToOffset(int offset) {
1071   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1072   web_contents()->GetController().GoToOffset(offset);
1073 }
1074
1075 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1076   return web_contents()->
1077     GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1078 }
1079
1080 void WebContents::SetWebRTCIPHandlingPolicy(
1081     const std::string& webrtc_ip_handling_policy) {
1082   if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1083     return;
1084   web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1085     webrtc_ip_handling_policy;
1086
1087   content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1088   if (host)
1089     host->SyncRendererPrefs();
1090 }
1091
1092 bool WebContents::IsCrashed() const {
1093   return web_contents()->IsCrashed();
1094 }
1095
1096 void WebContents::SetUserAgent(const std::string& user_agent,
1097                                mate::Arguments* args) {
1098   web_contents()->SetUserAgentOverride(user_agent);
1099 }
1100
1101 std::string WebContents::GetUserAgent() {
1102   return web_contents()->GetUserAgentOverride();
1103 }
1104
1105 bool WebContents::SavePage(const base::FilePath& full_file_path,
1106                            const content::SavePageType& save_type,
1107                            const SavePageHandler::SavePageCallback& callback) {
1108   auto handler = new SavePageHandler(web_contents(), callback);
1109   return handler->Handle(full_file_path, save_type);
1110 }
1111
1112 void WebContents::OpenDevTools(mate::Arguments* args) {
1113   if (type_ == REMOTE)
1114     return;
1115
1116   if (!enable_devtools_)
1117     return;
1118
1119   std::string state;
1120   if (type_ == WEB_VIEW || !owner_window()) {
1121     state = "detach";
1122   } else if (args && args->Length() == 1) {
1123     bool detach = false;
1124     mate::Dictionary options;
1125     if (args->GetNext(&options)) {
1126       options.Get("mode", &state);
1127
1128       // TODO(kevinsawicki) Remove in 2.0
1129       options.Get("detach", &detach);
1130       if (state.empty() && detach)
1131         state = "detach";
1132     }
1133   }
1134   managed_web_contents()->SetDockState(state);
1135   managed_web_contents()->ShowDevTools();
1136 }
1137
1138 void WebContents::CloseDevTools() {
1139   if (type_ == REMOTE)
1140     return;
1141
1142   managed_web_contents()->CloseDevTools();
1143 }
1144
1145 bool WebContents::IsDevToolsOpened() {
1146   if (type_ == REMOTE)
1147     return false;
1148
1149   return managed_web_contents()->IsDevToolsViewShowing();
1150 }
1151
1152 bool WebContents::IsDevToolsFocused() {
1153   if (type_ == REMOTE)
1154     return false;
1155
1156   return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1157 }
1158
1159 void WebContents::EnableDeviceEmulation(
1160     const blink::WebDeviceEmulationParams& params) {
1161   if (type_ == REMOTE)
1162     return;
1163
1164   Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1165 }
1166
1167 void WebContents::DisableDeviceEmulation() {
1168   if (type_ == REMOTE)
1169     return;
1170
1171   Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1172 }
1173
1174 void WebContents::ToggleDevTools() {
1175   if (IsDevToolsOpened())
1176     CloseDevTools();
1177   else
1178     OpenDevTools(nullptr);
1179 }
1180
1181 void WebContents::InspectElement(int x, int y) {
1182   if (type_ == REMOTE)
1183     return;
1184
1185   if (!enable_devtools_)
1186     return;
1187
1188   if (!managed_web_contents()->GetDevToolsWebContents())
1189     OpenDevTools(nullptr);
1190   managed_web_contents()->InspectElement(x, y);
1191 }
1192
1193 void WebContents::InspectServiceWorker() {
1194   if (type_ == REMOTE)
1195     return;
1196
1197   if (!enable_devtools_)
1198     return;
1199
1200   for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1201     if (agent_host->GetType() ==
1202         content::DevToolsAgentHost::kTypeServiceWorker) {
1203       OpenDevTools(nullptr);
1204       managed_web_contents()->AttachTo(agent_host);
1205       break;
1206     }
1207   }
1208 }
1209
1210 void WebContents::HasServiceWorker(
1211     const base::Callback<void(bool)>& callback) {
1212   auto context = GetServiceWorkerContext(web_contents());
1213   if (!context)
1214     return;
1215
1216   context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1217                                  GURL::EmptyGURL(),
1218                                  callback);
1219 }
1220
1221 void WebContents::UnregisterServiceWorker(
1222     const base::Callback<void(bool)>& callback) {
1223   auto context = GetServiceWorkerContext(web_contents());
1224   if (!context)
1225     return;
1226
1227   context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1228                                    callback);
1229 }
1230
1231 void WebContents::SetAudioMuted(bool muted) {
1232   web_contents()->SetAudioMuted(muted);
1233 }
1234
1235 bool WebContents::IsAudioMuted() {
1236   return web_contents()->IsAudioMuted();
1237 }
1238
1239 void WebContents::Print(mate::Arguments* args) {
1240   PrintSettings settings = { false, false };
1241   if (args->Length() == 1 && !args->GetNext(&settings)) {
1242     args->ThrowError();
1243     return;
1244   }
1245
1246   printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1247       PrintNow(web_contents()->GetMainFrame(),
1248                settings.silent,
1249                settings.print_background);
1250 }
1251
1252 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1253                              const PrintToPDFCallback& callback) {
1254   printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1255       PrintToPDF(setting, callback);
1256 }
1257
1258 void WebContents::AddWorkSpace(mate::Arguments* args,
1259                                const base::FilePath& path) {
1260   if (path.empty()) {
1261     args->ThrowError("path cannot be empty");
1262     return;
1263   }
1264   DevToolsAddFileSystem(path);
1265 }
1266
1267 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1268                                   const base::FilePath& path) {
1269   if (path.empty()) {
1270     args->ThrowError("path cannot be empty");
1271     return;
1272   }
1273   DevToolsRemoveFileSystem(path);
1274 }
1275
1276 void WebContents::Undo() {
1277   web_contents()->Undo();
1278 }
1279
1280 void WebContents::Redo() {
1281   web_contents()->Redo();
1282 }
1283
1284 void WebContents::Cut() {
1285   web_contents()->Cut();
1286 }
1287
1288 void WebContents::Copy() {
1289   web_contents()->Copy();
1290 }
1291
1292 void WebContents::Paste() {
1293   web_contents()->Paste();
1294 }
1295
1296 void WebContents::PasteAndMatchStyle() {
1297   web_contents()->PasteAndMatchStyle();
1298 }
1299
1300 void WebContents::Delete() {
1301   web_contents()->Delete();
1302 }
1303
1304 void WebContents::SelectAll() {
1305   web_contents()->SelectAll();
1306 }
1307
1308 void WebContents::Unselect() {
1309   web_contents()->Unselect();
1310 }
1311
1312 void WebContents::Replace(const base::string16& word) {
1313   web_contents()->Replace(word);
1314 }
1315
1316 void WebContents::ReplaceMisspelling(const base::string16& word) {
1317   web_contents()->ReplaceMisspelling(word);
1318 }
1319
1320 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1321   uint32_t request_id = GetNextRequestId();
1322   base::string16 search_text;
1323   blink::WebFindOptions options;
1324   if (!args->GetNext(&search_text) || search_text.empty()) {
1325     args->ThrowError("Must provide a non-empty search content");
1326     return 0;
1327   }
1328
1329   args->GetNext(&options);
1330
1331   web_contents()->Find(request_id, search_text, options);
1332   return request_id;
1333 }
1334
1335 void WebContents::StopFindInPage(content::StopFindAction action) {
1336   web_contents()->StopFinding(action);
1337 }
1338
1339 void WebContents::ShowDefinitionForSelection() {
1340 #if defined(OS_MACOSX)
1341   const auto view = web_contents()->GetRenderWidgetHostView();
1342   if (view)
1343     view->ShowDefinitionForSelection();
1344 #endif
1345 }
1346
1347 void WebContents::CopyImageAt(int x, int y) {
1348   const auto host = web_contents()->GetMainFrame();
1349   if (host)
1350     host->CopyImageAt(x, y);
1351 }
1352
1353 void WebContents::Focus() {
1354   web_contents()->Focus();
1355 }
1356
1357 #if !defined(OS_MACOSX)
1358 bool WebContents::IsFocused() const {
1359   auto view = web_contents()->GetRenderWidgetHostView();
1360   if (!view) return false;
1361
1362   if (GetType() != BACKGROUND_PAGE) {
1363     auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1364     if (window && !window->IsVisible())
1365       return false;
1366   }
1367
1368   return view->HasFocus();
1369 }
1370 #endif
1371
1372 void WebContents::TabTraverse(bool reverse) {
1373   web_contents()->FocusThroughTabTraversal(reverse);
1374 }
1375
1376 bool WebContents::SendIPCMessage(bool all_frames,
1377                                  const base::string16& channel,
1378                                  const base::ListValue& args) {
1379   return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1380 }
1381
1382 void WebContents::SendInputEvent(v8::Isolate* isolate,
1383                                  v8::Local<v8::Value> input_event) {
1384   const auto view = web_contents()->GetRenderWidgetHostView();
1385   if (!view)
1386     return;
1387   const auto host = view->GetRenderWidgetHost();
1388   if (!host)
1389     return;
1390
1391   int type = mate::GetWebInputEventType(isolate, input_event);
1392   if (blink::WebInputEvent::isMouseEventType(type)) {
1393     blink::WebMouseEvent mouse_event;
1394     if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1395       host->ForwardMouseEvent(mouse_event);
1396       return;
1397     }
1398   } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1399     content::NativeWebKeyboardEvent keyboard_event;
1400     if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1401       host->ForwardKeyboardEvent(keyboard_event);
1402       return;
1403     }
1404   } else if (type == blink::WebInputEvent::MouseWheel) {
1405     blink::WebMouseWheelEvent mouse_wheel_event;
1406     if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1407       host->ForwardWheelEvent(mouse_wheel_event);
1408       return;
1409     }
1410   }
1411
1412   isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1413       isolate, "Invalid event object")));
1414 }
1415
1416 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1417   bool only_dirty = false;
1418   FrameSubscriber::FrameCaptureCallback callback;
1419
1420   args->GetNext(&only_dirty);
1421   if (!args->GetNext(&callback)) {
1422     args->ThrowError();
1423     return;
1424   }
1425
1426   const auto view = web_contents()->GetRenderWidgetHostView();
1427   if (view) {
1428     std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1429         isolate(), view, callback, only_dirty));
1430     view->BeginFrameSubscription(std::move(frame_subscriber));
1431   }
1432 }
1433
1434 void WebContents::EndFrameSubscription() {
1435   const auto view = web_contents()->GetRenderWidgetHostView();
1436   if (view)
1437     view->EndFrameSubscription();
1438 }
1439
1440 void WebContents::StartDrag(const mate::Dictionary& item,
1441                             mate::Arguments* args) {
1442   base::FilePath file;
1443   std::vector<base::FilePath> files;
1444   if (!item.Get("files", &files) && item.Get("file", &file)) {
1445     files.push_back(file);
1446   }
1447
1448   mate::Handle<NativeImage> icon;
1449   if (!item.Get("icon", &icon) && !file.empty()) {
1450     // TODO(zcbenz): Set default icon from file.
1451   }
1452
1453   // Error checking.
1454   if (icon.IsEmpty()) {
1455     args->ThrowError("Must specify 'icon' option");
1456     return;
1457   }
1458
1459 #if defined(OS_MACOSX)
1460   // NSWindow.dragImage requires a non-empty NSImage
1461   if (icon->image().IsEmpty()) {
1462     args->ThrowError("Must specify non-empty 'icon' option");
1463     return;
1464   }
1465 #endif
1466
1467   // Start dragging.
1468   if (!files.empty()) {
1469     base::MessageLoop::ScopedNestableTaskAllower allow(
1470         base::MessageLoop::current());
1471     DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1472   } else {
1473     args->ThrowError("Must specify either 'file' or 'files' option");
1474   }
1475 }
1476
1477 void WebContents::CapturePage(mate::Arguments* args) {
1478   gfx::Rect rect;
1479   base::Callback<void(const gfx::Image&)> callback;
1480
1481   if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1482       !(args->Length() == 2 && args->GetNext(&rect)
1483                             && args->GetNext(&callback))) {
1484     args->ThrowError();
1485     return;
1486   }
1487
1488   const auto view = web_contents()->GetRenderWidgetHostView();
1489   const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1490   if (!view || !host) {
1491     callback.Run(gfx::Image());
1492     return;
1493   }
1494
1495   // Capture full page if user doesn't specify a |rect|.
1496   const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1497                                                rect.size();
1498
1499   // By default, the requested bitmap size is the view size in screen
1500   // coordinates.  However, if there's more pixel detail available on the
1501   // current system, increase the requested bitmap size to capture it all.
1502   gfx::Size bitmap_size = view_size;
1503   const gfx::NativeView native_view = view->GetNativeView();
1504   const float scale =
1505       display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1506       .device_scale_factor();
1507   if (scale > 1.0f)
1508     bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1509
1510   host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1511                              bitmap_size,
1512                              base::Bind(&OnCapturePageDone, callback),
1513                              kBGRA_8888_SkColorType);
1514 }
1515
1516 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1517   content::WebCursor::CursorInfo info;
1518   cursor.GetCursorInfo(&info);
1519
1520   if (cursor.IsCustom()) {
1521     Emit("cursor-changed", CursorTypeToString(info),
1522       gfx::Image::CreateFrom1xBitmap(info.custom_image),
1523       info.image_scale_factor,
1524       gfx::Size(info.custom_image.width(), info.custom_image.height()),
1525       info.hotspot);
1526   } else {
1527     Emit("cursor-changed", CursorTypeToString(info));
1528   }
1529 }
1530
1531 void WebContents::SetSize(const SetSizeParams& params) {
1532   if (guest_delegate_)
1533     guest_delegate_->SetSize(params);
1534 }
1535
1536 bool WebContents::IsGuest() const {
1537   return type_ == WEB_VIEW;
1538 }
1539
1540 bool WebContents::IsOffScreen() const {
1541   return type_ == OFF_SCREEN;
1542 }
1543
1544 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1545   mate::Handle<NativeImage> image =
1546       NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1547   Emit("paint", dirty_rect, image);
1548 }
1549
1550 void WebContents::StartPainting() {
1551   if (!IsOffScreen())
1552     return;
1553
1554   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1555       web_contents()->GetRenderWidgetHostView());
1556   if (osr_rwhv)
1557     osr_rwhv->SetPainting(true);
1558 }
1559
1560 void WebContents::StopPainting() {
1561   if (!IsOffScreen())
1562     return;
1563
1564   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1565       web_contents()->GetRenderWidgetHostView());
1566   if (osr_rwhv)
1567     osr_rwhv->SetPainting(false);
1568 }
1569
1570 bool WebContents::IsPainting() const {
1571   if (!IsOffScreen())
1572     return false;
1573
1574   const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1575       web_contents()->GetRenderWidgetHostView());
1576   return osr_rwhv && osr_rwhv->IsPainting();
1577 }
1578
1579 void WebContents::SetFrameRate(int frame_rate) {
1580   if (!IsOffScreen())
1581     return;
1582
1583   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1584       web_contents()->GetRenderWidgetHostView());
1585   if (osr_rwhv)
1586     osr_rwhv->SetFrameRate(frame_rate);
1587 }
1588
1589 int WebContents::GetFrameRate() const {
1590   if (!IsOffScreen())
1591     return 0;
1592
1593   const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1594       web_contents()->GetRenderWidgetHostView());
1595   return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1596 }
1597
1598 void WebContents::Invalidate() {
1599   if (IsOffScreen()) {
1600     auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1601       web_contents()->GetRenderWidgetHostView());
1602     if (osr_rwhv)
1603       osr_rwhv->Invalidate();
1604   } else {
1605     const auto window = owner_window();
1606     if (window)
1607       window->Invalidate();
1608   }
1609 }
1610
1611 void WebContents::SetZoomLevel(double level) {
1612   zoom_controller_->SetZoomLevel(level);
1613 }
1614
1615 double WebContents::GetZoomLevel() {
1616   return zoom_controller_->GetZoomLevel();
1617 }
1618
1619 void WebContents::SetZoomFactor(double factor) {
1620   auto level = content::ZoomFactorToZoomLevel(factor);
1621   SetZoomLevel(level);
1622 }
1623
1624 double WebContents::GetZoomFactor() {
1625   auto level = GetZoomLevel();
1626   return content::ZoomLevelToZoomFactor(level);
1627 }
1628
1629 void WebContents::OnSetTemporaryZoomLevel(double level,
1630                                           IPC::Message* reply_msg) {
1631   zoom_controller_->SetTemporaryZoomLevel(level);
1632   double new_level = zoom_controller_->GetZoomLevel();
1633   AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1634   Send(reply_msg);
1635 }
1636
1637 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1638   AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1639   Send(reply_msg);
1640 }
1641
1642 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1643   WebContentsPreferences* web_preferences =
1644       WebContentsPreferences::FromWebContents(web_contents());
1645   return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1646 }
1647
1648 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1649   if (owner_window())
1650     return Window::From(isolate(), owner_window());
1651   else
1652     return v8::Null(isolate());
1653 }
1654
1655 int32_t WebContents::ID() const {
1656   return weak_map_id();
1657 }
1658
1659 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1660   return v8::Local<v8::Value>::New(isolate, session_);
1661 }
1662
1663 content::WebContents* WebContents::HostWebContents() {
1664   if (!embedder_)
1665     return nullptr;
1666   return embedder_->web_contents();
1667 }
1668
1669 void WebContents::SetEmbedder(const WebContents* embedder) {
1670   if (embedder) {
1671     NativeWindow* owner_window = nullptr;
1672     auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1673     if (relay) {
1674       owner_window = relay->window.get();
1675     }
1676     if (owner_window)
1677       SetOwnerWindow(owner_window);
1678
1679     content::RenderWidgetHostView* rwhv =
1680         web_contents()->GetRenderWidgetHostView();
1681     if (rwhv) {
1682       rwhv->Hide();
1683       rwhv->Show();
1684     }
1685   }
1686 }
1687
1688 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1689   if (devtools_web_contents_.IsEmpty())
1690     return v8::Null(isolate);
1691   else
1692     return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1693 }
1694
1695 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1696   if (debugger_.IsEmpty()) {
1697     auto handle = atom::api::Debugger::Create(isolate, web_contents());
1698     debugger_.Reset(isolate, handle.ToV8());
1699   }
1700   return v8::Local<v8::Value>::New(isolate, debugger_);
1701 }
1702
1703 // static
1704 void WebContents::BuildPrototype(v8::Isolate* isolate,
1705                                  v8::Local<v8::FunctionTemplate> prototype) {
1706   prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1707   mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1708       .MakeDestroyable()
1709       .SetMethod("getId", &WebContents::GetID)
1710       .SetMethod("getProcessId", &WebContents::GetProcessID)
1711       .SetMethod("equal", &WebContents::Equal)
1712       .SetMethod("_loadURL", &WebContents::LoadURL)
1713       .SetMethod("downloadURL", &WebContents::DownloadURL)
1714       .SetMethod("_getURL", &WebContents::GetURL)
1715       .SetMethod("getTitle", &WebContents::GetTitle)
1716       .SetMethod("isLoading", &WebContents::IsLoading)
1717       .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1718       .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1719       .SetMethod("_stop", &WebContents::Stop)
1720       .SetMethod("_goBack", &WebContents::GoBack)
1721       .SetMethod("_goForward", &WebContents::GoForward)
1722       .SetMethod("_goToOffset", &WebContents::GoToOffset)
1723       .SetMethod("isCrashed", &WebContents::IsCrashed)
1724       .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1725       .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1726       .SetMethod("savePage", &WebContents::SavePage)
1727       .SetMethod("openDevTools", &WebContents::OpenDevTools)
1728       .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1729       .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1730       .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1731       .SetMethod("enableDeviceEmulation",
1732                  &WebContents::EnableDeviceEmulation)
1733       .SetMethod("disableDeviceEmulation",
1734                  &WebContents::DisableDeviceEmulation)
1735       .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1736       .SetMethod("inspectElement", &WebContents::InspectElement)
1737       .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1738       .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1739       .SetMethod("undo", &WebContents::Undo)
1740       .SetMethod("redo", &WebContents::Redo)
1741       .SetMethod("cut", &WebContents::Cut)
1742       .SetMethod("copy", &WebContents::Copy)
1743       .SetMethod("paste", &WebContents::Paste)
1744       .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1745       .SetMethod("delete", &WebContents::Delete)
1746       .SetMethod("selectAll", &WebContents::SelectAll)
1747       .SetMethod("unselect", &WebContents::Unselect)
1748       .SetMethod("replace", &WebContents::Replace)
1749       .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1750       .SetMethod("findInPage", &WebContents::FindInPage)
1751       .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1752       .SetMethod("focus", &WebContents::Focus)
1753       .SetMethod("isFocused", &WebContents::IsFocused)
1754       .SetMethod("tabTraverse", &WebContents::TabTraverse)
1755       .SetMethod("_send", &WebContents::SendIPCMessage)
1756       .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1757       .SetMethod("beginFrameSubscription",
1758                  &WebContents::BeginFrameSubscription)
1759       .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1760       .SetMethod("startDrag", &WebContents::StartDrag)
1761       .SetMethod("setSize", &WebContents::SetSize)
1762       .SetMethod("isGuest", &WebContents::IsGuest)
1763       .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1764       .SetMethod("startPainting", &WebContents::StartPainting)
1765       .SetMethod("stopPainting", &WebContents::StopPainting)
1766       .SetMethod("isPainting", &WebContents::IsPainting)
1767       .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1768       .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1769       .SetMethod("invalidate", &WebContents::Invalidate)
1770       .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1771       .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1772       .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1773       .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1774       .SetMethod("getType", &WebContents::GetType)
1775       .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1776       .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1777       .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1778       .SetMethod("unregisterServiceWorker",
1779                  &WebContents::UnregisterServiceWorker)
1780       .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1781       .SetMethod("print", &WebContents::Print)
1782       .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1783       .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1784       .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1785       .SetMethod("showDefinitionForSelection",
1786                  &WebContents::ShowDefinitionForSelection)
1787       .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1788       .SetMethod("capturePage", &WebContents::CapturePage)
1789       .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1790       .SetMethod("setWebRTCIPHandlingPolicy",
1791                  &WebContents::SetWebRTCIPHandlingPolicy)
1792       .SetMethod("getWebRTCIPHandlingPolicy",
1793                  &WebContents::GetWebRTCIPHandlingPolicy)
1794       .SetProperty("id", &WebContents::ID)
1795       .SetProperty("session", &WebContents::Session)
1796       .SetProperty("hostWebContents", &WebContents::HostWebContents)
1797       .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1798       .SetProperty("debugger", &WebContents::Debugger);
1799 }
1800
1801 AtomBrowserContext* WebContents::GetBrowserContext() const {
1802   return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1803 }
1804
1805 void WebContents::OnRendererMessage(const base::string16& channel,
1806                                     const base::ListValue& args) {
1807   // webContents.emit(channel, new Event(), args...);
1808   Emit(base::UTF16ToUTF8(channel), args);
1809 }
1810
1811 void WebContents::OnRendererMessageSync(const base::string16& channel,
1812                                         const base::ListValue& args,
1813                                         IPC::Message* message) {
1814   // webContents.emit(channel, new Event(sender, message), args...);
1815   EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1816 }
1817
1818 // static
1819 mate::Handle<WebContents> WebContents::CreateFrom(
1820     v8::Isolate* isolate, content::WebContents* web_contents) {
1821   // We have an existing WebContents object in JS.
1822   auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1823   if (existing)
1824     return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1825
1826   // Otherwise create a new WebContents wrapper object.
1827   return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1828         REMOTE));
1829 }
1830
1831 mate::Handle<WebContents> WebContents::CreateFrom(
1832     v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1833   // Otherwise create a new WebContents wrapper object.
1834   return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1835         type));
1836 }
1837
1838 // static
1839 mate::Handle<WebContents> WebContents::Create(
1840     v8::Isolate* isolate, const mate::Dictionary& options) {
1841   return mate::CreateHandle(isolate, new WebContents(isolate, options));
1842 }
1843
1844 }  // namespace api
1845
1846 }  // namespace atom
1847
1848 namespace {
1849
1850 using atom::api::WebContents;
1851
1852 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1853                 v8::Local<v8::Context> context, void* priv) {
1854   v8::Isolate* isolate = context->GetIsolate();
1855   mate::Dictionary dict(isolate, exports);
1856   dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1857   dict.SetMethod("create", &WebContents::Create);
1858   dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1859   dict.SetMethod("getAllWebContents",
1860                  &mate::TrackableObject<WebContents>::GetAll);
1861 }
1862
1863 }  // namespace
1864
1865 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)