atom_api_app.cc 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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/api/gpuinfo_manager.h"
  11. #include "atom/browser/atom_browser_context.h"
  12. #include "atom/browser/atom_browser_main_parts.h"
  13. #include "atom/browser/atom_paths.h"
  14. #include "atom/browser/login_handler.h"
  15. #include "atom/browser/relauncher.h"
  16. #include "atom/common/atom_command_line.h"
  17. #include "atom/common/native_mate_converters/callback.h"
  18. #include "atom/common/native_mate_converters/file_path_converter.h"
  19. #include "atom/common/native_mate_converters/gurl_converter.h"
  20. #include "atom/common/native_mate_converters/image_converter.h"
  21. #include "atom/common/native_mate_converters/net_converter.h"
  22. #include "atom/common/native_mate_converters/network_converter.h"
  23. #include "atom/common/native_mate_converters/value_converter.h"
  24. #include "atom/common/options_switches.h"
  25. #include "base/command_line.h"
  26. #include "base/environment.h"
  27. #include "base/files/file_path.h"
  28. #include "base/files/file_util.h"
  29. #include "base/path_service.h"
  30. #include "base/system/sys_info.h"
  31. #include "chrome/browser/browser_process.h"
  32. #include "chrome/browser/icon_manager.h"
  33. #include "chrome/common/chrome_paths.h"
  34. #include "content/browser/gpu/compositor_util.h"
  35. #include "content/browser/gpu/gpu_data_manager_impl.h"
  36. #include "content/public/browser/browser_accessibility_state.h"
  37. #include "content/public/browser/browser_child_process_host.h"
  38. #include "content/public/browser/child_process_data.h"
  39. #include "content/public/browser/client_certificate_delegate.h"
  40. #include "content/public/browser/gpu_data_manager.h"
  41. #include "content/public/browser/render_frame_host.h"
  42. #include "content/public/common/content_switches.h"
  43. #include "media/audio/audio_manager.h"
  44. #include "native_mate/object_template_builder.h"
  45. #include "net/ssl/client_cert_identity.h"
  46. #include "net/ssl/ssl_cert_request_info.h"
  47. #include "services/service_manager/sandbox/switches.h"
  48. #include "ui/base/l10n/l10n_util.h"
  49. #include "ui/gfx/image/image.h"
  50. // clang-format off
  51. // This header should be declared at the end to avoid
  52. // redefinition errors.
  53. #include "atom/common/node_includes.h" // NOLINT(build/include_alpha)
  54. // clang-format on
  55. #if defined(OS_WIN)
  56. #include "atom/browser/ui/win/jump_list.h"
  57. #include "base/strings/utf_string_conversions.h"
  58. #endif
  59. #if defined(OS_MACOSX)
  60. #include <CoreFoundation/CoreFoundation.h>
  61. #include "atom/browser/ui/cocoa/atom_bundle_mover.h"
  62. #endif
  63. using atom::Browser;
  64. namespace mate {
  65. #if defined(OS_WIN)
  66. template <>
  67. struct Converter<Browser::UserTask> {
  68. static bool FromV8(v8::Isolate* isolate,
  69. v8::Local<v8::Value> val,
  70. Browser::UserTask* out) {
  71. mate::Dictionary dict;
  72. if (!ConvertFromV8(isolate, val, &dict))
  73. return false;
  74. if (!dict.Get("program", &(out->program)) ||
  75. !dict.Get("title", &(out->title)))
  76. return false;
  77. if (dict.Get("iconPath", &(out->icon_path)) &&
  78. !dict.Get("iconIndex", &(out->icon_index)))
  79. return false;
  80. dict.Get("arguments", &(out->arguments));
  81. dict.Get("description", &(out->description));
  82. return true;
  83. }
  84. };
  85. using atom::JumpListCategory;
  86. using atom::JumpListItem;
  87. using atom::JumpListResult;
  88. template <>
  89. struct Converter<JumpListItem::Type> {
  90. static bool FromV8(v8::Isolate* isolate,
  91. v8::Local<v8::Value> val,
  92. JumpListItem::Type* out) {
  93. std::string item_type;
  94. if (!ConvertFromV8(isolate, val, &item_type))
  95. return false;
  96. if (item_type == "task")
  97. *out = JumpListItem::Type::TASK;
  98. else if (item_type == "separator")
  99. *out = JumpListItem::Type::SEPARATOR;
  100. else if (item_type == "file")
  101. *out = JumpListItem::Type::FILE;
  102. else
  103. return false;
  104. return true;
  105. }
  106. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  107. JumpListItem::Type val) {
  108. std::string item_type;
  109. switch (val) {
  110. case JumpListItem::Type::TASK:
  111. item_type = "task";
  112. break;
  113. case JumpListItem::Type::SEPARATOR:
  114. item_type = "separator";
  115. break;
  116. case JumpListItem::Type::FILE:
  117. item_type = "file";
  118. break;
  119. }
  120. return mate::ConvertToV8(isolate, item_type);
  121. }
  122. };
  123. template <>
  124. struct Converter<JumpListItem> {
  125. static bool FromV8(v8::Isolate* isolate,
  126. v8::Local<v8::Value> val,
  127. JumpListItem* out) {
  128. mate::Dictionary dict;
  129. if (!ConvertFromV8(isolate, val, &dict))
  130. return false;
  131. if (!dict.Get("type", &(out->type)))
  132. return false;
  133. switch (out->type) {
  134. case JumpListItem::Type::TASK:
  135. if (!dict.Get("program", &(out->path)) ||
  136. !dict.Get("title", &(out->title)))
  137. return false;
  138. if (dict.Get("iconPath", &(out->icon_path)) &&
  139. !dict.Get("iconIndex", &(out->icon_index)))
  140. return false;
  141. dict.Get("args", &(out->arguments));
  142. dict.Get("description", &(out->description));
  143. return true;
  144. case JumpListItem::Type::SEPARATOR:
  145. return true;
  146. case JumpListItem::Type::FILE:
  147. return dict.Get("path", &(out->path));
  148. }
  149. assert(false);
  150. return false;
  151. }
  152. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  153. const JumpListItem& val) {
  154. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  155. dict.Set("type", val.type);
  156. switch (val.type) {
  157. case JumpListItem::Type::TASK:
  158. dict.Set("program", val.path);
  159. dict.Set("args", val.arguments);
  160. dict.Set("title", val.title);
  161. dict.Set("iconPath", val.icon_path);
  162. dict.Set("iconIndex", val.icon_index);
  163. dict.Set("description", val.description);
  164. break;
  165. case JumpListItem::Type::SEPARATOR:
  166. break;
  167. case JumpListItem::Type::FILE:
  168. dict.Set("path", val.path);
  169. break;
  170. }
  171. return dict.GetHandle();
  172. }
  173. };
  174. template <>
  175. struct Converter<JumpListCategory::Type> {
  176. static bool FromV8(v8::Isolate* isolate,
  177. v8::Local<v8::Value> val,
  178. JumpListCategory::Type* out) {
  179. std::string category_type;
  180. if (!ConvertFromV8(isolate, val, &category_type))
  181. return false;
  182. if (category_type == "tasks")
  183. *out = JumpListCategory::Type::TASKS;
  184. else if (category_type == "frequent")
  185. *out = JumpListCategory::Type::FREQUENT;
  186. else if (category_type == "recent")
  187. *out = JumpListCategory::Type::RECENT;
  188. else if (category_type == "custom")
  189. *out = JumpListCategory::Type::CUSTOM;
  190. else
  191. return false;
  192. return true;
  193. }
  194. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  195. JumpListCategory::Type val) {
  196. std::string category_type;
  197. switch (val) {
  198. case JumpListCategory::Type::TASKS:
  199. category_type = "tasks";
  200. break;
  201. case JumpListCategory::Type::FREQUENT:
  202. category_type = "frequent";
  203. break;
  204. case JumpListCategory::Type::RECENT:
  205. category_type = "recent";
  206. break;
  207. case JumpListCategory::Type::CUSTOM:
  208. category_type = "custom";
  209. break;
  210. }
  211. return mate::ConvertToV8(isolate, category_type);
  212. }
  213. };
  214. template <>
  215. struct Converter<JumpListCategory> {
  216. static bool FromV8(v8::Isolate* isolate,
  217. v8::Local<v8::Value> val,
  218. JumpListCategory* out) {
  219. mate::Dictionary dict;
  220. if (!ConvertFromV8(isolate, val, &dict))
  221. return false;
  222. if (dict.Get("name", &(out->name)) && out->name.empty())
  223. return false;
  224. if (!dict.Get("type", &(out->type))) {
  225. if (out->name.empty())
  226. out->type = JumpListCategory::Type::TASKS;
  227. else
  228. out->type = JumpListCategory::Type::CUSTOM;
  229. }
  230. if ((out->type == JumpListCategory::Type::TASKS) ||
  231. (out->type == JumpListCategory::Type::CUSTOM)) {
  232. if (!dict.Get("items", &(out->items)))
  233. return false;
  234. }
  235. return true;
  236. }
  237. };
  238. // static
  239. template <>
  240. struct Converter<JumpListResult> {
  241. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
  242. std::string result_code;
  243. switch (val) {
  244. case JumpListResult::SUCCESS:
  245. result_code = "ok";
  246. break;
  247. case JumpListResult::ARGUMENT_ERROR:
  248. result_code = "argumentError";
  249. break;
  250. case JumpListResult::GENERIC_ERROR:
  251. result_code = "error";
  252. break;
  253. case JumpListResult::CUSTOM_CATEGORY_SEPARATOR_ERROR:
  254. result_code = "invalidSeparatorError";
  255. break;
  256. case JumpListResult::MISSING_FILE_TYPE_REGISTRATION_ERROR:
  257. result_code = "fileTypeRegistrationError";
  258. break;
  259. case JumpListResult::CUSTOM_CATEGORY_ACCESS_DENIED_ERROR:
  260. result_code = "customCategoryAccessDeniedError";
  261. break;
  262. }
  263. return ConvertToV8(isolate, result_code);
  264. }
  265. };
  266. #endif
  267. template <>
  268. struct Converter<Browser::LoginItemSettings> {
  269. static bool FromV8(v8::Isolate* isolate,
  270. v8::Local<v8::Value> val,
  271. Browser::LoginItemSettings* out) {
  272. mate::Dictionary dict;
  273. if (!ConvertFromV8(isolate, val, &dict))
  274. return false;
  275. dict.Get("openAtLogin", &(out->open_at_login));
  276. dict.Get("openAsHidden", &(out->open_as_hidden));
  277. dict.Get("path", &(out->path));
  278. dict.Get("args", &(out->args));
  279. return true;
  280. }
  281. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  282. Browser::LoginItemSettings val) {
  283. mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  284. dict.Set("openAtLogin", val.open_at_login);
  285. dict.Set("openAsHidden", val.open_as_hidden);
  286. dict.Set("restoreState", val.restore_state);
  287. dict.Set("wasOpenedAtLogin", val.opened_at_login);
  288. dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
  289. return dict.GetHandle();
  290. }
  291. };
  292. template <>
  293. struct Converter<content::CertificateRequestResultType> {
  294. static bool FromV8(v8::Isolate* isolate,
  295. v8::Local<v8::Value> val,
  296. content::CertificateRequestResultType* out) {
  297. bool b;
  298. if (!ConvertFromV8(isolate, val, &b))
  299. return false;
  300. *out = b ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE
  301. : content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
  302. return true;
  303. }
  304. };
  305. } // namespace mate
  306. namespace atom {
  307. ProcessMetric::ProcessMetric(int type,
  308. base::ProcessId pid,
  309. std::unique_ptr<base::ProcessMetrics> metrics) {
  310. this->type = type;
  311. this->pid = pid;
  312. this->metrics = std::move(metrics);
  313. }
  314. ProcessMetric::~ProcessMetric() = default;
  315. namespace api {
  316. namespace {
  317. class AppIdProcessIterator : public base::ProcessIterator {
  318. public:
  319. AppIdProcessIterator() : base::ProcessIterator(nullptr) {}
  320. protected:
  321. bool IncludeEntry() override {
  322. return (entry().parent_pid() == base::GetCurrentProcId() ||
  323. entry().pid() == base::GetCurrentProcId());
  324. }
  325. };
  326. IconLoader::IconSize GetIconSizeByString(const std::string& size) {
  327. if (size == "small") {
  328. return IconLoader::IconSize::SMALL;
  329. } else if (size == "large") {
  330. return IconLoader::IconSize::LARGE;
  331. }
  332. return IconLoader::IconSize::NORMAL;
  333. }
  334. // Return the path constant from string.
  335. int GetPathConstant(const std::string& name) {
  336. if (name == "appData")
  337. return DIR_APP_DATA;
  338. else if (name == "userData")
  339. return DIR_USER_DATA;
  340. else if (name == "cache")
  341. return DIR_CACHE;
  342. else if (name == "userCache")
  343. return DIR_USER_CACHE;
  344. else if (name == "logs")
  345. return DIR_APP_LOGS;
  346. else if (name == "home")
  347. return base::DIR_HOME;
  348. else if (name == "temp")
  349. return base::DIR_TEMP;
  350. else if (name == "userDesktop" || name == "desktop")
  351. return base::DIR_USER_DESKTOP;
  352. else if (name == "exe")
  353. return base::FILE_EXE;
  354. else if (name == "module")
  355. return base::FILE_MODULE;
  356. else if (name == "documents")
  357. return chrome::DIR_USER_DOCUMENTS;
  358. else if (name == "downloads")
  359. return chrome::DIR_DEFAULT_DOWNLOADS;
  360. else if (name == "music")
  361. return chrome::DIR_USER_MUSIC;
  362. else if (name == "pictures")
  363. return chrome::DIR_USER_PICTURES;
  364. else if (name == "videos")
  365. return chrome::DIR_USER_VIDEOS;
  366. else if (name == "pepperFlashSystemPlugin")
  367. return chrome::FILE_PEPPER_FLASH_SYSTEM_PLUGIN;
  368. else
  369. return -1;
  370. }
  371. bool NotificationCallbackWrapper(
  372. const base::Callback<
  373. void(const base::CommandLine::StringVector& command_line,
  374. const base::FilePath& current_directory)>& callback,
  375. const base::CommandLine::StringVector& cmd,
  376. const base::FilePath& cwd) {
  377. // Make sure the callback is called after app gets ready.
  378. if (Browser::Get()->is_ready()) {
  379. callback.Run(cmd, cwd);
  380. } else {
  381. scoped_refptr<base::SingleThreadTaskRunner> task_runner(
  382. base::ThreadTaskRunnerHandle::Get());
  383. task_runner->PostTask(
  384. FROM_HERE, base::BindOnce(base::IgnoreResult(callback), cmd, cwd));
  385. }
  386. // ProcessSingleton needs to know whether current process is quiting.
  387. return !Browser::Get()->is_shutting_down();
  388. }
  389. void GotPrivateKey(std::shared_ptr<content::ClientCertificateDelegate> delegate,
  390. scoped_refptr<net::X509Certificate> cert,
  391. scoped_refptr<net::SSLPrivateKey> private_key) {
  392. delegate->ContinueWithCertificate(cert, private_key);
  393. }
  394. void OnClientCertificateSelected(
  395. v8::Isolate* isolate,
  396. std::shared_ptr<content::ClientCertificateDelegate> delegate,
  397. std::shared_ptr<net::ClientCertIdentityList> identities,
  398. mate::Arguments* args) {
  399. if (args->Length() == 2) {
  400. delegate->ContinueWithCertificate(nullptr, nullptr);
  401. return;
  402. }
  403. v8::Local<v8::Value> val;
  404. args->GetNext(&val);
  405. if (val->IsNull()) {
  406. delegate->ContinueWithCertificate(nullptr, nullptr);
  407. return;
  408. }
  409. mate::Dictionary cert_data;
  410. if (!mate::ConvertFromV8(isolate, val, &cert_data)) {
  411. args->ThrowError("Must pass valid certificate object.");
  412. return;
  413. }
  414. std::string data;
  415. if (!cert_data.Get("data", &data))
  416. return;
  417. auto certs = net::X509Certificate::CreateCertificateListFromBytes(
  418. data.c_str(), data.length(), net::X509Certificate::FORMAT_AUTO);
  419. if (!certs.empty()) {
  420. scoped_refptr<net::X509Certificate> cert(certs[0].get());
  421. for (size_t i = 0; i < identities->size(); ++i) {
  422. if (cert->EqualsExcludingChain((*identities)[i]->certificate())) {
  423. net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
  424. std::move((*identities)[i]),
  425. base::Bind(&GotPrivateKey, delegate, std::move(cert)));
  426. break;
  427. }
  428. }
  429. }
  430. }
  431. void PassLoginInformation(scoped_refptr<LoginHandler> login_handler,
  432. mate::Arguments* args) {
  433. base::string16 username, password;
  434. if (args->GetNext(&username) && args->GetNext(&password))
  435. login_handler->Login(username, password);
  436. else
  437. login_handler->CancelAuth();
  438. }
  439. #if defined(USE_NSS_CERTS)
  440. int ImportIntoCertStore(CertificateManagerModel* model,
  441. const base::DictionaryValue& options) {
  442. std::string file_data, cert_path;
  443. base::string16 password;
  444. net::ScopedCERTCertificateList imported_certs;
  445. int rv = -1;
  446. options.GetString("certificate", &cert_path);
  447. options.GetString("password", &password);
  448. if (!cert_path.empty()) {
  449. if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
  450. auto module = model->cert_db()->GetPrivateSlot();
  451. rv = model->ImportFromPKCS12(module.get(), file_data, password, true,
  452. &imported_certs);
  453. if (imported_certs.size() > 1) {
  454. auto it = imported_certs.begin();
  455. ++it; // skip first which would be the client certificate.
  456. for (; it != imported_certs.end(); ++it)
  457. rv &= model->SetCertTrust(it->get(), net::CA_CERT,
  458. net::NSSCertDatabase::TRUSTED_SSL);
  459. }
  460. }
  461. }
  462. return rv;
  463. }
  464. #endif
  465. void OnIconDataAvailable(util::Promise promise, gfx::Image* icon) {
  466. if (icon && !icon->IsEmpty()) {
  467. promise.Resolve(*icon);
  468. } else {
  469. promise.RejectWithErrorMessage("Failed to get file icon.");
  470. }
  471. }
  472. } // namespace
  473. App::App(v8::Isolate* isolate) {
  474. static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())->set_delegate(this);
  475. Browser::Get()->AddObserver(this);
  476. content::GpuDataManager::GetInstance()->AddObserver(this);
  477. base::ProcessId pid = base::GetCurrentProcId();
  478. auto process_metric = std::make_unique<atom::ProcessMetric>(
  479. content::PROCESS_TYPE_BROWSER, pid,
  480. base::ProcessMetrics::CreateCurrentProcessMetrics());
  481. app_metrics_[pid] = std::move(process_metric);
  482. Init(isolate);
  483. }
  484. App::~App() {
  485. static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())
  486. ->set_delegate(nullptr);
  487. Browser::Get()->RemoveObserver(this);
  488. content::GpuDataManager::GetInstance()->RemoveObserver(this);
  489. content::BrowserChildProcessObserver::Remove(this);
  490. }
  491. void App::OnBeforeQuit(bool* prevent_default) {
  492. if (Emit("before-quit")) {
  493. *prevent_default = true;
  494. }
  495. }
  496. void App::OnWillQuit(bool* prevent_default) {
  497. if (Emit("will-quit")) {
  498. *prevent_default = true;
  499. }
  500. }
  501. void App::OnWindowAllClosed() {
  502. Emit("window-all-closed");
  503. }
  504. void App::OnQuit() {
  505. int exitCode = AtomBrowserMainParts::Get()->GetExitCode();
  506. Emit("quit", exitCode);
  507. if (process_singleton_) {
  508. process_singleton_->Cleanup();
  509. process_singleton_.reset();
  510. }
  511. }
  512. void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
  513. if (Emit("open-file", file_path)) {
  514. *prevent_default = true;
  515. }
  516. }
  517. void App::OnOpenURL(const std::string& url) {
  518. Emit("open-url", url);
  519. }
  520. void App::OnActivate(bool has_visible_windows) {
  521. Emit("activate", has_visible_windows);
  522. }
  523. void App::OnWillFinishLaunching() {
  524. Emit("will-finish-launching");
  525. }
  526. void App::OnFinishLaunching(const base::DictionaryValue& launch_info) {
  527. #if defined(OS_LINUX)
  528. // Set the application name for audio streams shown in external
  529. // applications. Only affects pulseaudio currently.
  530. media::AudioManager::SetGlobalAppName(Browser::Get()->GetName());
  531. #endif
  532. Emit("ready", launch_info);
  533. }
  534. void App::OnPreMainMessageLoopRun() {
  535. content::BrowserChildProcessObserver::Add(this);
  536. if (process_singleton_) {
  537. process_singleton_->OnBrowserReady();
  538. }
  539. }
  540. void App::OnAccessibilitySupportChanged() {
  541. Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
  542. }
  543. #if defined(OS_MACOSX)
  544. void App::OnWillContinueUserActivity(bool* prevent_default,
  545. const std::string& type) {
  546. if (Emit("will-continue-activity", type)) {
  547. *prevent_default = true;
  548. }
  549. }
  550. void App::OnDidFailToContinueUserActivity(const std::string& type,
  551. const std::string& error) {
  552. Emit("continue-activity-error", type, error);
  553. }
  554. void App::OnContinueUserActivity(bool* prevent_default,
  555. const std::string& type,
  556. const base::DictionaryValue& user_info) {
  557. if (Emit("continue-activity", type, user_info)) {
  558. *prevent_default = true;
  559. }
  560. }
  561. void App::OnUserActivityWasContinued(const std::string& type,
  562. const base::DictionaryValue& user_info) {
  563. Emit("activity-was-continued", type, user_info);
  564. }
  565. void App::OnUpdateUserActivityState(bool* prevent_default,
  566. const std::string& type,
  567. const base::DictionaryValue& user_info) {
  568. if (Emit("update-activity-state", type, user_info)) {
  569. *prevent_default = true;
  570. }
  571. }
  572. void App::OnNewWindowForTab() {
  573. Emit("new-window-for-tab");
  574. }
  575. #endif
  576. void App::OnLogin(scoped_refptr<LoginHandler> login_handler,
  577. const base::DictionaryValue& request_details) {
  578. v8::Locker locker(isolate());
  579. v8::HandleScope handle_scope(isolate());
  580. bool prevent_default = false;
  581. content::WebContents* web_contents = login_handler->GetWebContents();
  582. if (web_contents) {
  583. prevent_default = Emit(
  584. "login", WebContents::FromOrCreate(isolate(), web_contents),
  585. request_details, login_handler->auth_info(),
  586. base::Bind(&PassLoginInformation, base::RetainedRef(login_handler)));
  587. }
  588. // Default behavior is to always cancel the auth.
  589. if (!prevent_default)
  590. login_handler->CancelAuth();
  591. }
  592. bool App::CanCreateWindow(
  593. content::RenderFrameHost* opener,
  594. const GURL& opener_url,
  595. const GURL& opener_top_level_frame_url,
  596. const url::Origin& source_origin,
  597. content::mojom::WindowContainerType container_type,
  598. const GURL& target_url,
  599. const content::Referrer& referrer,
  600. const std::string& frame_name,
  601. WindowOpenDisposition disposition,
  602. const blink::mojom::WindowFeatures& features,
  603. const std::vector<std::string>& additional_features,
  604. const scoped_refptr<network::ResourceRequestBody>& body,
  605. bool user_gesture,
  606. bool opener_suppressed,
  607. bool* no_javascript_access) {
  608. v8::Locker locker(isolate());
  609. v8::HandleScope handle_scope(isolate());
  610. content::WebContents* web_contents =
  611. content::WebContents::FromRenderFrameHost(opener);
  612. if (web_contents) {
  613. auto api_web_contents = WebContents::From(isolate(), web_contents);
  614. // No need to emit any event if the WebContents is not available in JS.
  615. if (!api_web_contents.IsEmpty()) {
  616. api_web_contents->OnCreateWindow(target_url, referrer, frame_name,
  617. disposition, additional_features, body);
  618. }
  619. }
  620. return false;
  621. }
  622. void App::AllowCertificateError(
  623. content::WebContents* web_contents,
  624. int cert_error,
  625. const net::SSLInfo& ssl_info,
  626. const GURL& request_url,
  627. content::ResourceType resource_type,
  628. bool strict_enforcement,
  629. bool expired_previous_decision,
  630. const base::Callback<void(content::CertificateRequestResultType)>&
  631. callback) {
  632. v8::Locker locker(isolate());
  633. v8::HandleScope handle_scope(isolate());
  634. bool prevent_default = Emit(
  635. "certificate-error", WebContents::FromOrCreate(isolate(), web_contents),
  636. request_url, net::ErrorToString(cert_error), ssl_info.cert, callback);
  637. // Deny the certificate by default.
  638. if (!prevent_default)
  639. callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
  640. }
  641. void App::SelectClientCertificate(
  642. content::WebContents* web_contents,
  643. net::SSLCertRequestInfo* cert_request_info,
  644. net::ClientCertIdentityList identities,
  645. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  646. std::shared_ptr<content::ClientCertificateDelegate> shared_delegate(
  647. delegate.release());
  648. // Convert the ClientCertIdentityList to a CertificateList
  649. // to avoid changes in the API.
  650. auto client_certs = net::CertificateList();
  651. for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities)
  652. client_certs.push_back(identity->certificate());
  653. auto shared_identities =
  654. std::make_shared<net::ClientCertIdentityList>(std::move(identities));
  655. bool prevent_default =
  656. Emit("select-client-certificate",
  657. WebContents::FromOrCreate(isolate(), web_contents),
  658. cert_request_info->host_and_port.ToString(), std::move(client_certs),
  659. base::Bind(&OnClientCertificateSelected, isolate(), shared_delegate,
  660. shared_identities));
  661. // Default to first certificate from the platform store.
  662. if (!prevent_default) {
  663. scoped_refptr<net::X509Certificate> cert =
  664. (*shared_identities)[0]->certificate();
  665. net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
  666. std::move((*shared_identities)[0]),
  667. base::Bind(&GotPrivateKey, shared_delegate, std::move(cert)));
  668. }
  669. }
  670. void App::OnGpuProcessCrashed(base::TerminationStatus status) {
  671. Emit("gpu-process-crashed",
  672. status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
  673. }
  674. void App::BrowserChildProcessLaunchedAndConnected(
  675. const content::ChildProcessData& data) {
  676. ChildProcessLaunched(data.process_type, data.GetProcess().Handle());
  677. }
  678. void App::BrowserChildProcessHostDisconnected(
  679. const content::ChildProcessData& data) {
  680. ChildProcessDisconnected(base::GetProcId(data.GetProcess().Handle()));
  681. }
  682. void App::BrowserChildProcessCrashed(
  683. const content::ChildProcessData& data,
  684. const content::ChildProcessTerminationInfo& info) {
  685. ChildProcessDisconnected(base::GetProcId(data.GetProcess().Handle()));
  686. }
  687. void App::BrowserChildProcessKilled(
  688. const content::ChildProcessData& data,
  689. const content::ChildProcessTerminationInfo& info) {
  690. ChildProcessDisconnected(base::GetProcId(data.GetProcess().Handle()));
  691. }
  692. void App::RenderProcessReady(content::RenderProcessHost* host) {
  693. ChildProcessLaunched(content::PROCESS_TYPE_RENDERER,
  694. host->GetProcess().Handle());
  695. }
  696. void App::RenderProcessDisconnected(base::ProcessId host_pid) {
  697. ChildProcessDisconnected(host_pid);
  698. }
  699. void App::ChildProcessLaunched(int process_type, base::ProcessHandle handle) {
  700. auto pid = base::GetProcId(handle);
  701. #if defined(OS_MACOSX)
  702. std::unique_ptr<base::ProcessMetrics> metrics(
  703. base::ProcessMetrics::CreateProcessMetrics(
  704. handle, content::BrowserChildProcessHost::GetPortProvider()));
  705. #else
  706. std::unique_ptr<base::ProcessMetrics> metrics(
  707. base::ProcessMetrics::CreateProcessMetrics(handle));
  708. #endif
  709. app_metrics_[pid] = std::make_unique<atom::ProcessMetric>(process_type, pid,
  710. std::move(metrics));
  711. }
  712. void App::ChildProcessDisconnected(base::ProcessId pid) {
  713. app_metrics_.erase(pid);
  714. }
  715. base::FilePath App::GetAppPath() const {
  716. return app_path_;
  717. }
  718. void App::SetAppPath(const base::FilePath& app_path) {
  719. app_path_ = app_path;
  720. }
  721. base::FilePath App::GetPath(mate::Arguments* args, const std::string& name) {
  722. bool succeed = false;
  723. base::FilePath path;
  724. int key = GetPathConstant(name);
  725. if (key >= 0)
  726. succeed = base::PathService::Get(key, &path);
  727. if (!succeed)
  728. args->ThrowError("Failed to get '" + name + "' path");
  729. return path;
  730. }
  731. void App::SetPath(mate::Arguments* args,
  732. const std::string& name,
  733. const base::FilePath& path) {
  734. if (!path.IsAbsolute()) {
  735. args->ThrowError("Path must be absolute");
  736. return;
  737. }
  738. bool succeed = false;
  739. int key = GetPathConstant(name);
  740. if (key >= 0)
  741. succeed =
  742. base::PathService::OverrideAndCreateIfNeeded(key, path, true, false);
  743. if (!succeed)
  744. args->ThrowError("Failed to set path");
  745. }
  746. void App::SetDesktopName(const std::string& desktop_name) {
  747. #if defined(OS_LINUX)
  748. std::unique_ptr<base::Environment> env(base::Environment::Create());
  749. env->SetVar("CHROME_DESKTOP", desktop_name);
  750. #endif
  751. }
  752. std::string App::GetLocale() {
  753. return g_browser_process->GetApplicationLocale();
  754. }
  755. std::string App::GetLocaleCountryCode() {
  756. std::string region;
  757. #if defined(OS_WIN)
  758. WCHAR locale_name[LOCALE_NAME_MAX_LENGTH] = {0};
  759. if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
  760. (LPWSTR)&locale_name,
  761. sizeof(locale_name) / sizeof(WCHAR)) ||
  762. GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SISO3166CTRYNAME,
  763. (LPWSTR)&locale_name,
  764. sizeof(locale_name) / sizeof(WCHAR))) {
  765. base::WideToUTF8(locale_name, wcslen(locale_name), &region);
  766. }
  767. #elif defined(OS_MACOSX)
  768. CFLocaleRef locale = CFLocaleCopyCurrent();
  769. CFStringRef value = CFStringRef(
  770. static_cast<CFTypeRef>(CFLocaleGetValue(locale, kCFLocaleCountryCode)));
  771. const CFIndex kCStringSize = 128;
  772. char temporaryCString[kCStringSize] = {0};
  773. CFStringGetCString(value, temporaryCString, kCStringSize,
  774. kCFStringEncodingUTF8);
  775. region = temporaryCString;
  776. #else
  777. const char* locale_ptr = setlocale(LC_TIME, NULL);
  778. if (!locale_ptr)
  779. locale_ptr = setlocale(LC_NUMERIC, NULL);
  780. if (locale_ptr) {
  781. std::string locale = locale_ptr;
  782. std::string::size_type rpos = locale.find('.');
  783. if (rpos != std::string::npos)
  784. locale = locale.substr(0, rpos);
  785. rpos = locale.find('_');
  786. if (rpos != std::string::npos && rpos + 1 < locale.size())
  787. region = locale.substr(rpos + 1);
  788. }
  789. #endif
  790. return region.size() == 2 ? region : std::string();
  791. }
  792. void App::OnSecondInstance(const base::CommandLine::StringVector& cmd,
  793. const base::FilePath& cwd) {
  794. Emit("second-instance", cmd, cwd);
  795. }
  796. bool App::HasSingleInstanceLock() const {
  797. if (process_singleton_)
  798. return true;
  799. return false;
  800. }
  801. bool App::RequestSingleInstanceLock() {
  802. if (HasSingleInstanceLock())
  803. return true;
  804. base::FilePath user_dir;
  805. base::PathService::Get(DIR_USER_DATA, &user_dir);
  806. auto cb = base::Bind(&App::OnSecondInstance, base::Unretained(this));
  807. process_singleton_.reset(new ProcessSingleton(
  808. user_dir, base::Bind(NotificationCallbackWrapper, cb)));
  809. switch (process_singleton_->NotifyOtherProcessOrCreate()) {
  810. case ProcessSingleton::NotifyResult::LOCK_ERROR:
  811. case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
  812. case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
  813. process_singleton_.reset();
  814. return false;
  815. }
  816. case ProcessSingleton::NotifyResult::PROCESS_NONE:
  817. default: // Shouldn't be needed, but VS warns if it is not there.
  818. return true;
  819. }
  820. }
  821. void App::ReleaseSingleInstanceLock() {
  822. if (process_singleton_) {
  823. process_singleton_->Cleanup();
  824. process_singleton_.reset();
  825. }
  826. }
  827. bool App::Relaunch(mate::Arguments* js_args) {
  828. // Parse parameters.
  829. bool override_argv = false;
  830. base::FilePath exec_path;
  831. relauncher::StringVector args;
  832. mate::Dictionary options;
  833. if (js_args->GetNext(&options)) {
  834. if (options.Get("execPath", &exec_path) | options.Get("args", &args))
  835. override_argv = true;
  836. }
  837. if (!override_argv) {
  838. const relauncher::StringVector& argv = atom::AtomCommandLine::argv();
  839. return relauncher::RelaunchApp(argv);
  840. }
  841. relauncher::StringVector argv;
  842. argv.reserve(1 + args.size());
  843. if (exec_path.empty()) {
  844. base::FilePath current_exe_path;
  845. base::PathService::Get(base::FILE_EXE, &current_exe_path);
  846. argv.push_back(current_exe_path.value());
  847. } else {
  848. argv.push_back(exec_path.value());
  849. }
  850. argv.insert(argv.end(), args.begin(), args.end());
  851. return relauncher::RelaunchApp(argv);
  852. }
  853. void App::DisableHardwareAcceleration(mate::Arguments* args) {
  854. if (Browser::Get()->is_ready()) {
  855. args->ThrowError(
  856. "app.disableHardwareAcceleration() can only be called "
  857. "before app is ready");
  858. return;
  859. }
  860. content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
  861. }
  862. void App::DisableDomainBlockingFor3DAPIs(mate::Arguments* args) {
  863. if (Browser::Get()->is_ready()) {
  864. args->ThrowError(
  865. "app.disableDomainBlockingFor3DAPIs() can only be called "
  866. "before app is ready");
  867. return;
  868. }
  869. content::GpuDataManagerImpl::GetInstance()
  870. ->DisableDomainBlockingFor3DAPIsForTesting();
  871. }
  872. bool App::IsAccessibilitySupportEnabled() {
  873. auto* ax_state = content::BrowserAccessibilityState::GetInstance();
  874. return ax_state->IsAccessibleBrowser();
  875. }
  876. void App::SetAccessibilitySupportEnabled(bool enabled, mate::Arguments* args) {
  877. if (!Browser::Get()->is_ready()) {
  878. args->ThrowError(
  879. "app.setAccessibilitySupportEnabled() can only be called "
  880. "after app is ready");
  881. return;
  882. }
  883. auto* ax_state = content::BrowserAccessibilityState::GetInstance();
  884. if (enabled) {
  885. ax_state->OnScreenReaderDetected();
  886. } else {
  887. ax_state->DisableAccessibility();
  888. }
  889. Browser::Get()->OnAccessibilitySupportChanged();
  890. }
  891. Browser::LoginItemSettings App::GetLoginItemSettings(mate::Arguments* args) {
  892. Browser::LoginItemSettings options;
  893. args->GetNext(&options);
  894. return Browser::Get()->GetLoginItemSettings(options);
  895. }
  896. #if defined(USE_NSS_CERTS)
  897. void App::ImportCertificate(const base::DictionaryValue& options,
  898. const net::CompletionCallback& callback) {
  899. auto browser_context = AtomBrowserContext::From("", false);
  900. if (!certificate_manager_model_) {
  901. auto copy = base::DictionaryValue::From(
  902. base::Value::ToUniquePtrValue(options.Clone()));
  903. CertificateManagerModel::Create(
  904. browser_context.get(),
  905. base::Bind(&App::OnCertificateManagerModelCreated,
  906. base::Unretained(this), base::Passed(&copy), callback));
  907. return;
  908. }
  909. int rv = ImportIntoCertStore(certificate_manager_model_.get(), options);
  910. callback.Run(rv);
  911. }
  912. void App::OnCertificateManagerModelCreated(
  913. std::unique_ptr<base::DictionaryValue> options,
  914. const net::CompletionCallback& callback,
  915. std::unique_ptr<CertificateManagerModel> model) {
  916. certificate_manager_model_ = std::move(model);
  917. int rv =
  918. ImportIntoCertStore(certificate_manager_model_.get(), *(options.get()));
  919. callback.Run(rv);
  920. }
  921. #endif
  922. #if defined(OS_WIN)
  923. v8::Local<v8::Value> App::GetJumpListSettings() {
  924. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  925. int min_items = 10;
  926. std::vector<JumpListItem> removed_items;
  927. if (jump_list.Begin(&min_items, &removed_items)) {
  928. // We don't actually want to change anything, so abort the transaction.
  929. jump_list.Abort();
  930. } else {
  931. LOG(ERROR) << "Failed to begin Jump List transaction.";
  932. }
  933. auto dict = mate::Dictionary::CreateEmpty(isolate());
  934. dict.Set("minItems", min_items);
  935. dict.Set("removedItems", mate::ConvertToV8(isolate(), removed_items));
  936. return dict.GetHandle();
  937. }
  938. JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
  939. mate::Arguments* args) {
  940. std::vector<JumpListCategory> categories;
  941. bool delete_jump_list = val->IsNull();
  942. if (!delete_jump_list &&
  943. !mate::ConvertFromV8(args->isolate(), val, &categories)) {
  944. args->ThrowError("Argument must be null or an array of categories");
  945. return JumpListResult::ARGUMENT_ERROR;
  946. }
  947. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  948. if (delete_jump_list) {
  949. return jump_list.Delete() ? JumpListResult::SUCCESS
  950. : JumpListResult::GENERIC_ERROR;
  951. }
  952. // Start a transaction that updates the JumpList of this application.
  953. if (!jump_list.Begin())
  954. return JumpListResult::GENERIC_ERROR;
  955. JumpListResult result = jump_list.AppendCategories(categories);
  956. // AppendCategories may have failed to add some categories, but it's better
  957. // to have something than nothing so try to commit the changes anyway.
  958. if (!jump_list.Commit()) {
  959. LOG(ERROR) << "Failed to commit changes to custom Jump List.";
  960. // It's more useful to return the earlier error code that might give
  961. // some indication as to why the transaction actually failed, so don't
  962. // overwrite it with a "generic error" code here.
  963. if (result == JumpListResult::SUCCESS)
  964. result = JumpListResult::GENERIC_ERROR;
  965. }
  966. return result;
  967. }
  968. #endif // defined(OS_WIN)
  969. v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
  970. mate::Arguments* args) {
  971. util::Promise promise(isolate());
  972. v8::Local<v8::Promise> handle = promise.GetHandle();
  973. base::FilePath normalized_path = path.NormalizePathSeparators();
  974. IconLoader::IconSize icon_size;
  975. mate::Dictionary options;
  976. if (!args->GetNext(&options)) {
  977. icon_size = IconLoader::IconSize::NORMAL;
  978. } else {
  979. std::string icon_size_string;
  980. options.Get("size", &icon_size_string);
  981. icon_size = GetIconSizeByString(icon_size_string);
  982. }
  983. auto* icon_manager = AtomBrowserMainParts::Get()->GetIconManager();
  984. gfx::Image* icon =
  985. icon_manager->LookupIconFromFilepath(normalized_path, icon_size);
  986. if (icon) {
  987. promise.Resolve(*icon);
  988. } else {
  989. icon_manager->LoadIcon(
  990. normalized_path, icon_size,
  991. base::BindOnce(&OnIconDataAvailable, std::move(promise)),
  992. &cancelable_task_tracker_);
  993. }
  994. return handle;
  995. }
  996. std::vector<mate::Dictionary> App::GetAppMetrics(v8::Isolate* isolate) {
  997. std::vector<mate::Dictionary> result;
  998. int processor_count = base::SysInfo::NumberOfProcessors();
  999. for (const auto& process_metric : app_metrics_) {
  1000. mate::Dictionary pid_dict = mate::Dictionary::CreateEmpty(isolate);
  1001. mate::Dictionary cpu_dict = mate::Dictionary::CreateEmpty(isolate);
  1002. pid_dict.SetHidden("simple", true);
  1003. cpu_dict.SetHidden("simple", true);
  1004. cpu_dict.Set(
  1005. "percentCPUUsage",
  1006. process_metric.second->metrics->GetPlatformIndependentCPUUsage() /
  1007. processor_count);
  1008. #if !defined(OS_WIN)
  1009. cpu_dict.Set("idleWakeupsPerSecond",
  1010. process_metric.second->metrics->GetIdleWakeupsPerSecond());
  1011. #else
  1012. // Chrome's underlying process_metrics.cc will throw a non-fatal warning
  1013. // that this method isn't implemented on Windows, so set it to 0 instead
  1014. // of calling it
  1015. cpu_dict.Set("idleWakeupsPerSecond", 0);
  1016. #endif
  1017. pid_dict.Set("cpu", cpu_dict);
  1018. pid_dict.Set("pid", process_metric.second->pid);
  1019. pid_dict.Set("type", content::GetProcessTypeNameInEnglish(
  1020. process_metric.second->type));
  1021. result.push_back(pid_dict);
  1022. }
  1023. return result;
  1024. }
  1025. v8::Local<v8::Value> App::GetGPUFeatureStatus(v8::Isolate* isolate) {
  1026. auto status = content::GetFeatureStatus();
  1027. base::DictionaryValue temp;
  1028. return mate::ConvertToV8(isolate, status ? *status : temp);
  1029. }
  1030. v8::Local<v8::Promise> App::GetGPUInfo(v8::Isolate* isolate,
  1031. const std::string& info_type) {
  1032. auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance();
  1033. util::Promise promise(isolate);
  1034. v8::Local<v8::Promise> handle = promise.GetHandle();
  1035. if (info_type != "basic" && info_type != "complete") {
  1036. promise.RejectWithErrorMessage(
  1037. "Invalid info type. Use 'basic' or 'complete'");
  1038. return handle;
  1039. }
  1040. std::string reason;
  1041. if (!gpu_data_manager->GpuAccessAllowed(&reason)) {
  1042. promise.RejectWithErrorMessage("GPU access not allowed. Reason: " + reason);
  1043. return handle;
  1044. }
  1045. auto* const info_mgr = GPUInfoManager::GetInstance();
  1046. if (info_type == "complete") {
  1047. #if defined(OS_WIN) || defined(OS_MACOSX)
  1048. info_mgr->FetchCompleteInfo(std::move(promise));
  1049. #else
  1050. info_mgr->FetchBasicInfo(std::move(promise));
  1051. #endif
  1052. } else /* (info_type == "basic") */ {
  1053. info_mgr->FetchBasicInfo(std::move(promise));
  1054. }
  1055. return handle;
  1056. }
  1057. static void RemoveNoSandboxSwitch(base::CommandLine* command_line) {
  1058. if (command_line->HasSwitch(service_manager::switches::kNoSandbox)) {
  1059. const base::CommandLine::CharType* noSandboxArg =
  1060. FILE_PATH_LITERAL("--no-sandbox");
  1061. base::CommandLine::StringVector modified_command_line;
  1062. for (auto& arg : command_line->argv()) {
  1063. if (arg.compare(noSandboxArg) != 0) {
  1064. modified_command_line.push_back(arg);
  1065. }
  1066. }
  1067. command_line->InitFromArgv(modified_command_line);
  1068. }
  1069. }
  1070. void App::EnableSandbox(mate::Arguments* args) {
  1071. if (Browser::Get()->is_ready()) {
  1072. args->ThrowError(
  1073. "app.enableSandbox() can only be called "
  1074. "before app is ready");
  1075. return;
  1076. }
  1077. auto* command_line = base::CommandLine::ForCurrentProcess();
  1078. RemoveNoSandboxSwitch(command_line);
  1079. command_line->AppendSwitch(switches::kEnableSandbox);
  1080. }
  1081. #if defined(OS_MACOSX)
  1082. bool App::MoveToApplicationsFolder(mate::Arguments* args) {
  1083. return ui::cocoa::AtomBundleMover::Move(args);
  1084. }
  1085. bool App::IsInApplicationsFolder() {
  1086. return ui::cocoa::AtomBundleMover::IsCurrentAppInApplicationsFolder();
  1087. }
  1088. #endif
  1089. // static
  1090. mate::Handle<App> App::Create(v8::Isolate* isolate) {
  1091. return mate::CreateHandle(isolate, new App(isolate));
  1092. }
  1093. // static
  1094. void App::BuildPrototype(v8::Isolate* isolate,
  1095. v8::Local<v8::FunctionTemplate> prototype) {
  1096. prototype->SetClassName(mate::StringToV8(isolate, "App"));
  1097. auto browser = base::Unretained(Browser::Get());
  1098. mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
  1099. .SetMethod("quit", base::Bind(&Browser::Quit, browser))
  1100. .SetMethod("exit", base::Bind(&Browser::Exit, browser))
  1101. .SetMethod("focus", base::Bind(&Browser::Focus, browser))
  1102. .SetMethod("getVersion", base::Bind(&Browser::GetVersion, browser))
  1103. .SetMethod("setVersion", base::Bind(&Browser::SetVersion, browser))
  1104. .SetMethod("getName", base::Bind(&Browser::GetName, browser))
  1105. .SetMethod("setName", base::Bind(&Browser::SetName, browser))
  1106. .SetMethod("isReady", base::Bind(&Browser::is_ready, browser))
  1107. .SetMethod("whenReady", base::Bind(&Browser::WhenReady, browser))
  1108. .SetMethod("addRecentDocument",
  1109. base::Bind(&Browser::AddRecentDocument, browser))
  1110. .SetMethod("clearRecentDocuments",
  1111. base::Bind(&Browser::ClearRecentDocuments, browser))
  1112. .SetMethod("setAppUserModelId",
  1113. base::Bind(&Browser::SetAppUserModelID, browser))
  1114. .SetMethod("isDefaultProtocolClient",
  1115. base::Bind(&Browser::IsDefaultProtocolClient, browser))
  1116. .SetMethod("setAsDefaultProtocolClient",
  1117. base::Bind(&Browser::SetAsDefaultProtocolClient, browser))
  1118. .SetMethod("removeAsDefaultProtocolClient",
  1119. base::Bind(&Browser::RemoveAsDefaultProtocolClient, browser))
  1120. .SetMethod("setBadgeCount", base::Bind(&Browser::SetBadgeCount, browser))
  1121. .SetMethod("getBadgeCount", base::Bind(&Browser::GetBadgeCount, browser))
  1122. .SetMethod("getLoginItemSettings", &App::GetLoginItemSettings)
  1123. .SetMethod("setLoginItemSettings",
  1124. base::Bind(&Browser::SetLoginItemSettings, browser))
  1125. #if defined(OS_MACOSX)
  1126. .SetMethod("hide", base::Bind(&Browser::Hide, browser))
  1127. .SetMethod("show", base::Bind(&Browser::Show, browser))
  1128. .SetMethod("setUserActivity",
  1129. base::Bind(&Browser::SetUserActivity, browser))
  1130. .SetMethod("getCurrentActivityType",
  1131. base::Bind(&Browser::GetCurrentActivityType, browser))
  1132. .SetMethod("invalidateCurrentActivity",
  1133. base::Bind(&Browser::InvalidateCurrentActivity, browser))
  1134. .SetMethod("updateCurrentActivity",
  1135. base::Bind(&Browser::UpdateCurrentActivity, browser))
  1136. // TODO(juturu): Remove in 2.0, deprecate before then with warnings
  1137. .SetMethod("moveToApplicationsFolder", &App::MoveToApplicationsFolder)
  1138. .SetMethod("isInApplicationsFolder", &App::IsInApplicationsFolder)
  1139. #endif
  1140. #if defined(OS_MACOSX) || defined(OS_LINUX)
  1141. .SetMethod("setAboutPanelOptions",
  1142. base::Bind(&Browser::SetAboutPanelOptions, browser))
  1143. .SetMethod("showAboutPanel",
  1144. base::Bind(&Browser::ShowAboutPanel, browser))
  1145. #endif
  1146. #if defined(OS_WIN)
  1147. .SetMethod("setUserTasks", base::Bind(&Browser::SetUserTasks, browser))
  1148. .SetMethod("getJumpListSettings", &App::GetJumpListSettings)
  1149. .SetMethod("setJumpList", &App::SetJumpList)
  1150. #endif
  1151. #if defined(OS_LINUX)
  1152. .SetMethod("isUnityRunning",
  1153. base::Bind(&Browser::IsUnityRunning, browser))
  1154. #endif
  1155. .SetMethod("setAppPath", &App::SetAppPath)
  1156. .SetMethod("getAppPath", &App::GetAppPath)
  1157. .SetMethod("setPath", &App::SetPath)
  1158. .SetMethod("getPath", &App::GetPath)
  1159. .SetMethod("setDesktopName", &App::SetDesktopName)
  1160. .SetMethod("getLocale", &App::GetLocale)
  1161. .SetMethod("getLocaleCountryCode", &App::GetLocaleCountryCode)
  1162. #if defined(USE_NSS_CERTS)
  1163. .SetMethod("importCertificate", &App::ImportCertificate)
  1164. #endif
  1165. .SetMethod("hasSingleInstanceLock", &App::HasSingleInstanceLock)
  1166. .SetMethod("requestSingleInstanceLock", &App::RequestSingleInstanceLock)
  1167. .SetMethod("releaseSingleInstanceLock", &App::ReleaseSingleInstanceLock)
  1168. .SetMethod("relaunch", &App::Relaunch)
  1169. .SetMethod("isAccessibilitySupportEnabled",
  1170. &App::IsAccessibilitySupportEnabled)
  1171. .SetMethod("setAccessibilitySupportEnabled",
  1172. &App::SetAccessibilitySupportEnabled)
  1173. .SetMethod("disableHardwareAcceleration",
  1174. &App::DisableHardwareAcceleration)
  1175. .SetMethod("disableDomainBlockingFor3DAPIs",
  1176. &App::DisableDomainBlockingFor3DAPIs)
  1177. .SetMethod("getFileIcon", &App::GetFileIcon)
  1178. .SetMethod("getAppMetrics", &App::GetAppMetrics)
  1179. .SetMethod("getGPUFeatureStatus", &App::GetGPUFeatureStatus)
  1180. .SetMethod("getGPUInfo", &App::GetGPUInfo)
  1181. #if defined(MAS_BUILD)
  1182. .SetMethod("startAccessingSecurityScopedResource",
  1183. &App::StartAccessingSecurityScopedResource)
  1184. #endif
  1185. .SetMethod("enableSandbox", &App::EnableSandbox);
  1186. }
  1187. } // namespace api
  1188. } // namespace atom
  1189. namespace {
  1190. #if defined(OS_MACOSX)
  1191. int DockBounce(const std::string& type) {
  1192. int request_id = -1;
  1193. if (type == "critical")
  1194. request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL);
  1195. else if (type == "informational")
  1196. request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL);
  1197. return request_id;
  1198. }
  1199. void DockSetMenu(atom::api::Menu* menu) {
  1200. Browser::Get()->DockSetMenu(menu->model());
  1201. }
  1202. #endif
  1203. void Initialize(v8::Local<v8::Object> exports,
  1204. v8::Local<v8::Value> unused,
  1205. v8::Local<v8::Context> context,
  1206. void* priv) {
  1207. v8::Isolate* isolate = context->GetIsolate();
  1208. mate::Dictionary dict(isolate, exports);
  1209. dict.Set("App", atom::api::App::GetConstructor(isolate)
  1210. ->GetFunction(context)
  1211. .ToLocalChecked());
  1212. dict.Set("app", atom::api::App::Create(isolate));
  1213. #if defined(OS_MACOSX)
  1214. auto browser = base::Unretained(Browser::Get());
  1215. dict.SetMethod("dockBounce", &DockBounce);
  1216. dict.SetMethod("dockCancelBounce",
  1217. base::Bind(&Browser::DockCancelBounce, browser));
  1218. dict.SetMethod("dockDownloadFinished",
  1219. base::Bind(&Browser::DockDownloadFinished, browser));
  1220. dict.SetMethod("dockSetBadgeText",
  1221. base::Bind(&Browser::DockSetBadgeText, browser));
  1222. dict.SetMethod("dockGetBadgeText",
  1223. base::Bind(&Browser::DockGetBadgeText, browser));
  1224. dict.SetMethod("dockHide", base::Bind(&Browser::DockHide, browser));
  1225. dict.SetMethod("dockShow", base::Bind(&Browser::DockShow, browser));
  1226. dict.SetMethod("dockIsVisible", base::Bind(&Browser::DockIsVisible, browser));
  1227. dict.SetMethod("dockSetMenu", &DockSetMenu);
  1228. dict.SetMethod("dockSetIcon", base::Bind(&Browser::DockSetIcon, browser));
  1229. #endif
  1230. }
  1231. } // namespace
  1232. NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_app, Initialize)