atom_api_app.cc 44 KB

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