atom_renderer_client.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/renderer/atom_renderer_client.h"
  5. #include <string>
  6. #include <vector>
  7. #include "atom_natives.h" // NOLINT: This file is generated with js2c
  8. #include "atom/common/api/api_messages.h"
  9. #include "atom/common/api/atom_bindings.h"
  10. #include "atom/common/api/event_emitter_caller.h"
  11. #include "atom/common/color_util.h"
  12. #include "atom/common/native_mate_converters/value_converter.h"
  13. #include "atom/common/node_bindings.h"
  14. #include "atom/common/options_switches.h"
  15. #include "atom/renderer/api/atom_api_renderer_ipc.h"
  16. #include "atom/renderer/atom_render_view_observer.h"
  17. #include "atom/renderer/content_settings_observer.h"
  18. #include "atom/renderer/guest_view_container.h"
  19. #include "atom/renderer/node_array_buffer_bridge.h"
  20. #include "atom/renderer/preferences_manager.h"
  21. #include "base/command_line.h"
  22. #include "chrome/renderer/media/chrome_key_systems.h"
  23. #include "chrome/renderer/pepper/pepper_helper.h"
  24. #include "chrome/renderer/printing/print_web_view_helper.h"
  25. #include "chrome/renderer/tts_dispatcher.h"
  26. #include "content/public/common/content_constants.h"
  27. #include "content/public/renderer/render_frame.h"
  28. #include "content/public/renderer/render_frame_observer.h"
  29. #include "content/public/renderer/render_thread.h"
  30. #include "content/public/renderer/render_view.h"
  31. #include "ipc/ipc_message_macros.h"
  32. #include "native_mate/dictionary.h"
  33. #include "third_party/WebKit/public/web/WebCustomElement.h"
  34. #include "third_party/WebKit/public/web/WebDocument.h"
  35. #include "third_party/WebKit/public/web/WebFrameWidget.h"
  36. #include "third_party/WebKit/public/web/WebKit.h"
  37. #include "third_party/WebKit/public/web/WebLocalFrame.h"
  38. #include "third_party/WebKit/public/web/WebPluginParams.h"
  39. #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
  40. #include "third_party/WebKit/public/web/WebScriptSource.h"
  41. #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
  42. #include "third_party/WebKit/public/web/WebView.h"
  43. #if defined(OS_MACOSX)
  44. #include "base/mac/mac_util.h"
  45. #include "base/strings/sys_string_conversions.h"
  46. #endif
  47. #if defined(OS_WIN)
  48. #include <shlobj.h>
  49. #endif
  50. #include "atom/common/node_includes.h"
  51. namespace atom {
  52. namespace {
  53. enum World {
  54. MAIN_WORLD = 0,
  55. // Use a high number far away from 0 to not collide with any other world
  56. // IDs created internally by Chrome.
  57. ISOLATED_WORLD = 999
  58. };
  59. enum ExtensionGroup {
  60. MAIN_GROUP = 1
  61. };
  62. // Helper class to forward the messages to the client.
  63. class AtomRenderFrameObserver : public content::RenderFrameObserver {
  64. public:
  65. AtomRenderFrameObserver(content::RenderFrame* frame,
  66. AtomRendererClient* renderer_client)
  67. : content::RenderFrameObserver(frame),
  68. render_frame_(frame),
  69. renderer_client_(renderer_client) {}
  70. // content::RenderFrameObserver:
  71. void DidClearWindowObject() override {
  72. renderer_client_->DidClearWindowObject(render_frame_);
  73. }
  74. void CreateIsolatedWorldContext() {
  75. // This maps to the name shown in the context combo box in the Console tab
  76. // of the dev tools.
  77. render_frame_->GetWebFrame()->setIsolatedWorldHumanReadableName(
  78. World::ISOLATED_WORLD,
  79. blink::WebString::fromUTF8("Electron Isolated Context"));
  80. blink::WebScriptSource source("void 0");
  81. render_frame_->GetWebFrame()->executeScriptInIsolatedWorld(
  82. World::ISOLATED_WORLD, &source, 1, ExtensionGroup::MAIN_GROUP);
  83. }
  84. void SetupMainWorldOverrides(v8::Handle<v8::Context> context) {
  85. // Setup window overrides in the main world context
  86. v8::Isolate* isolate = context->GetIsolate();
  87. // Wrap the bundle into a function that receives the binding object as
  88. // an argument.
  89. std::string bundle(node::isolated_bundle_native,
  90. node::isolated_bundle_native + sizeof(node::isolated_bundle_native));
  91. std::string wrapper = "(function (binding) {\n" + bundle + "\n})";
  92. auto script = v8::Script::Compile(
  93. mate::ConvertToV8(isolate, wrapper)->ToString());
  94. auto func = v8::Handle<v8::Function>::Cast(
  95. script->Run(context).ToLocalChecked());
  96. auto binding = v8::Object::New(isolate);
  97. api::Initialize(binding, v8::Null(isolate), context, nullptr);
  98. // Pass in CLI flags needed to setup window
  99. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  100. mate::Dictionary dict(isolate, binding);
  101. if (command_line->HasSwitch(switches::kGuestInstanceID))
  102. dict.Set(options::kGuestInstanceID,
  103. command_line->GetSwitchValueASCII(switches::kGuestInstanceID));
  104. if (command_line->HasSwitch(switches::kOpenerID))
  105. dict.Set(options::kOpenerID,
  106. command_line->GetSwitchValueASCII(switches::kOpenerID));
  107. dict.Set("hiddenPage", command_line->HasSwitch(switches::kHiddenPage));
  108. v8::Local<v8::Value> args[] = { binding };
  109. ignore_result(func->Call(context, v8::Null(isolate), 1, args));
  110. }
  111. bool IsMainWorld(int world_id) {
  112. return world_id == World::MAIN_WORLD;
  113. }
  114. bool IsIsolatedWorld(int world_id) {
  115. return world_id == World::ISOLATED_WORLD;
  116. }
  117. bool ShouldNotifyClient(int world_id) {
  118. if (renderer_client_->isolated_world() && render_frame_->IsMainFrame())
  119. return IsIsolatedWorld(world_id);
  120. else
  121. return IsMainWorld(world_id);
  122. }
  123. void DidCreateScriptContext(v8::Handle<v8::Context> context,
  124. int extension_group,
  125. int world_id) override {
  126. if (ShouldNotifyClient(world_id))
  127. renderer_client_->DidCreateScriptContext(context, render_frame_);
  128. if (renderer_client_->isolated_world() && IsMainWorld(world_id)
  129. && render_frame_->IsMainFrame()) {
  130. CreateIsolatedWorldContext();
  131. SetupMainWorldOverrides(context);
  132. }
  133. }
  134. void WillReleaseScriptContext(v8::Local<v8::Context> context,
  135. int world_id) override {
  136. if (ShouldNotifyClient(world_id))
  137. renderer_client_->WillReleaseScriptContext(context, render_frame_);
  138. }
  139. void OnDestruct() override {
  140. delete this;
  141. }
  142. private:
  143. content::RenderFrame* render_frame_;
  144. AtomRendererClient* renderer_client_;
  145. DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver);
  146. };
  147. v8::Local<v8::Value> GetRenderProcessPreferences(
  148. const PreferencesManager* preferences_manager, v8::Isolate* isolate) {
  149. if (preferences_manager->preferences())
  150. return mate::ConvertToV8(isolate, *preferences_manager->preferences());
  151. else
  152. return v8::Null(isolate);
  153. }
  154. void AddRenderBindings(v8::Isolate* isolate,
  155. v8::Local<v8::Object> process,
  156. const PreferencesManager* preferences_manager) {
  157. mate::Dictionary dict(isolate, process);
  158. dict.SetMethod(
  159. "getRenderProcessPreferences",
  160. base::Bind(GetRenderProcessPreferences, preferences_manager));
  161. }
  162. bool IsDevToolsExtension(content::RenderFrame* render_frame) {
  163. return static_cast<GURL>(render_frame->GetWebFrame()->document().url())
  164. .SchemeIs("chrome-extension");
  165. }
  166. std::vector<std::string> ParseSchemesCLISwitch(const char* switch_name) {
  167. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  168. std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
  169. return base::SplitString(
  170. custom_schemes, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  171. }
  172. } // namespace
  173. AtomRendererClient::AtomRendererClient()
  174. : node_bindings_(NodeBindings::Create(false)),
  175. atom_bindings_(new AtomBindings) {
  176. isolated_world_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
  177. switches::kContextIsolation);
  178. // Parse --standard-schemes=scheme1,scheme2
  179. std::vector<std::string> standard_schemes_list =
  180. ParseSchemesCLISwitch(switches::kStandardSchemes);
  181. for (const std::string& scheme : standard_schemes_list)
  182. url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
  183. }
  184. AtomRendererClient::~AtomRendererClient() {
  185. }
  186. void AtomRendererClient::RenderThreadStarted() {
  187. blink::WebCustomElement::addEmbedderCustomElementName("webview");
  188. blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
  189. OverrideNodeArrayBuffer();
  190. preferences_manager_.reset(new PreferencesManager);
  191. #if defined(OS_WIN)
  192. // Set ApplicationUserModelID in renderer process.
  193. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  194. base::string16 app_id =
  195. command_line->GetSwitchValueNative(switches::kAppUserModelId);
  196. if (!app_id.empty()) {
  197. SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
  198. }
  199. #endif
  200. #if defined(OS_MACOSX)
  201. // Disable rubber banding by default.
  202. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  203. if (!command_line->HasSwitch(switches::kScrollBounce)) {
  204. base::ScopedCFTypeRef<CFStringRef> key(
  205. base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
  206. base::ScopedCFTypeRef<CFStringRef> value(
  207. base::SysUTF8ToCFStringRef("false"));
  208. CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication);
  209. CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
  210. }
  211. #endif
  212. }
  213. void AtomRendererClient::RenderFrameCreated(
  214. content::RenderFrame* render_frame) {
  215. new PepperHelper(render_frame);
  216. new AtomRenderFrameObserver(render_frame, this);
  217. new ContentSettingsObserver(render_frame);
  218. // Allow file scheme to handle service worker by default.
  219. // FIXME(zcbenz): Can this be moved elsewhere?
  220. blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers("file");
  221. // Parse --secure-schemes=scheme1,scheme2
  222. std::vector<std::string> secure_schemes_list =
  223. ParseSchemesCLISwitch(switches::kSecureSchemes);
  224. for (const std::string& secure_scheme : secure_schemes_list)
  225. blink::WebSecurityPolicy::registerURLSchemeAsSecure(
  226. blink::WebString::fromUTF8(secure_scheme));
  227. }
  228. void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) {
  229. new printing::PrintWebViewHelper(render_view);
  230. new AtomRenderViewObserver(render_view, this);
  231. blink::WebFrameWidget* web_frame_widget = render_view->GetWebFrameWidget();
  232. if (!web_frame_widget)
  233. return;
  234. base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
  235. if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview.
  236. web_frame_widget->setBaseBackgroundColor(SK_ColorTRANSPARENT);
  237. } else { // normal window.
  238. // If backgroundColor is specified then use it.
  239. std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor);
  240. // Otherwise use white background.
  241. SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name);
  242. web_frame_widget->setBaseBackgroundColor(color);
  243. }
  244. }
  245. void AtomRendererClient::DidClearWindowObject(
  246. content::RenderFrame* render_frame) {
  247. // Make sure every page will get a script context created.
  248. render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0"));
  249. }
  250. void AtomRendererClient::RunScriptsAtDocumentStart(
  251. content::RenderFrame* render_frame) {
  252. // Inform the document start pharse.
  253. node::Environment* env = node_bindings_->uv_env();
  254. if (env) {
  255. v8::HandleScope handle_scope(env->isolate());
  256. mate::EmitEvent(env->isolate(), env->process_object(), "document-start");
  257. }
  258. }
  259. void AtomRendererClient::RunScriptsAtDocumentEnd(
  260. content::RenderFrame* render_frame) {
  261. // Inform the document end pharse.
  262. node::Environment* env = node_bindings_->uv_env();
  263. if (env) {
  264. v8::HandleScope handle_scope(env->isolate());
  265. mate::EmitEvent(env->isolate(), env->process_object(), "document-end");
  266. }
  267. }
  268. blink::WebSpeechSynthesizer* AtomRendererClient::OverrideSpeechSynthesizer(
  269. blink::WebSpeechSynthesizerClient* client) {
  270. return new TtsDispatcher(client);
  271. }
  272. bool AtomRendererClient::OverrideCreatePlugin(
  273. content::RenderFrame* render_frame,
  274. blink::WebLocalFrame* frame,
  275. const blink::WebPluginParams& params,
  276. blink::WebPlugin** plugin) {
  277. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  278. if (params.mimeType.utf8() == content::kBrowserPluginMimeType ||
  279. command_line->HasSwitch(switches::kEnablePlugins))
  280. return false;
  281. *plugin = nullptr;
  282. return true;
  283. }
  284. void AtomRendererClient::DidCreateScriptContext(
  285. v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
  286. // Only allow node integration for the main frame, unless it is a devtools
  287. // extension page.
  288. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
  289. return;
  290. // Whether the node binding has been initialized.
  291. bool first_time = node_bindings_->uv_env() == nullptr;
  292. // Prepare the node bindings.
  293. if (first_time) {
  294. node_bindings_->Initialize();
  295. node_bindings_->PrepareMessageLoop();
  296. }
  297. // Setup node environment for each window.
  298. node::Environment* env = node_bindings_->CreateEnvironment(context);
  299. // Add Electron extended APIs.
  300. atom_bindings_->BindTo(env->isolate(), env->process_object());
  301. AddRenderBindings(env->isolate(), env->process_object(),
  302. preferences_manager_.get());
  303. // Load everything.
  304. node_bindings_->LoadEnvironment(env);
  305. if (first_time) {
  306. // Make uv loop being wrapped by window context.
  307. node_bindings_->set_uv_env(env);
  308. // Give the node loop a run to make sure everything is ready.
  309. node_bindings_->RunMessageLoop();
  310. }
  311. }
  312. void AtomRendererClient::WillReleaseScriptContext(
  313. v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
  314. // Only allow node integration for the main frame, unless it is a devtools
  315. // extension page.
  316. if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
  317. return;
  318. node::Environment* env = node::Environment::GetCurrent(context);
  319. if (env)
  320. mate::EmitEvent(env->isolate(), env->process_object(), "exit");
  321. }
  322. bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame,
  323. const GURL& url,
  324. const std::string& http_method,
  325. bool is_initial_navigation,
  326. bool is_server_redirect,
  327. bool* send_referrer) {
  328. // Handle all the navigations and reloads in browser.
  329. // FIXME We only support GET here because http method will be ignored when
  330. // the OpenURLFromTab is triggered, which means form posting would not work,
  331. // we should solve this by patching Chromium in future.
  332. *send_referrer = true;
  333. return http_method == "GET";
  334. }
  335. content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate(
  336. content::RenderFrame* render_frame,
  337. const std::string& mime_type,
  338. const GURL& original_url) {
  339. if (mime_type == content::kBrowserPluginMimeType) {
  340. return new GuestViewContainer(render_frame);
  341. } else {
  342. return nullptr;
  343. }
  344. }
  345. void AtomRendererClient::AddSupportedKeySystems(
  346. std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) {
  347. AddChromeKeySystems(key_systems);
  348. }
  349. v8::Local<v8::Context> AtomRendererClient::GetContext(
  350. blink::WebFrame* frame, v8::Isolate* isolate) {
  351. if (isolated_world())
  352. return frame->worldScriptContext(
  353. isolate, World::ISOLATED_WORLD, ExtensionGroup::MAIN_GROUP);
  354. else
  355. return frame->mainWorldScriptContext();
  356. }
  357. } // namespace atom