electron_api_app.cc 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  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 "shell/browser/api/electron_api_app.h"
  5. #include <memory>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9. #include "base/command_line.h"
  10. #include "base/containers/fixed_flat_map.h"
  11. #include "base/containers/span.h"
  12. #include "base/environment.h"
  13. #include "base/files/file_path.h"
  14. #include "base/files/file_util.h"
  15. #include "base/functional/callback_helpers.h"
  16. #include "base/path_service.h"
  17. #include "base/system/sys_info.h"
  18. #include "base/values.h"
  19. #include "chrome/browser/browser_process.h"
  20. #include "chrome/browser/icon_manager.h"
  21. #include "chrome/common/chrome_features.h"
  22. #include "chrome/common/chrome_paths.h"
  23. #include "content/browser/gpu/compositor_util.h" // nogncheck
  24. #include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
  25. #include "content/public/browser/browser_accessibility_state.h"
  26. #include "content/public/browser/browser_child_process_host.h"
  27. #include "content/public/browser/child_process_data.h"
  28. #include "content/public/browser/client_certificate_delegate.h"
  29. #include "content/public/browser/gpu_data_manager.h"
  30. #include "content/public/browser/network_service_instance.h"
  31. #include "content/public/browser/render_frame_host.h"
  32. #include "content/public/common/content_switches.h"
  33. #include "crypto/crypto_buildflags.h"
  34. #include "media/audio/audio_manager.h"
  35. #include "net/dns/public/dns_over_https_config.h"
  36. #include "net/dns/public/dns_over_https_server_config.h"
  37. #include "net/dns/public/util.h"
  38. #include "net/ssl/client_cert_identity.h"
  39. #include "net/ssl/ssl_cert_request_info.h"
  40. #include "net/ssl/ssl_private_key.h"
  41. #include "sandbox/policy/switches.h"
  42. #include "services/network/network_service.h"
  43. #include "shell/app/command_line_args.h"
  44. #include "shell/browser/api/electron_api_menu.h"
  45. #include "shell/browser/api/electron_api_session.h"
  46. #include "shell/browser/api/electron_api_utility_process.h"
  47. #include "shell/browser/api/electron_api_web_contents.h"
  48. #include "shell/browser/api/gpuinfo_manager.h"
  49. #include "shell/browser/browser_process_impl.h"
  50. #include "shell/browser/electron_browser_context.h"
  51. #include "shell/browser/electron_browser_main_parts.h"
  52. #include "shell/browser/javascript_environment.h"
  53. #include "shell/browser/login_handler.h"
  54. #include "shell/browser/relauncher.h"
  55. #include "shell/common/application_info.h"
  56. #include "shell/common/electron_command_line.h"
  57. #include "shell/common/electron_paths.h"
  58. #include "shell/common/gin_converters/base_converter.h"
  59. #include "shell/common/gin_converters/blink_converter.h"
  60. #include "shell/common/gin_converters/callback_converter.h"
  61. #include "shell/common/gin_converters/file_path_converter.h"
  62. #include "shell/common/gin_converters/gurl_converter.h"
  63. #include "shell/common/gin_converters/image_converter.h"
  64. #include "shell/common/gin_converters/net_converter.h"
  65. #include "shell/common/gin_converters/value_converter.h"
  66. #include "shell/common/gin_helper/dictionary.h"
  67. #include "shell/common/gin_helper/object_template_builder.h"
  68. #include "shell/common/language_util.h"
  69. #include "shell/common/node_includes.h"
  70. #include "shell/common/options_switches.h"
  71. #include "shell/common/platform_util.h"
  72. #include "shell/common/thread_restrictions.h"
  73. #include "shell/common/v8_value_serializer.h"
  74. #include "third_party/abseil-cpp/absl/types/optional.h"
  75. #include "ui/gfx/image/image.h"
  76. #if BUILDFLAG(IS_WIN)
  77. #include "base/strings/utf_string_conversions.h"
  78. #include "shell/browser/ui/win/jump_list.h"
  79. #endif
  80. #if BUILDFLAG(IS_MAC)
  81. #include <CoreFoundation/CoreFoundation.h>
  82. #include "shell/browser/ui/cocoa/electron_bundle_mover.h"
  83. #endif
  84. using electron::Browser;
  85. namespace gin {
  86. #if BUILDFLAG(IS_WIN)
  87. template <>
  88. struct Converter<electron::ProcessIntegrityLevel> {
  89. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  90. electron::ProcessIntegrityLevel value) {
  91. switch (value) {
  92. case electron::ProcessIntegrityLevel::kUntrusted:
  93. return StringToV8(isolate, "untrusted");
  94. case electron::ProcessIntegrityLevel::kLow:
  95. return StringToV8(isolate, "low");
  96. case electron::ProcessIntegrityLevel::kMedium:
  97. return StringToV8(isolate, "medium");
  98. case electron::ProcessIntegrityLevel::kHigh:
  99. return StringToV8(isolate, "high");
  100. default:
  101. return StringToV8(isolate, "unknown");
  102. }
  103. }
  104. };
  105. template <>
  106. struct Converter<Browser::UserTask> {
  107. static bool FromV8(v8::Isolate* isolate,
  108. v8::Local<v8::Value> val,
  109. Browser::UserTask* out) {
  110. gin_helper::Dictionary dict;
  111. if (!ConvertFromV8(isolate, val, &dict))
  112. return false;
  113. if (!dict.Get("program", &(out->program)) ||
  114. !dict.Get("title", &(out->title)))
  115. return false;
  116. if (dict.Get("iconPath", &(out->icon_path)) &&
  117. !dict.Get("iconIndex", &(out->icon_index)))
  118. return false;
  119. dict.Get("arguments", &(out->arguments));
  120. dict.Get("description", &(out->description));
  121. dict.Get("workingDirectory", &(out->working_dir));
  122. return true;
  123. }
  124. };
  125. using electron::JumpListCategory;
  126. using electron::JumpListItem;
  127. using electron::JumpListResult;
  128. template <>
  129. struct Converter<JumpListItem::Type> {
  130. static bool FromV8(v8::Isolate* isolate,
  131. v8::Local<v8::Value> val,
  132. JumpListItem::Type* out) {
  133. return FromV8WithLookup(isolate, val, Lookup, out);
  134. }
  135. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  136. JumpListItem::Type val) {
  137. for (const auto& [name, item_val] : Lookup)
  138. if (item_val == val)
  139. return gin::ConvertToV8(isolate, name);
  140. return gin::ConvertToV8(isolate, "");
  141. }
  142. private:
  143. static constexpr auto Lookup =
  144. base::MakeFixedFlatMapSorted<base::StringPiece, JumpListItem::Type>({
  145. {"file", JumpListItem::Type::kFile},
  146. {"separator", JumpListItem::Type::kSeparator},
  147. {"task", JumpListItem::Type::kTask},
  148. });
  149. };
  150. template <>
  151. struct Converter<JumpListItem> {
  152. static bool FromV8(v8::Isolate* isolate,
  153. v8::Local<v8::Value> val,
  154. JumpListItem* out) {
  155. gin_helper::Dictionary dict;
  156. if (!ConvertFromV8(isolate, val, &dict))
  157. return false;
  158. if (!dict.Get("type", &(out->type)))
  159. return false;
  160. switch (out->type) {
  161. case JumpListItem::Type::kTask:
  162. if (!dict.Get("program", &(out->path)) ||
  163. !dict.Get("title", &(out->title)))
  164. return false;
  165. if (dict.Get("iconPath", &(out->icon_path)) &&
  166. !dict.Get("iconIndex", &(out->icon_index)))
  167. return false;
  168. dict.Get("args", &(out->arguments));
  169. dict.Get("description", &(out->description));
  170. dict.Get("workingDirectory", &(out->working_dir));
  171. return true;
  172. case JumpListItem::Type::kSeparator:
  173. return true;
  174. case JumpListItem::Type::kFile:
  175. return dict.Get("path", &(out->path));
  176. }
  177. assert(false);
  178. return false;
  179. }
  180. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  181. const JumpListItem& val) {
  182. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  183. dict.Set("type", val.type);
  184. switch (val.type) {
  185. case JumpListItem::Type::kTask:
  186. dict.Set("program", val.path);
  187. dict.Set("args", val.arguments);
  188. dict.Set("title", val.title);
  189. dict.Set("iconPath", val.icon_path);
  190. dict.Set("iconIndex", val.icon_index);
  191. dict.Set("description", val.description);
  192. dict.Set("workingDirectory", val.working_dir);
  193. break;
  194. case JumpListItem::Type::kSeparator:
  195. break;
  196. case JumpListItem::Type::kFile:
  197. dict.Set("path", val.path);
  198. break;
  199. }
  200. return dict.GetHandle();
  201. }
  202. };
  203. template <>
  204. struct Converter<JumpListCategory::Type> {
  205. static bool FromV8(v8::Isolate* isolate,
  206. v8::Local<v8::Value> val,
  207. JumpListCategory::Type* out) {
  208. return FromV8WithLookup(isolate, val, Lookup, out);
  209. }
  210. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  211. JumpListCategory::Type val) {
  212. for (const auto& [name, type_val] : Lookup)
  213. if (type_val == val)
  214. return gin::ConvertToV8(isolate, name);
  215. return gin::ConvertToV8(isolate, "");
  216. }
  217. private:
  218. static constexpr auto Lookup =
  219. base::MakeFixedFlatMapSorted<base::StringPiece, JumpListCategory::Type>({
  220. {"custom", JumpListCategory::Type::kCustom},
  221. {"frequent", JumpListCategory::Type::kFrequent},
  222. {"recent", JumpListCategory::Type::kRecent},
  223. {"tasks", JumpListCategory::Type::kTasks},
  224. });
  225. };
  226. template <>
  227. struct Converter<JumpListCategory> {
  228. static bool FromV8(v8::Isolate* isolate,
  229. v8::Local<v8::Value> val,
  230. JumpListCategory* out) {
  231. gin_helper::Dictionary dict;
  232. if (!ConvertFromV8(isolate, val, &dict))
  233. return false;
  234. if (dict.Get("name", &(out->name)) && out->name.empty())
  235. return false;
  236. if (!dict.Get("type", &(out->type))) {
  237. if (out->name.empty())
  238. out->type = JumpListCategory::Type::kTasks;
  239. else
  240. out->type = JumpListCategory::Type::kCustom;
  241. }
  242. if ((out->type == JumpListCategory::Type::kTasks) ||
  243. (out->type == JumpListCategory::Type::kCustom)) {
  244. if (!dict.Get("items", &(out->items)))
  245. return false;
  246. }
  247. return true;
  248. }
  249. };
  250. // static
  251. template <>
  252. struct Converter<JumpListResult> {
  253. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
  254. std::string result_code;
  255. switch (val) {
  256. case JumpListResult::kSuccess:
  257. result_code = "ok";
  258. break;
  259. case JumpListResult::kArgumentError:
  260. result_code = "argumentError";
  261. break;
  262. case JumpListResult::kGenericError:
  263. result_code = "error";
  264. break;
  265. case JumpListResult::kCustomCategorySeparatorError:
  266. result_code = "invalidSeparatorError";
  267. break;
  268. case JumpListResult::kMissingFileTypeRegistrationError:
  269. result_code = "fileTypeRegistrationError";
  270. break;
  271. case JumpListResult::kCustomCategoryAccessDeniedError:
  272. result_code = "customCategoryAccessDeniedError";
  273. break;
  274. }
  275. return ConvertToV8(isolate, result_code);
  276. }
  277. };
  278. #endif
  279. #if BUILDFLAG(IS_WIN)
  280. template <>
  281. struct Converter<Browser::LaunchItem> {
  282. static bool FromV8(v8::Isolate* isolate,
  283. v8::Local<v8::Value> val,
  284. Browser::LaunchItem* out) {
  285. gin_helper::Dictionary dict;
  286. if (!ConvertFromV8(isolate, val, &dict))
  287. return false;
  288. dict.Get("name", &(out->name));
  289. dict.Get("path", &(out->path));
  290. dict.Get("args", &(out->args));
  291. dict.Get("scope", &(out->scope));
  292. dict.Get("enabled", &(out->enabled));
  293. return true;
  294. }
  295. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  296. Browser::LaunchItem val) {
  297. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  298. dict.Set("name", val.name);
  299. dict.Set("path", val.path);
  300. dict.Set("args", val.args);
  301. dict.Set("scope", val.scope);
  302. dict.Set("enabled", val.enabled);
  303. return dict.GetHandle();
  304. }
  305. };
  306. #endif
  307. template <>
  308. struct Converter<Browser::LoginItemSettings> {
  309. static bool FromV8(v8::Isolate* isolate,
  310. v8::Local<v8::Value> val,
  311. Browser::LoginItemSettings* out) {
  312. gin_helper::Dictionary dict;
  313. if (!ConvertFromV8(isolate, val, &dict))
  314. return false;
  315. dict.Get("openAtLogin", &(out->open_at_login));
  316. dict.Get("openAsHidden", &(out->open_as_hidden));
  317. dict.Get("path", &(out->path));
  318. dict.Get("args", &(out->args));
  319. #if BUILDFLAG(IS_WIN)
  320. dict.Get("enabled", &(out->enabled));
  321. dict.Get("name", &(out->name));
  322. #endif
  323. return true;
  324. }
  325. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  326. Browser::LoginItemSettings val) {
  327. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  328. dict.Set("openAtLogin", val.open_at_login);
  329. dict.Set("openAsHidden", val.open_as_hidden);
  330. dict.Set("restoreState", val.restore_state);
  331. dict.Set("wasOpenedAtLogin", val.opened_at_login);
  332. dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
  333. #if BUILDFLAG(IS_WIN)
  334. dict.Set("launchItems", val.launch_items);
  335. dict.Set("executableWillLaunchAtLogin",
  336. val.executable_will_launch_at_login);
  337. #endif
  338. return dict.GetHandle();
  339. }
  340. };
  341. template <>
  342. struct Converter<content::CertificateRequestResultType> {
  343. static bool FromV8(v8::Isolate* isolate,
  344. v8::Local<v8::Value> val,
  345. content::CertificateRequestResultType* out) {
  346. bool b;
  347. if (!ConvertFromV8(isolate, val, &b))
  348. return false;
  349. *out = b ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE
  350. : content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
  351. return true;
  352. }
  353. };
  354. template <>
  355. struct Converter<net::SecureDnsMode> {
  356. static bool FromV8(v8::Isolate* isolate,
  357. v8::Local<v8::Value> val,
  358. net::SecureDnsMode* out) {
  359. static constexpr auto Lookup =
  360. base::MakeFixedFlatMapSorted<base::StringPiece, net::SecureDnsMode>({
  361. {"automatic", net::SecureDnsMode::kAutomatic},
  362. {"off", net::SecureDnsMode::kOff},
  363. {"secure", net::SecureDnsMode::kSecure},
  364. });
  365. return FromV8WithLookup(isolate, val, Lookup, out);
  366. }
  367. };
  368. } // namespace gin
  369. namespace electron::api {
  370. gin::WrapperInfo App::kWrapperInfo = {gin::kEmbedderNativeGin};
  371. namespace {
  372. IconLoader::IconSize GetIconSizeByString(const std::string& size) {
  373. if (size == "small") {
  374. return IconLoader::IconSize::SMALL;
  375. } else if (size == "large") {
  376. return IconLoader::IconSize::LARGE;
  377. }
  378. return IconLoader::IconSize::NORMAL;
  379. }
  380. // Return the path constant from string.
  381. constexpr int GetPathConstant(base::StringPiece name) {
  382. // clang-format off
  383. constexpr auto Lookup = base::MakeFixedFlatMapSorted<base::StringPiece, int>({
  384. {"appData", DIR_APP_DATA},
  385. #if BUILDFLAG(IS_POSIX)
  386. {"cache", base::DIR_CACHE},
  387. #else
  388. {"cache", base::DIR_ROAMING_APP_DATA},
  389. #endif
  390. {"crashDumps", DIR_CRASH_DUMPS},
  391. {"desktop", base::DIR_USER_DESKTOP},
  392. {"documents", chrome::DIR_USER_DOCUMENTS},
  393. {"downloads", chrome::DIR_DEFAULT_DOWNLOADS},
  394. {"exe", base::FILE_EXE},
  395. {"home", base::DIR_HOME},
  396. {"logs", DIR_APP_LOGS},
  397. {"module", base::FILE_MODULE},
  398. {"music", chrome::DIR_USER_MUSIC},
  399. {"pictures", chrome::DIR_USER_PICTURES},
  400. #if BUILDFLAG(IS_WIN)
  401. {"recent", electron::DIR_RECENT},
  402. #endif
  403. {"sessionData", DIR_SESSION_DATA},
  404. {"temp", base::DIR_TEMP},
  405. {"userCache", DIR_USER_CACHE},
  406. {"userData", chrome::DIR_USER_DATA},
  407. {"userDesktop", base::DIR_USER_DESKTOP},
  408. {"videos", chrome::DIR_USER_VIDEOS},
  409. });
  410. // clang-format on
  411. const auto* iter = Lookup.find(name);
  412. return iter != Lookup.end() ? iter->second : -1;
  413. }
  414. bool NotificationCallbackWrapper(
  415. const base::RepeatingCallback<
  416. void(const base::CommandLine& command_line,
  417. const base::FilePath& current_directory,
  418. const std::vector<const uint8_t> additional_data)>& callback,
  419. const base::CommandLine& cmd,
  420. const base::FilePath& cwd,
  421. const std::vector<const uint8_t> additional_data) {
  422. // Make sure the callback is called after app gets ready.
  423. if (Browser::Get()->is_ready()) {
  424. callback.Run(cmd, cwd, std::move(additional_data));
  425. } else {
  426. scoped_refptr<base::SingleThreadTaskRunner> task_runner(
  427. base::SingleThreadTaskRunner::GetCurrentDefault());
  428. // Make a copy of the span so that the data isn't lost.
  429. task_runner->PostTask(FROM_HERE,
  430. base::BindOnce(base::IgnoreResult(callback), cmd, cwd,
  431. std::move(additional_data)));
  432. }
  433. // ProcessSingleton needs to know whether current process is quiting.
  434. return !Browser::Get()->is_shutting_down();
  435. }
  436. void GotPrivateKey(std::shared_ptr<content::ClientCertificateDelegate> delegate,
  437. scoped_refptr<net::X509Certificate> cert,
  438. scoped_refptr<net::SSLPrivateKey> private_key) {
  439. delegate->ContinueWithCertificate(cert, private_key);
  440. }
  441. void OnClientCertificateSelected(
  442. v8::Isolate* isolate,
  443. std::shared_ptr<content::ClientCertificateDelegate> delegate,
  444. std::shared_ptr<net::ClientCertIdentityList> identities,
  445. gin::Arguments* args) {
  446. if (args->Length() == 2) {
  447. delegate->ContinueWithCertificate(nullptr, nullptr);
  448. return;
  449. }
  450. v8::Local<v8::Value> val;
  451. args->GetNext(&val);
  452. if (val->IsNull()) {
  453. delegate->ContinueWithCertificate(nullptr, nullptr);
  454. return;
  455. }
  456. gin_helper::Dictionary cert_data;
  457. if (!gin::ConvertFromV8(isolate, val, &cert_data)) {
  458. gin_helper::ErrorThrower(isolate).ThrowError(
  459. "Must pass valid certificate object.");
  460. return;
  461. }
  462. std::string data;
  463. if (!cert_data.Get("data", &data))
  464. return;
  465. auto certs = net::X509Certificate::CreateCertificateListFromBytes(
  466. base::as_bytes(base::make_span(data.c_str(), data.size())),
  467. net::X509Certificate::FORMAT_AUTO);
  468. if (!certs.empty()) {
  469. scoped_refptr<net::X509Certificate> cert(certs[0].get());
  470. for (auto& identity : *identities) {
  471. scoped_refptr<net::X509Certificate> identity_cert =
  472. identity->certificate();
  473. // Since |cert| was recreated from |data|, it won't include any
  474. // intermediates. That's fine for checking equality, but once a match is
  475. // found then |identity_cert| should be used since it will include the
  476. // intermediates which would otherwise be lost.
  477. if (cert->EqualsExcludingChain(identity_cert.get())) {
  478. net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
  479. std::move(identity), base::BindRepeating(&GotPrivateKey, delegate,
  480. std::move(identity_cert)));
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. #if BUILDFLAG(USE_NSS_CERTS)
  487. int ImportIntoCertStore(CertificateManagerModel* model, base::Value options) {
  488. std::string file_data, cert_path;
  489. std::u16string password;
  490. net::ScopedCERTCertificateList imported_certs;
  491. int rv = -1;
  492. if (const base::Value::Dict* dict = options.GetIfDict(); dict != nullptr) {
  493. if (const std::string* str = dict->FindString("certificate"); str)
  494. cert_path = *str;
  495. if (const std::string* str = dict->FindString("password"); str)
  496. password = base::UTF8ToUTF16(*str);
  497. }
  498. if (!cert_path.empty()) {
  499. if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
  500. auto module = model->cert_db()->GetPrivateSlot();
  501. rv = model->ImportFromPKCS12(module.get(), file_data, password, true,
  502. &imported_certs);
  503. if (imported_certs.size() > 1) {
  504. auto it = imported_certs.begin();
  505. ++it; // skip first which would be the client certificate.
  506. for (; it != imported_certs.end(); ++it)
  507. rv &= model->SetCertTrust(it->get(), net::CA_CERT,
  508. net::NSSCertDatabase::TRUSTED_SSL);
  509. }
  510. }
  511. }
  512. return rv;
  513. }
  514. #endif
  515. void OnIconDataAvailable(gin_helper::Promise<gfx::Image> promise,
  516. gfx::Image icon) {
  517. if (!icon.IsEmpty()) {
  518. promise.Resolve(icon);
  519. } else {
  520. promise.RejectWithErrorMessage("Failed to get file icon.");
  521. }
  522. }
  523. } // namespace
  524. App::App() {
  525. static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
  526. ->set_delegate(this);
  527. Browser::Get()->AddObserver(this);
  528. auto pid = content::ChildProcessHost::kInvalidUniqueID;
  529. auto process_metric = std::make_unique<electron::ProcessMetric>(
  530. content::PROCESS_TYPE_BROWSER, base::GetCurrentProcessHandle(),
  531. base::ProcessMetrics::CreateCurrentProcessMetrics());
  532. app_metrics_[pid] = std::move(process_metric);
  533. }
  534. App::~App() {
  535. static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
  536. ->set_delegate(nullptr);
  537. Browser::Get()->RemoveObserver(this);
  538. content::GpuDataManager::GetInstance()->RemoveObserver(this);
  539. content::BrowserChildProcessObserver::Remove(this);
  540. }
  541. void App::OnBeforeQuit(bool* prevent_default) {
  542. if (Emit("before-quit")) {
  543. *prevent_default = true;
  544. }
  545. }
  546. void App::OnWillQuit(bool* prevent_default) {
  547. if (Emit("will-quit")) {
  548. *prevent_default = true;
  549. }
  550. }
  551. void App::OnWindowAllClosed() {
  552. Emit("window-all-closed");
  553. }
  554. void App::OnQuit() {
  555. const int exitCode = ElectronBrowserMainParts::Get()->GetExitCode();
  556. Emit("quit", exitCode);
  557. if (process_singleton_) {
  558. process_singleton_->Cleanup();
  559. process_singleton_.reset();
  560. }
  561. }
  562. void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
  563. if (Emit("open-file", file_path)) {
  564. *prevent_default = true;
  565. }
  566. }
  567. void App::OnOpenURL(const std::string& url) {
  568. Emit("open-url", url);
  569. }
  570. void App::OnActivate(bool has_visible_windows) {
  571. Emit("activate", has_visible_windows);
  572. }
  573. void App::OnWillFinishLaunching() {
  574. Emit("will-finish-launching");
  575. }
  576. void App::OnFinishLaunching(base::Value::Dict launch_info) {
  577. #if BUILDFLAG(IS_LINUX)
  578. // Set the application name for audio streams shown in external
  579. // applications. Only affects pulseaudio currently.
  580. media::AudioManager::SetGlobalAppName(Browser::Get()->GetName());
  581. #endif
  582. Emit("ready", base::Value(std::move(launch_info)));
  583. }
  584. void App::OnPreMainMessageLoopRun() {
  585. content::BrowserChildProcessObserver::Add(this);
  586. if (process_singleton_ && watch_singleton_socket_on_ready_) {
  587. process_singleton_->StartWatching();
  588. watch_singleton_socket_on_ready_ = false;
  589. }
  590. }
  591. void App::OnPreCreateThreads() {
  592. DCHECK(!content::GpuDataManager::Initialized());
  593. content::GpuDataManager* manager = content::GpuDataManager::GetInstance();
  594. manager->AddObserver(this);
  595. if (disable_hw_acceleration_) {
  596. manager->DisableHardwareAcceleration();
  597. }
  598. if (disable_domain_blocking_for_3DAPIs_) {
  599. content::GpuDataManagerImpl::GetInstance()
  600. ->DisableDomainBlockingFor3DAPIsForTesting();
  601. }
  602. }
  603. void App::OnAccessibilitySupportChanged() {
  604. Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
  605. }
  606. #if BUILDFLAG(IS_MAC)
  607. void App::OnWillContinueUserActivity(bool* prevent_default,
  608. const std::string& type) {
  609. if (Emit("will-continue-activity", type)) {
  610. *prevent_default = true;
  611. }
  612. }
  613. void App::OnDidFailToContinueUserActivity(const std::string& type,
  614. const std::string& error) {
  615. Emit("continue-activity-error", type, error);
  616. }
  617. void App::OnContinueUserActivity(bool* prevent_default,
  618. const std::string& type,
  619. base::Value::Dict user_info,
  620. base::Value::Dict details) {
  621. if (Emit("continue-activity", type, base::Value(std::move(user_info)),
  622. base::Value(std::move(details)))) {
  623. *prevent_default = true;
  624. }
  625. }
  626. void App::OnUserActivityWasContinued(const std::string& type,
  627. base::Value::Dict user_info) {
  628. Emit("activity-was-continued", type, base::Value(std::move(user_info)));
  629. }
  630. void App::OnUpdateUserActivityState(bool* prevent_default,
  631. const std::string& type,
  632. base::Value::Dict user_info) {
  633. if (Emit("update-activity-state", type, base::Value(std::move(user_info)))) {
  634. *prevent_default = true;
  635. }
  636. }
  637. void App::OnNewWindowForTab() {
  638. Emit("new-window-for-tab");
  639. }
  640. void App::OnDidBecomeActive() {
  641. Emit("did-become-active");
  642. }
  643. void App::OnDidResignActive() {
  644. Emit("did-resign-active");
  645. }
  646. #endif
  647. bool App::CanCreateWindow(
  648. content::RenderFrameHost* opener,
  649. const GURL& opener_url,
  650. const GURL& opener_top_level_frame_url,
  651. const url::Origin& source_origin,
  652. content::mojom::WindowContainerType container_type,
  653. const GURL& target_url,
  654. const content::Referrer& referrer,
  655. const std::string& frame_name,
  656. WindowOpenDisposition disposition,
  657. const blink::mojom::WindowFeatures& features,
  658. const std::string& raw_features,
  659. const scoped_refptr<network::ResourceRequestBody>& body,
  660. bool user_gesture,
  661. bool opener_suppressed,
  662. bool* no_javascript_access) {
  663. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  664. v8::HandleScope handle_scope(isolate);
  665. content::WebContents* web_contents =
  666. content::WebContents::FromRenderFrameHost(opener);
  667. if (web_contents) {
  668. WebContents* api_web_contents = WebContents::From(web_contents);
  669. // No need to emit any event if the WebContents is not available in JS.
  670. if (api_web_contents) {
  671. api_web_contents->OnCreateWindow(target_url, referrer, frame_name,
  672. disposition, raw_features, body);
  673. }
  674. }
  675. return false;
  676. }
  677. void App::AllowCertificateError(
  678. content::WebContents* web_contents,
  679. int cert_error,
  680. const net::SSLInfo& ssl_info,
  681. const GURL& request_url,
  682. bool is_main_frame_request,
  683. bool strict_enforcement,
  684. base::OnceCallback<void(content::CertificateRequestResultType)> callback) {
  685. auto adapted_callback = base::AdaptCallbackForRepeating(std::move(callback));
  686. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  687. v8::HandleScope handle_scope(isolate);
  688. bool prevent_default = Emit(
  689. "certificate-error", WebContents::FromOrCreate(isolate, web_contents),
  690. request_url, net::ErrorToString(cert_error), ssl_info.cert,
  691. adapted_callback, is_main_frame_request);
  692. // Deny the certificate by default.
  693. if (!prevent_default)
  694. adapted_callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
  695. }
  696. base::OnceClosure App::SelectClientCertificate(
  697. content::BrowserContext* browser_context,
  698. content::WebContents* web_contents,
  699. net::SSLCertRequestInfo* cert_request_info,
  700. net::ClientCertIdentityList identities,
  701. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  702. std::shared_ptr<content::ClientCertificateDelegate> shared_delegate(
  703. delegate.release());
  704. // Convert the ClientCertIdentityList to a CertificateList
  705. // to avoid changes in the API.
  706. auto client_certs = net::CertificateList();
  707. for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities)
  708. client_certs.emplace_back(identity->certificate());
  709. auto shared_identities =
  710. std::make_shared<net::ClientCertIdentityList>(std::move(identities));
  711. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  712. v8::HandleScope handle_scope(isolate);
  713. bool prevent_default =
  714. Emit("select-client-certificate",
  715. WebContents::FromOrCreate(isolate, web_contents),
  716. cert_request_info->host_and_port.ToString(), std::move(client_certs),
  717. base::BindOnce(&OnClientCertificateSelected, isolate,
  718. shared_delegate, shared_identities));
  719. // Default to first certificate from the platform store.
  720. if (!prevent_default) {
  721. scoped_refptr<net::X509Certificate> cert =
  722. (*shared_identities)[0]->certificate();
  723. net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
  724. std::move((*shared_identities)[0]),
  725. base::BindRepeating(&GotPrivateKey, shared_delegate, std::move(cert)));
  726. }
  727. return base::OnceClosure();
  728. }
  729. void App::OnGpuInfoUpdate() {
  730. Emit("gpu-info-update");
  731. }
  732. void App::OnGpuProcessCrashed() {
  733. Emit("gpu-process-crashed", true);
  734. }
  735. void App::BrowserChildProcessLaunchedAndConnected(
  736. const content::ChildProcessData& data) {
  737. ChildProcessLaunched(data.process_type, data.id, data.GetProcess().Handle(),
  738. data.metrics_name, base::UTF16ToUTF8(data.name));
  739. }
  740. void App::BrowserChildProcessHostDisconnected(
  741. const content::ChildProcessData& data) {
  742. ChildProcessDisconnected(data.id);
  743. }
  744. void App::BrowserChildProcessCrashed(
  745. const content::ChildProcessData& data,
  746. const content::ChildProcessTerminationInfo& info) {
  747. ChildProcessDisconnected(data.id);
  748. BrowserChildProcessCrashedOrKilled(data, info);
  749. }
  750. void App::BrowserChildProcessKilled(
  751. const content::ChildProcessData& data,
  752. const content::ChildProcessTerminationInfo& info) {
  753. ChildProcessDisconnected(data.id);
  754. BrowserChildProcessCrashedOrKilled(data, info);
  755. }
  756. void App::BrowserChildProcessCrashedOrKilled(
  757. const content::ChildProcessData& data,
  758. const content::ChildProcessTerminationInfo& info) {
  759. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  760. v8::HandleScope handle_scope(isolate);
  761. auto details = gin_helper::Dictionary::CreateEmpty(isolate);
  762. details.Set("type", content::GetProcessTypeNameInEnglish(data.process_type));
  763. details.Set("reason", info.status);
  764. details.Set("exitCode", info.exit_code);
  765. details.Set("serviceName", data.metrics_name);
  766. if (!data.name.empty()) {
  767. details.Set("name", data.name);
  768. }
  769. if (data.process_type == content::PROCESS_TYPE_UTILITY) {
  770. base::ProcessId pid = data.GetProcess().Pid();
  771. auto utility_process_wrapper = UtilityProcessWrapper::FromProcessId(pid);
  772. if (utility_process_wrapper)
  773. utility_process_wrapper->Shutdown(info.exit_code);
  774. }
  775. Emit("child-process-gone", details);
  776. }
  777. void App::RenderProcessReady(content::RenderProcessHost* host) {
  778. ChildProcessLaunched(content::PROCESS_TYPE_RENDERER, host->GetID(),
  779. host->GetProcess().Handle());
  780. }
  781. void App::RenderProcessExited(content::RenderProcessHost* host) {
  782. ChildProcessDisconnected(host->GetID());
  783. }
  784. void App::ChildProcessLaunched(int process_type,
  785. int pid,
  786. base::ProcessHandle handle,
  787. const std::string& service_name,
  788. const std::string& name) {
  789. #if BUILDFLAG(IS_MAC)
  790. auto metrics = base::ProcessMetrics::CreateProcessMetrics(
  791. handle, content::BrowserChildProcessHost::GetPortProvider());
  792. #else
  793. auto metrics = base::ProcessMetrics::CreateProcessMetrics(handle);
  794. #endif
  795. app_metrics_[pid] = std::make_unique<electron::ProcessMetric>(
  796. process_type, handle, std::move(metrics), service_name, name);
  797. }
  798. void App::ChildProcessDisconnected(int pid) {
  799. app_metrics_.erase(pid);
  800. }
  801. base::FilePath App::GetAppPath() const {
  802. return app_path_;
  803. }
  804. void App::SetAppPath(const base::FilePath& app_path) {
  805. app_path_ = app_path;
  806. }
  807. #if !BUILDFLAG(IS_MAC)
  808. void App::SetAppLogsPath(gin_helper::ErrorThrower thrower,
  809. absl::optional<base::FilePath> custom_path) {
  810. if (custom_path.has_value()) {
  811. if (!custom_path->IsAbsolute()) {
  812. thrower.ThrowError("Path must be absolute");
  813. return;
  814. }
  815. {
  816. ScopedAllowBlockingForElectron allow_blocking;
  817. base::PathService::Override(DIR_APP_LOGS, custom_path.value());
  818. }
  819. } else {
  820. base::FilePath path;
  821. if (base::PathService::Get(chrome::DIR_USER_DATA, &path)) {
  822. path = path.Append(base::FilePath::FromUTF8Unsafe("logs"));
  823. {
  824. ScopedAllowBlockingForElectron allow_blocking;
  825. base::PathService::Override(DIR_APP_LOGS, path);
  826. }
  827. }
  828. }
  829. }
  830. #endif
  831. // static
  832. bool App::IsPackaged() {
  833. auto env = base::Environment::Create();
  834. if (env->HasVar("ELECTRON_FORCE_IS_PACKAGED"))
  835. return true;
  836. base::FilePath exe_path;
  837. base::PathService::Get(base::FILE_EXE, &exe_path);
  838. base::FilePath::StringType base_name =
  839. base::ToLowerASCII(exe_path.BaseName().value());
  840. #if BUILDFLAG(IS_WIN)
  841. return base_name != FILE_PATH_LITERAL("electron.exe");
  842. #else
  843. return base_name != FILE_PATH_LITERAL("electron");
  844. #endif
  845. }
  846. base::FilePath App::GetPath(gin_helper::ErrorThrower thrower,
  847. const std::string& name) {
  848. base::FilePath path;
  849. int key = GetPathConstant(name);
  850. if (key < 0 || !base::PathService::Get(key, &path))
  851. thrower.ThrowError("Failed to get '" + name + "' path");
  852. return path;
  853. }
  854. void App::SetPath(gin_helper::ErrorThrower thrower,
  855. const std::string& name,
  856. const base::FilePath& path) {
  857. if (!path.IsAbsolute()) {
  858. thrower.ThrowError("Path must be absolute");
  859. return;
  860. }
  861. int key = GetPathConstant(name);
  862. if (key < 0 || !base::PathService::OverrideAndCreateIfNeeded(
  863. key, path, /* is_absolute = */ true, /* create = */ false))
  864. thrower.ThrowError("Failed to set path");
  865. }
  866. void App::SetDesktopName(const std::string& desktop_name) {
  867. #if BUILDFLAG(IS_LINUX)
  868. auto env = base::Environment::Create();
  869. env->SetVar("CHROME_DESKTOP", desktop_name);
  870. #endif
  871. }
  872. std::string App::GetLocale() {
  873. return g_browser_process->GetApplicationLocale();
  874. }
  875. std::string App::GetSystemLocale(gin_helper::ErrorThrower thrower) const {
  876. if (!Browser::Get()->is_ready()) {
  877. thrower.ThrowError(
  878. "app.getSystemLocale() can only be called "
  879. "after app is ready");
  880. return std::string();
  881. }
  882. return static_cast<BrowserProcessImpl*>(g_browser_process)->GetSystemLocale();
  883. }
  884. std::string App::GetLocaleCountryCode() {
  885. std::string region;
  886. #if BUILDFLAG(IS_WIN)
  887. WCHAR locale_name[LOCALE_NAME_MAX_LENGTH] = {0};
  888. if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
  889. (LPWSTR)&locale_name,
  890. sizeof(locale_name) / sizeof(WCHAR)) ||
  891. GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SISO3166CTRYNAME,
  892. (LPWSTR)&locale_name,
  893. sizeof(locale_name) / sizeof(WCHAR))) {
  894. base::WideToUTF8(locale_name, wcslen(locale_name), &region);
  895. }
  896. #elif BUILDFLAG(IS_MAC)
  897. CFLocaleRef locale = CFLocaleCopyCurrent();
  898. CFStringRef value = CFStringRef(
  899. static_cast<CFTypeRef>(CFLocaleGetValue(locale, kCFLocaleCountryCode)));
  900. if (value != nil) {
  901. char temporaryCString[3];
  902. const CFIndex kCStringSize = sizeof(temporaryCString);
  903. if (CFStringGetCString(value, temporaryCString, kCStringSize,
  904. kCFStringEncodingUTF8)) {
  905. region = temporaryCString;
  906. }
  907. }
  908. #else
  909. const char* locale_ptr = setlocale(LC_TIME, nullptr);
  910. if (!locale_ptr)
  911. locale_ptr = setlocale(LC_NUMERIC, nullptr);
  912. if (locale_ptr) {
  913. std::string locale = locale_ptr;
  914. std::string::size_type rpos = locale.find('.');
  915. if (rpos != std::string::npos)
  916. locale = locale.substr(0, rpos);
  917. rpos = locale.find('_');
  918. if (rpos != std::string::npos && rpos + 1 < locale.size())
  919. region = locale.substr(rpos + 1);
  920. }
  921. #endif
  922. return region.size() == 2 ? region : std::string();
  923. }
  924. void App::OnSecondInstance(const base::CommandLine& cmd,
  925. const base::FilePath& cwd,
  926. const std::vector<const uint8_t> additional_data) {
  927. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  928. v8::HandleScope handle_scope(isolate);
  929. v8::Local<v8::Value> data_value =
  930. DeserializeV8Value(isolate, std::move(additional_data));
  931. Emit("second-instance", cmd.argv(), cwd, data_value);
  932. }
  933. bool App::HasSingleInstanceLock() const {
  934. if (process_singleton_)
  935. return true;
  936. return false;
  937. }
  938. bool App::RequestSingleInstanceLock(gin::Arguments* args) {
  939. if (HasSingleInstanceLock())
  940. return true;
  941. std::string program_name = electron::Browser::Get()->GetName();
  942. base::FilePath user_dir;
  943. base::PathService::Get(chrome::DIR_USER_DATA, &user_dir);
  944. // The user_dir may not have been created yet.
  945. base::CreateDirectoryAndGetError(user_dir, nullptr);
  946. auto cb = base::BindRepeating(&App::OnSecondInstance, base::Unretained(this));
  947. blink::CloneableMessage additional_data_message;
  948. args->GetNext(&additional_data_message);
  949. #if BUILDFLAG(IS_WIN)
  950. bool app_is_sandboxed =
  951. IsSandboxEnabled(base::CommandLine::ForCurrentProcess());
  952. process_singleton_ = std::make_unique<ProcessSingleton>(
  953. program_name, user_dir, additional_data_message.encoded_message,
  954. app_is_sandboxed, base::BindRepeating(NotificationCallbackWrapper, cb));
  955. #else
  956. process_singleton_ = std::make_unique<ProcessSingleton>(
  957. user_dir, additional_data_message.encoded_message,
  958. base::BindRepeating(NotificationCallbackWrapper, cb));
  959. #endif
  960. switch (process_singleton_->NotifyOtherProcessOrCreate()) {
  961. case ProcessSingleton::NotifyResult::PROCESS_NONE:
  962. if (content::BrowserThread::IsThreadInitialized(
  963. content::BrowserThread::IO)) {
  964. process_singleton_->StartWatching();
  965. } else {
  966. watch_singleton_socket_on_ready_ = true;
  967. }
  968. return true;
  969. case ProcessSingleton::NotifyResult::LOCK_ERROR:
  970. case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
  971. case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
  972. process_singleton_.reset();
  973. return false;
  974. }
  975. }
  976. }
  977. void App::ReleaseSingleInstanceLock() {
  978. if (process_singleton_) {
  979. process_singleton_->Cleanup();
  980. process_singleton_.reset();
  981. }
  982. }
  983. bool App::Relaunch(gin::Arguments* js_args) {
  984. // Parse parameters.
  985. bool override_argv = false;
  986. base::FilePath exec_path;
  987. relauncher::StringVector args;
  988. gin_helper::Dictionary options;
  989. if (js_args->GetNext(&options)) {
  990. bool has_exec_path = options.Get("execPath", &exec_path);
  991. bool has_args = options.Get("args", &args);
  992. if (has_exec_path || has_args)
  993. override_argv = true;
  994. }
  995. if (!override_argv) {
  996. const relauncher::StringVector& argv =
  997. electron::ElectronCommandLine::argv();
  998. return relauncher::RelaunchApp(argv);
  999. }
  1000. relauncher::StringVector argv;
  1001. argv.reserve(1 + args.size());
  1002. if (exec_path.empty()) {
  1003. base::FilePath current_exe_path;
  1004. base::PathService::Get(base::FILE_EXE, &current_exe_path);
  1005. argv.push_back(current_exe_path.value());
  1006. } else {
  1007. argv.push_back(exec_path.value());
  1008. }
  1009. argv.insert(argv.end(), args.begin(), args.end());
  1010. return relauncher::RelaunchApp(argv);
  1011. }
  1012. void App::DisableHardwareAcceleration(gin_helper::ErrorThrower thrower) {
  1013. if (Browser::Get()->is_ready()) {
  1014. thrower.ThrowError(
  1015. "app.disableHardwareAcceleration() can only be called "
  1016. "before app is ready");
  1017. return;
  1018. }
  1019. if (content::GpuDataManager::Initialized()) {
  1020. content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
  1021. } else {
  1022. disable_hw_acceleration_ = true;
  1023. }
  1024. }
  1025. void App::DisableDomainBlockingFor3DAPIs(gin_helper::ErrorThrower thrower) {
  1026. if (Browser::Get()->is_ready()) {
  1027. thrower.ThrowError(
  1028. "app.disableDomainBlockingFor3DAPIs() can only be called "
  1029. "before app is ready");
  1030. return;
  1031. }
  1032. if (content::GpuDataManager::Initialized()) {
  1033. content::GpuDataManagerImpl::GetInstance()
  1034. ->DisableDomainBlockingFor3DAPIsForTesting();
  1035. } else {
  1036. disable_domain_blocking_for_3DAPIs_ = true;
  1037. }
  1038. }
  1039. bool App::IsAccessibilitySupportEnabled() {
  1040. auto* ax_state = content::BrowserAccessibilityState::GetInstance();
  1041. return ax_state->IsAccessibleBrowser();
  1042. }
  1043. void App::SetAccessibilitySupportEnabled(gin_helper::ErrorThrower thrower,
  1044. bool enabled) {
  1045. if (!Browser::Get()->is_ready()) {
  1046. thrower.ThrowError(
  1047. "app.setAccessibilitySupportEnabled() can only be called "
  1048. "after app is ready");
  1049. return;
  1050. }
  1051. auto* ax_state = content::BrowserAccessibilityState::GetInstance();
  1052. if (enabled) {
  1053. ax_state->OnScreenReaderDetected();
  1054. } else {
  1055. ax_state->DisableAccessibility();
  1056. }
  1057. Browser::Get()->OnAccessibilitySupportChanged();
  1058. }
  1059. Browser::LoginItemSettings App::GetLoginItemSettings(gin::Arguments* args) {
  1060. Browser::LoginItemSettings options;
  1061. args->GetNext(&options);
  1062. return Browser::Get()->GetLoginItemSettings(options);
  1063. }
  1064. #if BUILDFLAG(USE_NSS_CERTS)
  1065. void App::ImportCertificate(gin_helper::ErrorThrower thrower,
  1066. base::Value options,
  1067. net::CompletionOnceCallback callback) {
  1068. if (!options.is_dict()) {
  1069. thrower.ThrowTypeError("Expected options to be an object");
  1070. return;
  1071. }
  1072. auto* browser_context = ElectronBrowserContext::From("", false);
  1073. if (!certificate_manager_model_) {
  1074. CertificateManagerModel::Create(
  1075. browser_context,
  1076. base::BindOnce(&App::OnCertificateManagerModelCreated,
  1077. base::Unretained(this), std::move(options),
  1078. std::move(callback)));
  1079. return;
  1080. }
  1081. int rv =
  1082. ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
  1083. std::move(callback).Run(rv);
  1084. }
  1085. void App::OnCertificateManagerModelCreated(
  1086. base::Value options,
  1087. net::CompletionOnceCallback callback,
  1088. std::unique_ptr<CertificateManagerModel> model) {
  1089. certificate_manager_model_ = std::move(model);
  1090. int rv =
  1091. ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
  1092. std::move(callback).Run(rv);
  1093. }
  1094. #endif
  1095. #if BUILDFLAG(IS_WIN)
  1096. v8::Local<v8::Value> App::GetJumpListSettings() {
  1097. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  1098. int min_items = 10;
  1099. std::vector<JumpListItem> removed_items;
  1100. if (jump_list.Begin(&min_items, &removed_items)) {
  1101. // We don't actually want to change anything, so abort the transaction.
  1102. jump_list.Abort();
  1103. } else {
  1104. LOG(ERROR) << "Failed to begin Jump List transaction.";
  1105. }
  1106. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1107. auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
  1108. dict.Set("minItems", min_items);
  1109. dict.Set("removedItems", gin::ConvertToV8(isolate, removed_items));
  1110. return dict.GetHandle();
  1111. }
  1112. JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
  1113. gin::Arguments* args) {
  1114. std::vector<JumpListCategory> categories;
  1115. bool delete_jump_list = val->IsNull();
  1116. if (!delete_jump_list &&
  1117. !gin::ConvertFromV8(args->isolate(), val, &categories)) {
  1118. gin_helper::ErrorThrower(args->isolate())
  1119. .ThrowError("Argument must be null or an array of categories");
  1120. return JumpListResult::kArgumentError;
  1121. }
  1122. JumpList jump_list(Browser::Get()->GetAppUserModelID());
  1123. if (delete_jump_list) {
  1124. return jump_list.Delete() ? JumpListResult::kSuccess
  1125. : JumpListResult::kGenericError;
  1126. }
  1127. // Start a transaction that updates the JumpList of this application.
  1128. if (!jump_list.Begin())
  1129. return JumpListResult::kGenericError;
  1130. JumpListResult result = jump_list.AppendCategories(categories);
  1131. // AppendCategories may have failed to add some categories, but it's better
  1132. // to have something than nothing so try to commit the changes anyway.
  1133. if (!jump_list.Commit()) {
  1134. LOG(ERROR) << "Failed to commit changes to custom Jump List.";
  1135. // It's more useful to return the earlier error code that might give
  1136. // some indication as to why the transaction actually failed, so don't
  1137. // overwrite it with a "generic error" code here.
  1138. if (result == JumpListResult::kSuccess)
  1139. result = JumpListResult::kGenericError;
  1140. }
  1141. return result;
  1142. }
  1143. #endif // BUILDFLAG(IS_WIN)
  1144. v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
  1145. gin::Arguments* args) {
  1146. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1147. gin_helper::Promise<gfx::Image> promise(isolate);
  1148. v8::Local<v8::Promise> handle = promise.GetHandle();
  1149. base::FilePath normalized_path = path.NormalizePathSeparators();
  1150. IconLoader::IconSize icon_size;
  1151. gin_helper::Dictionary options;
  1152. if (!args->GetNext(&options)) {
  1153. icon_size = IconLoader::IconSize::NORMAL;
  1154. } else {
  1155. std::string icon_size_string;
  1156. options.Get("size", &icon_size_string);
  1157. icon_size = GetIconSizeByString(icon_size_string);
  1158. }
  1159. auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager();
  1160. gfx::Image* icon =
  1161. icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f);
  1162. if (icon) {
  1163. promise.Resolve(*icon);
  1164. } else {
  1165. icon_manager->LoadIcon(
  1166. normalized_path, icon_size, 1.0f,
  1167. base::BindOnce(&OnIconDataAvailable, std::move(promise)),
  1168. &cancelable_task_tracker_);
  1169. }
  1170. return handle;
  1171. }
  1172. std::vector<gin_helper::Dictionary> App::GetAppMetrics(v8::Isolate* isolate) {
  1173. std::vector<gin_helper::Dictionary> result;
  1174. result.reserve(app_metrics_.size());
  1175. int processor_count = base::SysInfo::NumberOfProcessors();
  1176. for (const auto& process_metric : app_metrics_) {
  1177. auto pid_dict = gin_helper::Dictionary::CreateEmpty(isolate);
  1178. auto cpu_dict = gin_helper::Dictionary::CreateEmpty(isolate);
  1179. cpu_dict.Set(
  1180. "percentCPUUsage",
  1181. process_metric.second->metrics->GetPlatformIndependentCPUUsage() /
  1182. processor_count);
  1183. #if !BUILDFLAG(IS_WIN)
  1184. cpu_dict.Set("idleWakeupsPerSecond",
  1185. process_metric.second->metrics->GetIdleWakeupsPerSecond());
  1186. #else
  1187. // Chrome's underlying process_metrics.cc will throw a non-fatal warning
  1188. // that this method isn't implemented on Windows, so set it to 0 instead
  1189. // of calling it
  1190. cpu_dict.Set("idleWakeupsPerSecond", 0);
  1191. #endif
  1192. pid_dict.Set("cpu", cpu_dict);
  1193. pid_dict.Set("pid", process_metric.second->process.Pid());
  1194. pid_dict.Set("type", content::GetProcessTypeNameInEnglish(
  1195. process_metric.second->type));
  1196. pid_dict.Set("creationTime",
  1197. process_metric.second->process.CreationTime().ToJsTime());
  1198. if (!process_metric.second->service_name.empty()) {
  1199. pid_dict.Set("serviceName", process_metric.second->service_name);
  1200. }
  1201. if (!process_metric.second->name.empty()) {
  1202. pid_dict.Set("name", process_metric.second->name);
  1203. }
  1204. #if !BUILDFLAG(IS_LINUX)
  1205. auto memory_info = process_metric.second->GetMemoryInfo();
  1206. auto memory_dict = gin_helper::Dictionary::CreateEmpty(isolate);
  1207. memory_dict.Set("workingSetSize",
  1208. static_cast<double>(memory_info.working_set_size >> 10));
  1209. memory_dict.Set(
  1210. "peakWorkingSetSize",
  1211. static_cast<double>(memory_info.peak_working_set_size >> 10));
  1212. #if BUILDFLAG(IS_WIN)
  1213. memory_dict.Set("privateBytes",
  1214. static_cast<double>(memory_info.private_bytes >> 10));
  1215. #endif
  1216. pid_dict.Set("memory", memory_dict);
  1217. #endif
  1218. #if BUILDFLAG(IS_MAC)
  1219. pid_dict.Set("sandboxed", process_metric.second->IsSandboxed());
  1220. #elif BUILDFLAG(IS_WIN)
  1221. auto integrity_level = process_metric.second->GetIntegrityLevel();
  1222. auto sandboxed = ProcessMetric::IsSandboxed(integrity_level);
  1223. pid_dict.Set("integrityLevel", integrity_level);
  1224. pid_dict.Set("sandboxed", sandboxed);
  1225. #endif
  1226. result.push_back(pid_dict);
  1227. }
  1228. return result;
  1229. }
  1230. v8::Local<v8::Value> App::GetGPUFeatureStatus(v8::Isolate* isolate) {
  1231. return gin::ConvertToV8(isolate, content::GetFeatureStatus());
  1232. }
  1233. v8::Local<v8::Promise> App::GetGPUInfo(v8::Isolate* isolate,
  1234. const std::string& info_type) {
  1235. auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance();
  1236. gin_helper::Promise<base::Value> promise(isolate);
  1237. v8::Local<v8::Promise> handle = promise.GetHandle();
  1238. if (info_type != "basic" && info_type != "complete") {
  1239. promise.RejectWithErrorMessage(
  1240. "Invalid info type. Use 'basic' or 'complete'");
  1241. return handle;
  1242. }
  1243. std::string reason;
  1244. if (!gpu_data_manager->GpuAccessAllowed(&reason)) {
  1245. promise.RejectWithErrorMessage("GPU access not allowed. Reason: " + reason);
  1246. return handle;
  1247. }
  1248. auto* const info_mgr = GPUInfoManager::GetInstance();
  1249. if (info_type == "complete") {
  1250. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  1251. info_mgr->FetchCompleteInfo(std::move(promise));
  1252. #else
  1253. info_mgr->FetchBasicInfo(std::move(promise));
  1254. #endif
  1255. } else /* (info_type == "basic") */ {
  1256. info_mgr->FetchBasicInfo(std::move(promise));
  1257. }
  1258. return handle;
  1259. }
  1260. static void RemoveNoSandboxSwitch(base::CommandLine* command_line) {
  1261. if (command_line->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
  1262. const base::CommandLine::CharType* noSandboxArg =
  1263. FILE_PATH_LITERAL("--no-sandbox");
  1264. base::CommandLine::StringVector modified_command_line;
  1265. for (auto& arg : command_line->argv()) {
  1266. if (arg.compare(noSandboxArg) != 0) {
  1267. modified_command_line.push_back(arg);
  1268. }
  1269. }
  1270. command_line->InitFromArgv(modified_command_line);
  1271. }
  1272. }
  1273. void App::EnableSandbox(gin_helper::ErrorThrower thrower) {
  1274. if (Browser::Get()->is_ready()) {
  1275. thrower.ThrowError(
  1276. "app.enableSandbox() can only be called "
  1277. "before app is ready");
  1278. return;
  1279. }
  1280. auto* command_line = base::CommandLine::ForCurrentProcess();
  1281. RemoveNoSandboxSwitch(command_line);
  1282. command_line->AppendSwitch(switches::kEnableSandbox);
  1283. }
  1284. void App::SetUserAgentFallback(const std::string& user_agent) {
  1285. ElectronBrowserClient::Get()->SetUserAgent(user_agent);
  1286. }
  1287. #if BUILDFLAG(IS_WIN)
  1288. bool App::IsRunningUnderARM64Translation() const {
  1289. USHORT processMachine = 0;
  1290. USHORT nativeMachine = 0;
  1291. auto IsWow64Process2 = reinterpret_cast<decltype(&::IsWow64Process2)>(
  1292. GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process2"));
  1293. if (IsWow64Process2 == nullptr) {
  1294. return false;
  1295. }
  1296. if (!IsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine)) {
  1297. return false;
  1298. }
  1299. return nativeMachine == IMAGE_FILE_MACHINE_ARM64;
  1300. }
  1301. #endif
  1302. std::string App::GetUserAgentFallback() {
  1303. return ElectronBrowserClient::Get()->GetUserAgent();
  1304. }
  1305. #if BUILDFLAG(IS_MAC)
  1306. bool App::MoveToApplicationsFolder(gin_helper::ErrorThrower thrower,
  1307. gin::Arguments* args) {
  1308. return ElectronBundleMover::Move(thrower, args);
  1309. }
  1310. bool App::IsInApplicationsFolder() {
  1311. return ElectronBundleMover::IsCurrentAppInApplicationsFolder();
  1312. }
  1313. int DockBounce(gin::Arguments* args) {
  1314. int request_id = -1;
  1315. std::string type = "informational";
  1316. args->GetNext(&type);
  1317. if (type == "critical")
  1318. request_id = Browser::Get()->DockBounce(Browser::BounceType::kCritical);
  1319. else if (type == "informational")
  1320. request_id =
  1321. Browser::Get()->DockBounce(Browser::BounceType::kInformational);
  1322. return request_id;
  1323. }
  1324. void DockSetMenu(electron::api::Menu* menu) {
  1325. Browser::Get()->DockSetMenu(menu->model());
  1326. }
  1327. v8::Local<v8::Value> App::GetDockAPI(v8::Isolate* isolate) {
  1328. if (dock_.IsEmpty()) {
  1329. // Initialize the Dock API, the methods are bound to "dock" which exists
  1330. // for the lifetime of "app"
  1331. auto browser = base::Unretained(Browser::Get());
  1332. auto dock_obj = gin_helper::Dictionary::CreateEmpty(isolate);
  1333. dock_obj.SetMethod("bounce", &DockBounce);
  1334. dock_obj.SetMethod(
  1335. "cancelBounce",
  1336. base::BindRepeating(&Browser::DockCancelBounce, browser));
  1337. dock_obj.SetMethod(
  1338. "downloadFinished",
  1339. base::BindRepeating(&Browser::DockDownloadFinished, browser));
  1340. dock_obj.SetMethod(
  1341. "setBadge", base::BindRepeating(&Browser::DockSetBadgeText, browser));
  1342. dock_obj.SetMethod(
  1343. "getBadge", base::BindRepeating(&Browser::DockGetBadgeText, browser));
  1344. dock_obj.SetMethod("hide",
  1345. base::BindRepeating(&Browser::DockHide, browser));
  1346. dock_obj.SetMethod("show",
  1347. base::BindRepeating(&Browser::DockShow, browser));
  1348. dock_obj.SetMethod("isVisible",
  1349. base::BindRepeating(&Browser::DockIsVisible, browser));
  1350. dock_obj.SetMethod("setMenu", &DockSetMenu);
  1351. dock_obj.SetMethod("setIcon",
  1352. base::BindRepeating(&Browser::DockSetIcon, browser));
  1353. dock_.Reset(isolate, dock_obj.GetHandle());
  1354. }
  1355. return v8::Local<v8::Value>::New(isolate, dock_);
  1356. }
  1357. #endif
  1358. void ConfigureHostResolver(v8::Isolate* isolate,
  1359. const gin_helper::Dictionary& opts) {
  1360. gin_helper::ErrorThrower thrower(isolate);
  1361. if (!Browser::Get()->is_ready()) {
  1362. thrower.ThrowError(
  1363. "configureHostResolver cannot be called before the app is ready");
  1364. return;
  1365. }
  1366. net::SecureDnsMode secure_dns_mode = net::SecureDnsMode::kOff;
  1367. std::string default_doh_templates;
  1368. if (base::FeatureList::IsEnabled(features::kDnsOverHttps)) {
  1369. if (features::kDnsOverHttpsFallbackParam.Get()) {
  1370. secure_dns_mode = net::SecureDnsMode::kAutomatic;
  1371. } else {
  1372. secure_dns_mode = net::SecureDnsMode::kSecure;
  1373. }
  1374. default_doh_templates = features::kDnsOverHttpsTemplatesParam.Get();
  1375. }
  1376. net::DnsOverHttpsConfig doh_config;
  1377. if (!default_doh_templates.empty() &&
  1378. secure_dns_mode != net::SecureDnsMode::kOff) {
  1379. auto maybe_doh_config =
  1380. net::DnsOverHttpsConfig::FromString(default_doh_templates);
  1381. if (maybe_doh_config.has_value())
  1382. doh_config = maybe_doh_config.value();
  1383. }
  1384. bool enable_built_in_resolver =
  1385. base::FeatureList::IsEnabled(features::kAsyncDns);
  1386. bool additional_dns_query_types_enabled = true;
  1387. if (opts.Has("enableBuiltInResolver") &&
  1388. !opts.Get("enableBuiltInResolver", &enable_built_in_resolver)) {
  1389. thrower.ThrowTypeError("enableBuiltInResolver must be a boolean");
  1390. return;
  1391. }
  1392. if (opts.Has("secureDnsMode") &&
  1393. !opts.Get("secureDnsMode", &secure_dns_mode)) {
  1394. thrower.ThrowTypeError(
  1395. "secureDnsMode must be one of: off, automatic, secure");
  1396. return;
  1397. }
  1398. std::vector<std::string> secure_dns_server_strings;
  1399. if (opts.Has("secureDnsServers")) {
  1400. if (!opts.Get("secureDnsServers", &secure_dns_server_strings)) {
  1401. thrower.ThrowTypeError("secureDnsServers must be an array of strings");
  1402. return;
  1403. }
  1404. // Validate individual server templates prior to batch-assigning to
  1405. // doh_config.
  1406. std::vector<net::DnsOverHttpsServerConfig> servers;
  1407. for (const std::string& server_template : secure_dns_server_strings) {
  1408. absl::optional<net::DnsOverHttpsServerConfig> server_config =
  1409. net::DnsOverHttpsServerConfig::FromString(server_template);
  1410. if (!server_config.has_value()) {
  1411. thrower.ThrowTypeError(std::string("not a valid DoH template: ") +
  1412. server_template);
  1413. return;
  1414. }
  1415. servers.push_back(*server_config);
  1416. }
  1417. doh_config = net::DnsOverHttpsConfig(std::move(servers));
  1418. }
  1419. if (opts.Has("enableAdditionalDnsQueryTypes") &&
  1420. !opts.Get("enableAdditionalDnsQueryTypes",
  1421. &additional_dns_query_types_enabled)) {
  1422. thrower.ThrowTypeError("enableAdditionalDnsQueryTypes must be a boolean");
  1423. return;
  1424. }
  1425. // Configure the stub resolver. This must be done after the system
  1426. // NetworkContext is created, but before anything has the chance to use it.
  1427. content::GetNetworkService()->ConfigureStubHostResolver(
  1428. enable_built_in_resolver, secure_dns_mode, doh_config,
  1429. additional_dns_query_types_enabled);
  1430. }
  1431. // static
  1432. App* App::Get() {
  1433. static base::NoDestructor<App> app;
  1434. return app.get();
  1435. }
  1436. // static
  1437. gin::Handle<App> App::Create(v8::Isolate* isolate) {
  1438. return gin::CreateHandle(isolate, Get());
  1439. }
  1440. gin::ObjectTemplateBuilder App::GetObjectTemplateBuilder(v8::Isolate* isolate) {
  1441. auto browser = base::Unretained(Browser::Get());
  1442. return gin_helper::EventEmitterMixin<App>::GetObjectTemplateBuilder(isolate)
  1443. .SetMethod("quit", base::BindRepeating(&Browser::Quit, browser))
  1444. .SetMethod("exit", base::BindRepeating(&Browser::Exit, browser))
  1445. .SetMethod("focus", base::BindRepeating(&Browser::Focus, browser))
  1446. .SetMethod("getVersion",
  1447. base::BindRepeating(&Browser::GetVersion, browser))
  1448. .SetMethod("setVersion",
  1449. base::BindRepeating(&Browser::SetVersion, browser))
  1450. .SetMethod("getName", base::BindRepeating(&Browser::GetName, browser))
  1451. .SetMethod("setName", base::BindRepeating(&Browser::SetName, browser))
  1452. .SetMethod("isReady", base::BindRepeating(&Browser::is_ready, browser))
  1453. .SetMethod("whenReady", base::BindRepeating(&Browser::WhenReady, browser))
  1454. .SetMethod("addRecentDocument",
  1455. base::BindRepeating(&Browser::AddRecentDocument, browser))
  1456. .SetMethod("clearRecentDocuments",
  1457. base::BindRepeating(&Browser::ClearRecentDocuments, browser))
  1458. #if BUILDFLAG(IS_WIN)
  1459. .SetMethod("setAppUserModelId",
  1460. base::BindRepeating(&Browser::SetAppUserModelID, browser))
  1461. #endif
  1462. .SetMethod(
  1463. "isDefaultProtocolClient",
  1464. base::BindRepeating(&Browser::IsDefaultProtocolClient, browser))
  1465. .SetMethod(
  1466. "setAsDefaultProtocolClient",
  1467. base::BindRepeating(&Browser::SetAsDefaultProtocolClient, browser))
  1468. .SetMethod(
  1469. "removeAsDefaultProtocolClient",
  1470. base::BindRepeating(&Browser::RemoveAsDefaultProtocolClient, browser))
  1471. #if !BUILDFLAG(IS_LINUX)
  1472. .SetMethod(
  1473. "getApplicationInfoForProtocol",
  1474. base::BindRepeating(&Browser::GetApplicationInfoForProtocol, browser))
  1475. #endif
  1476. .SetMethod(
  1477. "getApplicationNameForProtocol",
  1478. base::BindRepeating(&Browser::GetApplicationNameForProtocol, browser))
  1479. .SetMethod("setBadgeCount",
  1480. base::BindRepeating(&Browser::SetBadgeCount, browser))
  1481. .SetMethod("getBadgeCount",
  1482. base::BindRepeating(&Browser::GetBadgeCount, browser))
  1483. .SetMethod("getLoginItemSettings", &App::GetLoginItemSettings)
  1484. .SetMethod("setLoginItemSettings",
  1485. base::BindRepeating(&Browser::SetLoginItemSettings, browser))
  1486. .SetMethod("isEmojiPanelSupported",
  1487. base::BindRepeating(&Browser::IsEmojiPanelSupported, browser))
  1488. #if BUILDFLAG(IS_MAC)
  1489. .SetMethod("hide", base::BindRepeating(&Browser::Hide, browser))
  1490. .SetMethod("isHidden", base::BindRepeating(&Browser::IsHidden, browser))
  1491. .SetMethod("show", base::BindRepeating(&Browser::Show, browser))
  1492. .SetMethod("setUserActivity",
  1493. base::BindRepeating(&Browser::SetUserActivity, browser))
  1494. .SetMethod("getCurrentActivityType",
  1495. base::BindRepeating(&Browser::GetCurrentActivityType, browser))
  1496. .SetMethod(
  1497. "invalidateCurrentActivity",
  1498. base::BindRepeating(&Browser::InvalidateCurrentActivity, browser))
  1499. .SetMethod("resignCurrentActivity",
  1500. base::BindRepeating(&Browser::ResignCurrentActivity, browser))
  1501. .SetMethod("updateCurrentActivity",
  1502. base::BindRepeating(&Browser::UpdateCurrentActivity, browser))
  1503. .SetMethod("moveToApplicationsFolder", &App::MoveToApplicationsFolder)
  1504. .SetMethod("isInApplicationsFolder", &App::IsInApplicationsFolder)
  1505. .SetMethod("setActivationPolicy", &App::SetActivationPolicy)
  1506. #endif
  1507. .SetMethod("setAboutPanelOptions",
  1508. base::BindRepeating(&Browser::SetAboutPanelOptions, browser))
  1509. .SetMethod("showAboutPanel",
  1510. base::BindRepeating(&Browser::ShowAboutPanel, browser))
  1511. #if BUILDFLAG(IS_MAC)
  1512. .SetMethod(
  1513. "isSecureKeyboardEntryEnabled",
  1514. base::BindRepeating(&Browser::IsSecureKeyboardEntryEnabled, browser))
  1515. .SetMethod(
  1516. "setSecureKeyboardEntryEnabled",
  1517. base::BindRepeating(&Browser::SetSecureKeyboardEntryEnabled, browser))
  1518. #endif
  1519. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  1520. .SetMethod("showEmojiPanel",
  1521. base::BindRepeating(&Browser::ShowEmojiPanel, browser))
  1522. #endif
  1523. #if BUILDFLAG(IS_WIN)
  1524. .SetMethod("setUserTasks",
  1525. base::BindRepeating(&Browser::SetUserTasks, browser))
  1526. .SetMethod("getJumpListSettings", &App::GetJumpListSettings)
  1527. .SetMethod("setJumpList", &App::SetJumpList)
  1528. #endif
  1529. #if BUILDFLAG(IS_LINUX)
  1530. .SetMethod("isUnityRunning",
  1531. base::BindRepeating(&Browser::IsUnityRunning, browser))
  1532. #endif
  1533. .SetProperty("isPackaged", &App::IsPackaged)
  1534. .SetMethod("setAppPath", &App::SetAppPath)
  1535. .SetMethod("getAppPath", &App::GetAppPath)
  1536. .SetMethod("setPath", &App::SetPath)
  1537. .SetMethod("getPath", &App::GetPath)
  1538. .SetMethod("setAppLogsPath", &App::SetAppLogsPath)
  1539. .SetMethod("setDesktopName", &App::SetDesktopName)
  1540. .SetMethod("getLocale", &App::GetLocale)
  1541. .SetMethod("getPreferredSystemLanguages", &GetPreferredLanguages)
  1542. .SetMethod("getSystemLocale", &App::GetSystemLocale)
  1543. .SetMethod("getLocaleCountryCode", &App::GetLocaleCountryCode)
  1544. #if BUILDFLAG(USE_NSS_CERTS)
  1545. .SetMethod("importCertificate", &App::ImportCertificate)
  1546. #endif
  1547. .SetMethod("hasSingleInstanceLock", &App::HasSingleInstanceLock)
  1548. .SetMethod("requestSingleInstanceLock", &App::RequestSingleInstanceLock)
  1549. .SetMethod("releaseSingleInstanceLock", &App::ReleaseSingleInstanceLock)
  1550. .SetMethod("relaunch", &App::Relaunch)
  1551. .SetMethod("isAccessibilitySupportEnabled",
  1552. &App::IsAccessibilitySupportEnabled)
  1553. .SetMethod("setAccessibilitySupportEnabled",
  1554. &App::SetAccessibilitySupportEnabled)
  1555. .SetMethod("disableHardwareAcceleration",
  1556. &App::DisableHardwareAcceleration)
  1557. .SetMethod("disableDomainBlockingFor3DAPIs",
  1558. &App::DisableDomainBlockingFor3DAPIs)
  1559. .SetMethod("getFileIcon", &App::GetFileIcon)
  1560. .SetMethod("getAppMetrics", &App::GetAppMetrics)
  1561. .SetMethod("getGPUFeatureStatus", &App::GetGPUFeatureStatus)
  1562. .SetMethod("getGPUInfo", &App::GetGPUInfo)
  1563. #if IS_MAS_BUILD()
  1564. .SetMethod("startAccessingSecurityScopedResource",
  1565. &App::StartAccessingSecurityScopedResource)
  1566. #endif
  1567. #if BUILDFLAG(IS_MAC)
  1568. .SetProperty("dock", &App::GetDockAPI)
  1569. .SetProperty("runningUnderRosettaTranslation",
  1570. &App::IsRunningUnderRosettaTranslation)
  1571. #endif
  1572. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  1573. .SetProperty("runningUnderARM64Translation",
  1574. &App::IsRunningUnderARM64Translation)
  1575. #endif
  1576. .SetProperty("userAgentFallback", &App::GetUserAgentFallback,
  1577. &App::SetUserAgentFallback)
  1578. .SetMethod("configureHostResolver", &ConfigureHostResolver)
  1579. .SetMethod("enableSandbox", &App::EnableSandbox);
  1580. }
  1581. const char* App::GetTypeName() {
  1582. return "App";
  1583. }
  1584. } // namespace electron::api
  1585. namespace {
  1586. void Initialize(v8::Local<v8::Object> exports,
  1587. v8::Local<v8::Value> unused,
  1588. v8::Local<v8::Context> context,
  1589. void* priv) {
  1590. v8::Isolate* isolate = context->GetIsolate();
  1591. gin_helper::Dictionary dict(isolate, exports);
  1592. dict.Set("app", electron::api::App::Create(isolate));
  1593. }
  1594. } // namespace
  1595. NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_app, Initialize)