chore: bump chromium to 141.0.7390.7 (main) (#48212)

* chore: bump chromium in DEPS to 141.0.7381.3

* chore: update patches

* chore: bump chromium in DEPS to 141.0.7382.0

* chore: update patches

* chore: bump chromium in DEPS to 141.0.7384.0

* chore: bump chromium in DEPS to 141.0.7386.0

* [Extensions] Move devtools_page and chrome_url_overrides handlers

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6862700

* Reland "[api] Advance deprecation of GetIsolate"

Refs https://chromium-review.googlesource.com/c/v8/v8/+/6875273

* Move "system integrated UI" concept out of NativeTheme.

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6867375

* chore: update patches

* Reland "[PermissionOptions] Return PermissionResult in callback for requests"

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6851838

* Reland "[exit-time-destructors] Enable by default"

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6859042

* chore: update patches

* [FSA] Revoke Read access after removing file via FileSystemAccess API

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6677249

* chore: IWYU

* [DevToolsUIBindings] Accept an object for `dispatchHttpRequest` params

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6877528

* chore: IWYU

* Pass navigation UI parameters on EnterFullscreen in EAM

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6874923

* chore: rm band-aid_over_an_issue_with_using_deprecated_nsopenpanel_api.patch

* Remove unused PreHandleMouseEvent

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6880411

* 6878583: siso: update to version 1.4.1

https://chromium-review.googlesource.com/c/chromium/src/+/6878583

* Fold native_theme_browser into native_theme.

https://chromium-review.googlesource.com/c/chromium/src/+/6882627

* fixup: Reland "[exit-time-destructors] Enable by default

https://chromium-review.googlesource.com/c/chromium/src/+/6859042

* chore: update filenames.libcxx.gni

* chore: IWYU

* fixup: chore: IWYU

* fixup: Reland "[exit-time-destructors] Enable by default

* fixup: Reland "[exit-time-destructors] Enable by default

* Remove common_theme.*; place its method in NativeTheme instead.

https://chromium-review.googlesource.com/c/chromium/src/+/6886029

* fixup: Reland "[exit-time-destructors] Enable by default

* Better track when WebPreferences need updates for color-related changes.

Refs https://chromium-review.googlesource.com/c/chromium/src/+/6886797

* chore: bump chromium in DEPS to 141.0.7390.7

* 6904664: Reland "Make BrowserContext::GetPath() const"

https://chromium-review.googlesource.com/c/chromium/src/+/6904664

* Restore read access after certain file modification operations

https://chromium-review.googlesource.com/c/chromium/src/+/6861041

* fixup: Move "system integrated UI" concept out of NativeTheme.

* fixup: Reland "[exit-time-destructors] Enable by default

* chore: update patches

* 6906096: Remove GetSysSkColor().

https://chromium-review.googlesource.com/c/chromium/src/+/6906096

* Inline implementation of SysColorChangeListener into the lone user.

https://chromium-review.googlesource.com/c/chromium/src/+/6905083

Also 6906096: Remove GetSysSkColor(). | https://chromium-review.googlesource.com/c/chromium/src/+/6906096

* fixup: 6906096: Remove GetSysSkColor()

---------

Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: deepak1556 <hop2deep@gmail.com>
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
This commit is contained in:
electron-roller[bot]
2025-09-08 12:57:15 +02:00
committed by GitHub
parent 1f322ebce3
commit 793565e4be
157 changed files with 1418 additions and 883 deletions

View File

@@ -369,9 +369,6 @@ namespace electron::api {
gin::WrapperInfo App::kWrapperInfo = {{gin::kEmbedderNativeGin},
gin::kElectronApp};
// static
cppgc::Persistent<App> App::instance_;
namespace {
IconLoader::IconSize GetIconSizeByString(const std::string& size) {
@@ -1701,17 +1698,15 @@ void ConfigureHostResolver(v8::Isolate* isolate,
// static
App* App::Get() {
CHECK_NE(instance_, nullptr);
return instance_.Get();
return Create(nullptr);
}
// static
App* App::Create(v8::Isolate* isolate) {
if (!instance_) {
instance_ = cppgc::MakeGarbageCollected<App>(
isolate->GetCppHeap()->GetAllocationHandle());
}
return instance_.Get();
static base::NoDestructor<cppgc::Persistent<App>> instance(
cppgc::MakeGarbageCollected<App>(
isolate->GetCppHeap()->GetAllocationHandle()));
return instance->Get();
}
const gin::WrapperInfo* App::wrapper_info() const {

View File

@@ -282,8 +282,6 @@ class App final : public gin::Wrappable<App>,
bool watch_singleton_socket_on_ready_ = false;
std::unique_ptr<content::ScopedAccessibilityMode> scoped_accessibility_mode_;
static cppgc::Persistent<App> instance_;
};
} // namespace api

View File

@@ -25,6 +25,12 @@ NativeTheme::NativeTheme(v8::Isolate* isolate,
ui::NativeTheme* web_theme)
: ui_theme_(ui_theme), web_theme_(web_theme) {
ui_theme_->AddObserver(this);
#if BUILDFLAG(IS_WIN)
std::ignore = hkcu_themes_regkey_.Open(HKEY_CURRENT_USER,
L"Software\\Microsoft\\Windows\\"
L"CurrentVersion\\Themes\\Personalize",
KEY_READ);
#endif
}
NativeTheme::~NativeTheme() {
@@ -32,6 +38,16 @@ NativeTheme::~NativeTheme() {
}
void NativeTheme::OnNativeThemeUpdatedOnUI() {
#if BUILDFLAG(IS_WIN)
if (hkcu_themes_regkey_.Valid()) {
DWORD system_uses_light_theme = 1;
hkcu_themes_regkey_.ReadValueDW(L"SystemUsesLightTheme",
&system_uses_light_theme);
bool system_dark_mode_enabled = (system_uses_light_theme == 0);
should_use_dark_colors_for_system_integrated_ui_ =
std::make_optional<bool>(system_dark_mode_enabled);
}
#endif
Emit("updated");
}
@@ -65,7 +81,8 @@ bool NativeTheme::ShouldUseHighContrastColors() {
}
bool NativeTheme::ShouldUseDarkColorsForSystemIntegratedUI() {
return ui_theme_->ShouldUseDarkColorsForSystemIntegratedUI();
return should_use_dark_colors_for_system_integrated_ui_.value_or(
ShouldUseDarkColors());
}
bool NativeTheme::InForcedColorsMode() {

View File

@@ -11,6 +11,10 @@
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/native_theme_observer.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/registry.h"
#endif
namespace gin_helper {
template <typename T>
class Handle;
@@ -58,6 +62,11 @@ class NativeTheme final : public gin_helper::DeprecatedWrappable<NativeTheme>,
void OnNativeThemeUpdatedOnUI();
private:
#if BUILDFLAG(IS_WIN)
base::win::RegKey hkcu_themes_regkey_;
#endif
std::optional<bool> should_use_dark_colors_for_system_integrated_ui_ =
std::nullopt;
raw_ptr<ui::NativeTheme> ui_theme_;
raw_ptr<ui::NativeTheme> web_theme_;
};

View File

@@ -9,6 +9,7 @@
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/no_destructor.h"
#include "content/common/url_schemes.h"
#include "content/public/browser/child_process_security_policy.h"
#include "gin/object_template_builder.h"
@@ -28,15 +29,6 @@
namespace {
// List of registered custom standard schemes.
std::vector<std::string> g_standard_schemes;
// List of registered custom streaming schemes.
std::vector<std::string> g_streaming_schemes;
// Schemes that support V8 code cache.
std::vector<std::string> g_code_cache_schemes;
struct SchemeOptions {
bool standard = false;
bool secure = false;
@@ -89,12 +81,19 @@ namespace electron::api {
gin::DeprecatedWrapperInfo Protocol::kWrapperInfo = {gin::kEmbedderNativeGin};
const std::vector<std::string>& GetStandardSchemes() {
return g_standard_schemes;
std::vector<std::string>& GetStandardSchemes() {
static base::NoDestructor<std::vector<std::string>> g_standard_schemes;
return *g_standard_schemes;
}
const std::vector<std::string>& GetCodeCacheSchemes() {
return g_code_cache_schemes;
std::vector<std::string>& GetCodeCacheSchemes() {
static base::NoDestructor<std::vector<std::string>> g_code_cache_schemes;
return *g_code_cache_schemes;
}
std::vector<std::string>& GetStreamingSchemes() {
static base::NoDestructor<std::vector<std::string>> g_streaming_schemes;
return *g_streaming_schemes;
}
void AddServiceWorkerScheme(const std::string& scheme) {
@@ -132,7 +131,7 @@ void RegisterSchemesAsPrivileged(gin_helper::ErrorThrower thrower,
auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
url::AddStandardScheme(custom_scheme.scheme.c_str(),
url::SCHEME_WITH_HOST);
g_standard_schemes.push_back(custom_scheme.scheme);
GetStandardSchemes().push_back(custom_scheme.scheme);
policy->RegisterWebSafeScheme(custom_scheme.scheme);
}
if (custom_scheme.options.secure) {
@@ -155,10 +154,10 @@ void RegisterSchemesAsPrivileged(gin_helper::ErrorThrower thrower,
AddServiceWorkerScheme(custom_scheme.scheme);
}
if (custom_scheme.options.stream) {
g_streaming_schemes.push_back(custom_scheme.scheme);
GetStreamingSchemes().push_back(custom_scheme.scheme);
}
if (custom_scheme.options.codeCache) {
g_code_cache_schemes.push_back(custom_scheme.scheme);
GetCodeCacheSchemes().push_back(custom_scheme.scheme);
url::AddCodeCacheScheme(custom_scheme.scheme.c_str());
}
}
@@ -181,11 +180,11 @@ void RegisterSchemesAsPrivileged(gin_helper::ErrorThrower thrower,
AppendSchemesToCmdLine(electron::switches::kServiceWorkerSchemes,
service_worker_schemes);
AppendSchemesToCmdLine(electron::switches::kStandardSchemes,
g_standard_schemes);
GetStandardSchemes());
AppendSchemesToCmdLine(electron::switches::kStreamingSchemes,
g_streaming_schemes);
GetStreamingSchemes());
AppendSchemesToCmdLine(electron::switches::kCodeCacheSchemes,
g_code_cache_schemes);
GetCodeCacheSchemes());
}
namespace {

View File

@@ -29,8 +29,8 @@ class ProtocolRegistry;
namespace api {
const std::vector<std::string>& GetStandardSchemes();
const std::vector<std::string>& GetCodeCacheSchemes();
std::vector<std::string>& GetStandardSchemes();
std::vector<std::string>& GetCodeCacheSchemes();
void AddServiceWorkerScheme(const std::string& scheme);

View File

@@ -8,6 +8,7 @@
#include <memory>
#include <string>
#include "base/functional/bind.h"
#include "base/values.h"
#include "shell/browser/event_emitter_mixin.h"
#include "shell/common/gin_helper/wrappable.h"
@@ -15,7 +16,7 @@
#if BUILDFLAG(IS_WIN)
#include "shell/browser/browser.h"
#include "shell/browser/browser_observer.h"
#include "ui/gfx/sys_color_change_listener.h"
#include "ui/gfx/win/singleton_hwnd_observer.h"
#endif
namespace gin_helper {
@@ -42,8 +43,7 @@ class SystemPreferences final
public gin_helper::EventEmitterMixin<SystemPreferences>
#if BUILDFLAG(IS_WIN)
,
public BrowserObserver,
public gfx::SysColorChangeListener
public BrowserObserver
#endif
{
public:
@@ -65,8 +65,8 @@ class SystemPreferences final
#if BUILDFLAG(IS_WIN)
void InitializeWindow();
// gfx::SysColorChangeListener:
void OnSysColorChange() override;
// Called by `singleton_hwnd_observer_`.
void OnWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
// BrowserObserver:
void OnFinishLaunching(base::Value::Dict launch_info) override;
@@ -159,7 +159,8 @@ class SystemPreferences final
std::string current_color_;
std::unique_ptr<gfx::ScopedSysColorChangeListener> color_change_listener_;
// Color/high contrast mode change observer.
std::unique_ptr<gfx::SingletonHwndObserver> singleton_hwnd_observer_;
#endif
};

View File

@@ -14,6 +14,7 @@
#include "base/apple/scoped_cftyperef.h"
#include "base/containers/flat_map.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/values.h"
@@ -80,7 +81,10 @@ namespace {
int g_next_id = 0;
// The map to convert |id| to |int|.
base::flat_map<int, id> g_id_map;
auto& GetIdMap() {
static base::NoDestructor<base::flat_map<int, id>> g_id_map;
return *g_id_map;
}
AVMediaType ParseMediaType(const std::string& media_type) {
if (media_type == "camera") {
@@ -214,7 +218,7 @@ int SystemPreferences::DoSubscribeNotification(
auto* name = maybe_name->IsNull() ? nil : base::SysUTF8ToNSString(name_str);
g_id_map[request_id] = [GetNotificationCenter(kind)
GetIdMap()[request_id] = [GetNotificationCenter(kind)
addObserverForName:name
object:nil
queue:nil
@@ -240,11 +244,11 @@ int SystemPreferences::DoSubscribeNotification(
void SystemPreferences::DoUnsubscribeNotification(int request_id,
NotificationCenterKind kind) {
auto iter = g_id_map.find(request_id);
if (iter != g_id_map.end()) {
auto iter = GetIdMap().find(request_id);
if (iter != GetIdMap().end()) {
id observer = iter->second;
[GetNotificationCenter(kind) removeObserver:observer];
g_id_map.erase(iter);
GetIdMap().erase(iter);
}
}

View File

@@ -16,7 +16,6 @@
#include "base/win/wrapped_window_proc.h"
#include "shell/common/color_util.h"
#include "shell/common/process_util.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/win/hwnd_util.h"
namespace electron {
@@ -127,7 +126,7 @@ std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower,
});
if (auto iter = Lookup.find(color); iter != Lookup.end())
return ToRGBAHex(color_utils::GetSysSkColor(iter->second));
return ToRGBAHex(GetSysSkColor(iter->second));
thrower.ThrowError("Unknown color: " + color);
return "";
@@ -158,8 +157,9 @@ void SystemPreferences::InitializeWindow() {
// Creating this listener before the app is ready causes global shortcuts
// to not fire
if (Browser::Get()->is_ready())
color_change_listener_ =
std::make_unique<gfx::ScopedSysColorChangeListener>(this);
singleton_hwnd_observer_ =
std::make_unique<gfx::SingletonHwndObserver>(base::BindRepeating(
&SystemPreferences::OnWndProc, base::Unretained(this)));
else
Browser::Get()->AddObserver(this);
@@ -208,13 +208,21 @@ LRESULT CALLBACK SystemPreferences::WndProc(HWND hwnd,
return ::DefWindowProc(hwnd, message, wparam, lparam);
}
void SystemPreferences::OnSysColorChange() {
void SystemPreferences::OnWndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message != WM_SYSCOLORCHANGE &&
(message != WM_SETTINGCHANGE || wparam != SPI_SETHIGHCONTRAST)) {
return;
}
Emit("color-changed");
}
void SystemPreferences::OnFinishLaunching(base::Value::Dict launch_info) {
color_change_listener_ =
std::make_unique<gfx::ScopedSysColorChangeListener>(this);
singleton_hwnd_observer_ =
std::make_unique<gfx::SingletonHwndObserver>(base::BindRepeating(
&SystemPreferences::OnWndProc, base::Unretained(this)));
}
} // namespace api

View File

@@ -1434,7 +1434,7 @@ bool WebContents::IsFullscreen() const {
void WebContents::EnterFullscreen(const url::Origin& origin,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
FullscreenTabParams fullscreen_tab_params) {}
content::WebContents* WebContents::GetWebContentsForExclusiveAccess() {
return web_contents();
@@ -1480,7 +1480,7 @@ void WebContents::OnEnterFullscreenModeForTab(
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
requesting_frame, FullscreenTabParams{options.display_id});
SetHtmlApiFullscreen(true);

View File

@@ -697,7 +697,7 @@ class WebContents final : public ExclusiveAccessContext,
bool IsFullscreen() const override;
void EnterFullscreen(const url::Origin& origin,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) override;
FullscreenTabParams fullscreen_tab_params) override;
void ExitFullscreen() override {}
void UpdateExclusiveAccessBubble(
const ExclusiveAccessBubbleParams& params,

View File

@@ -6,6 +6,7 @@
#include <utility>
#include "content/public/browser/page.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"

View File

@@ -4,6 +4,7 @@
#include "shell/browser/auto_updater.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "electron/mas.h"
@@ -19,11 +20,12 @@ void AutoUpdater::SetDelegate(Delegate* delegate) {
delegate_ = delegate;
}
#if !BUILDFLAG(IS_MAC) || IS_MAS_BUILD()
std::string AutoUpdater::GetFeedURL() {
return "";
std::string& AutoUpdater::GetFeedURL() {
static base::NoDestructor<std::string> feed_url;
return *feed_url;
}
#if !BUILDFLAG(IS_MAC) || IS_MAS_BUILD()
void AutoUpdater::SetFeedURL(gin::Arguments* args) {}
void AutoUpdater::CheckForUpdates() {}

View File

@@ -60,7 +60,7 @@ class AutoUpdater {
static Delegate* GetDelegate();
static void SetDelegate(Delegate* delegate);
static std::string GetFeedURL();
static std::string& GetFeedURL();
// FIXME(zcbenz): We should not do V8 in this file, this method should only
// accept C++ struct as parameter, and atom_api_auto_updater.cc is responsible
// for parsing the parameter from JavaScript.

View File

@@ -26,20 +26,10 @@ namespace {
// The global SQRLUpdater object.
SQRLUpdater* __strong g_updater = nil;
} // namespace
namespace {
bool g_update_available = false;
std::string update_url_ = ""; // NOLINT(runtime/string)
} // namespace
std::string AutoUpdater::GetFeedURL() {
return update_url_;
}
// static
void AutoUpdater::SetFeedURL(gin::Arguments* args) {
gin_helper::ErrorThrower thrower(args->isolate());
@@ -76,7 +66,7 @@ void AutoUpdater::SetFeedURL(gin::Arguments* args) {
if (!delegate)
return;
update_url_ = feed;
GetFeedURL() = feed;
NSURL* url = [NSURL URLWithString:base::SysUTF8ToNSString(feed)];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];

View File

@@ -441,6 +441,20 @@ void ElectronBrowserClient::OverrideWebPreferences(
}
}
bool ElectronBrowserClient::WebPreferencesNeedUpdateForColorRelatedStateChanges(
content::WebContents& web_contents,
const content::SiteInstance& main_frame_site) const {
const auto& prefs = web_contents.GetOrCreateWebPreferences();
ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi();
bool in_forced_colors = native_theme->InForcedColorsMode();
blink::mojom::PreferredColorScheme preferred_color_scheme =
native_theme->ShouldUseDarkColors()
? blink::mojom::PreferredColorScheme::kDark
: blink::mojom::PreferredColorScheme::kLight;
return prefs.in_forced_colors != in_forced_colors ||
prefs.preferred_color_scheme != preferred_color_scheme;
}
void ElectronBrowserClient::RegisterPendingSiteInstance(
content::RenderFrameHost* rfh,
content::SiteInstance* pending_site_instance) {

View File

@@ -133,6 +133,9 @@ class ElectronBrowserClient : public content::ContentBrowserClient,
void OverrideWebPreferences(content::WebContents* web_contents,
content::SiteInstance& main_frame_site,
blink::web_pref::WebPreferences* prefs) override;
bool WebPreferencesNeedUpdateForColorRelatedStateChanges(
content::WebContents& web_contents,
const content::SiteInstance& main_frame_site) const override;
void RegisterPendingSiteInstance(
content::RenderFrameHost* render_frame_host,
content::SiteInstance* pending_site_instance) override;

View File

@@ -499,7 +499,7 @@ void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) {
user_agent_ = user_agent;
}
base::FilePath ElectronBrowserContext::GetPath() {
base::FilePath ElectronBrowserContext::GetPath() const {
return path_;
}

View File

@@ -94,7 +94,7 @@ class ElectronBrowserContext : public content::BrowserContext {
std::string GetMediaDeviceIDSalt();
// content::BrowserContext:
base::FilePath GetPath() override;
base::FilePath GetPath() const override;
bool IsOffTheRecord() override;
std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
const base::FilePath& partition_path) override;

View File

@@ -46,7 +46,7 @@ bool WebContentsDestroyed(content::RenderFrameHost* rfh) {
void PermissionRequestResponseCallbackWrapper(
ElectronPermissionManager::StatusCallback callback,
const std::vector<blink::mojom::PermissionStatus>& vector) {
const std::vector<content::PermissionResult>& vector) {
std::move(callback).Run(vector[0]);
}
@@ -60,7 +60,10 @@ class ElectronPermissionManager::PendingRequest {
: render_frame_host_id_(render_frame_host->GetGlobalId()),
callback_(std::move(callback)),
permissions_(std::move(permissions)),
results_(permissions_.size(), blink::mojom::PermissionStatus::DENIED),
results_(permissions_.size(),
content::PermissionResult(
blink::mojom::PermissionStatus::DENIED,
content::PermissionStatusSource::UNSPECIFIED)),
remaining_results_(permissions_.size()) {}
void SetPermissionStatus(int permission_id,
@@ -80,7 +83,8 @@ class ElectronPermissionManager::PendingRequest {
}
}
results_[permission_id] = status;
results_[permission_id] = content::PermissionResult(
status, content::PermissionStatusSource::UNSPECIFIED);
--remaining_results_;
}
@@ -100,7 +104,7 @@ class ElectronPermissionManager::PendingRequest {
content::GlobalRenderFrameHostId render_frame_host_id_;
StatusesCallback callback_;
std::vector<blink::mojom::PermissionDescriptorPtr> permissions_;
std::vector<blink::mojom::PermissionStatus> results_;
std::vector<content::PermissionResult> results_;
size_t remaining_results_;
};
@@ -150,7 +154,10 @@ void ElectronPermissionManager::RequestPermissionWithDetails(
base::Value::Dict details,
StatusCallback response_callback) {
if (render_frame_host->IsNestedWithinFencedFrame()) {
std::move(response_callback).Run(blink::mojom::PermissionStatus::DENIED);
std::move(response_callback)
.Run(content::PermissionResult(
blink::mojom::PermissionStatus::DENIED,
content::PermissionStatusSource::UNSPECIFIED));
return;
}
@@ -168,9 +175,11 @@ void ElectronPermissionManager::RequestPermissions(
const content::PermissionRequestDescription& request_description,
StatusesCallback callback) {
if (render_frame_host->IsNestedWithinFencedFrame()) {
std::move(callback).Run(std::vector<blink::mojom::PermissionStatus>(
std::move(callback).Run(std::vector<content::PermissionResult>(
request_description.permissions.size(),
blink::mojom::PermissionStatus::DENIED));
content::PermissionResult(
blink::mojom::PermissionStatus::DENIED,
content::PermissionStatusSource::UNSPECIFIED)));
return;
}
@@ -194,7 +203,7 @@ void ElectronPermissionManager::RequestPermissionsWithDetails(
});
if (request_handler_.is_null()) {
std::vector<blink::mojom::PermissionStatus> statuses;
std::vector<content::PermissionResult> results;
for (const auto& permission : permissions) {
const auto permission_type =
blink::PermissionDescriptorToPermissionType(permission);
@@ -207,9 +216,11 @@ void ElectronPermissionManager::RequestPermissionsWithDetails(
->GetGeolocationControl()
->UserDidOptIntoLocationServices();
}
statuses.push_back(blink::mojom::PermissionStatus::GRANTED);
results.push_back(content::PermissionResult(
blink::mojom::PermissionStatus::GRANTED,
content::PermissionStatusSource::UNSPECIFIED));
}
std::move(response_callback).Run(statuses);
std::move(response_callback).Run(results);
return;
}
@@ -235,12 +246,12 @@ void ElectronPermissionManager::RequestPermissionsWithDetails(
void ElectronPermissionManager::OnPermissionResponse(
int request_id,
int permission_id,
blink::mojom::PermissionStatus status) {
content::PermissionResult result) {
auto* pending_request = pending_requests_.Lookup(request_id);
if (!pending_request)
return;
pending_request->SetPermissionStatus(permission_id, status);
pending_request->SetPermissionStatus(permission_id, result.status);
if (pending_request->IsComplete()) {
pending_request->RunCallback();
pending_requests_.Remove(request_id);
@@ -255,12 +266,14 @@ void ElectronPermissionManager::ResetPermission(
void ElectronPermissionManager::RequestPermissionsFromCurrentDocument(
content::RenderFrameHost* render_frame_host,
const content::PermissionRequestDescription& request_description,
base::OnceCallback<void(const std::vector<blink::mojom::PermissionStatus>&)>
base::OnceCallback<void(const std::vector<content::PermissionResult>&)>
callback) {
if (render_frame_host->IsNestedWithinFencedFrame()) {
std::move(callback).Run(std::vector<blink::mojom::PermissionStatus>(
std::move(callback).Run(std::vector<content::PermissionResult>(
request_description.permissions.size(),
blink::mojom::PermissionStatus::DENIED));
content::PermissionResult(
blink::mojom::PermissionStatus::DENIED,
content::PermissionStatusSource::UNSPECIFIED)));
return;
}

View File

@@ -43,10 +43,9 @@ class ElectronPermissionManager : public content::PermissionControllerDelegate {
using USBProtectedClasses = std::vector<uint8_t>;
using StatusCallback =
base::OnceCallback<void(blink::mojom::PermissionStatus)>;
using StatusesCallback = base::OnceCallback<void(
const std::vector<blink::mojom::PermissionStatus>&)>;
using StatusCallback = base::OnceCallback<void(content::PermissionResult)>;
using StatusesCallback =
base::OnceCallback<void(const std::vector<content::PermissionResult>&)>;
using PairCallback = base::OnceCallback<void(base::Value::Dict)>;
using RequestHandler = base::RepeatingCallback<void(content::WebContents*,
blink::PermissionType,
@@ -111,7 +110,7 @@ class ElectronPermissionManager : public content::PermissionControllerDelegate {
protected:
void OnPermissionResponse(int request_id,
int permission_id,
blink::mojom::PermissionStatus status);
content::PermissionResult result);
// content::PermissionControllerDelegate:
void RequestPermissions(
@@ -128,9 +127,8 @@ class ElectronPermissionManager : public content::PermissionControllerDelegate {
void RequestPermissionsFromCurrentDocument(
content::RenderFrameHost* render_frame_host,
const content::PermissionRequestDescription& request_description,
base::OnceCallback<
void(const std::vector<blink::mojom::PermissionStatus>&)> callback)
override;
base::OnceCallback<void(const std::vector<content::PermissionResult>&)>
callback) override;
content::PermissionResult GetPermissionResultForOriginWithoutContext(
const blink::mojom::PermissionDescriptorPtr& permission_descriptor,
const url::Origin& requesting_origin,

View File

@@ -12,7 +12,6 @@
#include "base/path_service.h"
#include "chrome/browser/extensions/chrome_url_request_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/chrome_manifest_url_handlers.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
@@ -32,6 +31,8 @@
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/chrome_url_overrides_handler.h"
#include "extensions/common/manifest_handlers/devtools_page_handler.h"
#include "extensions/common/manifest_url_handlers.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "shell/browser/browser.h"

View File

@@ -415,10 +415,10 @@ class FileSystemAccessPermissionContext::PermissionGrantImpl
private:
void OnPermissionRequestResult(
base::OnceCallback<void(PermissionRequestOutcome)> callback,
blink::mojom::PermissionStatus status) {
content::PermissionResult result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (status == blink::mojom::PermissionStatus::GRANTED) {
if (result.status == blink::mojom::PermissionStatus::GRANTED) {
SetStatus(PermissionStatus::GRANTED);
std::move(callback).Run(PermissionRequestOutcome::kUserGranted);
} else {
@@ -916,6 +916,14 @@ void FileSystemAccessPermissionContext::NotifyEntryMoved(
}
}
void FileSystemAccessPermissionContext::NotifyEntryModified(
const url::Origin& origin,
const content::PathInfo& path) {}
void FileSystemAccessPermissionContext::NotifyEntryRemoved(
const url::Origin& origin,
const content::PathInfo& path) {}
void FileSystemAccessPermissionContext::OnFileCreatedFromShowSaveFilePicker(
const GURL& file_picker_binding_context,
const storage::FileSystemURL& url) {}

View File

@@ -102,6 +102,10 @@ class FileSystemAccessPermissionContext
void NotifyEntryMoved(const url::Origin& origin,
const content::PathInfo& old_path,
const content::PathInfo& new_path) override;
void NotifyEntryModified(const url::Origin& origin,
const content::PathInfo& path) override;
void NotifyEntryRemoved(const url::Origin& origin,
const content::PathInfo& path) override;
void OnFileCreatedFromShowSaveFilePicker(
const GURL& file_picker_binding_context,

View File

@@ -308,7 +308,7 @@ auto MakeDefaultFontCopier() {
namespace electron {
void SetFontDefaults(blink::web_pref::WebPreferences* prefs) {
static const auto copy_default_fonts_to_web_prefs = MakeDefaultFontCopier();
static const auto& copy_default_fonts_to_web_prefs = MakeDefaultFontCopier();
copy_default_fonts_to_web_prefs(prefs);
}

View File

@@ -85,7 +85,6 @@
#include "shell/common/color_util.h"
#include "skia/ext/skia_utils_win.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/win/hwnd_util.h"
#include "ui/gfx/win/msg_util.h"
#endif
@@ -216,8 +215,8 @@ NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
if (transparent())
thick_frame_ = false;
overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE);
overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT);
overlay_button_color_ = GetSysSkColor(COLOR_BTNFACE);
overlay_symbol_color_ = GetSysSkColor(COLOR_BTNTEXT);
if (std::string str; options.Get(options::kAccentColor, &str)) {
std::optional<SkColor> parsed_color = ParseCSSColor(str);

View File

@@ -12,6 +12,7 @@
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "shell/browser/ui/views/root_view.h"
#include "third_party/abseil-cpp/absl/container/flat_hash_set.h"
#include "ui/base/ozone_buildflags.h"
@@ -302,7 +303,8 @@ class NativeWindowViews : public NativeWindow,
base::win::ScopedGDIObject<HICON> app_icon_;
// The set of windows currently forwarding mouse messages.
static inline absl::flat_hash_set<NativeWindowViews*> forwarding_windows_;
static inline base::NoDestructor<absl::flat_hash_set<NativeWindowViews*>>
forwarding_windows_;
static HHOOK mouse_hook_;
bool forwarding_mouse_messages_ = false;
HWND legacy_window_ = nullptr;

View File

@@ -663,7 +663,7 @@ void NativeWindowViews::SetRoundedCorners(bool rounded) {
void NativeWindowViews::SetForwardMouseMessages(bool forward) {
if (forward && !forwarding_mouse_messages_) {
forwarding_mouse_messages_ = true;
forwarding_windows_.insert(this);
forwarding_windows_->insert(this);
// Subclassing is used to fix some issues when forwarding mouse messages;
// see comments in |SubclassProc|.
@@ -675,11 +675,11 @@ void NativeWindowViews::SetForwardMouseMessages(bool forward) {
}
} else if (!forward && forwarding_mouse_messages_) {
forwarding_mouse_messages_ = false;
forwarding_windows_.erase(this);
forwarding_windows_->erase(this);
RemoveWindowSubclass(legacy_window_, SubclassProc, 1);
if (forwarding_windows_.empty()) {
if (forwarding_windows_->empty()) {
UnhookWindowsHookEx(mouse_hook_);
mouse_hook_ = nullptr;
}
@@ -726,7 +726,7 @@ LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code,
// the cursor since they are in a state where they would otherwise ignore all
// mouse input.
if (w_param == WM_MOUSEMOVE) {
for (auto* window : forwarding_windows_) {
for (auto* window : *forwarding_windows_) {
// At first I considered enumerating windows to check whether the cursor
// was directly above the window, but since nothing bad seems to happen
// if we post the message even if some other window occludes it I have

View File

@@ -10,6 +10,7 @@
#include "base/files/file_enumerator.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/process/process_handle.h"
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/notifications/notification_delegate.h"
@@ -22,17 +23,20 @@ namespace electron {
namespace {
LibNotifyLoader libnotify_loader_;
LibNotifyLoader& GetLibNotifyLoader() {
static base::NoDestructor<LibNotifyLoader> loader;
return *loader;
}
const base::flat_set<std::string>& GetServerCapabilities() {
static base::flat_set<std::string> caps;
if (caps.empty()) {
auto* capabilities = libnotify_loader_.notify_get_server_caps();
static base::NoDestructor<base::flat_set<std::string>> caps;
if (caps->empty()) {
auto* capabilities = GetLibNotifyLoader().notify_get_server_caps();
for (auto* l = capabilities; l != nullptr; l = l->next)
caps.insert(static_cast<const char*>(l->data));
caps->insert(static_cast<const char*>(l->data));
g_list_free_full(capabilities, g_free);
}
return caps;
return *caps;
}
bool HasCapability(const std::string& capability) {
@@ -57,15 +61,15 @@ void log_and_clear_error(GError* error, const char* context) {
// static
bool LibnotifyNotification::Initialize() {
if (!libnotify_loader_.Load("libnotify.so.4") && // most common one
!libnotify_loader_.Load("libnotify.so.5") &&
!libnotify_loader_.Load("libnotify.so.1") &&
!libnotify_loader_.Load("libnotify.so")) {
if (!GetLibNotifyLoader().Load("libnotify.so.4") && // most common one
!GetLibNotifyLoader().Load("libnotify.so.5") &&
!GetLibNotifyLoader().Load("libnotify.so.1") &&
!GetLibNotifyLoader().Load("libnotify.so")) {
LOG(WARNING) << "Unable to find libnotify; notifications disabled";
return false;
}
if (!libnotify_loader_.notify_is_initted() &&
!libnotify_loader_.notify_init(GetApplicationName().c_str())) {
if (!GetLibNotifyLoader().notify_is_initted() &&
!GetLibNotifyLoader().notify_init(GetApplicationName().c_str())) {
LOG(WARNING) << "Unable to initialize libnotify; notifications disabled";
return false;
}
@@ -84,7 +88,7 @@ LibnotifyNotification::~LibnotifyNotification() {
}
void LibnotifyNotification::Show(const NotificationOptions& options) {
notification_ = libnotify_loader_.notify_notification_new(
notification_ = GetLibNotifyLoader().notify_notification_new(
base::UTF16ToUTF8(options.title).c_str(),
base::UTF16ToUTF8(options.msg).c_str(), nullptr);
@@ -96,7 +100,7 @@ void LibnotifyNotification::Show(const NotificationOptions& options) {
// NB: On Unity and on any other DE using Notify-OSD, adding a notification
// action will cause the notification to display as a modal dialog box.
if (NotifierSupportsActions()) {
libnotify_loader_.notify_notification_add_action(
GetLibNotifyLoader().notify_notification_add_action(
notification_, "default", "View", OnNotificationView, this, nullptr);
}
@@ -108,19 +112,19 @@ void LibnotifyNotification::Show(const NotificationOptions& options) {
}
// Set the urgency level of the notification.
libnotify_loader_.notify_notification_set_urgency(notification_, urgency);
GetLibNotifyLoader().notify_notification_set_urgency(notification_, urgency);
if (!options.icon.drawsNothing()) {
GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(options.icon);
libnotify_loader_.notify_notification_set_image_from_pixbuf(notification_,
pixbuf);
GetLibNotifyLoader().notify_notification_set_image_from_pixbuf(
notification_, pixbuf);
g_object_unref(pixbuf);
}
// Set the timeout duration for the notification
bool neverTimeout = options.timeout_type == u"never";
int timeout = (neverTimeout) ? NOTIFY_EXPIRES_NEVER : NOTIFY_EXPIRES_DEFAULT;
libnotify_loader_.notify_notification_set_timeout(notification_, timeout);
GetLibNotifyLoader().notify_notification_set_timeout(notification_, timeout);
if (!options.tag.empty()) {
GQuark id = g_quark_from_string(options.tag.c_str());
@@ -130,10 +134,10 @@ void LibnotifyNotification::Show(const NotificationOptions& options) {
// Always try to append notifications.
// Unique tags can be used to prevent this.
if (HasCapability("append")) {
libnotify_loader_.notify_notification_set_hint(
GetLibNotifyLoader().notify_notification_set_hint(
notification_, "append", g_variant_new_string("true"));
} else if (HasCapability("x-canonical-append")) {
libnotify_loader_.notify_notification_set_hint(
GetLibNotifyLoader().notify_notification_set_hint(
notification_, "x-canonical-append", g_variant_new_string("true"));
}
@@ -141,17 +145,17 @@ void LibnotifyNotification::Show(const NotificationOptions& options) {
// The desktop-entry is the part before the .desktop
std::string desktop_id = platform_util::GetXdgAppId();
if (!desktop_id.empty()) {
libnotify_loader_.notify_notification_set_hint(
GetLibNotifyLoader().notify_notification_set_hint(
notification_, "desktop-entry",
g_variant_new_string(desktop_id.c_str()));
}
libnotify_loader_.notify_notification_set_hint(
GetLibNotifyLoader().notify_notification_set_hint(
notification_, "sender-pid",
g_variant_new_int64(base::GetCurrentProcId()));
GError* error = nullptr;
libnotify_loader_.notify_notification_show(notification_, &error);
GetLibNotifyLoader().notify_notification_show(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_show");
NotificationFailed();
@@ -169,7 +173,7 @@ void LibnotifyNotification::Dismiss() {
GError* error = nullptr;
on_dismissing_ = true;
libnotify_loader_.notify_notification_close(notification_, &error);
GetLibNotifyLoader().notify_notification_close(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_close");
}

View File

@@ -147,12 +147,12 @@ const char* GetTemplateType(bool two_lines, bool has_icon) {
} // namespace
// static
ComPtr<winui::Notifications::IToastNotificationManagerStatics>
WindowsToastNotification::toast_manager_;
ComPtr<winui::Notifications::IToastNotificationManagerStatics>*
WindowsToastNotification::toast_manager_ = nullptr;
// static
ComPtr<winui::Notifications::IToastNotifier>
WindowsToastNotification::toast_notifier_;
ComPtr<winui::Notifications::IToastNotifier>*
WindowsToastNotification::toast_notifier_ = nullptr;
// static
bool WindowsToastNotification::Initialize() {
@@ -163,21 +163,35 @@ bool WindowsToastNotification::Initialize() {
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager);
if (!toast_manager_str.success())
return false;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str,
&toast_manager_)))
if (!toast_manager_) {
toast_manager_ = new ComPtr<
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>();
}
if (FAILED(Windows::Foundation::GetActivationFactory(
toast_manager_str, toast_manager_->GetAddressOf())))
return false;
if (!toast_notifier_) {
toast_notifier_ =
new ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>();
}
if (IsRunningInDesktopBridge()) {
// Ironically, the Desktop Bridge / UWP environment
// requires us to not give Windows an appUserModelId.
return SUCCEEDED(toast_manager_->CreateToastNotifier(&toast_notifier_));
return SUCCEEDED(
(*toast_manager_)
->CreateToastNotifier(toast_notifier_->GetAddressOf()));
} else {
ScopedHString app_id;
if (!GetAppUserModelID(&app_id))
return false;
return SUCCEEDED(
toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_));
return SUCCEEDED((*toast_manager_)
->CreateToastNotifierWithId(
app_id, toast_notifier_->GetAddressOf()));
}
}
@@ -207,7 +221,7 @@ void WindowsToastNotification::Remove() {
ComPtr<winui::Notifications::IToastNotificationManagerStatics2>
toast_manager2;
if (FAILED(toast_manager_.As(&toast_manager2)))
if (FAILED(toast_manager_->As(&toast_manager2)))
return;
ComPtr<winui::Notifications::IToastNotificationHistory> notification_history;
@@ -226,7 +240,7 @@ void WindowsToastNotification::Remove() {
void WindowsToastNotification::Dismiss() {
DebugLog("Hiding notification");
toast_notifier_->Hide(toast_notification_.Get());
(*toast_notifier_)->Hide(toast_notification_.Get());
}
HRESULT WindowsToastNotification::ShowInternal(
@@ -281,8 +295,9 @@ HRESULT WindowsToastNotification::ShowInternal(
REPORT_AND_RETURN_IF_FAILED(SetupCallbacks(toast_notification_.Get()),
"WinAPI: SetupCallbacks failed");
REPORT_AND_RETURN_IF_FAILED(toast_notifier_->Show(toast_notification_.Get()),
"WinAPI: Show failed");
REPORT_AND_RETURN_IF_FAILED(
(*toast_notifier_)->Show(toast_notification_.Get()),
"WinAPI: Show failed");
return S_OK;
}

View File

@@ -72,9 +72,9 @@ class WindowsToastNotification : public Notification {
ABI::Windows::UI::Notifications::IToastNotification* toast);
static ComPtr<
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>*
toast_manager_;
static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>*
toast_notifier_;
EventRegistrationToken activated_token_;

View File

@@ -11,6 +11,7 @@
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/posix/eintr_wrapper.h"
#include "base/process/launch.h"
#include "base/synchronization/waitable_event.h"
@@ -18,7 +19,10 @@
namespace relauncher::internal {
// this is global to be visible to the sa_handler
base::WaitableEvent parentWaiter;
auto& GetParentWaiter() {
static base::NoDestructor<base::WaitableEvent> parentWaiter;
return *parentWaiter;
}
void RelauncherSynchronizeWithParent() {
base::ScopedFD relauncher_sync_fd(kRelauncherSyncFD);
@@ -32,7 +36,7 @@ void RelauncherSynchronizeWithParent() {
// set up a signum handler
struct sigaction action = {};
action.sa_handler = [](int /*signum*/) { parentWaiter.Signal(); };
action.sa_handler = [](int /*signum*/) { GetParentWaiter().Signal(); };
if (sigaction(signum, &action, nullptr) != 0) {
PLOG(ERROR) << "sigaction";
return;
@@ -46,7 +50,7 @@ void RelauncherSynchronizeWithParent() {
}
// Wait for the parent to exit
parentWaiter.Wait();
GetParentWaiter().Wait();
}
int LaunchProgram(const StringVector& relauncher_args,

View File

@@ -13,6 +13,10 @@
#include "base/files/file_path.h"
#include "base/memory/raw_ptr_exclusion.h"
#if BUILDFLAG(IS_LINUX)
#include <bits/stdint-uintn.h>
#endif
namespace electron {
class NativeWindow;
}

View File

@@ -60,10 +60,11 @@
#include "v8/include/v8.h"
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "chrome/common/extensions/chrome_manifest_url_handlers.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/render_process_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/manifest_handlers/chrome_url_overrides_handler.h"
#include "extensions/common/manifest_handlers/devtools_page_handler.h"
#include "extensions/common/permissions/permissions_data.h"
#endif

View File

@@ -195,6 +195,9 @@ class InspectableWebContents
const std::string& request) override {}
void RegisterAidaClientEvent(DispatchCallback callback,
const std::string& request) override {}
void DispatchHttpRequest(
DispatchCallback callback,
const DevToolsDispatchHttpRequestParams& params) override {}
// content::DevToolsFrontendHostDelegate:
void HandleMessageFromDevToolsFrontend(base::Value::Dict message);

View File

@@ -9,8 +9,8 @@ namespace electron {
// static
TrayIcon* TrayIcon::Create(std::optional<base::Uuid> guid) {
static NotifyIconHost host;
return host.CreateNotifyIcon(guid);
static NotifyIconHost* host = new NotifyIconHost();
return host->CreateNotifyIcon(guid);
}
} // namespace electron

View File

@@ -10,7 +10,6 @@
#include "shell/browser/ui/views/submenu_button.h"
#include "ui/base/mojom/menu_source_type.mojom.h"
#include "ui/color/color_provider.h"
#include "ui/native_theme/common_theme.h"
#include "ui/views/background.h"
#include "ui/views/layout/box_layout.h"
@@ -19,7 +18,7 @@
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/gfx/color_utils.h"
#include "shell/common/color_util.h"
#endif
namespace electron {
@@ -261,7 +260,7 @@ void MenuBar::UpdateViewColors() {
#elif BUILDFLAG(IS_WIN)
for (views::View* child : GetChildrenInZOrder()) {
auto* button = static_cast<SubmenuButton*>(child);
button->SetUnderlineColor(color_utils::GetSysSkColor(COLOR_MENUTEXT));
button->SetUnderlineColor(GetSysSkColor(COLOR_MENUTEXT));
}
#endif
}

View File

@@ -9,6 +9,7 @@
#include "base/observer_list.h"
#include "base/scoped_observation.h"
#include "content/public/browser/page.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "electron/buildflags/buildflags.h"

View File

@@ -195,8 +195,8 @@ void MediaAccessAllowed(const content::MediaStreamRequest& request,
}
void OnPermissionResponse(base::OnceCallback<void(bool)> callback,
blink::mojom::PermissionStatus status) {
if (status == blink::mojom::PermissionStatus::GRANTED)
content::PermissionResult result) {
if (result.status == blink::mojom::PermissionStatus::GRANTED)
std::move(callback).Run(true);
else
std::move(callback).Run(false);

View File

@@ -13,6 +13,7 @@
#include <memory>
#include "base/file_version_info.h"
#include "base/no_destructor.h"
#include "base/strings/string_util.h"
#include "base/strings/string_util_win.h"
#include "base/strings/utf_string_conversions.h"
@@ -20,13 +21,13 @@
namespace electron {
namespace {
std::wstring g_app_user_model_id;
}
const wchar_t kAppUserModelIDFormat[] = L"electron.app.$1";
std::wstring& GetAppUserModelId() {
static base::NoDestructor<std::wstring> g_app_user_model_id;
return *g_app_user_model_id;
}
std::string GetApplicationName() {
auto* module = GetModuleHandle(nullptr);
std::unique_ptr<FileVersionInfo> info(
@@ -42,15 +43,15 @@ std::string GetApplicationVersion() {
}
void SetAppUserModelID(const std::wstring& name) {
g_app_user_model_id = name;
SetCurrentProcessExplicitAppUserModelID(g_app_user_model_id.c_str());
GetAppUserModelId() = name;
SetCurrentProcessExplicitAppUserModelID(GetAppUserModelId().c_str());
}
PCWSTR GetRawAppUserModelID() {
if (g_app_user_model_id.empty()) {
if (GetAppUserModelId().empty()) {
PWSTR current_app_id;
if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) {
g_app_user_model_id = current_app_id;
GetAppUserModelId() = current_app_id;
} else {
std::string name = GetApplicationName();
std::wstring generated_app_id = base::ReplaceStringPlaceholders(
@@ -60,7 +61,7 @@ PCWSTR GetRawAppUserModelID() {
CoTaskMemFree(current_app_id);
}
return g_app_user_model_id.c_str();
return GetAppUserModelId().c_str();
}
bool GetAppUserModelID(ScopedHString* app_id) {

View File

@@ -14,6 +14,7 @@
#include <dwmapi.h>
#include "base/win/registry.h"
#include "skia/ext/skia_utils_win.h"
#endif
namespace {
@@ -83,6 +84,10 @@ std::optional<DWORD> GetSystemAccentColor() {
return accent_color;
}
SkColor GetSysSkColor(int which) {
return skia::COLORREFToSkColor(GetSysColor(which));
}
#endif
} // namespace electron

View File

@@ -39,6 +39,7 @@ std::string ToRGBAHex(SkColor color, bool include_hash = true);
#if BUILDFLAG(IS_WIN)
std::optional<DWORD> GetSystemAccentColor();
SkColor GetSysSkColor(int which);
#endif
} // namespace electron

View File

@@ -6,39 +6,43 @@
#include "base/command_line.h"
#include "base/containers/to_vector.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
namespace electron {
// static
base::CommandLine::StringVector ElectronCommandLine::argv_;
base::CommandLine::StringVector& ElectronCommandLine::argv() {
static base::NoDestructor<base::CommandLine::StringVector> g_argv;
return *g_argv;
}
// static
void ElectronCommandLine::Init(int argc,
base::CommandLine::CharType const* const* argv) {
DCHECK(argv_.empty());
DCHECK(ElectronCommandLine::argv().empty());
// Safety: as is normal in command lines, argc and argv must correspond
// to one another. Otherwise there will be out-of-bounds accesses.
argv_.assign(argv, UNSAFE_BUFFERS(argv + argc));
ElectronCommandLine::argv().assign(argv, UNSAFE_BUFFERS(argv + argc));
}
// static
std::vector<std::string> ElectronCommandLine::AsUtf8() {
DCHECK(!argv_.empty());
DCHECK(!argv().empty());
#if BUILDFLAG(IS_WIN)
return base::ToVector(
argv_, [](const auto& wstr) { return base::WideToUTF8(wstr); });
argv(), [](const auto& wstr) { return base::WideToUTF8(wstr); });
#else
return argv_;
return argv();
#endif
}
#if BUILDFLAG(IS_LINUX)
// static
void ElectronCommandLine::InitializeFromCommandLine() {
argv_ = base::CommandLine::ForCurrentProcess()->argv();
argv() = base::CommandLine::ForCurrentProcess()->argv();
}
#endif

View File

@@ -18,7 +18,7 @@ class ElectronCommandLine {
ElectronCommandLine(const ElectronCommandLine&) = delete;
ElectronCommandLine& operator=(const ElectronCommandLine&) = delete;
static const base::CommandLine::StringVector& argv() { return argv_; }
static base::CommandLine::StringVector& argv();
static std::vector<std::string> AsUtf8();
@@ -29,9 +29,6 @@ class ElectronCommandLine {
// it is using zygote.
static void InitializeFromCommandLine();
#endif
private:
static base::CommandLine::StringVector argv_;
};
} // namespace electron

View File

@@ -22,10 +22,6 @@
"extension_types": ["extension"],
"platforms": ["win", "mac"]
},
"chrome_url_overrides": {
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]
},
"content_scripts": {
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]
@@ -36,10 +32,6 @@
"extension", "legacy_packaged_app", "hosted_app"
]
},
"devtools_page": {
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]
},
"file_browser_handlers": {
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]

View File

@@ -8,7 +8,6 @@
#include <string>
#include "base/containers/span.h"
#include "chrome/common/extensions/chrome_manifest_url_handlers.h"
#include "chrome/common/extensions/manifest_handlers/minimum_chrome_version_checker.h" // nogncheck
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/extensions/api/generated_schemas.h"
@@ -19,6 +18,7 @@
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handler.h"
#include "extensions/common/manifest_handler_registry.h"
#include "extensions/common/manifest_handlers/chrome_url_overrides_handler.h"
#include "extensions/common/manifest_handlers/permissions_parser.h"
#include "extensions/common/manifest_url_handlers.h"
#include "extensions/common/permissions/permissions_info.h"
@@ -30,10 +30,6 @@ namespace extensions {
namespace {
constexpr APIPermissionInfo::InitInfo permissions_to_register[] = {
{mojom::APIPermissionID::kDevtools, "devtools",
APIPermissionInfo::kFlagImpliesFullURLAccess |
APIPermissionInfo::kFlagCannotBeOptional |
APIPermissionInfo::kFlagInternal},
{mojom::APIPermissionID::kResourcesPrivate, "resourcesPrivate",
APIPermissionInfo::kFlagCannotBeOptional},
#if BUILDFLAG(ENABLE_PDF_VIEWER)
@@ -104,8 +100,6 @@ void ElectronExtensionsAPIProvider::RegisterPermissions(
void ElectronExtensionsAPIProvider::RegisterManifestHandlers() {
extensions::ManifestHandlerRegistry* registry =
extensions::ManifestHandlerRegistry::Get();
registry->RegisterHandler(
std::make_unique<extensions::DevToolsPageHandler>());
registry->RegisterHandler(
std::make_unique<extensions::MinimumChromeVersionChecker>());
}

View File

@@ -10,6 +10,7 @@
#include "base/containers/fixed_flat_map.h"
#include "components/input/native_web_keyboard_event.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/permission_result.h"
#include "content/public/browser/web_contents.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/web_contents_permission_helper.h"
@@ -128,18 +129,22 @@ v8::Local<v8::Value> Converter<ContextMenuParamsWithRenderFrameHost>::ToV8(
}
// static
bool Converter<blink::mojom::PermissionStatus>::FromV8(
bool Converter<content::PermissionResult>::FromV8(
v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::mojom::PermissionStatus* out) {
content::PermissionResult* out) {
bool result;
if (!ConvertFromV8(isolate, val, &result))
return false;
if (result)
*out = blink::mojom::PermissionStatus::GRANTED;
*out =
content::PermissionResult(blink::mojom::PermissionStatus::GRANTED,
content::PermissionStatusSource::UNSPECIFIED);
else
*out = blink::mojom::PermissionStatus::DENIED;
*out =
content::PermissionResult(blink::mojom::PermissionStatus::DENIED,
content::PermissionStatusSource::UNSPECIFIED);
return true;
}

View File

@@ -17,6 +17,7 @@
namespace content {
struct ContextMenuParams;
struct PermissionResult;
class RenderFrameHost;
class WebContents;
} // namespace content
@@ -53,10 +54,10 @@ struct Converter<ui::mojom::MenuSourceType> {
};
template <>
struct Converter<blink::mojom::PermissionStatus> {
struct Converter<content::PermissionResult> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::mojom::PermissionStatus* out);
content::PermissionResult* out);
};
template <>

View File

@@ -12,12 +12,6 @@
namespace gin {
namespace {
v8::Persistent<v8::ObjectTemplate> rfh_templ;
} // namespace
// static
v8::Local<v8::Value> Converter<content::FrameTreeNodeId>::ToV8(
v8::Isolate* isolate,
@@ -59,17 +53,11 @@ Converter<gin_helper::AccessorValue<content::RenderFrameHost*>>::ToV8(
const int32_t process_id = rfh->GetProcess()->GetID().GetUnsafeValue();
const int routing_id = rfh->GetRoutingID();
if (rfh_templ.IsEmpty()) {
v8::EscapableHandleScope inner(isolate);
v8::Local<v8::ObjectTemplate> local = v8::ObjectTemplate::New(isolate);
local->SetInternalFieldCount(2);
rfh_templ.Reset(isolate, inner.Escape(local));
}
v8::Local<v8::ObjectTemplate> templ = v8::ObjectTemplate::New(isolate);
templ->SetInternalFieldCount(2);
v8::Local<v8::Object> rfh_obj =
v8::Local<v8::ObjectTemplate>::New(isolate, rfh_templ)
->NewInstance(isolate->GetCurrentContext())
.ToLocalChecked();
templ->NewInstance(isolate->GetCurrentContext()).ToLocalChecked();
rfh_obj->SetInternalField(0, v8::Number::New(isolate, process_id));
rfh_obj->SetInternalField(1, v8::Number::New(isolate, routing_id));

View File

@@ -28,15 +28,14 @@ struct TranslatorHolder {
delete data.GetParameter();
}
static gin::DeprecatedWrapperInfo kWrapperInfo;
v8::Global<v8::External> handle;
Translator translator;
};
// Cached JavaScript version of |CallTranslator|.
// v8::Persistent handles are bound to a specific v8::Isolate. Require
// initializing per-thread to avoid using the wrong isolate from service
// worker preload scripts.
thread_local v8::Persistent<v8::FunctionTemplate> g_call_translator;
gin::DeprecatedWrapperInfo TranslatorHolder::kWrapperInfo = {
gin::kEmbedderNativeGin};
void CallTranslator(v8::Local<v8::External> external,
v8::Local<v8::Object> state,
@@ -117,14 +116,17 @@ v8::Local<v8::Function> SafeV8Function::NewHandle(v8::Isolate* isolate) const {
v8::Local<v8::Value> CreateFunctionFromTranslator(v8::Isolate* isolate,
const Translator& translator,
bool one_time) {
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
auto* wrapper_info = &TranslatorHolder::kWrapperInfo;
v8::Local<v8::FunctionTemplate> constructor =
data->DeprecatedGetFunctionTemplate(wrapper_info);
// The FunctionTemplate is cached.
if (g_call_translator.IsEmpty())
g_call_translator.Reset(
isolate,
CreateFunctionTemplate(isolate, base::BindRepeating(&CallTranslator)));
if (constructor.IsEmpty()) {
constructor =
CreateFunctionTemplate(isolate, base::BindRepeating(&CallTranslator));
data->DeprecatedSetFunctionTemplate(wrapper_info, constructor);
}
v8::Local<v8::FunctionTemplate> call_translator =
v8::Local<v8::FunctionTemplate>::New(isolate, g_call_translator);
auto* holder = new TranslatorHolder(isolate);
holder->translator = translator;
auto state = gin::Dictionary::CreateEmpty(isolate);
@@ -132,7 +134,7 @@ v8::Local<v8::Value> CreateFunctionFromTranslator(v8::Isolate* isolate,
state.Set("oneTime", true);
auto context = isolate->GetCurrentContext();
return BindFunctionWith(
isolate, context, call_translator->GetFunction(context).ToLocalChecked(),
isolate, context, constructor->GetFunction(context).ToLocalChecked(),
holder->handle.Get(isolate), gin::ConvertToV8(isolate, state));
}

View File

@@ -8,8 +8,11 @@
#include "base/containers/to_value_list.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/no_destructor.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/threading/thread_local.h"
#include "base/values.h"
#include "gin/converter.h"
#include "shell/browser/javascript_environment.h"
@@ -28,9 +31,15 @@ v8::MaybeLocal<v8::Value> CompileAndCall(
v8::LocalVector<v8::Value>* arguments) {
v8::TryCatch try_catch{isolate};
thread_local node::builtins::BuiltinLoader builtin_loader;
v8::MaybeLocal<v8::Function> compiled = builtin_loader.LookupAndCompile(
context, id, parameters, node::Realm::GetCurrent(context));
static base::NoDestructor<
base::ThreadLocalOwnedPointer<node::builtins::BuiltinLoader>>
builtin_loader;
if (!builtin_loader->Get()) {
builtin_loader->Set(base::WrapUnique(new node::builtins::BuiltinLoader));
}
v8::MaybeLocal<v8::Function> compiled =
builtin_loader->Get()->LookupAndCompile(context, id, parameters,
node::Realm::GetCurrent(context));
if (compiled.IsEmpty()) {
// TODO(samuelmaddock): how can we get the compilation error message?

View File

@@ -269,10 +269,11 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContextInner(
v8::TryCatch try_catch(isolate);
v8::Local<v8::Context> source_context =
global_source_context.Get(isolate);
val = PassValueToOtherContext(
source_context, global_destination_context.Get(isolate), result,
source_context->Global(), false,
BridgeErrorTarget::kDestination);
val =
PassValueToOtherContext(isolate, source_context, isolate,
global_destination_context.Get(isolate),
result, source_context->Global(), false,
BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
@@ -316,10 +317,11 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContextInner(
v8::TryCatch try_catch(isolate);
v8::Local<v8::Context> source_context =
global_source_context.Get(isolate);
val = PassValueToOtherContext(
source_context, global_destination_context.Get(isolate), result,
source_context->Global(), false,
BridgeErrorTarget::kDestination);
val =
PassValueToOtherContext(isolate, source_context, isolate,
global_destination_context.Get(isolate),
result, source_context->Global(), false,
BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
@@ -419,10 +421,10 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContextInner(
// Custom logic to "clone" VideoFrame references
blink::VideoFrame* video_frame =
blink::V8VideoFrame::ToWrappable(source_context->GetIsolate(), value);
blink::V8VideoFrame::ToWrappable(source_isolate, value);
if (video_frame != nullptr) {
blink::ScriptState* script_state = blink::ScriptState::ForCurrentRealm(
destination_context->GetIsolate());
blink::ScriptState* script_state =
blink::ScriptState::ForCurrentRealm(destination_isolate);
return v8::MaybeLocal<v8::Value>(
blink::ToV8Traits<blink::VideoFrame>::ToV8(script_state,
video_frame));
@@ -467,7 +469,9 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContextInner(
}
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Isolate* source_isolate,
v8::Local<v8::Context> source_context,
v8::Isolate* destination_isolate,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
v8::Local<v8::Value> parent_value,
@@ -484,9 +488,9 @@ v8::MaybeLocal<v8::Value> PassValueToOtherContext(
blink::ExecutionContext::From(source_context);
DCHECK(source_execution_context);
return PassValueToOtherContextInner(
source_context->GetIsolate(), source_context, source_execution_context,
destination_context->GetIsolate(), destination_context, value,
parent_value, object_cache, support_dynamic_properties, 0, error_target);
source_isolate, source_context, source_execution_context,
destination_isolate, destination_context, value, parent_value,
object_cache, support_dynamic_properties, 0, error_target);
}
void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -529,7 +533,7 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) {
for (auto value : original_args) {
auto arg = PassValueToOtherContext(
calling_context, func_owning_context, value,
isolate, calling_context, isolate, func_owning_context, value,
calling_context->Global(), support_dynamic_properties,
BridgeErrorTarget::kSource, &object_cache);
if (arg.IsEmpty())
@@ -597,7 +601,7 @@ void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) {
{
v8::TryCatch try_catch(isolate);
ret = PassValueToOtherContext(
func_owning_context, calling_context,
isolate, func_owning_context, isolate, calling_context,
maybe_return_value.ToLocalChecked(), func_owning_context->Global(),
support_dynamic_properties, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
@@ -732,14 +736,14 @@ namespace {
void ExposeAPI(v8::Isolate* isolate,
v8::Local<v8::Context> source_context,
v8::Isolate* target_isolate,
v8::Local<v8::Context> target_context,
const std::string& key,
v8::Local<v8::Value> api,
gin_helper::Arguments* args) {
DCHECK(!target_context.IsEmpty());
v8::Context::Scope target_context_scope(target_context);
gin_helper::Dictionary global(target_context->GetIsolate(),
target_context->Global());
gin_helper::Dictionary global(target_isolate, target_context->Global());
if (global.Has(key)) {
args->ThrowError(
@@ -749,8 +753,8 @@ void ExposeAPI(v8::Isolate* isolate,
}
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
source_context, target_context, api, source_context->Global(), false,
BridgeErrorTarget::kSource);
isolate, source_context, target_isolate, target_context, api,
source_context->Global(), false, BridgeErrorTarget::kSource);
if (maybe_proxy.IsEmpty())
return;
auto proxy = maybe_proxy.ToLocalChecked();
@@ -773,7 +777,8 @@ void ExposeAPI(v8::Isolate* isolate,
// world ID. For service workers, Electron only supports one isolated
// context and the main worker context. Anything else is invalid.
v8::MaybeLocal<v8::Context> GetTargetContext(v8::Isolate* isolate,
const int world_id) {
const int world_id,
v8::Isolate* target_isolate) {
v8::Local<v8::Context> source_context = isolate->GetCurrentContext();
v8::MaybeLocal<v8::Context> maybe_target_context;
@@ -795,8 +800,8 @@ v8::MaybeLocal<v8::Context> GetTargetContext(v8::Isolate* isolate,
isolate, "Isolated worlds are not supported in preload realms.")));
return maybe_target_context;
}
maybe_target_context =
electron::preload_realm::GetInitiatorContext(source_context);
maybe_target_context = electron::preload_realm::GetInitiatorContext(
source_context, target_isolate);
} else {
NOTREACHED();
}
@@ -814,12 +819,14 @@ void ExposeAPIInWorld(v8::Isolate* isolate,
"worldId", world_id);
v8::Local<v8::Context> source_context = isolate->GetCurrentContext();
CHECK(!source_context.IsEmpty());
v8::Isolate* target_isolate = isolate;
v8::MaybeLocal<v8::Context> maybe_target_context =
GetTargetContext(isolate, world_id);
if (maybe_target_context.IsEmpty())
GetTargetContext(isolate, world_id, target_isolate);
if (maybe_target_context.IsEmpty() || !target_isolate)
return;
v8::Local<v8::Context> target_context = maybe_target_context.ToLocalChecked();
ExposeAPI(isolate, source_context, target_context, key, api, args);
ExposeAPI(isolate, source_context, target_isolate, target_context, key, api,
args);
}
gin_helper::Dictionary TraceKeyPath(const gin_helper::Dictionary& start,
@@ -844,8 +851,7 @@ void OverrideGlobalValueFromIsolatedWorld(
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
gin_helper::Dictionary global(isolate, main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
gin_helper::Dictionary target_object = TraceKeyPath(global, key_path);
@@ -855,8 +861,9 @@ void OverrideGlobalValueFromIsolatedWorld(
v8::Local<v8::Context> source_context =
value->GetCreationContextChecked(isolate);
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
source_context, main_context, value, source_context->Global(),
support_dynamic_properties, BridgeErrorTarget::kSource);
isolate, source_context, isolate, main_context, value,
source_context->Global(), support_dynamic_properties,
BridgeErrorTarget::kSource);
DCHECK(!maybe_proxy.IsEmpty());
auto proxy = maybe_proxy.ToLocalChecked();
@@ -878,8 +885,7 @@ bool OverrideGlobalPropertyFromIsolatedWorld(
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
gin_helper::Dictionary global(isolate, main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
v8::Local<v8::Object> target_object =
@@ -894,8 +900,8 @@ bool OverrideGlobalPropertyFromIsolatedWorld(
v8::Local<v8::Context> source_context =
getter->GetCreationContextChecked(isolate);
v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext(
source_context, main_context, getter, source_context->Global(), false,
BridgeErrorTarget::kSource);
isolate, source_context, isolate, main_context, getter,
source_context->Global(), false, BridgeErrorTarget::kSource);
DCHECK(!maybe_getter_proxy.IsEmpty());
getter_proxy = maybe_getter_proxy.ToLocalChecked();
}
@@ -903,8 +909,8 @@ bool OverrideGlobalPropertyFromIsolatedWorld(
v8::Local<v8::Context> source_context =
getter->GetCreationContextChecked(isolate);
v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext(
source_context, main_context, setter, source_context->Global(), false,
BridgeErrorTarget::kSource);
isolate, source_context, isolate, main_context, setter,
source_context->Global(), false, BridgeErrorTarget::kSource);
DCHECK(!maybe_setter_proxy.IsEmpty());
setter_proxy = maybe_setter_proxy.ToLocalChecked();
}
@@ -966,8 +972,9 @@ v8::Local<v8::Value> ExecuteInWorld(v8::Isolate* isolate,
}
// Get the target context
v8::Isolate* target_isolate = isolate;
v8::MaybeLocal<v8::Context> maybe_target_context =
GetTargetContext(isolate, world_id);
GetTargetContext(isolate, world_id, target_isolate);
v8::Local<v8::Context> target_context;
if (!maybe_target_context.ToLocal(&target_context)) {
isolate->ThrowException(v8::Exception::Error(gin::StringToV8(
@@ -1053,9 +1060,9 @@ v8::Local<v8::Value> ExecuteInWorld(v8::Isolate* isolate,
}
auto proxied_arg = PassValueToOtherContext(
source_context, target_context, arg, source_context->Global(),
support_dynamic_properties, BridgeErrorTarget::kSource,
&object_cache);
isolate, source_context, target_isolate, target_context, arg,
source_context->Global(), support_dynamic_properties,
BridgeErrorTarget::kSource, &object_cache);
if (proxied_arg.IsEmpty()) {
gin_helper::ErrorThrower(isolate).ThrowError(
absl::StrFormat("Failed to proxy argument at index %d", i));
@@ -1100,8 +1107,8 @@ v8::Local<v8::Value> ExecuteInWorld(v8::Isolate* isolate,
v8::TryCatch try_catch(isolate);
// Pass value from target context back to source context
maybe_cloned_result = PassValueToOtherContext(
target_context, source_context, result, target_context->Global(),
false, BridgeErrorTarget::kSource);
target_isolate, target_context, isolate, source_context, result,
target_context->Global(), false, BridgeErrorTarget::kSource);
if (try_catch.HasCaught()) {
v8::String::Utf8Value utf8(isolate, try_catch.Exception());
error_message = *utf8 ? *utf8 : "Unknown error cloning result";

View File

@@ -31,7 +31,9 @@ enum class BridgeErrorTarget {
};
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Isolate* source_isolate,
v8::Local<v8::Context> source_context,
v8::Isolate* destination_isolate,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
/**

View File

@@ -221,10 +221,10 @@ class IPCRenderFrame : public IPCBase<IPCRenderFrame>,
void OnDestruct() override { electron_ipc_remote_.reset(); }
void WillReleaseScriptContext(v8::Local<v8::Context> context,
void WillReleaseScriptContext(v8::Isolate* const isolate,
v8::Local<v8::Context> context,
int32_t world_id) override {
if (weak_context_.IsEmpty() ||
weak_context_.Get(context->GetIsolate()) == context) {
if (weak_context_.IsEmpty() || weak_context_.Get(isolate) == context) {
OnDestruct();
}
}

View File

@@ -11,6 +11,7 @@
#include "base/containers/span.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/no_destructor.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "components/spellcheck/renderer/spellcheck.h"
@@ -107,6 +108,13 @@ namespace api {
namespace {
class SpellCheckerHolder;
std::set<SpellCheckerHolder*>& GetSpellCheckerHolderInstances() {
static base::NoDestructor<std::set<SpellCheckerHolder*>> instances;
return *instances;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
bool SpellCheckWord(content::RenderFrame* render_frame,
@@ -160,8 +168,8 @@ class ScriptExecutionCallback {
v8::Local<v8::Context> source_context =
result->GetCreationContextChecked(isolate);
maybe_result = PassValueToOtherContext(
source_context, promise_.GetContext(), result,
source_context->Global(), false, BridgeErrorTarget::kSource);
isolate, source_context, promise_.isolate(), promise_.GetContext(),
result, source_context->Global(), false, BridgeErrorTarget::kSource);
if (maybe_result.IsEmpty() || try_catch.HasCaught()) {
success = false;
}
@@ -282,7 +290,7 @@ class SpellCheckerHolder final : private content::RenderFrameObserver {
// Find existing holder for the |render_frame|.
static SpellCheckerHolder* FromRenderFrame(
content::RenderFrame* render_frame) {
for (auto* holder : instances_) {
for (auto* holder : GetSpellCheckerHolderInstances()) {
if (holder->render_frame() == render_frame)
return holder;
}
@@ -294,10 +302,10 @@ class SpellCheckerHolder final : private content::RenderFrameObserver {
: content::RenderFrameObserver(render_frame),
spell_check_client_(std::move(spell_check_client)) {
DCHECK(!FromRenderFrame(render_frame));
instances_.insert(this);
GetSpellCheckerHolderInstances().insert(this);
}
~SpellCheckerHolder() final { instances_.erase(this); }
~SpellCheckerHolder() final { GetSpellCheckerHolderInstances().erase(this); }
void UnsetAndDestroy() {
FrameSetSpellChecker set_spell_checker(nullptr, render_frame());
@@ -319,7 +327,8 @@ class SpellCheckerHolder final : private content::RenderFrameObserver {
delete this;
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
void WillReleaseScriptContext(v8::Isolate* const isolate,
v8::Local<v8::Context> context,
int world_id) final {
// Unset spell checker when the script context is going to be released, as
// the spell check implementation lives there.
@@ -327,8 +336,6 @@ class SpellCheckerHolder final : private content::RenderFrameObserver {
}
private:
static std::set<SpellCheckerHolder*> instances_;
std::unique_ptr<SpellCheckClient> spell_check_client_;
};
@@ -941,9 +948,6 @@ class WebFrameRenderer final
gin::DeprecatedWrapperInfo WebFrameRenderer::kWrapperInfo = {
gin::kEmbedderNativeGin};
// static
std::set<SpellCheckerHolder*> SpellCheckerHolder::instances_;
} // namespace api
} // namespace electron

View File

@@ -120,7 +120,7 @@ void ElectronApiServiceImpl::ReceivePostMessage(
for (auto& port : message.ports) {
ports.emplace_back(
blink::WebMessagePortConverter::EntangleAndInjectMessagePortChannel(
context, std::move(port)));
isolate, context, std::move(port)));
}
std::vector<v8::Local<v8::Value>> args = {message_value};

View File

@@ -148,11 +148,11 @@ void ElectronRenderFrameObserver::DidInstallConditionalFeatures(
}
void ElectronRenderFrameObserver::WillReleaseScriptContext(
v8::Isolate* const isolate,
v8::Local<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->WillReleaseScriptContext(context->GetIsolate(), context,
render_frame_);
renderer_client_->WillReleaseScriptContext(isolate, context, render_frame_);
}
void ElectronRenderFrameObserver::OnDestruct() {

View File

@@ -31,7 +31,8 @@ class ElectronRenderFrameObserver : private content::RenderFrameObserver {
void DidClearWindowObject() override;
void DidInstallConditionalFeatures(v8::Local<v8::Context> context,
int world_id) override;
void WillReleaseScriptContext(v8::Local<v8::Context> context,
void WillReleaseScriptContext(v8::Isolate* const isolate,
v8::Local<v8::Context> context,
int world_id) override;
void OnDestruct() override;
void DidMeaningfulLayout(blink::WebMeaningfulLayout layout_type) override;

View File

@@ -172,19 +172,18 @@ void ElectronSandboxedRendererClient::EmitProcessEvent(
void ElectronSandboxedRendererClient::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Isolate* const v8_isolate,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url,
const blink::ServiceWorkerToken& service_worker_token) {
RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
context_proxy, v8_context, service_worker_version_id,
context_proxy, v8_isolate, v8_context, service_worker_version_id,
service_worker_scope, script_url, service_worker_token);
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kServiceWorkerPreload)) {
v8::Isolate* const v8_isolate = v8_context->GetIsolate();
if (!service_worker_data) {
service_worker_data = new ServiceWorkerData{
context_proxy, service_worker_version_id, v8_isolate, v8_context};

View File

@@ -47,6 +47,7 @@ class ElectronSandboxedRendererClient : public RendererClientBase {
void RunScriptsAtDocumentEnd(content::RenderFrame* render_frame) override;
void WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Isolate* const isolate,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,

View File

@@ -98,6 +98,12 @@ class PreloadRealmLifetimeController
: v8::MaybeLocal<v8::Context>();
}
v8::Isolate* GetInitiatorIsolate() {
return initiator_script_state_->ContextIsValid()
? initiator_script_state_->GetIsolate()
: nullptr;
}
electron::ServiceWorkerData* service_worker_data() {
return service_worker_data_;
}
@@ -199,16 +205,19 @@ class PreloadRealmLifetimeController
} // namespace
v8::MaybeLocal<v8::Context> GetInitiatorContext(
v8::Local<v8::Context> context) {
v8::MaybeLocal<v8::Context> GetInitiatorContext(v8::Local<v8::Context> context,
v8::Isolate* target_isolate) {
DCHECK(!context.IsEmpty());
DCHECK(target_isolate);
blink::ExecutionContext* execution_context =
blink::ExecutionContext::From(context);
if (!execution_context->IsShadowRealmGlobalScope())
return v8::MaybeLocal<v8::Context>();
auto* controller = PreloadRealmLifetimeController::From(context);
if (controller)
if (controller) {
target_isolate = controller->GetInitiatorIsolate();
return controller->GetInitiatorContext();
}
return v8::MaybeLocal<v8::Context>();
}

View File

@@ -14,7 +14,8 @@ class ServiceWorkerData;
namespace electron::preload_realm {
// Get initiator context given the preload context.
v8::MaybeLocal<v8::Context> GetInitiatorContext(v8::Local<v8::Context> context);
v8::MaybeLocal<v8::Context> GetInitiatorContext(v8::Local<v8::Context> context,
v8::Isolate* target_isolate);
// Get the preload context given the initiator context.
v8::MaybeLocal<v8::Context> GetPreloadRealmContext(

View File

@@ -489,6 +489,7 @@ void RendererClientBase::DidInitializeServiceWorkerContextOnWorkerThread(
void RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Isolate* const v8_isolate,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
@@ -497,7 +498,7 @@ void RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->dispatcher()
->WillEvaluateServiceWorkerOnWorkerThread(
context_proxy, v8_context, service_worker_version_id,
context_proxy, v8_isolate, v8_context, service_worker_version_id,
service_worker_scope, script_url, service_worker_token);
#endif
}
@@ -591,8 +592,8 @@ void RendererClientBase::SetupMainWorldOverrides(
v8::Local<v8::Value> guest_view_internal;
if (global.GetHidden("guestViewInternal", &guest_view_internal)) {
auto result = api::PassValueToOtherContext(
source_context, context, guest_view_internal, source_context->Global(),
false, api::BridgeErrorTarget::kSource);
isolate, source_context, isolate, context, guest_view_internal,
source_context->Global(), false, api::BridgeErrorTarget::kSource);
if (!result.IsEmpty()) {
isolated_api.Set("guestViewInternal", result.ToLocalChecked());
}

View File

@@ -124,6 +124,7 @@ class RendererClientBase : public content::ContentRendererClient
const GURL& script_url) override;
void WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Isolate* const isolate,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,

View File

@@ -30,15 +30,19 @@
namespace electron {
mojo::Remote<node::mojom::NodeServiceClient> g_client_remote;
mojo::Remote<node::mojom::NodeServiceClient>& GetRemote() {
static base::NoDestructor<mojo::Remote<node::mojom::NodeServiceClient>>
instance;
return *instance;
}
void V8FatalErrorCallback(const char* location, const char* message) {
if (g_client_remote.is_bound() && g_client_remote.is_connected()) {
if (GetRemote().is_bound() && GetRemote().is_connected()) {
auto* isolate = v8::Isolate::TryGetCurrent();
std::ostringstream outstream;
node::GetNodeReport(isolate, message, location,
v8::Local<v8::Object>() /* error */, outstream);
g_client_remote->OnV8FatalError(location, outstream.str());
GetRemote()->OnV8FatalError(location, outstream.str());
}
#if !IS_MAS_BUILD()
@@ -101,7 +105,7 @@ NodeService::~NodeService() {
ParentPort::GetInstance()->Close();
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate);
g_client_remote.reset();
GetRemote().reset();
}
}
@@ -111,8 +115,8 @@ void NodeService::Initialize(
if (NodeBindings::IsInitialized())
return;
g_client_remote.Bind(std::move(client_pending_remote));
g_client_remote.reset_on_disconnect();
GetRemote().Bind(std::move(client_pending_remote));
GetRemote().reset_on_disconnect();
ParentPort::GetInstance()->Initialize(std::move(params->port));
@@ -155,7 +159,7 @@ void NodeService::Initialize(
node_env_stopped_ = true;
ParentPort::GetInstance()->Close();
js_env_->DestroyMicrotasksRunner();
g_client_remote.reset();
GetRemote().reset();
receiver_.ResetWithReason(exit_code, "process_exit_termination");
node::DefaultProcessExitHandler(env, exit_code);
});