electron_browser_main_parts.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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/electron_browser_main_parts.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/base_switches.h"
  11. #include "base/command_line.h"
  12. #include "base/feature_list.h"
  13. #include "base/i18n/rtl.h"
  14. #include "base/metrics/field_trial.h"
  15. #include "base/nix/xdg_util.h"
  16. #include "base/path_service.h"
  17. #include "base/run_loop.h"
  18. #include "base/strings/string_number_conversions.h"
  19. #include "base/task/single_thread_task_runner.h"
  20. #include "chrome/browser/icon_manager.h"
  21. #include "chrome/browser/ui/color/chrome_color_mixers.h"
  22. #include "chrome/common/chrome_switches.h"
  23. #include "components/os_crypt/sync/key_storage_config_linux.h"
  24. #include "components/os_crypt/sync/key_storage_util_linux.h"
  25. #include "components/os_crypt/sync/os_crypt.h"
  26. #include "components/password_manager/core/browser/password_manager_switches.h" // nogncheck
  27. #include "content/browser/browser_main_loop.h" // nogncheck
  28. #include "content/public/browser/browser_child_process_host_delegate.h"
  29. #include "content/public/browser/browser_child_process_host_iterator.h"
  30. #include "content/public/browser/browser_thread.h"
  31. #include "content/public/browser/child_process_data.h"
  32. #include "content/public/browser/child_process_security_policy.h"
  33. #include "content/public/browser/device_service.h"
  34. #include "content/public/browser/download_manager.h"
  35. #include "content/public/browser/first_party_sets_handler.h"
  36. #include "content/public/browser/web_ui_controller_factory.h"
  37. #include "content/public/common/content_features.h"
  38. #include "content/public/common/content_switches.h"
  39. #include "content/public/common/process_type.h"
  40. #include "content/public/common/result_codes.h"
  41. #include "electron/buildflags/buildflags.h"
  42. #include "media/base/localized_strings.h"
  43. #include "services/network/public/cpp/features.h"
  44. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
  45. #include "shell/app/electron_main_delegate.h"
  46. #include "shell/browser/api/electron_api_utility_process.h"
  47. #include "shell/browser/browser.h"
  48. #include "shell/browser/browser_process_impl.h"
  49. #include "shell/browser/electron_browser_client.h"
  50. #include "shell/browser/electron_browser_context.h"
  51. #include "shell/browser/electron_web_ui_controller_factory.h"
  52. #include "shell/browser/feature_list.h"
  53. #include "shell/browser/javascript_environment.h"
  54. #include "shell/browser/media/media_capture_devices_dispatcher.h"
  55. #include "shell/browser/ui/devtools_manager_delegate.h"
  56. #include "shell/common/api/electron_bindings.h"
  57. #include "shell/common/application_info.h"
  58. #include "shell/common/electron_paths.h"
  59. #include "shell/common/gin_helper/trackable_object.h"
  60. #include "shell/common/logging.h"
  61. #include "shell/common/node_bindings.h"
  62. #include "shell/common/node_includes.h"
  63. #include "ui/base/idle/idle.h"
  64. #include "ui/base/l10n/l10n_util.h"
  65. #include "ui/base/ui_base_switches.h"
  66. #include "ui/color/color_provider_manager.h"
  67. #include "ui/display/screen.h"
  68. #include "ui/views/layout/layout_provider.h"
  69. #include "url/url_util.h"
  70. #if defined(USE_AURA)
  71. #include "ui/views/widget/desktop_aura/desktop_screen.h"
  72. #include "ui/wm/core/wm_state.h"
  73. #endif
  74. #if BUILDFLAG(IS_LINUX)
  75. #include "base/environment.h"
  76. #include "chrome/browser/ui/views/dark_mode_manager_linux.h"
  77. #include "device/bluetooth/bluetooth_adapter_factory.h"
  78. #include "device/bluetooth/dbus/bluez_dbus_manager.h"
  79. #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
  80. #include "electron/electron_gtk_stubs.h"
  81. #include "ui/base/cursor/cursor_factory.h"
  82. #include "ui/base/ime/linux/linux_input_method_context_factory.h"
  83. #include "ui/gtk/gtk_compat.h" // nogncheck
  84. #include "ui/gtk/gtk_util.h" // nogncheck
  85. #include "ui/linux/linux_ui.h"
  86. #include "ui/linux/linux_ui_factory.h"
  87. #include "ui/linux/linux_ui_getter.h"
  88. #include "ui/ozone/public/ozone_platform.h"
  89. #endif
  90. #if BUILDFLAG(IS_WIN)
  91. #include "chrome/browser/win/chrome_select_file_dialog_factory.h"
  92. #include "ui/base/l10n/l10n_util_win.h"
  93. #include "ui/gfx/system_fonts_win.h"
  94. #include "ui/strings/grit/app_locale_settings.h"
  95. #endif
  96. #if BUILDFLAG(IS_MAC)
  97. #include "components/os_crypt/sync/keychain_password_mac.h"
  98. #include "shell/browser/ui/cocoa/views_delegate_mac.h"
  99. #else
  100. #include "shell/browser/ui/views/electron_views_delegate.h"
  101. #endif
  102. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  103. #include "components/keyed_service/content/browser_context_dependency_manager.h"
  104. #include "extensions/browser/browser_context_keyed_service_factories.h"
  105. #include "extensions/common/extension_api.h"
  106. #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h"
  107. #include "shell/browser/extensions/electron_extensions_browser_client.h"
  108. #include "shell/common/extensions/electron_extensions_client.h"
  109. #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  110. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  111. #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
  112. #endif
  113. #if BUILDFLAG(ENABLE_PLUGINS)
  114. #include "content/public/browser/plugin_service.h"
  115. #include "shell/common/plugin_info.h"
  116. #endif // BUILDFLAG(ENABLE_PLUGINS)
  117. namespace electron {
  118. namespace {
  119. #if BUILDFLAG(IS_LINUX)
  120. class LinuxUiGetterImpl : public ui::LinuxUiGetter {
  121. public:
  122. LinuxUiGetterImpl() = default;
  123. ~LinuxUiGetterImpl() override = default;
  124. // ui::LinuxUiGetter
  125. ui::LinuxUiTheme* GetForWindow(aura::Window* window) override {
  126. return GetForProfile(nullptr);
  127. }
  128. ui::LinuxUiTheme* GetForProfile(Profile* profile) override {
  129. return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk);
  130. }
  131. };
  132. #endif
  133. #if BUILDFLAG(IS_WIN)
  134. int GetMinimumFontSize() {
  135. int min_font_size;
  136. base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
  137. &min_font_size);
  138. return min_font_size;
  139. }
  140. #endif
  141. std::u16string MediaStringProvider(media::MessageId id) {
  142. switch (id) {
  143. case media::DEFAULT_AUDIO_DEVICE_NAME:
  144. return u"Default";
  145. #if BUILDFLAG(IS_WIN)
  146. case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
  147. return u"Communications";
  148. #endif
  149. default:
  150. return {};
  151. }
  152. }
  153. } // namespace
  154. // static
  155. ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr;
  156. ElectronBrowserMainParts::ElectronBrowserMainParts()
  157. : fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
  158. node_bindings_{
  159. NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)},
  160. electron_bindings_{
  161. std::make_unique<ElectronBindings>(node_bindings_->uv_loop())},
  162. browser_{std::make_unique<Browser>()} {
  163. DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
  164. self_ = this;
  165. }
  166. ElectronBrowserMainParts::~ElectronBrowserMainParts() = default;
  167. // static
  168. ElectronBrowserMainParts* ElectronBrowserMainParts::Get() {
  169. DCHECK(self_);
  170. return self_;
  171. }
  172. bool ElectronBrowserMainParts::SetExitCode(int code) {
  173. if (!exit_code_)
  174. return false;
  175. content::BrowserMainLoop::GetInstance()->SetResultCode(code);
  176. *exit_code_ = code;
  177. return true;
  178. }
  179. int ElectronBrowserMainParts::GetExitCode() const {
  180. return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT);
  181. }
  182. int ElectronBrowserMainParts::PreEarlyInitialization() {
  183. field_trial_list_ = std::make_unique<base::FieldTrialList>();
  184. #if BUILDFLAG(IS_POSIX)
  185. HandleSIGCHLD();
  186. #endif
  187. #if BUILDFLAG(IS_LINUX)
  188. DetectOzonePlatform();
  189. ui::OzonePlatform::PreEarlyInitialization();
  190. #endif
  191. #if BUILDFLAG(IS_MAC)
  192. screen_ = std::make_unique<display::ScopedNativeScreen>();
  193. #endif
  194. ui::ColorProviderManager::Get().AppendColorProviderInitializer(
  195. base::BindRepeating(AddChromeColorMixers));
  196. return GetExitCode();
  197. }
  198. void ElectronBrowserMainParts::PostEarlyInitialization() {
  199. // A workaround was previously needed because there was no ThreadTaskRunner
  200. // set. If this check is failing we may need to re-add that workaround
  201. DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault());
  202. // The ProxyResolverV8 has setup a complete V8 environment, in order to
  203. // avoid conflicts we only initialize our V8 environment after that.
  204. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
  205. v8::HandleScope scope(js_env_->isolate());
  206. node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext());
  207. // Create the global environment.
  208. node_env_ = node_bindings_->CreateEnvironment(
  209. js_env_->isolate()->GetCurrentContext(), js_env_->platform(),
  210. js_env_->max_young_generation_size_in_bytes());
  211. node_env_->set_trace_sync_io(node_env_->options()->trace_sync_io);
  212. // We do not want to crash the main process on unhandled rejections.
  213. node_env_->options()->unhandled_rejections = "warn-with-error-code";
  214. // Add Electron extended APIs.
  215. electron_bindings_->BindTo(js_env_->isolate(), node_env_->process_object());
  216. // Create explicit microtasks runner.
  217. js_env_->CreateMicrotasksRunner();
  218. // Wrap the uv loop with global env.
  219. node_bindings_->set_uv_env(node_env_.get());
  220. // Load everything.
  221. node_bindings_->LoadEnvironment(node_env_.get());
  222. // Wait for app
  223. node_bindings_->JoinAppCode();
  224. // We already initialized the feature list in PreEarlyInitialization(), but
  225. // the user JS script would not have had a chance to alter the command-line
  226. // switches at that point. Lets reinitialize it here to pick up the
  227. // command-line changes.
  228. base::FeatureList::ClearInstanceForTesting();
  229. InitializeFeatureList();
  230. // Initialize field trials.
  231. InitializeFieldTrials();
  232. // Reinitialize logging now that the app has had a chance to set the app name
  233. // and/or user data directory.
  234. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
  235. /* is_preinit = */ false);
  236. // Initialize after user script environment creation.
  237. fake_browser_process_->PostEarlyInitialization();
  238. }
  239. int ElectronBrowserMainParts::PreCreateThreads() {
  240. if (!views::LayoutProvider::Get()) {
  241. layout_provider_ = std::make_unique<views::LayoutProvider>();
  242. }
  243. // Fetch the system locale for Electron.
  244. #if BUILDFLAG(IS_MAC)
  245. fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale());
  246. #else
  247. fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale());
  248. #endif
  249. auto* command_line = base::CommandLine::ForCurrentProcess();
  250. std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
  251. #if BUILDFLAG(IS_MAC)
  252. // The browser process only wants to support the language Cocoa will use,
  253. // so force the app locale to be overridden with that value. This must
  254. // happen before the ResourceBundle is loaded
  255. if (locale.empty())
  256. l10n_util::OverrideLocaleWithCocoaLocale();
  257. #elif BUILDFLAG(IS_LINUX)
  258. // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(),
  259. // which keys off of getenv("LC_ALL").
  260. // We must set this env first to make ui::ResourceBundle accept the custom
  261. // locale.
  262. auto env = base::Environment::Create();
  263. std::optional<std::string> lc_all;
  264. if (!locale.empty()) {
  265. std::string str;
  266. if (env->GetVar("LC_ALL", &str))
  267. lc_all.emplace(std::move(str));
  268. env->SetVar("LC_ALL", locale);
  269. }
  270. #endif
  271. // Load resources bundle according to locale.
  272. std::string loaded_locale = LoadResourceBundle(locale);
  273. #if defined(USE_AURA)
  274. // NB: must be called _after_ locale resource bundle is loaded,
  275. // because ui lib makes use of it in X11
  276. if (!display::Screen::GetScreen()) {
  277. screen_ = views::CreateDesktopScreen();
  278. }
  279. #endif
  280. // Initialize the app locale for Electron and Chromium.
  281. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale);
  282. ElectronBrowserClient::SetApplicationLocale(app_locale);
  283. fake_browser_process_->SetApplicationLocale(app_locale);
  284. #if BUILDFLAG(IS_LINUX)
  285. // Reset to the original LC_ALL since we should not be changing it.
  286. if (!locale.empty()) {
  287. if (lc_all)
  288. env->SetVar("LC_ALL", *lc_all);
  289. else
  290. env->UnSetVar("LC_ALL");
  291. }
  292. #endif
  293. // Force MediaCaptureDevicesDispatcher to be created on UI thread.
  294. MediaCaptureDevicesDispatcher::GetInstance();
  295. #if BUILDFLAG(IS_MAC)
  296. ui::InitIdleMonitor();
  297. Browser::Get()->ApplyForcedRTL();
  298. #endif
  299. fake_browser_process_->PreCreateThreads();
  300. // Notify observers.
  301. Browser::Get()->PreCreateThreads();
  302. return 0;
  303. }
  304. void ElectronBrowserMainParts::PostCreateThreads() {
  305. content::GetIOThreadTaskRunner({})->PostTask(
  306. FROM_HERE,
  307. base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
  308. #if BUILDFLAG(ENABLE_PLUGINS)
  309. // PluginService can only be used on the UI thread
  310. // and ContentClient::AddPlugins gets called for both browser and render
  311. // process where the latter will not have UI thread which leads to DCHECK.
  312. // Separate the WebPluginInfo registration for these processes.
  313. std::vector<content::WebPluginInfo> plugins;
  314. auto* plugin_service = content::PluginService::GetInstance();
  315. plugin_service->RefreshPlugins();
  316. GetInternalPlugins(&plugins);
  317. for (const auto& plugin : plugins)
  318. plugin_service->RegisterInternalPlugin(plugin, true);
  319. #endif
  320. }
  321. void ElectronBrowserMainParts::PostDestroyThreads() {
  322. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  323. extensions_browser_client_.reset();
  324. extensions::ExtensionsBrowserClient::Set(nullptr);
  325. #endif
  326. #if BUILDFLAG(IS_LINUX)
  327. device::BluetoothAdapterFactory::Shutdown();
  328. bluez::DBusBluezManagerWrapperLinux::Shutdown();
  329. #endif
  330. fake_browser_process_->PostDestroyThreads();
  331. }
  332. void ElectronBrowserMainParts::ToolkitInitialized() {
  333. #if BUILDFLAG(IS_LINUX)
  334. auto* linux_ui = ui::GetDefaultLinuxUi();
  335. CHECK(linux_ui);
  336. linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>();
  337. electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf());
  338. CHECK(electron::IsElectron_gdk_pixbufInitialized())
  339. << "Failed to initialize libgdk_pixbuf-2.0.so.0";
  340. // source theme changes from system settings, including settings portal:
  341. // https://flatpak.github.io/xdg-desktop-portal/#gdbus-org.freedesktop.portal.Settings
  342. dark_mode_manager_ = std::make_unique<ui::DarkModeManagerLinux>();
  343. ui::LinuxUi::SetInstance(linux_ui);
  344. // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager
  345. // implementation). Start observing them once it's initialized.
  346. ui::CursorFactory::GetInstance()->ObserveThemeChanges();
  347. #endif
  348. #if defined(USE_AURA)
  349. wm_state_ = std::make_unique<wm::WMState>();
  350. #endif
  351. #if BUILDFLAG(IS_WIN)
  352. gfx::win::SetAdjustFontCallback(&l10n_util::AdjustUiFont);
  353. gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
  354. #endif
  355. #if BUILDFLAG(IS_MAC)
  356. views_delegate_ = std::make_unique<ViewsDelegateMac>();
  357. #else
  358. views_delegate_ = std::make_unique<ViewsDelegate>();
  359. #endif
  360. }
  361. int ElectronBrowserMainParts::PreMainMessageLoopRun() {
  362. // Run user's main script before most things get initialized, so we can have
  363. // a chance to setup everything.
  364. node_bindings_->PrepareEmbedThread();
  365. node_bindings_->StartPolling();
  366. // url::Add*Scheme are not threadsafe, this helps prevent data races.
  367. url::LockSchemeRegistries();
  368. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  369. extensions_client_ = std::make_unique<ElectronExtensionsClient>();
  370. extensions::ExtensionsClient::Set(extensions_client_.get());
  371. // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient.
  372. extensions_browser_client_ =
  373. std::make_unique<ElectronExtensionsBrowserClient>();
  374. extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
  375. extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt();
  376. extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt();
  377. #endif
  378. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  379. SpellcheckServiceFactory::GetInstance();
  380. #endif
  381. content::WebUIControllerFactory::RegisterFactory(
  382. ElectronWebUIControllerFactory::GetInstance());
  383. auto* command_line = base::CommandLine::ForCurrentProcess();
  384. if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) {
  385. // --remote-debugging-pipe
  386. auto on_disconnect = base::BindOnce([]() {
  387. content::GetUIThreadTaskRunner({})->PostTask(
  388. FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); }));
  389. });
  390. content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
  391. std::move(on_disconnect));
  392. } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
  393. // --remote-debugging-port
  394. DevToolsManagerDelegate::StartHttpHandler();
  395. }
  396. #if !BUILDFLAG(IS_MAC)
  397. // The corresponding call in macOS is in ElectronApplicationDelegate.
  398. Browser::Get()->WillFinishLaunching();
  399. Browser::Get()->DidFinishLaunching(base::Value::Dict());
  400. #endif
  401. // Notify observers that main thread message loop was initialized.
  402. Browser::Get()->PreMainMessageLoopRun();
  403. fake_browser_process_->PreMainMessageLoopRun();
  404. #if BUILDFLAG(IS_WIN)
  405. ui::SelectFileDialog::SetFactory(
  406. std::make_unique<ChromeSelectFileDialogFactory>());
  407. #endif
  408. return GetExitCode();
  409. }
  410. void ElectronBrowserMainParts::WillRunMainMessageLoop(
  411. std::unique_ptr<base::RunLoop>& run_loop) {
  412. exit_code_ = content::RESULT_CODE_NORMAL_EXIT;
  413. Browser::Get()->SetMainMessageLoopQuitClosure(
  414. run_loop->QuitWhenIdleClosure());
  415. }
  416. void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
  417. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
  418. std::string app_name = electron::Browser::Get()->GetName();
  419. #endif
  420. #if BUILDFLAG(IS_LINUX)
  421. auto shutdown_cb =
  422. base::BindOnce([] { LOG(FATAL) << "Failed to shutdown."; });
  423. ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop(
  424. std::move(shutdown_cb),
  425. content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput}));
  426. if (!bluez::BluezDBusManager::IsInitialized())
  427. bluez::DBusBluezManagerWrapperLinux::Initialize();
  428. // Set up crypt config. This needs to be done before anything starts the
  429. // network service, as the raw encryption key needs to be shared with the
  430. // network service for encrypted cookie storage.
  431. const base::CommandLine& command_line =
  432. *base::CommandLine::ForCurrentProcess();
  433. std::unique_ptr<os_crypt::Config> config =
  434. std::make_unique<os_crypt::Config>();
  435. // Forward to os_crypt the flag to use a specific password store.
  436. config->store =
  437. command_line.GetSwitchValueASCII(password_manager::kPasswordStore);
  438. config->product_name = app_name;
  439. config->application_name = app_name;
  440. // c.f.
  441. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
  442. config->should_use_preference =
  443. command_line.HasSwitch(password_manager::kEnableEncryptionSelection);
  444. base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
  445. bool use_backend = !config->should_use_preference ||
  446. os_crypt::GetBackendUse(config->user_data_path);
  447. std::unique_ptr<base::Environment> env(base::Environment::Create());
  448. base::nix::DesktopEnvironment desktop_env =
  449. base::nix::GetDesktopEnvironment(env.get());
  450. os_crypt::SelectedLinuxBackend selected_backend =
  451. os_crypt::SelectBackend(config->store, use_backend, desktop_env);
  452. fake_browser_process_->SetLinuxStorageBackend(selected_backend);
  453. OSCrypt::SetConfig(std::move(config));
  454. #endif
  455. #if BUILDFLAG(IS_MAC)
  456. KeychainPassword::GetServiceName() = app_name + " Safe Storage";
  457. KeychainPassword::GetAccountName() = app_name;
  458. #endif
  459. #if BUILDFLAG(IS_POSIX)
  460. // Exit in response to SIGINT, SIGTERM, etc.
  461. InstallShutdownSignalHandlers(
  462. base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())),
  463. content::GetUIThreadTaskRunner({}));
  464. #endif
  465. }
  466. void ElectronBrowserMainParts::PostMainMessageLoopRun() {
  467. #if BUILDFLAG(IS_MAC)
  468. FreeAppDelegate();
  469. #endif
  470. // Shutdown the DownloadManager before destroying Node to prevent
  471. // DownloadItem callbacks from crashing.
  472. for (auto* browser_context : ElectronBrowserContext::BrowserContexts()) {
  473. if (auto* download_manager = browser_context->GetDownloadManager())
  474. download_manager->Shutdown();
  475. }
  476. // Shutdown utility process created with Electron API before
  477. // stopping Node.js so that exit events can be emitted. We don't let
  478. // content layer perform this action since it destroys
  479. // child process only after this step (PostMainMessageLoopRun) via
  480. // BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our
  481. // use case.
  482. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108
  483. //
  484. // The following logic is based on
  485. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159
  486. //
  487. // Although content::BrowserChildProcessHostIterator is only to be called from
  488. // IO thread, it is safe to call from PostMainMessageLoopRun because thread
  489. // restrictions have been lifted.
  490. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078
  491. for (content::BrowserChildProcessHostIterator it(
  492. content::PROCESS_TYPE_UTILITY);
  493. !it.Done(); ++it) {
  494. if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) {
  495. auto& process = it.GetData().GetProcess();
  496. if (!process.IsValid())
  497. continue;
  498. auto utility_process_wrapper =
  499. api::UtilityProcessWrapper::FromProcessId(process.Pid());
  500. if (utility_process_wrapper)
  501. utility_process_wrapper->Shutdown(0 /* exit_code */);
  502. }
  503. }
  504. // Destroy node platform after all destructors_ are executed, as they may
  505. // invoke Node/V8 APIs inside them.
  506. node_env_->set_trace_sync_io(false);
  507. js_env_->DestroyMicrotasksRunner();
  508. node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate);
  509. node_bindings_->set_uv_env(nullptr);
  510. node_env_.reset();
  511. ElectronBrowserContext::DestroyAllContexts();
  512. fake_browser_process_->PostMainMessageLoopRun();
  513. content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler();
  514. #if BUILDFLAG(IS_LINUX)
  515. ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun();
  516. #endif
  517. }
  518. #if !BUILDFLAG(IS_MAC)
  519. void ElectronBrowserMainParts::PreCreateMainMessageLoop() {
  520. PreCreateMainMessageLoopCommon();
  521. }
  522. #endif
  523. void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() {
  524. #if BUILDFLAG(IS_MAC)
  525. InitializeMainNib();
  526. RegisterURLHandler();
  527. #endif
  528. media::SetLocalizedStringProvider(MediaStringProvider);
  529. #if BUILDFLAG(IS_WIN)
  530. auto* local_state = g_browser_process->local_state();
  531. DCHECK(local_state);
  532. bool os_crypt_init = OSCrypt::Init(local_state);
  533. DCHECK(os_crypt_init);
  534. #endif
  535. }
  536. device::mojom::GeolocationControl*
  537. ElectronBrowserMainParts::GetGeolocationControl() {
  538. if (!geolocation_control_) {
  539. content::GetDeviceService().BindGeolocationControl(
  540. geolocation_control_.BindNewPipeAndPassReceiver());
  541. }
  542. return geolocation_control_.get();
  543. }
  544. IconManager* ElectronBrowserMainParts::GetIconManager() {
  545. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  546. if (!icon_manager_.get())
  547. icon_manager_ = std::make_unique<IconManager>();
  548. return icon_manager_.get();
  549. }
  550. } // namespace electron