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