Revert "Initial implementation of app loop"
[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) && !defined(USE_EFL)
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
911     // FIXME: Disable OnCursorChange due to stach_chk_fail crash.
912     // IPC_MESSAGE_HANDLER_CODE(ViewHostMsg_SetCursor, OnCursorChange,
913     //   handled = false)
914     IPC_MESSAGE_UNHANDLED(handled = false)
915   IPC_END_MESSAGE_MAP()
916
917   return handled;
918 }
919
920 // There are three ways of destroying a webContents:
921 // 1. call webContents.destroy();
922 // 2. garbage collection;
923 // 3. user closes the window of webContents;
924 // For webview only #1 will happen, for BrowserWindow both #1 and #3 may
925 // happen. The #2 should never happen for webContents, because webview is
926 // managed by GuestViewManager, and BrowserWindow's webContents is managed
927 // by api::Window.
928 // For #1, the destructor will do the cleanup work and we only need to make
929 // sure "destroyed" event is emitted. For #3, the content::WebContents will
930 // be destroyed on close, and WebContentsDestroyed would be called for it, so
931 // we need to make sure the api::WebContents is also deleted.
932 void WebContents::WebContentsDestroyed() {
933   // Cleanup relationships with other parts.
934   RemoveFromWeakMap();
935
936   // We can not call Destroy here because we need to call Emit first, but we
937   // also do not want any method to be used, so just mark as destroyed here.
938   MarkDestroyed();
939
940   Emit("destroyed");
941
942   // Destroy the native class in next tick.
943   base::ThreadTaskRunnerHandle::Get()->PostTask(
944       FROM_HERE, GetDestroyClosure());
945 }
946
947 void WebContents::NavigationEntryCommitted(
948     const content::LoadCommittedDetails& details) {
949   Emit("navigation-entry-commited", details.entry->GetURL(),
950        details.is_in_page, details.did_replace_entry);
951 }
952
953 int64_t WebContents::GetID() const {
954   int64_t process_id = web_contents()->GetRenderProcessHost()->GetID();
955   int64_t routing_id = web_contents()->GetRoutingID();
956   int64_t rv = (process_id << 32) + routing_id;
957   return rv;
958 }
959
960 int WebContents::GetProcessID() const {
961   return web_contents()->GetRenderProcessHost()->GetID();
962 }
963
964 WebContents::Type WebContents::GetType() const {
965   return type_;
966 }
967
968 bool WebContents::Equal(const WebContents* web_contents) const {
969   return GetID() == web_contents->GetID();
970 }
971
972 void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
973   if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
974     Emit("did-fail-load",
975          static_cast<int>(net::ERR_INVALID_URL),
976          net::ErrorToShortString(net::ERR_INVALID_URL),
977          url.possibly_invalid_spec(),
978          true);
979     return;
980   }
981
982   content::NavigationController::LoadURLParams params(url);
983
984   GURL http_referrer;
985   if (options.Get("httpReferrer", &http_referrer))
986     params.referrer = content::Referrer(http_referrer.GetAsReferrer(),
987                                         blink::WebReferrerPolicyDefault);
988
989   std::string user_agent;
990   if (options.Get("userAgent", &user_agent))
991     web_contents()->SetUserAgentOverride(user_agent);
992
993   std::string extra_headers;
994   if (options.Get("extraHeaders", &extra_headers))
995     params.extra_headers = extra_headers;
996
997   scoped_refptr<content::ResourceRequestBodyImpl> body;
998   if (options.Get("postData", &body)) {
999     params.post_data = body;
1000     params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
1001   }
1002
1003   GURL base_url_for_data_url;
1004   if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
1005     params.base_url_for_data_url = base_url_for_data_url;
1006     params.load_type = content::NavigationController::LOAD_TYPE_DATA;
1007   }
1008
1009   params.transition_type = ui::PAGE_TRANSITION_TYPED;
1010   params.should_clear_history_list = true;
1011   params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
1012
1013   if (deferred_load_url_.id) {
1014     deferred_load_url_.params = params;
1015     return;
1016   }
1017
1018   web_contents()->GetController().LoadURLWithParams(params);
1019   // We have to call it right after LoadURL because the RenderViewHost is only
1020   // created after loading a page.
1021   SetBackgroundColor(web_contents());
1022 }
1023
1024 void WebContents::DownloadURL(const GURL& url) {
1025   auto browser_context = web_contents()->GetBrowserContext();
1026   auto download_manager =
1027     content::BrowserContext::GetDownloadManager(browser_context);
1028
1029   download_manager->DownloadUrl(
1030       content::DownloadUrlParameters::CreateForWebContentsMainFrame(
1031           web_contents(), url));
1032 }
1033
1034 GURL WebContents::GetURL() const {
1035   return web_contents()->GetURL();
1036 }
1037
1038 base::string16 WebContents::GetTitle() const {
1039   return web_contents()->GetTitle();
1040 }
1041
1042 bool WebContents::IsLoading() const {
1043   return web_contents()->IsLoading();
1044 }
1045
1046 bool WebContents::IsLoadingMainFrame() const {
1047   // Comparing site instances works because Electron always creates a new site
1048   // instance when navigating, regardless of origin. See AtomBrowserClient.
1049   return (web_contents()->GetLastCommittedURL().is_empty() ||
1050           web_contents()->GetSiteInstance() !=
1051           web_contents()->GetPendingSiteInstance()) && IsLoading();
1052 }
1053
1054 bool WebContents::IsWaitingForResponse() const {
1055   return web_contents()->IsWaitingForResponse();
1056 }
1057
1058 void WebContents::Stop() {
1059   web_contents()->Stop();
1060 }
1061
1062 void WebContents::GoBack() {
1063   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1064   web_contents()->GetController().GoBack();
1065 }
1066
1067 void WebContents::GoForward() {
1068   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1069   web_contents()->GetController().GoForward();
1070 }
1071
1072 void WebContents::GoToOffset(int offset) {
1073   atom::AtomBrowserClient::SuppressRendererProcessRestartForOnce();
1074   web_contents()->GetController().GoToOffset(offset);
1075 }
1076
1077 const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
1078   return web_contents()->
1079     GetMutableRendererPrefs()->webrtc_ip_handling_policy;
1080 }
1081
1082 void WebContents::SetWebRTCIPHandlingPolicy(
1083     const std::string& webrtc_ip_handling_policy) {
1084   if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
1085     return;
1086   web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
1087     webrtc_ip_handling_policy;
1088
1089   content::RenderViewHost* host = web_contents()->GetRenderViewHost();
1090   if (host)
1091     host->SyncRendererPrefs();
1092 }
1093
1094 bool WebContents::IsCrashed() const {
1095   return web_contents()->IsCrashed();
1096 }
1097
1098 void WebContents::SetUserAgent(const std::string& user_agent,
1099                                mate::Arguments* args) {
1100   web_contents()->SetUserAgentOverride(user_agent);
1101 }
1102
1103 std::string WebContents::GetUserAgent() {
1104   return web_contents()->GetUserAgentOverride();
1105 }
1106
1107 bool WebContents::SavePage(const base::FilePath& full_file_path,
1108                            const content::SavePageType& save_type,
1109                            const SavePageHandler::SavePageCallback& callback) {
1110   auto handler = new SavePageHandler(web_contents(), callback);
1111   return handler->Handle(full_file_path, save_type);
1112 }
1113
1114 void WebContents::OpenDevTools(mate::Arguments* args) {
1115   if (type_ == REMOTE)
1116     return;
1117
1118   if (!enable_devtools_)
1119     return;
1120
1121   std::string state;
1122   if (type_ == WEB_VIEW || !owner_window()) {
1123     state = "detach";
1124   } else if (args && args->Length() == 1) {
1125     bool detach = false;
1126     mate::Dictionary options;
1127     if (args->GetNext(&options)) {
1128       options.Get("mode", &state);
1129
1130       // TODO(kevinsawicki) Remove in 2.0
1131       options.Get("detach", &detach);
1132       if (state.empty() && detach)
1133         state = "detach";
1134     }
1135   }
1136   managed_web_contents()->SetDockState(state);
1137   managed_web_contents()->ShowDevTools();
1138 }
1139
1140 void WebContents::CloseDevTools() {
1141   if (type_ == REMOTE)
1142     return;
1143
1144   managed_web_contents()->CloseDevTools();
1145 }
1146
1147 bool WebContents::IsDevToolsOpened() {
1148   if (type_ == REMOTE)
1149     return false;
1150
1151   return managed_web_contents()->IsDevToolsViewShowing();
1152 }
1153
1154 bool WebContents::IsDevToolsFocused() {
1155   if (type_ == REMOTE)
1156     return false;
1157
1158   return managed_web_contents()->GetView()->IsDevToolsViewFocused();
1159 }
1160
1161 void WebContents::EnableDeviceEmulation(
1162     const blink::WebDeviceEmulationParams& params) {
1163   if (type_ == REMOTE)
1164     return;
1165
1166   Send(new ViewMsg_EnableDeviceEmulation(routing_id(), params));
1167 }
1168
1169 void WebContents::DisableDeviceEmulation() {
1170   if (type_ == REMOTE)
1171     return;
1172
1173   Send(new ViewMsg_DisableDeviceEmulation(routing_id()));
1174 }
1175
1176 void WebContents::ToggleDevTools() {
1177   if (IsDevToolsOpened())
1178     CloseDevTools();
1179   else
1180     OpenDevTools(nullptr);
1181 }
1182
1183 void WebContents::InspectElement(int x, int y) {
1184   if (type_ == REMOTE)
1185     return;
1186
1187   if (!enable_devtools_)
1188     return;
1189
1190   if (!managed_web_contents()->GetDevToolsWebContents())
1191     OpenDevTools(nullptr);
1192   managed_web_contents()->InspectElement(x, y);
1193 }
1194
1195 void WebContents::InspectServiceWorker() {
1196   if (type_ == REMOTE)
1197     return;
1198
1199   if (!enable_devtools_)
1200     return;
1201
1202   for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
1203     if (agent_host->GetType() ==
1204         content::DevToolsAgentHost::kTypeServiceWorker) {
1205       OpenDevTools(nullptr);
1206       managed_web_contents()->AttachTo(agent_host);
1207       break;
1208     }
1209   }
1210 }
1211
1212 void WebContents::HasServiceWorker(
1213     const base::Callback<void(bool)>& callback) {
1214   auto context = GetServiceWorkerContext(web_contents());
1215   if (!context)
1216     return;
1217
1218   context->CheckHasServiceWorker(web_contents()->GetLastCommittedURL(),
1219                                  GURL::EmptyGURL(),
1220                                  callback);
1221 }
1222
1223 void WebContents::UnregisterServiceWorker(
1224     const base::Callback<void(bool)>& callback) {
1225   auto context = GetServiceWorkerContext(web_contents());
1226   if (!context)
1227     return;
1228
1229   context->UnregisterServiceWorker(web_contents()->GetLastCommittedURL(),
1230                                    callback);
1231 }
1232
1233 void WebContents::SetAudioMuted(bool muted) {
1234   web_contents()->SetAudioMuted(muted);
1235 }
1236
1237 bool WebContents::IsAudioMuted() {
1238   return web_contents()->IsAudioMuted();
1239 }
1240
1241 void WebContents::Print(mate::Arguments* args) {
1242   PrintSettings settings = { false, false };
1243   if (args->Length() == 1 && !args->GetNext(&settings)) {
1244     args->ThrowError();
1245     return;
1246   }
1247
1248   printing::PrintViewManagerBasic::FromWebContents(web_contents())->
1249       PrintNow(web_contents()->GetMainFrame(),
1250                settings.silent,
1251                settings.print_background);
1252 }
1253
1254 void WebContents::PrintToPDF(const base::DictionaryValue& setting,
1255                              const PrintToPDFCallback& callback) {
1256   printing::PrintPreviewMessageHandler::FromWebContents(web_contents())->
1257       PrintToPDF(setting, callback);
1258 }
1259
1260 void WebContents::AddWorkSpace(mate::Arguments* args,
1261                                const base::FilePath& path) {
1262   if (path.empty()) {
1263     args->ThrowError("path cannot be empty");
1264     return;
1265   }
1266   DevToolsAddFileSystem(path);
1267 }
1268
1269 void WebContents::RemoveWorkSpace(mate::Arguments* args,
1270                                   const base::FilePath& path) {
1271   if (path.empty()) {
1272     args->ThrowError("path cannot be empty");
1273     return;
1274   }
1275   DevToolsRemoveFileSystem(path);
1276 }
1277
1278 void WebContents::Undo() {
1279   web_contents()->Undo();
1280 }
1281
1282 void WebContents::Redo() {
1283   web_contents()->Redo();
1284 }
1285
1286 void WebContents::Cut() {
1287   web_contents()->Cut();
1288 }
1289
1290 void WebContents::Copy() {
1291   web_contents()->Copy();
1292 }
1293
1294 void WebContents::Paste() {
1295   web_contents()->Paste();
1296 }
1297
1298 void WebContents::PasteAndMatchStyle() {
1299   web_contents()->PasteAndMatchStyle();
1300 }
1301
1302 void WebContents::Delete() {
1303   web_contents()->Delete();
1304 }
1305
1306 void WebContents::SelectAll() {
1307   web_contents()->SelectAll();
1308 }
1309
1310 void WebContents::Unselect() {
1311   web_contents()->Unselect();
1312 }
1313
1314 void WebContents::Replace(const base::string16& word) {
1315   web_contents()->Replace(word);
1316 }
1317
1318 void WebContents::ReplaceMisspelling(const base::string16& word) {
1319   web_contents()->ReplaceMisspelling(word);
1320 }
1321
1322 uint32_t WebContents::FindInPage(mate::Arguments* args) {
1323   uint32_t request_id = GetNextRequestId();
1324   base::string16 search_text;
1325   blink::WebFindOptions options;
1326   if (!args->GetNext(&search_text) || search_text.empty()) {
1327     args->ThrowError("Must provide a non-empty search content");
1328     return 0;
1329   }
1330
1331   args->GetNext(&options);
1332
1333   web_contents()->Find(request_id, search_text, options);
1334   return request_id;
1335 }
1336
1337 void WebContents::StopFindInPage(content::StopFindAction action) {
1338   web_contents()->StopFinding(action);
1339 }
1340
1341 void WebContents::ShowDefinitionForSelection() {
1342 #if defined(OS_MACOSX)
1343   const auto view = web_contents()->GetRenderWidgetHostView();
1344   if (view)
1345     view->ShowDefinitionForSelection();
1346 #endif
1347 }
1348
1349 void WebContents::CopyImageAt(int x, int y) {
1350   const auto host = web_contents()->GetMainFrame();
1351   if (host)
1352     host->CopyImageAt(x, y);
1353 }
1354
1355 void WebContents::Focus() {
1356   web_contents()->Focus();
1357 }
1358
1359 #if !defined(OS_MACOSX)
1360 bool WebContents::IsFocused() const {
1361   auto view = web_contents()->GetRenderWidgetHostView();
1362   if (!view) return false;
1363
1364 #if defined(USE_EFL)
1365   NOTIMPLEMENTED();
1366 #else
1367   if (GetType() != BACKGROUND_PAGE) {
1368     auto window = web_contents()->GetNativeView()->GetToplevelWindow();
1369     if (window && !window->IsVisible())
1370       return false;
1371   }
1372 #endif
1373
1374   return view->HasFocus();
1375 }
1376 #endif
1377
1378 void WebContents::TabTraverse(bool reverse) {
1379   web_contents()->FocusThroughTabTraversal(reverse);
1380 }
1381
1382 bool WebContents::SendIPCMessage(bool all_frames,
1383                                  const base::string16& channel,
1384                                  const base::ListValue& args) {
1385   return Send(new AtomViewMsg_Message(routing_id(), all_frames, channel, args));
1386 }
1387
1388 void WebContents::SendInputEvent(v8::Isolate* isolate,
1389                                  v8::Local<v8::Value> input_event) {
1390   const auto view = web_contents()->GetRenderWidgetHostView();
1391   if (!view)
1392     return;
1393   const auto host = view->GetRenderWidgetHost();
1394   if (!host)
1395     return;
1396
1397   int type = mate::GetWebInputEventType(isolate, input_event);
1398   if (blink::WebInputEvent::isMouseEventType(type)) {
1399     blink::WebMouseEvent mouse_event;
1400     if (mate::ConvertFromV8(isolate, input_event, &mouse_event)) {
1401       host->ForwardMouseEvent(mouse_event);
1402       return;
1403     }
1404   } else if (blink::WebInputEvent::isKeyboardEventType(type)) {
1405     content::NativeWebKeyboardEvent keyboard_event;
1406     if (mate::ConvertFromV8(isolate, input_event, &keyboard_event)) {
1407       host->ForwardKeyboardEvent(keyboard_event);
1408       return;
1409     }
1410   } else if (type == blink::WebInputEvent::MouseWheel) {
1411     blink::WebMouseWheelEvent mouse_wheel_event;
1412     if (mate::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
1413       host->ForwardWheelEvent(mouse_wheel_event);
1414       return;
1415     }
1416   }
1417
1418   isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
1419       isolate, "Invalid event object")));
1420 }
1421
1422 void WebContents::BeginFrameSubscription(mate::Arguments* args) {
1423   bool only_dirty = false;
1424   FrameSubscriber::FrameCaptureCallback callback;
1425
1426   args->GetNext(&only_dirty);
1427   if (!args->GetNext(&callback)) {
1428     args->ThrowError();
1429     return;
1430   }
1431
1432   const auto view = web_contents()->GetRenderWidgetHostView();
1433   if (view) {
1434     std::unique_ptr<FrameSubscriber> frame_subscriber(new FrameSubscriber(
1435         isolate(), view, callback, only_dirty));
1436     view->BeginFrameSubscription(std::move(frame_subscriber));
1437   }
1438 }
1439
1440 void WebContents::EndFrameSubscription() {
1441   const auto view = web_contents()->GetRenderWidgetHostView();
1442   if (view)
1443     view->EndFrameSubscription();
1444 }
1445
1446 void WebContents::StartDrag(const mate::Dictionary& item,
1447                             mate::Arguments* args) {
1448   base::FilePath file;
1449   std::vector<base::FilePath> files;
1450   if (!item.Get("files", &files) && item.Get("file", &file)) {
1451     files.push_back(file);
1452   }
1453
1454   mate::Handle<NativeImage> icon;
1455   if (!item.Get("icon", &icon) && !file.empty()) {
1456     // TODO(zcbenz): Set default icon from file.
1457   }
1458
1459   // Error checking.
1460   if (icon.IsEmpty()) {
1461     args->ThrowError("Must specify 'icon' option");
1462     return;
1463   }
1464
1465 #if defined(OS_MACOSX)
1466   // NSWindow.dragImage requires a non-empty NSImage
1467   if (icon->image().IsEmpty()) {
1468     args->ThrowError("Must specify non-empty 'icon' option");
1469     return;
1470   }
1471 #endif
1472
1473   // Start dragging.
1474   if (!files.empty()) {
1475     base::MessageLoop::ScopedNestableTaskAllower allow(
1476         base::MessageLoop::current());
1477     DragFileItems(files, icon->image(), web_contents()->GetNativeView());
1478   } else {
1479     args->ThrowError("Must specify either 'file' or 'files' option");
1480   }
1481 }
1482
1483 void WebContents::CapturePage(mate::Arguments* args) {
1484   gfx::Rect rect;
1485   base::Callback<void(const gfx::Image&)> callback;
1486
1487   if (!(args->Length() == 1 && args->GetNext(&callback)) &&
1488       !(args->Length() == 2 && args->GetNext(&rect)
1489                             && args->GetNext(&callback))) {
1490     args->ThrowError();
1491     return;
1492   }
1493
1494   const auto view = web_contents()->GetRenderWidgetHostView();
1495   const auto host = view ? view->GetRenderWidgetHost() : nullptr;
1496   if (!view || !host) {
1497     callback.Run(gfx::Image());
1498     return;
1499   }
1500
1501   // Capture full page if user doesn't specify a |rect|.
1502   const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() :
1503                                                rect.size();
1504
1505   // By default, the requested bitmap size is the view size in screen
1506   // coordinates.  However, if there's more pixel detail available on the
1507   // current system, increase the requested bitmap size to capture it all.
1508   gfx::Size bitmap_size = view_size;
1509   const gfx::NativeView native_view = view->GetNativeView();
1510   const float scale =
1511       display::Screen::GetScreen()->GetDisplayNearestWindow(native_view)
1512       .device_scale_factor();
1513   if (scale > 1.0f)
1514     bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
1515
1516   host->CopyFromBackingStore(gfx::Rect(rect.origin(), view_size),
1517                              bitmap_size,
1518                              base::Bind(&OnCapturePageDone, callback),
1519                              kBGRA_8888_SkColorType);
1520 }
1521
1522 void WebContents::OnCursorChange(const content::WebCursor& cursor) {
1523   content::WebCursor::CursorInfo info;
1524   cursor.GetCursorInfo(&info);
1525
1526   if (cursor.IsCustom()) {
1527     Emit("cursor-changed", CursorTypeToString(info),
1528       gfx::Image::CreateFrom1xBitmap(info.custom_image),
1529       info.image_scale_factor,
1530       gfx::Size(info.custom_image.width(), info.custom_image.height()),
1531       info.hotspot);
1532   } else {
1533     Emit("cursor-changed", CursorTypeToString(info));
1534   }
1535 }
1536
1537 void WebContents::SetSize(const SetSizeParams& params) {
1538   if (guest_delegate_)
1539     guest_delegate_->SetSize(params);
1540 }
1541
1542 bool WebContents::IsGuest() const {
1543   return type_ == WEB_VIEW;
1544 }
1545
1546 bool WebContents::IsOffScreen() const {
1547   return type_ == OFF_SCREEN;
1548 }
1549
1550 void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
1551   mate::Handle<NativeImage> image =
1552       NativeImage::Create(isolate(), gfx::Image::CreateFrom1xBitmap(bitmap));
1553   Emit("paint", dirty_rect, image);
1554 }
1555
1556 void WebContents::StartPainting() {
1557   if (!IsOffScreen())
1558     return;
1559
1560   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1561       web_contents()->GetRenderWidgetHostView());
1562   if (osr_rwhv)
1563     osr_rwhv->SetPainting(true);
1564 }
1565
1566 void WebContents::StopPainting() {
1567   if (!IsOffScreen())
1568     return;
1569
1570   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1571       web_contents()->GetRenderWidgetHostView());
1572   if (osr_rwhv)
1573     osr_rwhv->SetPainting(false);
1574 }
1575
1576 bool WebContents::IsPainting() const {
1577   if (!IsOffScreen())
1578     return false;
1579
1580   const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1581       web_contents()->GetRenderWidgetHostView());
1582   return osr_rwhv && osr_rwhv->IsPainting();
1583 }
1584
1585 void WebContents::SetFrameRate(int frame_rate) {
1586   if (!IsOffScreen())
1587     return;
1588
1589   auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1590       web_contents()->GetRenderWidgetHostView());
1591   if (osr_rwhv)
1592     osr_rwhv->SetFrameRate(frame_rate);
1593 }
1594
1595 int WebContents::GetFrameRate() const {
1596   if (!IsOffScreen())
1597     return 0;
1598
1599   const auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1600       web_contents()->GetRenderWidgetHostView());
1601   return osr_rwhv ? osr_rwhv->GetFrameRate() : 0;
1602 }
1603
1604 void WebContents::Invalidate() {
1605   if (IsOffScreen()) {
1606     auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(
1607       web_contents()->GetRenderWidgetHostView());
1608     if (osr_rwhv)
1609       osr_rwhv->Invalidate();
1610   } else {
1611     const auto window = owner_window();
1612     if (window)
1613       window->Invalidate();
1614   }
1615 }
1616
1617 void WebContents::SetZoomLevel(double level) {
1618   zoom_controller_->SetZoomLevel(level);
1619 }
1620
1621 double WebContents::GetZoomLevel() {
1622   return zoom_controller_->GetZoomLevel();
1623 }
1624
1625 void WebContents::SetZoomFactor(double factor) {
1626   auto level = content::ZoomFactorToZoomLevel(factor);
1627   SetZoomLevel(level);
1628 }
1629
1630 double WebContents::GetZoomFactor() {
1631   auto level = GetZoomLevel();
1632   return content::ZoomLevelToZoomFactor(level);
1633 }
1634
1635 void WebContents::OnSetTemporaryZoomLevel(double level,
1636                                           IPC::Message* reply_msg) {
1637   zoom_controller_->SetTemporaryZoomLevel(level);
1638   double new_level = zoom_controller_->GetZoomLevel();
1639   AtomViewHostMsg_SetTemporaryZoomLevel::WriteReplyParams(reply_msg, new_level);
1640   Send(reply_msg);
1641 }
1642
1643 void WebContents::OnGetZoomLevel(IPC::Message* reply_msg) {
1644   AtomViewHostMsg_GetZoomLevel::WriteReplyParams(reply_msg, GetZoomLevel());
1645   Send(reply_msg);
1646 }
1647
1648 v8::Local<v8::Value> WebContents::GetWebPreferences(v8::Isolate* isolate) {
1649   WebContentsPreferences* web_preferences =
1650       WebContentsPreferences::FromWebContents(web_contents());
1651   return mate::ConvertToV8(isolate, *web_preferences->web_preferences());
1652 }
1653
1654 v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow() {
1655   if (owner_window())
1656     return Window::From(isolate(), owner_window());
1657   else
1658     return v8::Null(isolate());
1659 }
1660
1661 int32_t WebContents::ID() const {
1662   return weak_map_id();
1663 }
1664
1665 v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
1666   return v8::Local<v8::Value>::New(isolate, session_);
1667 }
1668
1669 content::WebContents* WebContents::HostWebContents() {
1670   if (!embedder_)
1671     return nullptr;
1672   return embedder_->web_contents();
1673 }
1674
1675 void WebContents::SetEmbedder(const WebContents* embedder) {
1676   if (embedder) {
1677     NativeWindow* owner_window = nullptr;
1678     auto relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
1679     if (relay) {
1680       owner_window = relay->window.get();
1681     }
1682     if (owner_window)
1683       SetOwnerWindow(owner_window);
1684
1685     content::RenderWidgetHostView* rwhv =
1686         web_contents()->GetRenderWidgetHostView();
1687     if (rwhv) {
1688       rwhv->Hide();
1689       rwhv->Show();
1690     }
1691   }
1692 }
1693
1694 v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
1695   if (devtools_web_contents_.IsEmpty())
1696     return v8::Null(isolate);
1697   else
1698     return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
1699 }
1700
1701 v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
1702   if (debugger_.IsEmpty()) {
1703     auto handle = atom::api::Debugger::Create(isolate, web_contents());
1704     debugger_.Reset(isolate, handle.ToV8());
1705   }
1706   return v8::Local<v8::Value>::New(isolate, debugger_);
1707 }
1708
1709 // static
1710 void WebContents::BuildPrototype(v8::Isolate* isolate,
1711                                  v8::Local<v8::FunctionTemplate> prototype) {
1712   prototype->SetClassName(mate::StringToV8(isolate, "WebContents"));
1713   mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
1714       .MakeDestroyable()
1715       .SetMethod("getId", &WebContents::GetID)
1716       .SetMethod("getProcessId", &WebContents::GetProcessID)
1717       .SetMethod("equal", &WebContents::Equal)
1718       .SetMethod("_loadURL", &WebContents::LoadURL)
1719       .SetMethod("downloadURL", &WebContents::DownloadURL)
1720       .SetMethod("_getURL", &WebContents::GetURL)
1721       .SetMethod("getTitle", &WebContents::GetTitle)
1722       .SetMethod("isLoading", &WebContents::IsLoading)
1723       .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
1724       .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
1725       .SetMethod("_stop", &WebContents::Stop)
1726       .SetMethod("_goBack", &WebContents::GoBack)
1727       .SetMethod("_goForward", &WebContents::GoForward)
1728       .SetMethod("_goToOffset", &WebContents::GoToOffset)
1729       .SetMethod("isCrashed", &WebContents::IsCrashed)
1730       .SetMethod("setUserAgent", &WebContents::SetUserAgent)
1731       .SetMethod("getUserAgent", &WebContents::GetUserAgent)
1732       .SetMethod("savePage", &WebContents::SavePage)
1733       .SetMethod("openDevTools", &WebContents::OpenDevTools)
1734       .SetMethod("closeDevTools", &WebContents::CloseDevTools)
1735       .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
1736       .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
1737       .SetMethod("enableDeviceEmulation",
1738                  &WebContents::EnableDeviceEmulation)
1739       .SetMethod("disableDeviceEmulation",
1740                  &WebContents::DisableDeviceEmulation)
1741       .SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
1742       .SetMethod("inspectElement", &WebContents::InspectElement)
1743       .SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
1744       .SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
1745       .SetMethod("undo", &WebContents::Undo)
1746       .SetMethod("redo", &WebContents::Redo)
1747       .SetMethod("cut", &WebContents::Cut)
1748       .SetMethod("copy", &WebContents::Copy)
1749       .SetMethod("paste", &WebContents::Paste)
1750       .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
1751       .SetMethod("delete", &WebContents::Delete)
1752       .SetMethod("selectAll", &WebContents::SelectAll)
1753       .SetMethod("unselect", &WebContents::Unselect)
1754       .SetMethod("replace", &WebContents::Replace)
1755       .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
1756       .SetMethod("findInPage", &WebContents::FindInPage)
1757       .SetMethod("stopFindInPage", &WebContents::StopFindInPage)
1758       .SetMethod("focus", &WebContents::Focus)
1759       .SetMethod("isFocused", &WebContents::IsFocused)
1760       .SetMethod("tabTraverse", &WebContents::TabTraverse)
1761       .SetMethod("_send", &WebContents::SendIPCMessage)
1762       .SetMethod("sendInputEvent", &WebContents::SendInputEvent)
1763       .SetMethod("beginFrameSubscription",
1764                  &WebContents::BeginFrameSubscription)
1765       .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
1766       .SetMethod("startDrag", &WebContents::StartDrag)
1767       .SetMethod("setSize", &WebContents::SetSize)
1768       .SetMethod("isGuest", &WebContents::IsGuest)
1769       .SetMethod("isOffscreen", &WebContents::IsOffScreen)
1770       .SetMethod("startPainting", &WebContents::StartPainting)
1771       .SetMethod("stopPainting", &WebContents::StopPainting)
1772       .SetMethod("isPainting", &WebContents::IsPainting)
1773       .SetMethod("setFrameRate", &WebContents::SetFrameRate)
1774       .SetMethod("getFrameRate", &WebContents::GetFrameRate)
1775       .SetMethod("invalidate", &WebContents::Invalidate)
1776       .SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
1777       .SetMethod("_getZoomLevel", &WebContents::GetZoomLevel)
1778       .SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
1779       .SetMethod("_getZoomFactor", &WebContents::GetZoomFactor)
1780       .SetMethod("getType", &WebContents::GetType)
1781       .SetMethod("getWebPreferences", &WebContents::GetWebPreferences)
1782       .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
1783       .SetMethod("hasServiceWorker", &WebContents::HasServiceWorker)
1784       .SetMethod("unregisterServiceWorker",
1785                  &WebContents::UnregisterServiceWorker)
1786       .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
1787       .SetMethod("print", &WebContents::Print)
1788       .SetMethod("_printToPDF", &WebContents::PrintToPDF)
1789       .SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
1790       .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
1791       .SetMethod("showDefinitionForSelection",
1792                  &WebContents::ShowDefinitionForSelection)
1793       .SetMethod("copyImageAt", &WebContents::CopyImageAt)
1794       .SetMethod("capturePage", &WebContents::CapturePage)
1795       .SetMethod("setEmbedder", &WebContents::SetEmbedder)
1796       .SetMethod("setWebRTCIPHandlingPolicy",
1797                  &WebContents::SetWebRTCIPHandlingPolicy)
1798       .SetMethod("getWebRTCIPHandlingPolicy",
1799                  &WebContents::GetWebRTCIPHandlingPolicy)
1800       .SetProperty("id", &WebContents::ID)
1801       .SetProperty("session", &WebContents::Session)
1802       .SetProperty("hostWebContents", &WebContents::HostWebContents)
1803       .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
1804       .SetProperty("debugger", &WebContents::Debugger);
1805 }
1806
1807 AtomBrowserContext* WebContents::GetBrowserContext() const {
1808   return static_cast<AtomBrowserContext*>(web_contents()->GetBrowserContext());
1809 }
1810
1811 void WebContents::OnRendererMessage(const base::string16& channel,
1812                                     const base::ListValue& args) {
1813   // webContents.emit(channel, new Event(), args...);
1814   Emit(base::UTF16ToUTF8(channel), args);
1815 }
1816
1817 void WebContents::OnRendererMessageSync(const base::string16& channel,
1818                                         const base::ListValue& args,
1819                                         IPC::Message* message) {
1820   // webContents.emit(channel, new Event(sender, message), args...);
1821   EmitWithSender(base::UTF16ToUTF8(channel), web_contents(), message, args);
1822 }
1823
1824 // static
1825 mate::Handle<WebContents> WebContents::CreateFrom(
1826     v8::Isolate* isolate, content::WebContents* web_contents) {
1827   // We have an existing WebContents object in JS.
1828   auto existing = TrackableObject::FromWrappedClass(isolate, web_contents);
1829   if (existing)
1830     return mate::CreateHandle(isolate, static_cast<WebContents*>(existing));
1831
1832   // Otherwise create a new WebContents wrapper object.
1833   return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1834         REMOTE));
1835 }
1836
1837 mate::Handle<WebContents> WebContents::CreateFrom(
1838     v8::Isolate* isolate, content::WebContents* web_contents, Type type) {
1839   // Otherwise create a new WebContents wrapper object.
1840   return mate::CreateHandle(isolate, new WebContents(isolate, web_contents,
1841         type));
1842 }
1843
1844 // static
1845 mate::Handle<WebContents> WebContents::Create(
1846     v8::Isolate* isolate, const mate::Dictionary& options) {
1847   return mate::CreateHandle(isolate, new WebContents(isolate, options));
1848 }
1849
1850 }  // namespace api
1851
1852 }  // namespace atom
1853
1854 namespace {
1855
1856 using atom::api::WebContents;
1857
1858 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
1859                 v8::Local<v8::Context> context, void* priv) {
1860   v8::Isolate* isolate = context->GetIsolate();
1861   mate::Dictionary dict(isolate, exports);
1862   dict.Set("WebContents", WebContents::GetConstructor(isolate)->GetFunction());
1863   dict.SetMethod("create", &WebContents::Create);
1864   dict.SetMethod("fromId", &mate::TrackableObject<WebContents>::FromWeakMapID);
1865   dict.SetMethod("getAllWebContents",
1866                  &mate::TrackableObject<WebContents>::GetAll);
1867 }
1868
1869 }  // namespace
1870
1871 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_web_contents, Initialize)