resolves
[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/command_line.h"
15 #include "base/base_paths.h"
16 #include "base/environment.h"
17 #include "base/files/file_path.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/path_service.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/common/content_paths.h"
22 #include "native_mate/dictionary.h"
23
24 #include "atom/common/node_includes.h"
25
26 using content::BrowserThread;
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_content_tracing);
37 REFERENCE_MODULE(atom_browser_dialog);
38 REFERENCE_MODULE(atom_browser_debugger);
39 REFERENCE_MODULE(atom_browser_desktop_capturer);
40 REFERENCE_MODULE(atom_browser_download_item);
41 REFERENCE_MODULE(atom_browser_menu);
42 REFERENCE_MODULE(atom_browser_power_monitor);
43 REFERENCE_MODULE(atom_browser_power_save_blocker);
44 REFERENCE_MODULE(atom_browser_protocol);
45 REFERENCE_MODULE(atom_browser_global_shortcut);
46 REFERENCE_MODULE(atom_browser_render_process_preferences);
47 REFERENCE_MODULE(atom_browser_session);
48 REFERENCE_MODULE(atom_browser_system_preferences);
49 REFERENCE_MODULE(atom_browser_tray);
50 REFERENCE_MODULE(atom_browser_web_contents);
51 REFERENCE_MODULE(atom_browser_web_view_manager);
52 REFERENCE_MODULE(atom_browser_window);
53 REFERENCE_MODULE(atom_common_asar);
54 REFERENCE_MODULE(atom_common_clipboard);
55 REFERENCE_MODULE(atom_common_crash_reporter);
56 REFERENCE_MODULE(atom_common_native_image);
57 REFERENCE_MODULE(atom_common_screen);
58 REFERENCE_MODULE(atom_common_shell);
59 REFERENCE_MODULE(atom_common_v8_util);
60 REFERENCE_MODULE(atom_renderer_ipc);
61 REFERENCE_MODULE(atom_renderer_web_frame);
62 #undef REFERENCE_MODULE
63
64 // The "v8::Function::kLineOffsetNotFound" is exported in node.dll, but the
65 // linker can not find it, could be a bug of VS.
66 #if defined(OS_WIN) && !defined(DEBUG)
67 namespace v8 {
68 const int Function::kLineOffsetNotFound = -1;
69 }
70 #endif
71
72 namespace atom {
73
74 namespace {
75
76 // Empty callback for async handle.
77 void UvNoOp(uv_async_t* handle) {
78 }
79
80 // Convert the given vector to an array of C-strings. The strings in the
81 // returned vector are only guaranteed valid so long as the vector of strings
82 // is not modified.
83 std::unique_ptr<const char*[]> StringVectorToArgArray(
84     const std::vector<std::string>& vector) {
85   std::unique_ptr<const char*[]> array(new const char*[vector.size()]);
86   for (size_t i = 0; i < vector.size(); ++i) {
87     array[i] = vector[i].c_str();
88   }
89   return array;
90 }
91
92 base::FilePath GetResourcesPath(bool is_browser) {
93   auto command_line = base::CommandLine::ForCurrentProcess();
94   base::FilePath exec_path(command_line->GetProgram());
95   PathService::Get(base::FILE_EXE, &exec_path);
96
97   base::FilePath resources_path =
98 #if defined(OS_MACOSX)
99       is_browser ? exec_path.DirName().DirName().Append("Resources") :
100                    exec_path.DirName().DirName().DirName().DirName().DirName()
101                             .Append("Resources");
102 #else
103       exec_path.DirName().Append(FILE_PATH_LITERAL("resources"));
104 #endif
105   return resources_path;
106 }
107
108 }  // namespace
109
110 NodeBindings::NodeBindings(bool is_browser)
111     : is_browser_(is_browser),
112       message_loop_(nullptr),
113       uv_loop_(uv_default_loop()),
114       embed_closed_(false),
115       uv_env_(nullptr),
116       weak_factory_(this) {
117 }
118
119 NodeBindings::~NodeBindings() {
120   // Quit the embed thread.
121   embed_closed_ = true;
122   uv_sem_post(&embed_sem_);
123   WakeupEmbedThread();
124
125   // Wait for everything to be done.
126   uv_thread_join(&embed_thread_);
127
128   // Clear uv.
129   uv_sem_destroy(&embed_sem_);
130 }
131
132 void NodeBindings::Initialize() {
133   // Open node's error reporting system for browser process.
134   node::g_standalone_mode = is_browser_;
135   node::g_upstream_node_mode = false;
136
137 #if defined(OS_LINUX)
138   // Get real command line in renderer process forked by zygote.
139   if (!is_browser_)
140     AtomCommandLine::InitializeFromCommandLine();
141 #endif
142
143   // Init node.
144   // (we assume node::Init would not modify the parameters under embedded mode).
145   node::Init(nullptr, nullptr, nullptr, nullptr);
146
147 #if defined(OS_WIN)
148   // uv_init overrides error mode to suppress the default crash dialog, bring
149   // it back if user wants to show it.
150   std::unique_ptr<base::Environment> env(base::Environment::Create());
151   if (env->HasVar("ELECTRON_DEFAULT_ERROR_MODE"))
152     SetErrorMode(0);
153 #endif
154 }
155
156 node::Environment* NodeBindings::CreateEnvironment(
157     v8::Handle<v8::Context> context) {
158   auto args = AtomCommandLine::argv();
159
160   // Feed node the path to initialization script.
161   base::FilePath::StringType process_type = is_browser_ ?
162       FILE_PATH_LITERAL("browser") : FILE_PATH_LITERAL("renderer");
163   base::FilePath resources_path = GetResourcesPath(is_browser_);
164   base::FilePath script_path =
165       resources_path.Append(FILE_PATH_LITERAL("electron.asar"))
166                     .Append(process_type)
167                     .Append(FILE_PATH_LITERAL("init.js"));
168   std::string script_path_str = script_path.AsUTF8Unsafe();
169   args.insert(args.begin() + 1, script_path_str.c_str());
170
171   std::unique_ptr<const char*[]> c_argv = StringVectorToArgArray(args);
172   node::Environment* env = node::CreateEnvironment(
173       context->GetIsolate(), uv_default_loop(), context,
174       args.size(), c_argv.get(), 0, nullptr);
175
176   mate::Dictionary process(context->GetIsolate(), env->process_object());
177   process.Set("type", process_type);
178   process.Set("resourcesPath", resources_path);
179   // Do not set DOM globals for renderer process.
180   if (!is_browser_)
181     process.Set("_noBrowserGlobals", resources_path);
182   // The path to helper app.
183   base::FilePath helper_exec_path;
184   PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path);
185   process.Set("helperExecPath", helper_exec_path);
186   return env;
187 }
188
189 void NodeBindings::LoadEnvironment(node::Environment* env) {
190   node::LoadEnvironment(env);
191   mate::EmitEvent(env->isolate(), env->process_object(), "loaded");
192 }
193
194 void NodeBindings::PrepareMessageLoop() {
195   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
196
197   // Add dummy handle for libuv, otherwise libuv would quit when there is
198   // nothing to do.
199   uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);
200
201   // Start worker that will interrupt main loop when having uv events.
202   uv_sem_init(&embed_sem_, 0);
203   uv_thread_create(&embed_thread_, EmbedThreadRunner, this);
204 }
205
206 void NodeBindings::RunMessageLoop() {
207   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
208
209   // The MessageLoop should have been created, remember the one in main thread.
210   message_loop_ = base::MessageLoop::current();
211
212   // Run uv loop for once to give the uv__io_poll a chance to add all events.
213   UvRunOnce();
214 }
215
216 void NodeBindings::UvRunOnce() {
217   DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));
218
219   node::Environment* env = uv_env();
220
221   // Use Locker in browser process.
222   mate::Locker locker(env->isolate());
223   v8::HandleScope handle_scope(env->isolate());
224
225   // Enter node context while dealing with uv events.
226   v8::Context::Scope context_scope(env->context());
227
228   // Perform microtask checkpoint after running JavaScript.
229   v8::MicrotasksScope script_scope(env->isolate(),
230                                    v8::MicrotasksScope::kRunMicrotasks);
231
232   // Deal with uv events.
233   int r = uv_run(uv_loop_, UV_RUN_NOWAIT);
234   if (r == 0 || uv_loop_->stop_flag != 0)
235     message_loop_->QuitWhenIdle();  // Quit from uv.
236
237   // Tell the worker thread to continue polling.
238   uv_sem_post(&embed_sem_);
239 }
240
241 void NodeBindings::WakeupMainThread() {
242   DCHECK(message_loop_);
243   message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,
244                                                 weak_factory_.GetWeakPtr()));
245 }
246
247 void NodeBindings::WakeupEmbedThread() {
248   uv_async_send(&dummy_uv_handle_);
249 }
250
251 // static
252 void NodeBindings::EmbedThreadRunner(void *arg) {
253   NodeBindings* self = static_cast<NodeBindings*>(arg);
254
255   while (true) {
256     // Wait for the main loop to deal with events.
257     uv_sem_wait(&self->embed_sem_);
258     if (self->embed_closed_)
259       break;
260
261     // Wait for something to happen in uv loop.
262     // Note that the PollEvents() is implemented by derived classes, so when
263     // this class is being destructed the PollEvents() would not be available
264     // anymore. Because of it we must make sure we only invoke PollEvents()
265     // when this class is alive.
266     self->PollEvents();
267     if (self->embed_closed_)
268       break;
269
270     // Deal with event in main thread.
271     self->WakeupMainThread();
272   }
273 }
274
275 }  // namespace atom