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.
5 #include "atom/browser/api/atom_api_app.h"
10 #include "atom/browser/api/atom_api_menu.h"
11 #include "atom/browser/api/atom_api_session.h"
12 #include "atom/browser/api/atom_api_web_contents.h"
13 #include "atom/browser/atom_browser_context.h"
14 #include "atom/browser/atom_browser_main_parts.h"
15 #include "atom/browser/browser.h"
16 #include "atom/browser/login_handler.h"
17 #include "atom/browser/relauncher.h"
18 #include "atom/common/atom_command_line.h"
19 #include "atom/common/native_mate_converters/callback.h"
20 #include "atom/common/native_mate_converters/file_path_converter.h"
21 #include "atom/common/native_mate_converters/gurl_converter.h"
22 #include "atom/common/native_mate_converters/image_converter.h"
23 #include "atom/common/native_mate_converters/net_converter.h"
24 #include "atom/common/native_mate_converters/value_converter.h"
25 #include "atom/common/node_includes.h"
26 #include "atom/common/options_switches.h"
27 #include "base/command_line.h"
28 #include "base/environment.h"
29 #include "base/files/file_path.h"
30 #include "base/files/file_util.h"
31 #include "base/path_service.h"
32 #include "base/strings/string_util.h"
33 #include "brightray/browser/brightray_paths.h"
34 #include "chrome/common/chrome_paths.h"
35 #include "content/public/browser/browser_accessibility_state.h"
36 #include "content/public/browser/client_certificate_delegate.h"
37 #include "content/public/browser/gpu_data_manager.h"
38 #include "content/public/browser/render_frame_host.h"
39 #include "content/public/common/content_switches.h"
40 #include "native_mate/dictionary.h"
41 #include "native_mate/object_template_builder.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "ui/base/l10n/l10n_util.h"
44 #include "ui/gfx/image/image.h"
47 #include "base/strings/utf_string_conversions.h"
56 struct Converter<Browser::UserTask> {
57 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
58 Browser::UserTask* out) {
59 mate::Dictionary dict;
60 if (!ConvertFromV8(isolate, val, &dict))
62 if (!dict.Get("program", &(out->program)) ||
63 !dict.Get("title", &(out->title)))
65 if (dict.Get("iconPath", &(out->icon_path)) &&
66 !dict.Get("iconIndex", &(out->icon_index)))
68 dict.Get("arguments", &(out->arguments));
69 dict.Get("description", &(out->description));
76 struct Converter<Browser::LoginItemSettings> {
77 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
78 Browser::LoginItemSettings* out) {
79 mate::Dictionary dict;
80 if (!ConvertFromV8(isolate, val, &dict))
83 dict.Get("openAtLogin", &(out->open_at_login));
84 dict.Get("openAsHidden", &(out->open_as_hidden));
88 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
89 Browser::LoginItemSettings val) {
90 mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
91 dict.Set("openAtLogin", val.open_at_login);
92 dict.Set("openAsHidden", val.open_as_hidden);
93 dict.Set("restoreState", val.restore_state);
94 dict.Set("wasOpenedAtLogin", val.opened_at_login);
95 dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
96 return dict.GetHandle();
108 // Return the path constant from string.
109 int GetPathConstant(const std::string& name) {
110 if (name == "appData")
111 return brightray::DIR_APP_DATA;
112 else if (name == "userData")
113 return brightray::DIR_USER_DATA;
114 else if (name == "cache")
115 return brightray::DIR_CACHE;
116 else if (name == "userCache")
117 return brightray::DIR_USER_CACHE;
118 else if (name == "home")
119 return base::DIR_HOME;
120 else if (name == "temp")
121 return base::DIR_TEMP;
122 else if (name == "userDesktop" || name == "desktop")
123 return base::DIR_USER_DESKTOP;
124 else if (name == "exe")
125 return base::FILE_EXE;
126 else if (name == "module")
127 return base::FILE_MODULE;
128 else if (name == "documents")
129 return chrome::DIR_USER_DOCUMENTS;
130 else if (name == "downloads")
131 return chrome::DIR_DEFAULT_DOWNLOADS;
132 else if (name == "music")
133 return chrome::DIR_USER_MUSIC;
134 else if (name == "pictures")
135 return chrome::DIR_USER_PICTURES;
136 else if (name == "videos")
137 return chrome::DIR_USER_VIDEOS;
138 else if (name == "pepperFlashSystemPlugin")
139 return chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN;
144 bool NotificationCallbackWrapper(
145 const ProcessSingleton::NotificationCallback& callback,
146 const base::CommandLine::StringVector& cmd,
147 const base::FilePath& cwd) {
148 // Make sure the callback is called after app gets ready.
149 if (Browser::Get()->is_ready()) {
150 callback.Run(cmd, cwd);
152 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
153 base::ThreadTaskRunnerHandle::Get());
154 task_runner->PostTask(
155 FROM_HERE, base::Bind(base::IgnoreResult(callback), cmd, cwd));
157 // ProcessSingleton needs to know whether current process is quiting.
158 return !Browser::Get()->is_shutting_down();
161 void OnClientCertificateSelected(
162 v8::Isolate* isolate,
163 std::shared_ptr<content::ClientCertificateDelegate> delegate,
164 mate::Arguments* args) {
165 mate::Dictionary cert_data;
166 if (!args->GetNext(&cert_data)) {
171 v8::Local<v8::Object> data;
172 if (!cert_data.Get("data", &data))
175 auto certs = net::X509Certificate::CreateCertificateListFromBytes(
176 node::Buffer::Data(data), node::Buffer::Length(data),
177 net::X509Certificate::FORMAT_AUTO);
178 if (certs.size() > 0)
179 delegate->ContinueWithCertificate(certs[0].get());
182 void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
183 mate::Arguments* args) {
184 base::string16 username, password;
185 if (args->GetNext(&username) && args->GetNext(&password))
186 login_handler->Login(username, password);
188 login_handler->CancelAuth();
191 #if defined(USE_NSS_CERTS)
192 int ImportIntoCertStore(
193 CertificateManagerModel* model,
194 const base::DictionaryValue& options) {
195 std::string file_data, cert_path;
196 base::string16 password;
197 net::CertificateList imported_certs;
199 options.GetString("certificate", &cert_path);
200 options.GetString("password", &password);
202 if (!cert_path.empty()) {
203 if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
204 auto module = model->cert_db()->GetPublicModule();
205 rv = model->ImportFromPKCS12(module,
210 if (imported_certs.size() > 1) {
211 auto it = imported_certs.begin();
212 ++it; // skip first which would be the client certificate.
213 for (; it != imported_certs.end(); ++it)
214 rv &= model->SetCertTrust(it->get(),
216 net::NSSCertDatabase::TRUSTED_SSL);
226 App::App(v8::Isolate* isolate) {
227 static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
228 Browser::Get()->AddObserver(this);
229 content::GpuDataManager::GetInstance()->AddObserver(this);
234 static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(
236 Browser::Get()->RemoveObserver(this);
237 content::GpuDataManager::GetInstance()->RemoveObserver(this);
240 void App::OnBeforeQuit(bool* prevent_default) {
241 *prevent_default = Emit("before-quit");
244 void App::OnWillQuit(bool* prevent_default) {
245 *prevent_default = Emit("will-quit");
248 void App::OnWindowAllClosed() {
249 Emit("window-all-closed");
253 int exitCode = AtomBrowserMainParts::Get()->GetExitCode();
254 Emit("quit", exitCode);
256 if (process_singleton_.get()) {
257 process_singleton_->Cleanup();
258 process_singleton_.reset();
262 void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
263 *prevent_default = Emit("open-file", file_path);
266 void App::OnOpenURL(const std::string& url) {
267 Emit("open-url", url);
270 void App::OnActivate(bool has_visible_windows) {
271 Emit("activate", has_visible_windows);
274 void App::OnWillFinishLaunching() {
275 Emit("will-finish-launching");
278 void App::OnFinishLaunching() {
282 void App::OnAccessibilitySupportChanged() {
283 Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
286 #if defined(OS_MACOSX)
287 void App::OnContinueUserActivity(
288 bool* prevent_default,
289 const std::string& type,
290 const base::DictionaryValue& user_info) {
291 *prevent_default = Emit("continue-activity", type, user_info);
295 void App::OnLogin(LoginHandler* login_handler,
296 const base::DictionaryValue& request_details) {
297 v8::Locker locker(isolate());
298 v8::HandleScope handle_scope(isolate());
299 bool prevent_default = Emit(
301 WebContents::CreateFrom(isolate(), login_handler->GetWebContents()),
303 login_handler->auth_info(),
304 base::Bind(&PassLoginInformation, make_scoped_refptr(login_handler)));
306 // Default behavior is to always cancel the auth.
307 if (!prevent_default)
308 login_handler->CancelAuth();
311 void App::OnCreateWindow(const GURL& target_url,
312 const std::string& frame_name,
313 WindowOpenDisposition disposition,
314 int render_process_id,
315 int render_frame_id) {
316 v8::Locker locker(isolate());
317 v8::HandleScope handle_scope(isolate());
318 content::RenderFrameHost* rfh =
319 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
320 content::WebContents* web_contents =
321 content::WebContents::FromRenderFrameHost(rfh);
323 auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents);
324 api_web_contents->OnCreateWindow(target_url, frame_name, disposition);
328 void App::AllowCertificateError(
329 content::WebContents* web_contents,
331 const net::SSLInfo& ssl_info,
332 const GURL& request_url,
333 content::ResourceType resource_type,
335 bool strict_enforcement,
336 bool expired_previous_decision,
337 const base::Callback<void(bool)>& callback,
338 content::CertificateRequestResultType* request) {
339 v8::Locker locker(isolate());
340 v8::HandleScope handle_scope(isolate());
341 bool prevent_default = Emit("certificate-error",
342 WebContents::CreateFrom(isolate(), web_contents),
344 net::ErrorToString(cert_error),
348 // Deny the certificate by default.
349 if (!prevent_default)
350 *request = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
353 void App::SelectClientCertificate(
354 content::WebContents* web_contents,
355 net::SSLCertRequestInfo* cert_request_info,
356 std::unique_ptr<content::ClientCertificateDelegate> delegate) {
357 std::shared_ptr<content::ClientCertificateDelegate>
358 shared_delegate(delegate.release());
359 bool prevent_default =
360 Emit("select-client-certificate",
361 WebContents::CreateFrom(isolate(), web_contents),
362 cert_request_info->host_and_port.ToString(),
363 cert_request_info->client_certs,
364 base::Bind(&OnClientCertificateSelected,
368 // Default to first certificate from the platform store.
369 if (!prevent_default)
370 shared_delegate->ContinueWithCertificate(
371 cert_request_info->client_certs[0].get());
374 void App::OnGpuProcessCrashed(base::TerminationStatus exit_code) {
375 Emit("gpu-process-crashed");
378 base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
379 bool succeed = false;
381 int key = GetPathConstant(name);
383 succeed = PathService::Get(key, &path);
385 args->ThrowError("Failed to get path");
389 void App::SetPath(mate::Arguments* args,
390 const std::string& name,
391 const base::FilePath& path) {
392 if (!path.IsAbsolute()) {
393 args->ThrowError("path must be absolute");
397 bool succeed = false;
398 int key = GetPathConstant(name);
400 succeed = PathService::OverrideAndCreateIfNeeded(key, path, true, false);
402 args->ThrowError("Failed to set path");
405 void App::SetDesktopName(const std::string& desktop_name) {
406 #if defined(OS_LINUX)
407 std::unique_ptr<base::Environment> env(base::Environment::Create());
408 env->SetVar("CHROME_DESKTOP", desktop_name);
412 std::string App::GetLocale() {
413 return l10n_util::GetApplicationLocale("");
416 bool App::MakeSingleInstance(
417 const ProcessSingleton::NotificationCallback& callback) {
418 if (process_singleton_.get())
421 base::FilePath user_dir;
422 PathService::Get(brightray::DIR_USER_DATA, &user_dir);
423 process_singleton_.reset(new ProcessSingleton(
424 user_dir, base::Bind(NotificationCallbackWrapper, callback)));
426 switch (process_singleton_->NotifyOtherProcessOrCreate()) {
427 case ProcessSingleton::NotifyResult::LOCK_ERROR:
428 case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
429 case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED:
430 process_singleton_.reset();
432 case ProcessSingleton::NotifyResult::PROCESS_NONE:
433 default: // Shouldn't be needed, but VS warns if it is not there.
438 void App::ReleaseSingleInstance() {
439 if (process_singleton_.get()) {
440 process_singleton_->Cleanup();
441 process_singleton_.reset();
445 bool App::Relaunch(mate::Arguments* js_args) {
447 bool override_argv = false;
448 base::FilePath exec_path;
449 relauncher::StringVector args;
451 mate::Dictionary options;
452 if (js_args->GetNext(&options)) {
453 if (options.Get("execPath", &exec_path) | options.Get("args", &args))
454 override_argv = true;
457 if (!override_argv) {
459 const relauncher::StringVector& argv = atom::AtomCommandLine::wargv();
461 const relauncher::StringVector& argv = atom::AtomCommandLine::argv();
463 return relauncher::RelaunchApp(argv);
466 relauncher::StringVector argv;
467 argv.reserve(1 + args.size());
469 if (exec_path.empty()) {
470 base::FilePath current_exe_path;
471 PathService::Get(base::FILE_EXE, ¤t_exe_path);
472 argv.push_back(current_exe_path.value());
474 argv.push_back(exec_path.value());
477 argv.insert(argv.end(), args.begin(), args.end());
479 return relauncher::RelaunchApp(argv);
482 void App::DisableHardwareAcceleration(mate::Arguments* args) {
483 if (Browser::Get()->is_ready()) {
484 args->ThrowError("app.disableHardwareAcceleration() can only be called "
485 "before app is ready");
488 content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
491 bool App::IsAccessibilitySupportEnabled() {
492 auto ax_state = content::BrowserAccessibilityState::GetInstance();
493 return ax_state->IsAccessibleBrowser();
496 #if defined(USE_NSS_CERTS)
497 void App::ImportCertificate(
498 const base::DictionaryValue& options,
499 const net::CompletionCallback& callback) {
500 auto browser_context = AtomBrowserContext::From("", false);
501 if (!certificate_manager_model_) {
502 std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy();
503 CertificateManagerModel::Create(
504 browser_context.get(),
505 base::Bind(&App::OnCertificateManagerModelCreated,
506 base::Unretained(this),
512 int rv = ImportIntoCertStore(certificate_manager_model_.get(), options);
516 void App::OnCertificateManagerModelCreated(
517 std::unique_ptr<base::DictionaryValue> options,
518 const net::CompletionCallback& callback,
519 std::unique_ptr<CertificateManagerModel> model) {
520 certificate_manager_model_ = std::move(model);
521 int rv = ImportIntoCertStore(certificate_manager_model_.get(),
528 mate::Handle<App> App::Create(v8::Isolate* isolate) {
529 return mate::CreateHandle(isolate, new App(isolate));
533 void App::BuildPrototype(
534 v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
535 prototype->SetClassName(mate::StringToV8(isolate, "App"));
536 auto browser = base::Unretained(Browser::Get());
537 mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
538 .SetMethod("quit", base::Bind(&Browser::Quit, browser))
539 .SetMethod("exit", base::Bind(&Browser::Exit, browser))
540 .SetMethod("focus", base::Bind(&Browser::Focus, browser))
541 .SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser))
542 .SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser))
543 .SetMethod("getName", base::Bind(&Browser::GetName, browser))
544 .SetMethod("setName", base::Bind(&Browser::SetName, browser))
545 .SetMethod("isReady", base::Bind(&Browser::is_ready, browser))
546 .SetMethod("addRecentDocument",
547 base::Bind(&Browser::AddRecentDocument, browser))
548 .SetMethod("clearRecentDocuments",
549 base::Bind(&Browser::ClearRecentDocuments, browser))
550 .SetMethod("setAppUserModelId",
551 base::Bind(&Browser::SetAppUserModelID, browser))
552 .SetMethod("isDefaultProtocolClient",
553 base::Bind(&Browser::IsDefaultProtocolClient, browser))
554 .SetMethod("setAsDefaultProtocolClient",
555 base::Bind(&Browser::SetAsDefaultProtocolClient, browser))
556 .SetMethod("removeAsDefaultProtocolClient",
557 base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser))
558 .SetMethod("setBadgeCount", base::Bind(&Browser::SetBadgeCount, browser))
559 .SetMethod("getBadgeCount", base::Bind(&Browser::GetBadgeCount, browser))
560 .SetMethod("getLoginItemSettings",
561 base::Bind(&Browser::GetLoginItemSettings, browser))
562 .SetMethod("setLoginItemSettings",
563 base::Bind(&Browser::SetLoginItemSettings, browser))
564 #if defined(OS_MACOSX)
565 .SetMethod("hide", base::Bind(&Browser::Hide, browser))
566 .SetMethod("show", base::Bind(&Browser::Show, browser))
567 .SetMethod("setUserActivity",
568 base::Bind(&Browser::SetUserActivity, browser))
569 .SetMethod("getCurrentActivityType",
570 base::Bind(&Browser::GetCurrentActivityType, browser))
573 .SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser))
575 #if defined(OS_LINUX)
576 .SetMethod("isUnityRunning",
577 base::Bind(&Browser::IsUnityRunning, browser))
579 .SetMethod("setPath", &App::SetPath)
580 .SetMethod("getPath", &App::GetPath)
581 .SetMethod("setDesktopName", &App::SetDesktopName)
582 .SetMethod("getLocale", &App::GetLocale)
583 #if defined(USE_NSS_CERTS)
584 .SetMethod("importCertificate", &App::ImportCertificate)
586 .SetMethod("makeSingleInstance", &App::MakeSingleInstance)
587 .SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance)
588 .SetMethod("relaunch", &App::Relaunch)
589 .SetMethod("isAccessibilitySupportEnabled",
590 &App::IsAccessibilitySupportEnabled)
591 .SetMethod("disableHardwareAcceleration",
592 &App::DisableHardwareAcceleration);
602 void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
603 auto command_line = base::CommandLine::ForCurrentProcess();
605 if (base::EndsWith(switch_string, "-path",
606 base::CompareCase::INSENSITIVE_ASCII) ||
607 switch_string == switches::kLogNetLog) {
609 args->GetNext(&path);
610 command_line->AppendSwitchPath(switch_string, path);
615 if (args->GetNext(&value))
616 command_line->AppendSwitchASCII(switch_string, value);
618 command_line->AppendSwitch(switch_string);
621 #if defined(OS_MACOSX)
622 int DockBounce(const std::string& type) {
624 if (type == "critical")
625 request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL);
626 else if (type == "informational")
627 request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL);
631 void DockSetMenu(atom::api::Menu* menu) {
632 Browser::Get()->DockSetMenu(menu->model());
636 void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
637 v8::Local<v8::Context> context, void* priv) {
638 v8::Isolate* isolate = context->GetIsolate();
639 auto command_line = base::CommandLine::ForCurrentProcess();
641 mate::Dictionary dict(isolate, exports);
642 dict.Set("app", atom::api::App::Create(isolate));
643 dict.SetMethod("appendSwitch", &AppendSwitch);
644 dict.SetMethod("appendArgument",
645 base::Bind(&base::CommandLine::AppendArg,
646 base::Unretained(command_line)));
647 #if defined(OS_MACOSX)
648 auto browser = base::Unretained(Browser::Get());
649 dict.SetMethod("dockBounce", &DockBounce);
650 dict.SetMethod("dockCancelBounce",
651 base::Bind(&Browser::DockCancelBounce, browser));
652 dict.SetMethod("dockDownloadFinished",
653 base::Bind(&Browser::DockDownloadFinished, browser));
654 dict.SetMethod("dockSetBadgeText",
655 base::Bind(&Browser::DockSetBadgeText, browser));
656 dict.SetMethod("dockGetBadgeText",
657 base::Bind(&Browser::DockGetBadgeText, browser));
658 dict.SetMethod("dockHide", base::Bind(&Browser::DockHide, browser));
659 dict.SetMethod("dockShow", base::Bind(&Browser::DockShow, browser));
660 dict.SetMethod("dockIsVisible", base::Bind(&Browser::DockIsVisible, browser));
661 dict.SetMethod("dockSetMenu", &DockSetMenu);
662 dict.SetMethod("dockSetIcon", base::Bind(&Browser::DockSetIcon, browser));
668 NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_app, Initialize)