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