atom_api_app.cc 46 KB

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