atom_api_app.cc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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/browser/api/atom_api_app.h"
  5. #include <string>
  6. #include <vector>
  7. #include "atom/browser/api/atom_api_menu.h"
  8. #include "atom/browser/api/atom_api_session.h"
  9. #include "atom/browser/api/atom_api_web_contents.h"
  10. #include "atom/browser/atom_browser_context.h"
  11. #include "atom/browser/atom_browser_main_parts.h"
  12. #include "atom/browser/browser.h"
  13. #include "atom/browser/login_handler.h"
  14. #include "atom/browser/relauncher.h"
  15. #include "atom/common/atom_command_line.h"
  16. #include "atom/common/native_mate_converters/callback.h"
  17. #include "atom/common/native_mate_converters/file_path_converter.h"
  18. #include "atom/common/native_mate_converters/gurl_converter.h"
  19. #include "atom/common/native_mate_converters/image_converter.h"
  20. #include "atom/common/native_mate_converters/net_converter.h"
  21. #include "atom/common/native_mate_converters/value_converter.h"
  22. #include "atom/common/node_includes.h"
  23. #include "atom/common/options_switches.h"
  24. #include "base/command_line.h"
  25. #include "base/environment.h"
  26. #include "base/files/file_path.h"
  27. #include "base/files/file_util.h"
  28. #include "base/path_service.h"
  29. #include "base/strings/string_util.h"
  30. #include "brightray/browser/brightray_paths.h"
  31. #include "chrome/common/chrome_paths.h"
  32. #include "content/public/browser/browser_accessibility_state.h"
  33. #include "content/public/browser/client_certificate_delegate.h"
  34. #include "content/public/browser/gpu_data_manager.h"
  35. #include "content/public/browser/render_frame_host.h"
  36. #include "content/public/common/content_switches.h"
  37. #include "media/audio/audio_manager.h"
  38. #include "native_mate/dictionary.h"
  39. #include "native_mate/object_template_builder.h"
  40. #include "net/ssl/ssl_cert_request_info.h"
  41. #include "ui/base/l10n/l10n_util.h"
  42. #include "ui/gfx/image/image.h"
  43. #if defined(OS_WIN)
  44. #include "atom/browser/ui/win/jump_list.h"
  45. #include "base/strings/utf_string_conversions.h"
  46. #endif
  47. using atom::Browser;
  48. namespace mate {
  49. #if defined(OS_WIN)
  50. template<>
  51. struct Converter<Browser::UserTask> {
  52. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  53. Browser::UserTask* out) {
  54. mate::Dictionary dict;
  55. if (!ConvertFromV8(isolate, val, &dict))
  56. return false;
  57. if (!dict.Get("program", &(out->program)) ||
  58. !dict.Get("title", &(out->title)))
  59. return false;
  60. if (dict.Get("iconPath", &(out->icon_path)) &&
  61. !dict.Get("iconIndex", &(out->icon_index)))
  62. return false;
  63. dict.Get("arguments", &(out->arguments));
  64. dict.Get("description", &(out->description));
  65. return true;
  66. }
  67. };
  68. using atom::JumpListItem;
  69. using atom::JumpListCategory;
  70. using atom::JumpListResult;
  71. template<>
  72. struct Converter<JumpListItem::Type> {
  73. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  74. JumpListItem::Type* out) {
  75. std::string item_type;
  76. if (!ConvertFromV8(isolate, val, &item_type))
  77. return false;
  78. if (item_type == "task")
  79. *out = JumpListItem::Type::TASK;
  80. else if (item_type == "separator")
  81. *out = JumpListItem::Type::SEPARATOR;
  82. else if (item_type == "file")
  83. *out = JumpListItem::Type::FILE;
  84. else
  85. return false;
  86. return true;
  87. }
  88. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  89. JumpListItem::Type val) {
  90. std::string item_type;
  91. switch (val) {
  92. case JumpListItem::Type::TASK:
  93. item_type = "task";
  94. break;
  95. case JumpListItem::Type::SEPARATOR:
  96. item_type = "separator";
  97. break;
  98. case JumpListItem::Type::FILE:
  99. item_type = "file";
  100. break;
  101. }
  102. return mate::ConvertToV8(isolate, item_type);
  103. }
  104. };
  105. template<>
  106. struct Converter<JumpListItem> {
  107. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  108. JumpListItem* out) {
  109. mate::Dictionary dict;
  110. if (!ConvertFromV8(isolate, val, &dict))
  111. return false;
  112. if (!dict.Get("type", &(out->type)))
  113. return false;
  114. switch (out->type) {
  115. case JumpListItem::Type::TASK:
  116. if (!dict.Get("program", &(out->path)) ||
  117. !dict.Get("title", &(out->title)))
  118. return false;
  119. if (dict.Get("iconPath", &(out->icon_path)) &&
  120. !dict.Get("iconIndex", &(out->icon_index)))
  121. return false;
  122. dict.Get("args", &(out->arguments));
  123. dict.Get("description", &(out->description));
  124. return true;
  125. case JumpListItem::Type::SEPARATOR:
  126. return true;
  127. case JumpListItem::Type::FILE:
  128. return dict.Get("path", &(out->path));
  129. }
  130. assert(false);
  131. return false;
  132. }
  133. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  134. const JumpListItem& val) {
  135. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  136. dict.Set("type", val.type);
  137. switch (val.type) {
  138. case JumpListItem::Type::TASK:
  139. dict.Set("program", val.path);
  140. dict.Set("args", val.arguments);
  141. dict.Set("title", val.title);
  142. dict.Set("iconPath", val.icon_path);
  143. dict.Set("iconIndex", val.icon_index);
  144. dict.Set("description", val.description);
  145. break;
  146. case JumpListItem::Type::SEPARATOR:
  147. break;
  148. case JumpListItem::Type::FILE:
  149. dict.Set("path", val.path);
  150. break;
  151. }
  152. return dict.GetHandle();
  153. }
  154. };
  155. template<>
  156. struct Converter<JumpListCategory::Type> {
  157. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  158. JumpListCategory::Type* out) {
  159. std::string category_type;
  160. if (!ConvertFromV8(isolate, val, &category_type))
  161. return false;
  162. if (category_type == "tasks")
  163. *out = JumpListCategory::Type::TASKS;
  164. else if (category_type == "frequent")
  165. *out = JumpListCategory::Type::FREQUENT;
  166. else if (category_type == "recent")
  167. *out = JumpListCategory::Type::RECENT;
  168. else if (category_type == "custom")
  169. *out = JumpListCategory::Type::CUSTOM;
  170. else
  171. return false;
  172. return true;
  173. }
  174. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  175. JumpListCategory::Type val) {
  176. std::string category_type;
  177. switch (val) {
  178. case JumpListCategory::Type::TASKS:
  179. category_type = "tasks";
  180. break;
  181. case JumpListCategory::Type::FREQUENT:
  182. category_type = "frequent";
  183. break;
  184. case JumpListCategory::Type::RECENT:
  185. category_type = "recent";
  186. break;
  187. case JumpListCategory::Type::CUSTOM:
  188. category_type = "custom";
  189. break;
  190. }
  191. return mate::ConvertToV8(isolate, category_type);
  192. }
  193. };
  194. template<>
  195. struct Converter<JumpListCategory> {
  196. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  197. JumpListCategory* out) {
  198. mate::Dictionary dict;
  199. if (!ConvertFromV8(isolate, val, &dict))
  200. return false;
  201. if (dict.Get("name", &(out->name)) && out->name.empty())
  202. return false;
  203. if (!dict.Get("type", &(out->type))) {
  204. if (out->name.empty())
  205. out->type = JumpListCategory::Type::TASKS;
  206. else
  207. out->type = JumpListCategory::Type::CUSTOM;
  208. }
  209. if ((out->type == JumpListCategory::Type::TASKS) ||
  210. (out->type == JumpListCategory::Type::CUSTOM)) {
  211. if (!dict.Get("items", &(out->items)))
  212. return false;
  213. }
  214. return true;
  215. }
  216. };
  217. // static
  218. template<>
  219. struct Converter<JumpListResult> {
  220. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
  221. std::string result_code;
  222. switch (val) {
  223. case JumpListResult::SUCCESS:
  224. result_code = "ok";
  225. break;
  226. case JumpListResult::ARGUMENT_ERROR:
  227. result_code = "argumentError";
  228. break;
  229. case JumpListResult::GENERIC_ERROR:
  230. result_code = "error";
  231. break;
  232. case JumpListResult::CUSTOM_CATEGORY_SEPARATOR_ERROR:
  233. result_code = "invalidSeparatorError";
  234. break;
  235. case JumpListResult::MISSING_FILE_TYPE_REGISTRATION_ERROR:
  236. result_code = "fileTypeRegistrationError";
  237. break;
  238. case JumpListResult::CUSTOM_CATEGORY_ACCESS_DENIED_ERROR:
  239. result_code = "customCategoryAccessDeniedError";
  240. break;
  241. }
  242. return ConvertToV8(isolate, result_code);
  243. }
  244. };
  245. #endif
  246. template<>
  247. struct Converter<Browser::LoginItemSettings> {
  248. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  249. Browser::LoginItemSettings* out) {
  250. mate::Dictionary dict;
  251. if (!ConvertFromV8(isolate, val, &dict))
  252. return false;
  253. dict.Get("openAtLogin", &(out->open_at_login));
  254. dict.Get("openAsHidden", &(out->open_as_hidden));
  255. return true;
  256. }
  257. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  258. Browser::LoginItemSettings val) {
  259. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  260. dict.Set("openAtLogin", val.open_at_login);
  261. dict.Set("openAsHidden", val.open_as_hidden);
  262. dict.Set("restoreState", val.restore_state);
  263. dict.Set("wasOpenedAtLogin", val.opened_at_login);
  264. dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
  265. return dict.GetHandle();
  266. }
  267. };
  268. } // namespace mate
  269. namespace atom {
  270. namespace api {
  271. namespace {
  272. // Return the path constant from string.
  273. int GetPathConstant(const std::string& name) {
  274. if (name == "appData")
  275. return brightray::DIR_APP_DATA;
  276. else if (name == "userData")
  277. return brightray::DIR_USER_DATA;
  278. else if (name == "cache")
  279. return brightray::DIR_CACHE;
  280. else if (name == "userCache")
  281. return brightray::DIR_USER_CACHE;
  282. else if (name == "home")
  283. return base::DIR_HOME;
  284. else if (name == "temp")
  285. return base::DIR_TEMP;
  286. else if (name == "userDesktop" || name == "desktop")
  287. return base::DIR_USER_DESKTOP;
  288. else if (name == "exe")
  289. return base::FILE_EXE;
  290. else if (name == "module")
  291. return base::FILE_MODULE;
  292. else if (name == "documents")
  293. return chrome::DIR_USER_DOCUMENTS;
  294. else if (name == "downloads")
  295. return chrome::DIR_DEFAULT_DOWNLOADS;
  296. else if (name == "music")
  297. return chrome::DIR_USER_MUSIC;
  298. else if (name == "pictures")
  299. return chrome::DIR_USER_PICTURES;
  300. else if (name == "videos")
  301. return chrome::DIR_USER_VIDEOS;
  302. else if (name == "pepperFlashSystemPlugin")
  303. return chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN;
  304. else
  305. return -1;
  306. }
  307. bool NotificationCallbackWrapper(
  308. const ProcessSingleton::NotificationCallback& callback,
  309. const base::CommandLine::StringVector& cmd,
  310. const base::FilePath& cwd) {
  311. // Make sure the callback is called after app gets ready.
  312. if (Browser::Get()->is_ready()) {
  313. callback.Run(cmd, cwd);
  314. } else {
  315. scoped_refptr<base::SingleThreadTaskRunner> task_runner(
  316. base::ThreadTaskRunnerHandle::Get());
  317. task_runner->PostTask(
  318. FROM_HERE, base::Bind(base::IgnoreResult(callback), cmd, cwd));
  319. }
  320. // ProcessSingleton needs to know whether current process is quiting.
  321. return !Browser::Get()->is_shutting_down();
  322. }
  323. void OnClientCertificateSelected(
  324. v8::Isolate* isolate,
  325. std::shared_ptr<content::ClientCertificateDelegate> delegate,
  326. mate::Arguments* args) {
  327. if (args->Length() == 2) {
  328. delegate->ContinueWithCertificate(nullptr);
  329. return;
  330. }
  331. v8::Local<v8::Value> val;
  332. args->GetNext(&val);
  333. if (val->IsNull()) {
  334. delegate->ContinueWithCertificate(nullptr);
  335. return;
  336. }
  337. mate::Dictionary cert_data;
  338. if (!mate::ConvertFromV8(isolate, val, &cert_data)) {
  339. args->ThrowError("Must pass valid certificate object.");
  340. return;
  341. }
  342. std::string data;
  343. if (!cert_data.Get("data", &data))
  344. return;
  345. auto certs = net::X509Certificate::CreateCertificateListFromBytes(
  346. data.c_str(), data.length(), net::X509Certificate::FORMAT_AUTO);
  347. if (certs.size() > 0)
  348. delegate->ContinueWithCertificate(certs[0].get());
  349. }
  350. void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
  351. mate::Arguments* args) {
  352. base::string16 username, password;
  353. if (args->GetNext(&username) && args->GetNext(&password))
  354. login_handler->Login(username, password);
  355. else
  356. login_handler->CancelAuth();
  357. }
  358. #if defined(USE_NSS_CERTS)
  359. int ImportIntoCertStore(
  360. CertificateManagerModel* model,
  361. const base::DictionaryValue& options) {
  362. std::string file_data, cert_path;
  363. base::string16 password;
  364. net::CertificateList imported_certs;
  365. int rv = -1;
  366. options.GetString("certificate", &cert_path);
  367. options.GetString("password", &password);
  368. if (!cert_path.empty()) {
  369. if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
  370. auto module = model->cert_db()->GetPublicModule();
  371. rv = model->ImportFromPKCS12(module,
  372. file_data,
  373. password,
  374. true,
  375. &imported_certs);
  376. if (imported_certs.size() > 1) {
  377. auto it = imported_certs.begin();
  378. ++it; // skip first which would be the client certificate.
  379. for (; it != imported_certs.end(); ++it)
  380. rv &= model->SetCertTrust(it->get(),
  381. net::CA_CERT,
  382. net::NSSCertDatabase::TRUSTED_SSL);
  383. }
  384. }
  385. }
  386. return rv;
  387. }
  388. #endif
  389. } // namespace
  390. App::App(v8::Isolate* isolate) {
  391. static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
  392. Browser::Get()->AddObserver(this);
  393. content::GpuDataManager::GetInstance()->AddObserver(this);
  394. Init(isolate);
  395. }
  396. App::~App() {
  397. static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(
  398. nullptr);
  399. Browser::Get()->RemoveObserver(this);
  400. content::GpuDataManager::GetInstance()->RemoveObserver(this);
  401. }
  402. void App::OnBeforeQuit(bool* prevent_default) {
  403. *prevent_default = Emit("before-quit");
  404. }
  405. void App::OnWillQuit(bool* prevent_default) {
  406. *prevent_default = Emit("will-quit");
  407. }
  408. void App::OnWindowAllClosed() {
  409. Emit("window-all-closed");
  410. }
  411. void App::OnQuit() {
  412. int exitCode = AtomBrowserMainParts::Get()->GetExitCode();
  413. Emit("quit", exitCode);
  414. if (process_singleton_.get()) {
  415. process_singleton_->Cleanup();
  416. process_singleton_.reset();
  417. }
  418. }
  419. void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
  420. *prevent_default = Emit("open-file", file_path);
  421. }
  422. void App::OnOpenURL(const std::string& url) {
  423. Emit("open-url", url);
  424. }
  425. void App::OnActivate(bool has_visible_windows) {
  426. Emit("activate", has_visible_windows);
  427. }
  428. void App::OnWillFinishLaunching() {
  429. Emit("will-finish-launching");
  430. }
  431. void App::OnFinishLaunching(const base::DictionaryValue& launch_info) {
  432. #if defined(OS_LINUX)
  433. // Set the application name for audio streams shown in external
  434. // applications. Only affects pulseaudio currently.
  435. media::AudioManager::SetGlobalAppName(Browser::Get()->GetName());
  436. #endif
  437. Emit("ready", launch_info);
  438. }
  439. void App::OnAccessibilitySupportChanged() {
  440. Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
  441. }
  442. #if defined(OS_MACOSX)
  443. void App::OnContinueUserActivity(
  444. bool* prevent_default,
  445. const std::string& type,
  446. const base::DictionaryValue& user_info) {
  447. *prevent_default = Emit("continue-activity", type, user_info);
  448. }
  449. #endif
  450. void App::OnLogin(LoginHandler* login_handler,
  451. const base::DictionaryValue& request_details) {
  452. v8::Locker locker(isolate());
  453. v8::HandleScope handle_scope(isolate());
  454. bool prevent_default = Emit(
  455. "login",
  456. WebContents::CreateFrom(isolate(), login_handler->GetWebContents()),
  457. request_details,
  458. login_handler->auth_info(),
  459. base::Bind(&PassLoginInformation, make_scoped_refptr(login_handler)));
  460. // Default behavior is to always cancel the auth.
  461. if (!prevent_default)
  462. login_handler->CancelAuth();
  463. }
  464. void App::OnCreateWindow(
  465. const GURL& target_url,
  466. const std::string& frame_name,
  467. WindowOpenDisposition disposition,
  468. const std::vector<base::string16>& features,
  469. const scoped_refptr<content::ResourceRequestBodyImpl>& body,
  470. int render_process_id,
  471. int render_frame_id) {
  472. v8::Locker locker(isolate());
  473. v8::HandleScope handle_scope(isolate());
  474. content::RenderFrameHost* rfh =
  475. content::RenderFrameHost::FromID(render_process_id, render_frame_id);
  476. content::WebContents* web_contents =
  477. content::WebContents::FromRenderFrameHost(rfh);
  478. if (web_contents) {
  479. auto api_web_contents = WebContents::CreateFrom(isolate(), web_contents);
  480. api_web_contents->OnCreateWindow(target_url,
  481. frame_name,
  482. disposition,
  483. features,
  484. body);
  485. }
  486. }
  487. void App::AllowCertificateError(
  488. content::WebContents* web_contents,
  489. int cert_error,
  490. const net::SSLInfo& ssl_info,
  491. const GURL& request_url,
  492. content::ResourceType resource_type,
  493. bool overridable,
  494. bool strict_enforcement,
  495. bool expired_previous_decision,
  496. const base::Callback<void(bool)>& callback,
  497. content::CertificateRequestResultType* request) {
  498. v8::Locker locker(isolate());
  499. v8::HandleScope handle_scope(isolate());
  500. bool prevent_default = Emit("certificate-error",
  501. WebContents::CreateFrom(isolate(), web_contents),
  502. request_url,
  503. net::ErrorToString(cert_error),
  504. ssl_info.cert,
  505. callback);
  506. // Deny the certificate by default.
  507. if (!prevent_default)
  508. *request = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
  509. }
  510. void App::SelectClientCertificate(
  511. content::WebContents* web_contents,
  512. net::SSLCertRequestInfo* cert_request_info,
  513. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  514. std::shared_ptr<content::ClientCertificateDelegate>
  515. shared_delegate(delegate.release());
  516. bool prevent_default =
  517. Emit("select-client-certificate",
  518. WebContents::CreateFrom(isolate(), web_contents),
  519. cert_request_info->host_and_port.ToString(),
  520. cert_request_info->client_certs,
  521. base::Bind(&OnClientCertificateSelected,
  522. isolate(),
  523. shared_delegate));
  524. // Default to first certificate from the platform store.
  525. if (!prevent_default)
  526. shared_delegate->ContinueWithCertificate(
  527. cert_request_info->client_certs[0].get());
  528. }
  529. void App::OnGpuProcessCrashed(base::TerminationStatus status) {
  530. Emit("gpu-process-crashed",
  531. status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
  532. }
  533. base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
  534. bool succeed = false;
  535. base::FilePath path;
  536. int key = GetPathConstant(name);
  537. if (key >= 0)
  538. succeed = PathService::Get(key, &path);
  539. if (!succeed)
  540. args->ThrowError("Failed to get '" + name + "' path");
  541. return path;
  542. }
  543. void App::SetPath(mate::Arguments* args,
  544. const std::string& name,
  545. const base::FilePath& path) {
  546. if (!path.IsAbsolute()) {
  547. args->ThrowError("Path must be absolute");
  548. return;
  549. }
  550. bool succeed = false;
  551. int key = GetPathConstant(name);
  552. if (key >= 0)
  553. succeed = PathService::OverrideAndCreateIfNeeded(key, path, true, false);
  554. if (!succeed)
  555. args->ThrowError("Failed to set path");
  556. }
  557. void App::SetDesktopName(const std::string& desktop_name) {
  558. #if defined(OS_LINUX)
  559. std::unique_ptr<base::Environment> env(base::Environment::Create());
  560. env->SetVar("CHROME_DESKTOP", desktop_name);
  561. #endif
  562. }
  563. std::string App::GetLocale() {
  564. return l10n_util::GetApplicationLocale("");
  565. }
  566. bool App::MakeSingleInstance(
  567. const ProcessSingleton::NotificationCallback& callback) {
  568. if (process_singleton_.get())
  569. return false;
  570. base::FilePath user_dir;
  571. PathService::Get(brightray::DIR_USER_DATA, &user_dir);
  572. process_singleton_.reset(new ProcessSingleton(
  573. user_dir, base::Bind(NotificationCallbackWrapper, callback)));
  574. switch (process_singleton_->NotifyOtherProcessOrCreate()) {
  575. case ProcessSingleton::NotifyResult::LOCK_ERROR:
  576. case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
  577. case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED:
  578. process_singleton_.reset();
  579. return true;
  580. case ProcessSingleton::NotifyResult::PROCESS_NONE:
  581. default: // Shouldn't be needed, but VS warns if it is not there.
  582. return false;
  583. }
  584. }
  585. void App::ReleaseSingleInstance() {
  586. if (process_singleton_.get()) {
  587. process_singleton_->Cleanup();
  588. process_singleton_.reset();
  589. }
  590. }
  591. bool App::Relaunch(mate::Arguments* js_args) {
  592. // Parse parameters.
  593. bool override_argv = false;
  594. base::FilePath exec_path;
  595. relauncher::StringVector args;
  596. mate::Dictionary options;
  597. if (js_args->GetNext(&options)) {
  598. if (options.Get("execPath", &exec_path) | options.Get("args", &args))
  599. override_argv = true;
  600. }
  601. if (!override_argv) {
  602. #if defined(OS_WIN)
  603. const relauncher::StringVector& argv = atom::AtomCommandLine::wargv();
  604. #else
  605. const relauncher::StringVector& argv = atom::AtomCommandLine::argv();
  606. #endif
  607. return relauncher::RelaunchApp(argv);
  608. }
  609. relauncher::StringVector argv;
  610. argv.reserve(1 + args.size());
  611. if (exec_path.empty()) {
  612. base::FilePath current_exe_path;
  613. PathService::Get(base::FILE_EXE, &current_exe_path);
  614. argv.push_back(current_exe_path.value());
  615. } else {
  616. argv.push_back(exec_path.value());
  617. }
  618. argv.insert(argv.end(), args.begin(), args.end());
  619. return relauncher::RelaunchApp(argv);
  620. }
  621. void App::DisableHardwareAcceleration(mate::Arguments* args) {
  622. if (Browser::Get()->is_ready()) {
  623. args->ThrowError("app.disableHardwareAcceleration() can only be called "
  624. "before app is ready");
  625. return;
  626. }
  627. content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
  628. }
  629. bool App::IsAccessibilitySupportEnabled() {
  630. auto ax_state = content::BrowserAccessibilityState::GetInstance();
  631. return ax_state->IsAccessibleBrowser();
  632. }
  633. #if defined(USE_NSS_CERTS)
  634. void App::ImportCertificate(
  635. const base::DictionaryValue& options,
  636. const net::CompletionCallback& callback) {
  637. auto browser_context = AtomBrowserContext::From("", false);
  638. if (!certificate_manager_model_) {
  639. std::unique_ptr<base::DictionaryValue> copy = options.CreateDeepCopy();
  640. CertificateManagerModel::Create(
  641. browser_context.get(),
  642. base::Bind(&App::OnCertificateManagerModelCreated,
  643. base::Unretained(this),
  644. base::Passed(&copy),
  645. callback));
  646. return;
  647. }
  648. int rv = ImportIntoCertStore(certificate_manager_model_.get(), options);
  649. callback.Run(rv);
  650. }
  651. void App::OnCertificateManagerModelCreated(
  652. std::unique_ptr<base::DictionaryValue> options,
  653. const net::CompletionCallback& callback,
  654. std::unique_ptr<CertificateManagerModel> model) {
  655. certificate_manager_model_ = std::move(model);
  656. int rv = ImportIntoCertStore(certificate_manager_model_.get(),
  657. *(options.get()));
  658. callback.Run(rv);
  659. }
  660. #endif
  661. #if defined(OS_WIN)
  662. v8::Local<v8::Value> App::GetJumpListSettings() {
  663. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  664. int min_items = 10;
  665. std::vector<JumpListItem> removed_items;
  666. if (jump_list.Begin(&min_items, &removed_items)) {
  667. // We don't actually want to change anything, so abort the transaction.
  668. jump_list.Abort();
  669. } else {
  670. LOG(ERROR) << "Failed to begin Jump List transaction.";
  671. }
  672. auto dict = mate::Dictionary::CreateEmpty(isolate());
  673. dict.Set("minItems", min_items);
  674. dict.Set("removedItems", mate::ConvertToV8(isolate(), removed_items));
  675. return dict.GetHandle();
  676. }
  677. JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
  678. mate::Arguments* args) {
  679. std::vector<JumpListCategory> categories;
  680. bool delete_jump_list = val->IsNull();
  681. if (!delete_jump_list &&
  682. !mate::ConvertFromV8(args->isolate(), val, &categories)) {
  683. args->ThrowError("Argument must be null or an array of categories");
  684. return JumpListResult::ARGUMENT_ERROR;
  685. }
  686. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  687. if (delete_jump_list) {
  688. return jump_list.Delete()
  689. ? JumpListResult::SUCCESS
  690. : JumpListResult::GENERIC_ERROR;
  691. }
  692. // Start a transaction that updates the JumpList of this application.
  693. if (!jump_list.Begin())
  694. return JumpListResult::GENERIC_ERROR;
  695. JumpListResult result = jump_list.AppendCategories(categories);
  696. // AppendCategories may have failed to add some categories, but it's better
  697. // to have something than nothing so try to commit the changes anyway.
  698. if (!jump_list.Commit()) {
  699. LOG(ERROR) << "Failed to commit changes to custom Jump List.";
  700. // It's more useful to return the earlier error code that might give
  701. // some indication as to why the transaction actually failed, so don't
  702. // overwrite it with a "generic error" code here.
  703. if (result == JumpListResult::SUCCESS)
  704. result = JumpListResult::GENERIC_ERROR;
  705. }
  706. return result;
  707. }
  708. #endif // defined(OS_WIN)
  709. // static
  710. mate::Handle<App> App::Create(v8::Isolate* isolate) {
  711. return mate::CreateHandle(isolate, new App(isolate));
  712. }
  713. // static
  714. void App::BuildPrototype(
  715. v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) {
  716. prototype->SetClassName(mate::StringToV8(isolate, "App"));
  717. auto browser = base::Unretained(Browser::Get());
  718. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  719. .SetMethod("quit", base::Bind(&Browser::Quit, browser))
  720. .SetMethod("exit", base::Bind(&Browser::Exit, browser))
  721. .SetMethod("focus", base::Bind(&Browser::Focus, browser))
  722. .SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser))
  723. .SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser))
  724. .SetMethod("getName", base::Bind(&Browser::GetName, browser))
  725. .SetMethod("setName", base::Bind(&Browser::SetName, browser))
  726. .SetMethod("isReady", base::Bind(&Browser::is_ready, browser))
  727. .SetMethod("addRecentDocument",
  728. base::Bind(&Browser::AddRecentDocument, browser))
  729. .SetMethod("clearRecentDocuments",
  730. base::Bind(&Browser::ClearRecentDocuments, browser))
  731. .SetMethod("setAppUserModelId",
  732. base::Bind(&Browser::SetAppUserModelID, browser))
  733. .SetMethod("isDefaultProtocolClient",
  734. base::Bind(&Browser::IsDefaultProtocolClient, browser))
  735. .SetMethod("setAsDefaultProtocolClient",
  736. base::Bind(&Browser::SetAsDefaultProtocolClient, browser))
  737. .SetMethod("removeAsDefaultProtocolClient",
  738. base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser))
  739. .SetMethod("setBadgeCount", base::Bind(&Browser::SetBadgeCount, browser))
  740. .SetMethod("getBadgeCount", base::Bind(&Browser::GetBadgeCount, browser))
  741. .SetMethod("getLoginItemSettings",
  742. base::Bind(&Browser::GetLoginItemSettings, browser))
  743. .SetMethod("setLoginItemSettings",
  744. base::Bind(&Browser::SetLoginItemSettings, browser))
  745. #if defined(OS_MACOSX)
  746. .SetMethod("hide", base::Bind(&Browser::Hide, browser))
  747. .SetMethod("show", base::Bind(&Browser::Show, browser))
  748. .SetMethod("setUserActivity",
  749. base::Bind(&Browser::SetUserActivity, browser))
  750. .SetMethod("getCurrentActivityType",
  751. base::Bind(&Browser::GetCurrentActivityType, browser))
  752. .SetMethod("setAboutPanelOptions",
  753. base::Bind(&Browser::SetAboutPanelOptions, browser))
  754. #endif
  755. #if defined(OS_WIN)
  756. .SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser))
  757. .SetMethod("getJumpListSettings", &App::GetJumpListSettings)
  758. .SetMethod("setJumpList", &App::SetJumpList)
  759. #endif
  760. #if defined(OS_LINUX)
  761. .SetMethod("isUnityRunning",
  762. base::Bind(&Browser::IsUnityRunning, browser))
  763. #endif
  764. .SetMethod("setPath", &App::SetPath)
  765. .SetMethod("getPath", &App::GetPath)
  766. .SetMethod("setDesktopName", &App::SetDesktopName)
  767. .SetMethod("getLocale", &App::GetLocale)
  768. #if defined(USE_NSS_CERTS)
  769. .SetMethod("importCertificate", &App::ImportCertificate)
  770. #endif
  771. .SetMethod("makeSingleInstance", &App::MakeSingleInstance)
  772. .SetMethod("releaseSingleInstance", &App::ReleaseSingleInstance)
  773. .SetMethod("relaunch", &App::Relaunch)
  774. .SetMethod("isAccessibilitySupportEnabled",
  775. &App::IsAccessibilitySupportEnabled)
  776. .SetMethod("disableHardwareAcceleration",
  777. &App::DisableHardwareAcceleration);
  778. }
  779. } // namespace api
  780. } // namespace atom
  781. namespace {
  782. void AppendSwitch(const std::string& switch_string, mate::Arguments* args) {
  783. auto command_line = base::CommandLine::ForCurrentProcess();
  784. if (base::EndsWith(switch_string, "-path",
  785. base::CompareCase::INSENSITIVE_ASCII) ||
  786. switch_string == switches::kLogNetLog) {
  787. base::FilePath path;
  788. args->GetNext(&path);
  789. command_line->AppendSwitchPath(switch_string, path);
  790. return;
  791. }
  792. std::string value;
  793. if (args->GetNext(&value))
  794. command_line->AppendSwitchASCII(switch_string, value);
  795. else
  796. command_line->AppendSwitch(switch_string);
  797. }
  798. #if defined(OS_MACOSX)
  799. int DockBounce(const std::string& type) {
  800. int request_id = -1;
  801. if (type == "critical")
  802. request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL);
  803. else if (type == "informational")
  804. request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL);
  805. return request_id;
  806. }
  807. void DockSetMenu(atom::api::Menu* menu) {
  808. Browser::Get()->DockSetMenu(menu->model());
  809. }
  810. #endif
  811. void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
  812. v8::Local<v8::Context> context, void* priv) {
  813. v8::Isolate* isolate = context->GetIsolate();
  814. auto command_line = base::CommandLine::ForCurrentProcess();
  815. mate::Dictionary dict(isolate, exports);
  816. dict.Set("App", atom::api::App::GetConstructor(isolate)->GetFunction());
  817. dict.Set("app", atom::api::App::Create(isolate));
  818. dict.SetMethod("appendSwitch", &AppendSwitch);
  819. dict.SetMethod("appendArgument",
  820. base::Bind(&base::CommandLine::AppendArg,
  821. base::Unretained(command_line)));
  822. #if defined(OS_MACOSX)
  823. auto browser = base::Unretained(Browser::Get());
  824. dict.SetMethod("dockBounce", &DockBounce);
  825. dict.SetMethod("dockCancelBounce",
  826. base::Bind(&Browser::DockCancelBounce, browser));
  827. dict.SetMethod("dockDownloadFinished",
  828. base::Bind(&Browser::DockDownloadFinished, browser));
  829. dict.SetMethod("dockSetBadgeText",
  830. base::Bind(&Browser::DockSetBadgeText, browser));
  831. dict.SetMethod("dockGetBadgeText",
  832. base::Bind(&Browser::DockGetBadgeText, browser));
  833. dict.SetMethod("dockHide", base::Bind(&Browser::DockHide, browser));
  834. dict.SetMethod("dockShow", base::Bind(&Browser::DockShow, browser));
  835. dict.SetMethod("dockIsVisible", base::Bind(&Browser::DockIsVisible, browser));
  836. dict.SetMethod("dockSetMenu", &DockSetMenu);
  837. dict.SetMethod("dockSetIcon", base::Bind(&Browser::DockSetIcon, browser));
  838. #endif
  839. }
  840. } // namespace
  841. NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_app, Initialize)