electron_api_app.cc 62 KB

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