Run Tizen Webapps in single process mode
[platform/framework/web/crosswalk-tizen.git] / atom / common / node_bindings.cc
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
5 #include "atom/common/node_bindings.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "atom/common/api/event_emitter_caller.h"
11 #include "atom/common/api/locker.h"
12 #include "atom/common/atom_command_line.h"
13 #include "atom/common/native_mate_converters/file_path_converter.h"
14 #include "base/base_paths.h"
15 #include "base/command_line.h"
16 #include "base/environment.h"
17 #include "base/files/file_path.h"
18 #include "base/path_service.h"
19 #include "base/run_loop.h"
20 #include "base/threading/thread_task_runner_handle.h"
21 #include "base/trace_event/trace_event.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "content/public/common/content_paths.h"
24 #include "native_mate/dictionary.h"
25
26 #include "atom/common/node_includes.h"
27
28 // Force all builtin modules to be referenced so they can actually run their
29 // DSO constructors, see http://git.io/DRIqCg.
30 #define REFERENCE_MODULE(name) \
31   extern "C" void _register_ ## name(void); \
32   void (*fp_register_ ## name)(void) = _register_ ## name
33 // Electron's builtin modules.
34 REFERENCE_MODULE(atom_browser_app);
35 REFERENCE_MODULE(atom_browser_auto_updater);
36 REFERENCE_MODULE(atom_browser_browser_view);
37 REFERENCE_MODULE(atom_browser_content_tracing);
38 REFERENCE_MODULE(atom_browser_debugger);
39 #if !defined(DESKTOP_LINUX) && !defined(OS_TIZEN)
40 REFERENCE_MODULE(atom_browser_desktop_capturer);
41 #endif
42 REFERENCE_MODULE(atom_browser_dialog);
43 REFERENCE_MODULE(atom_browser_download_item);
44 REFERENCE_MODULE(atom_browser_global_shortcut);
45 REFERENCE_MODULE(atom_browser_menu);
46 REFERENCE_MODULE(atom_browser_net);
47 REFERENCE_MODULE(atom_browser_power_monitor);
48 REFERENCE_MODULE(atom_browser_power_save_blocker);
49 REFERENCE_MODULE(atom_browser_protocol);
50 REFERENCE_MODULE(atom_browser_render_process_preferences);
51 REFERENCE_MODULE(atom_browser_session);
52 REFERENCE_MODULE(atom_browser_system_preferences);
53 REFERENCE_MODULE(atom_browser_tray);
54 REFERENCE_MODULE(atom_browser_web_contents);
55 REFERENCE_MODULE(atom_browser_web_view_manager);
56 REFERENCE_MODULE(atom_browser_window);
57 REFERENCE_MODULE(atom_common_asar);
58 REFERENCE_MODULE(atom_common_clipboard);
59 REFERENCE_MODULE(atom_common_crash_reporter);
60 REFERENCE_MODULE(atom_common_native_image);
61 REFERENCE_MODULE(atom_common_screen);
62 REFERENCE_MODULE(atom_common_shell);
63 REFERENCE_MODULE(atom_common_v8_util);
64 REFERENCE_MODULE(atom_renderer_ipc);
65 REFERENCE_MODULE(atom_renderer_web_frame);
66 #undef REFERENCE_MODULE
67
68 namespace atom {
69
70 namespace {
71
72 // Convert the given vector to an array of C-strings. The strings in the
73 // returned vector are only guaranteed valid so long as the vector of strings
74 // is not modified.
75 std::unique_ptr<const char*[]> StringVectorToArgArray(
76     const std::vector<std::string>& vector) {
77   std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
78   for (size_t i = 0; i < vector.size(); ++i) {
79     array[i] = vector[i].c_str();
80   }
81   return array;
82 }
83
84 base::FilePath GetResourcesPath(bool is_browser) {
85 #if defined(OS_TIZEN)
86   return base::FilePath(FILE_PATH_LITERAL(TIZEN_RESOURCE_PATH));
87 #endif
88   auto command_line = base::CommandLine::ForCurrentProcess();
89   base::FilePath exec_path(command_line->GetProgram());
90   PathService::Get(base::FILE_EXE, &exec_path);
91
92   base::FilePath resources_path =
93 #if defined(OS_MACOSX)
94       is_browser ? exec_path.DirName().DirName().Append("Resources") :
95                    exec_path.DirName().DirName().DirName().DirName().DirName()
96                             .Append("Resources");
97 #else
98       exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
99 #endif
100   return resources_path;
101 }
102
103 }  // namespace
104
105 NodeBindings::NodeBindings(BrowserEnvironment browser_env)
106     : browser_env_(browser_env),
107       uv_loop_(browser_env == WORKER ? uv_loop_new() : uv_default_loop()),
108       embed_closed_(false),
109       uv_env_(nullptr),
110       weak_factory_(this) {
111 }
112
113 NodeBindings::~NodeBindings() {
114   // Quit the embed thread.
115   embed_closed_ = true;
116   uv_sem_post(&embed_sem_);
117   WakeupEmbedThread();
118
119   // Wait for everything to be done.
120   uv_thread_join(&embed_thread_);
121
122   // Clear uv.
123   uv_sem_destroy(&embed_sem_);
124   uv_close(reinterpret_cast<uv_handle_t*>(&dummy_uv_handle_), nullptr);
125
126   // Destroy loop.
127   if (uv_loop_ != uv_default_loop())
128     uv_loop_delete(uv_loop_);
129 }
130
131 void NodeBindings::Initialize() {
132   // Open node's error reporting system for browser process.
133   node::g_standalone_mode = browser_env_ == BROWSER;
134   node::g_upstream_node_mode = false;
135
136 #if defined(OS_LINUX)
137   // Get real command line in renderer process forked by zygote.
138   if (browser_env_ != BROWSER)
139     AtomCommandLine::InitializeFromCommandLine();
140 #endif
141
142   // Init node.
143   // (we assume node::Init would not modify the parameters under embedded mode).
144   node::Init(nullptr, nullptr, nullptr, nullptr, uv_loop_);
145
146 #if defined(OS_WIN)
147   // uv_init overrides error mode to suppress the default crash dialog, bring
148   // it back if user wants to show it.
149   std::unique_ptr<base::Environment> env(base::Environment::Create());
150   if (browser_env_ == BROWSER || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
151     SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX);
152 #endif
153 }
154
155 node::Environment* NodeBindings::CreateEnvironment(
156     v8::Handle<v8::Context> context) {
157   auto args = AtomCommandLine::argv();
158
159   // Feed node the path to initialization script.
160   base::FilePath::StringType process_type;
161   switch (browser_env_) {
162     case BROWSER:
163       process_type = FILE_PATH_LITERAL("browser");
164       break;
165     case RENDERER:
166       process_type = FILE_PATH_LITERAL("renderer");
167       break;
168     case WORKER:
169       process_type = FILE_PATH_LITERAL("worker");
170       break;
171   }
172   base::FilePath resources_path = GetResourcesPath(browser_env_ == BROWSER);
173   base::FilePath script_path =
174       resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
175                     .Append(process_type)
176                     .Append(FILE_PATH_LITERAL("init.js"));
177   std::string script_path_str = script_path.AsUTF8Unsafe();
178   args.insert(args.begin() + 1, script_path_str.c_str());
179
180   std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
181   node::Environment* env = node::CreateEnvironment(
182       new node::IsolateData(context->GetIsolate(), uv_loop_), context,
183       args.size(), c_argv.get(), 0, nullptr);
184
185   if (browser_env_ == BROWSER) {
186     // SetAutorunMicrotasks is no longer called in node::CreateEnvironment
187     // so instead call it here to match expected node behavior
188     context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
189   } else {
190     // Node uses the deprecated SetAutorunMicrotasks(false) mode, we should
191     // switch to use the scoped policy to match blink's behavior.
192     context->GetIsolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
193   }
194
195   mate::Dictionary process(context->GetIsolate(), env->process_object());
196   process.Set("type", process_type);
197   process.Set("resourcesPath", resources_path);
198   // Do not set DOM globals for renderer process.
199   if (browser_env_ != BROWSER)
200     process.Set("_noBrowserGlobals", resources_path);
201   // The path to helper app.
202   base::FilePath helper_exec_path;
203   PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
204   process.Set("helperExecPath", helper_exec_path);
205
206   // Set process._debugWaitConnect if --debug-brk was specified to stop
207   // the debugger on the first line
208   if (browser_env_ == BROWSER &&
209       base::CommandLine::ForCurrentProcess()->HasSwitch("debug-brk"))
210     process.Set("_debugWaitConnect", true);
211
212   return env;
213 }
214
215 void NodeBindings::LoadEnvironment(node::Environment* env) {
216   node::LoadEnvironment(env);
217   mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
218 }
219
220 void NodeBindings::PrepareMessageLoop() {
221   // Add dummy handle for libuv, otherwise libuv would quit when there is
222   // nothing to do.
223   uv_async_init(uv_loop_, &dummy_uv_handle_, nullptr);
224
225   // Start worker that will interrupt main loop when having uv events.
226   uv_sem_init(&embed_sem_, 0);
227   uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
228 }
229
230 void NodeBindings::RunMessageLoop() {
231   // The MessageLoop should have been created, remember the one in main thread.
232   task_runner_ = base::ThreadTaskRunnerHandle::Get();
233
234   // Run uv loop for once to give the uv__io_poll a chance to add all events.
235   UvRunOnce();
236 }
237
238 void NodeBindings::UvRunOnce() {
239   node::Environment* env = uv_env();
240
241   // When doing navigation without restarting renderer process, it may happen
242   // that the node environment is destroyed but the message loop is still there.
243   // In this case we should not run uv loop.
244   if (!env)
245     return;
246
247   // Use Locker in browser process.
248   mate::Locker locker(env->isolate());
249   v8::HandleScope handle_scope(env->isolate());
250
251   // Enter node context while dealing with uv events.
252   v8::Context::Scope context_scope(env->context());
253
254   // Perform microtask checkpoint after running JavaScript.
255   v8::MicrotasksScope script_scope(env->isolate(),
256                                    v8::MicrotasksScope::kRunMicrotasks);
257
258   if (browser_env_ != BROWSER)
259     TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall");
260
261   // Deal with uv events.
262   int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
263
264   if (browser_env_ != BROWSER)
265     TRACE_EVENT_END0("devtools.timeline", "FunctionCall");
266
267   if (r == 0)
268     base::RunLoop().QuitWhenIdle();  // Quit from uv.
269
270   // Tell the worker thread to continue polling.
271   uv_sem_post(&embed_sem_);
272 }
273
274 void NodeBindings::WakeupMainThread() {
275   DCHECK(task_runner_);
276   task_runner_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
277                                                weak_factory_.GetWeakPtr()));
278 }
279
280 void NodeBindings::WakeupEmbedThread() {
281   uv_async_send(&dummy_uv_handle_);
282 }
283
284 // static
285 void NodeBindings::EmbedThreadRunner(void *arg) {
286   NodeBindings* self = static_cast<NodeBindings*>(arg);
287
288   while (true) {
289     // Wait for the main loop to deal with events.
290     uv_sem_wait(&self->embed_sem_);
291     if (self->embed_closed_)
292       break;
293
294     // Wait for something to happen in uv loop.
295     // Note that the PollEvents() is implemented by derived classes, so when
296     // this class is being destructed the PollEvents() would not be available
297     // anymore. Because of it we must make sure we only invoke PollEvents()
298     // when this class is alive.
299     self->PollEvents();
300     if (self->embed_closed_)
301       break;
302
303     // Deal with event in main thread.
304     self->WakeupMainThread();
305   }
306 }
307
308 }  // namespace atom