status
stringclasses 1
value | repo_name
stringclasses 31
values | repo_url
stringclasses 31
values | issue_id
int64 1
104k
| title
stringlengths 4
369
| body
stringlengths 0
254k
⌀ | issue_url
stringlengths 37
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
timestamp[us, tz=UTC] | language
stringclasses 5
values | commit_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 4
188
| file_content
stringlengths 0
5.12M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,030 |
Enable crashpad support on linux for ELECTRON_RUN_AS_NODE processes
|
Refs https://github.com/electron/electron/pull/35900/commits/b10f24386cb37d736b10f4831235eedcf1f0db4b
Node.js forked child processes have been relying on breakpad for crash report generation, with https://chromium-review.googlesource.com/c/chromium/src/+/3764621 Linux has moved onto crashpad completely. For these processes to act as crashpad clients, they need the following
* Inherit FD for the handler process communication, which is usually inherited by the chromium spawned child processes via `ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess`. For Node.js the fork is performed by Libuv, we should pass it via stdio option of child_process.fork. The descriptor will eventually be looked up in [PlatformCrashpadInitialization](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad_linux.cc;l=197). Also we will need to setup `base::GlobalDescriptors` instance in the child process.
* Pass the PID of the handler process to the child process via the command line flag `--crashpad-handler-pid/crash_reporter::switches::kCrashpadHandlerPid` whose value can be extracted with the same API to obtain the FD [crash_reporter::GetHandlerSocket](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad.h;l=236).
|
https://github.com/electron/electron/issues/36030
|
https://github.com/electron/electron/pull/36460
|
16a7bd71024789fcabb9362888ee4638852b1eb1
|
2c723d7e84dfab5ad97fc0927426a0b2cd7a15b5
| 2022-10-14T11:57:59Z |
c++
| 2022-11-29T15:33:54Z |
spec/fixtures/apps/crash/fork.js
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,030 |
Enable crashpad support on linux for ELECTRON_RUN_AS_NODE processes
|
Refs https://github.com/electron/electron/pull/35900/commits/b10f24386cb37d736b10f4831235eedcf1f0db4b
Node.js forked child processes have been relying on breakpad for crash report generation, with https://chromium-review.googlesource.com/c/chromium/src/+/3764621 Linux has moved onto crashpad completely. For these processes to act as crashpad clients, they need the following
* Inherit FD for the handler process communication, which is usually inherited by the chromium spawned child processes via `ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess`. For Node.js the fork is performed by Libuv, we should pass it via stdio option of child_process.fork. The descriptor will eventually be looked up in [PlatformCrashpadInitialization](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad_linux.cc;l=197). Also we will need to setup `base::GlobalDescriptors` instance in the child process.
* Pass the PID of the handler process to the child process via the command line flag `--crashpad-handler-pid/crash_reporter::switches::kCrashpadHandlerPid` whose value can be extracted with the same API to obtain the FD [crash_reporter::GetHandlerSocket](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad.h;l=236).
|
https://github.com/electron/electron/issues/36030
|
https://github.com/electron/electron/pull/36460
|
16a7bd71024789fcabb9362888ee4638852b1eb1
|
2c723d7e84dfab5ad97fc0927426a0b2cd7a15b5
| 2022-10-14T11:57:59Z |
c++
| 2022-11-29T15:33:54Z |
spec/fixtures/apps/crash/main.js
|
const { app, BrowserWindow, crashReporter } = require('electron');
const path = require('path');
const childProcess = require('child_process');
app.setVersion('0.1.0');
const url = app.commandLine.getSwitchValue('crash-reporter-url');
const uploadToServer = !app.commandLine.hasSwitch('no-upload');
const setExtraParameters = app.commandLine.hasSwitch('set-extra-parameters-in-renderer');
const addGlobalParam = app.commandLine.getSwitchValue('add-global-param')?.split(':');
crashReporter.start({
productName: 'Zombies',
companyName: 'Umbrella Corporation',
compress: false,
uploadToServer,
submitURL: url,
ignoreSystemCrashHandler: true,
extra: {
mainProcessSpecific: 'mps'
},
globalExtra: addGlobalParam[0] ? { [addGlobalParam[0]]: addGlobalParam[1] } : {}
});
app.whenReady().then(() => {
const crashType = app.commandLine.getSwitchValue('crash-type');
if (crashType === 'main') {
process.crash();
} else if (crashType === 'renderer') {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
if (setExtraParameters) {
w.webContents.executeJavaScript(`
require('electron').crashReporter.addExtraParameter('rendererSpecific', 'rs');
require('electron').crashReporter.addExtraParameter('addedThenRemoved', 'to-be-removed');
require('electron').crashReporter.removeExtraParameter('addedThenRemoved');
`);
}
w.webContents.executeJavaScript('process.crash()');
w.webContents.on('render-process-gone', () => process.exit(0));
} else if (crashType === 'sandboxed-renderer') {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.resolve(__dirname, 'sandbox-preload.js'),
contextIsolation: false
}
});
w.loadURL(`about:blank?set_extra=${setExtraParameters ? 1 : 0}`);
w.webContents.on('render-process-gone', () => process.exit(0));
} else if (crashType === 'node') {
const crashPath = path.join(__dirname, 'node-crash.js');
const child = childProcess.fork(crashPath, { silent: true });
child.on('exit', () => process.exit(0));
} else {
console.error(`Unrecognized crash type: '${crashType}'`);
process.exit(1);
}
});
setTimeout(() => app.exit(), 30000);
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,030 |
Enable crashpad support on linux for ELECTRON_RUN_AS_NODE processes
|
Refs https://github.com/electron/electron/pull/35900/commits/b10f24386cb37d736b10f4831235eedcf1f0db4b
Node.js forked child processes have been relying on breakpad for crash report generation, with https://chromium-review.googlesource.com/c/chromium/src/+/3764621 Linux has moved onto crashpad completely. For these processes to act as crashpad clients, they need the following
* Inherit FD for the handler process communication, which is usually inherited by the chromium spawned child processes via `ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess`. For Node.js the fork is performed by Libuv, we should pass it via stdio option of child_process.fork. The descriptor will eventually be looked up in [PlatformCrashpadInitialization](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad_linux.cc;l=197). Also we will need to setup `base::GlobalDescriptors` instance in the child process.
* Pass the PID of the handler process to the child process via the command line flag `--crashpad-handler-pid/crash_reporter::switches::kCrashpadHandlerPid` whose value can be extracted with the same API to obtain the FD [crash_reporter::GetHandlerSocket](https://source.chromium.org/chromium/chromium/src/+/main:components/crash/core/app/crashpad.h;l=236).
|
https://github.com/electron/electron/issues/36030
|
https://github.com/electron/electron/pull/36460
|
16a7bd71024789fcabb9362888ee4638852b1eb1
|
2c723d7e84dfab5ad97fc0927426a0b2cd7a15b5
| 2022-10-14T11:57:59Z |
c++
| 2022-11-29T15:33:54Z |
spec/fixtures/apps/crash/node-extra-args.js
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 34,111 |
[Bug]: Window maxWidth and maxHeight is ignore if one of them set to 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.4.1
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
If one of BrowserWindow settings maxWidth or maxHeight is set to 0 and another one set to any positive value more than 0 the window will resize with limit by width or height if it set to positive value and with no limit by another one.
```javascript
new BrowserWindow({
x: 1000,
y: 800,
maxWidth: 0,
maxHeight: 500,
})
```
### Actual Behavior
If I set one of maxWidth or maxHeight for BrowserWindow to 0 and another one to any positive value more than 0 the window ignore this non zero value and can resize with no limit by width and height.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/34111
|
https://github.com/electron/electron/pull/36487
|
835e248dfff8bb585770be18ed0df74b29e81c7b
|
4ff0642af745e57df6736b9d68fe0228b8e28968
| 2022-05-06T04:30:50Z |
c++
| 2022-12-01T01:02:22Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent() || !ui::win::IsAeroGlassEnabled())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (std::find(draggable_region_providers_.begin(),
draggable_region_providers_.end(),
provider) == draggable_region_providers_.end()) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::NONE);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 34,111 |
[Bug]: Window maxWidth and maxHeight is ignore if one of them set to 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.4.1
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
If one of BrowserWindow settings maxWidth or maxHeight is set to 0 and another one set to any positive value more than 0 the window will resize with limit by width or height if it set to positive value and with no limit by another one.
```javascript
new BrowserWindow({
x: 1000,
y: 800,
maxWidth: 0,
maxHeight: 500,
})
```
### Actual Behavior
If I set one of maxWidth or maxHeight for BrowserWindow to 0 and another one to any positive value more than 0 the window ignore this non zero value and can resize with no limit by width and height.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/34111
|
https://github.com/electron/electron/pull/36487
|
835e248dfff8bb585770be18ed0df74b29e81c7b
|
4ff0642af745e57df6736b9d68fe0228b8e28968
| 2022-05-06T04:30:50Z |
c++
| 2022-12-01T01:02:22Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent() || !ui::win::IsAeroGlassEnabled())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (std::find(draggable_region_providers_.begin(),
draggable_region_providers_.end(),
provider) == draggable_region_providers_.end()) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::NONE);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
docs/api/browser-window.md
|
# BrowserWindow
> Create and control browser windows.
Process: [Main](../glossary.md#main-process)
This module cannot be used until the `ready` event of the `app`
module is emitted.
```javascript
// In the main process.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
// Load a remote URL
win.loadURL('https://github.com')
// Or load a local HTML file
win.loadFile('index.html')
```
## Window customization
The `BrowserWindow` class exposes various ways to modify the look and behavior of
your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md)
tutorial.
## Showing the window gracefully
When loading a page in the window directly, users may see the page load incrementally,
which is not a good experience for a native app. To make the window display
without a visual flash, there are two solutions for different situations.
### Using the `ready-to-show` event
While loading the page, the `ready-to-show` event will be emitted when the renderer
process has rendered the page for the first time if the window has not been shown yet. Showing
the window after this event will have no visual flash:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
```
This event is usually emitted after the `did-finish-load` event, but for
pages with many remote resources, it may be emitted before the `did-finish-load`
event.
Please note that using this event implies that the renderer will be considered "visible" and
paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false`
### Setting the `backgroundColor` property
For a complex app, the `ready-to-show` event could be emitted too late, making
the app feel slow. In this case, it is recommended to show the window
immediately, and use a `backgroundColor` close to your app's background:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
```
Note that even for apps that use `ready-to-show` event, it is still recommended
to set `backgroundColor` to make the app feel more native.
Some examples of valid `backgroundColor` values include:
```js
const win = new BrowserWindow()
win.setBackgroundColor('hsl(230, 100%, 50%)')
win.setBackgroundColor('rgb(255, 145, 145)')
win.setBackgroundColor('#ff00a3')
win.setBackgroundColor('blueviolet')
```
For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor).
## Parent and child windows
By using `parent` option, you can create child windows:
```javascript
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
```
The `child` window will always show on top of the `top` window.
## Modal windows
A modal window is a child window that disables parent window, to create a modal
window, you have to set both `parent` and `modal` options:
```javascript
const { BrowserWindow } = require('electron')
const child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})
```
## Page visibility
The [Page Visibility API][page-visibility-api] works as follows:
* On all platforms, the visibility state tracks whether the window is
hidden/minimized or not.
* Additionally, on macOS, the visibility state also tracks the window
occlusion state. If the window is occluded (i.e. fully covered) by another
window, the visibility state will be `hidden`. On other platforms, the
visibility state will be `hidden` only when the window is minimized or
explicitly hidden with `win.hide()`.
* If a `BrowserWindow` is created with `show: false`, the initial visibility
state will be `visible` despite the window actually being hidden.
* If `backgroundThrottling` is disabled, the visibility state will remain
`visible` even if the window is minimized, occluded, or hidden.
It is recommended that you pause expensive operations when the visibility
state is `hidden` in order to minimize power consumption.
## Platform notices
* On macOS modal windows will be displayed as sheets attached to the parent window.
* On macOS the child windows will keep the relative position to parent window
when parent window moves, while on Windows and Linux child windows will not
move.
* On Linux the type of modal windows will be changed to `dialog`.
* On Linux many desktop environments do not support hiding a modal window.
## Class: BrowserWindow
> Create and control browser windows.
Process: [Main](../glossary.md#main-process)
`BrowserWindow` is an [EventEmitter][event-emitter].
It creates a new `BrowserWindow` with native properties as set by the `options`.
### `new BrowserWindow([options])`
* `options` Object (optional)
* `width` Integer (optional) - Window's width in pixels. Default is `800`.
* `height` Integer (optional) - Window's height in pixels. Default is `600`.
* `x` Integer (optional) - (**required** if y is used) Window's left offset from screen.
Default is to center the window.
* `y` Integer (optional) - (**required** if x is used) Window's top offset from screen.
Default is to center the window.
* `useContentSize` boolean (optional) - The `width` and `height` would be used as web
page's size, which means the actual window's size will include window
frame's size and be slightly larger. Default is `false`.
* `center` boolean (optional) - Show window in the center of the screen. Default is `false`.
* `minWidth` Integer (optional) - Window's minimum width. Default is `0`.
* `minHeight` Integer (optional) - Window's minimum height. Default is `0`.
* `maxWidth` Integer (optional) - Window's maximum width. Default is no limit.
* `maxHeight` Integer (optional) - Window's maximum height. Default is no limit.
* `resizable` boolean (optional) - Whether window is resizable. Default is `true`.
* `movable` boolean (optional) _macOS_ _Windows_ - Whether window is
movable. This is not implemented on Linux. Default is `true`.
* `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is
minimizable. This is not implemented on Linux. Default is `true`.
* `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is
maximizable. This is not implemented on Linux. Default is `true`.
* `closable` boolean (optional) _macOS_ _Windows_ - Whether window is
closable. This is not implemented on Linux. Default is `true`.
* `focusable` boolean (optional) - Whether the window can be focused. Default is
`true`. On Windows setting `focusable: false` also implies setting
`skipTaskbar: true`. On Linux setting `focusable: false` makes the window
stop interacting with wm, so the window will always stay on top in all
workspaces.
* `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of
other windows. Default is `false`.
* `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When
explicitly set to `false` the fullscreen button will be hidden or disabled
on macOS. Default is `false`.
* `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen
mode. On macOS, also whether the maximize/zoom button should toggle full
screen mode or maximize window. Default is `true`.
* `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on
macOS. Default is `false`.
* `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar.
Default is `false`.
* `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control.
* `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`.
* `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored.
* `icon` ([NativeImage](native-image.md) | string) (optional) - The window icon. On Windows it is
recommended to use `ICO` icons to get best visual effects, you can also
leave it undefined so the executable's icon will be used.
* `show` boolean (optional) - Whether window should be shown when created. Default is
`true`.
* `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`.
* `frame` boolean (optional) - Specify `false` to create a
[frameless window](../tutorial/window-customization.md#create-frameless-windows). Default is `true`.
* `parent` BrowserWindow (optional) - Specify parent window. Default is `null`.
* `modal` boolean (optional) - Whether this is a modal window. This only works when the
window is a child window. Default is `false`.
* `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an
inactive window will also click through to the web contents. Default is
`false` on macOS. This option is not configurable on other platforms.
* `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing.
Default is `false`.
* `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt`
key is pressed. Default is `false`.
* `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to
be resized larger than screen. Only relevant for macOS, as other OSes
allow larger-than-screen windows by default. Default is `false`.
* `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information.
* `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`.
* `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of
the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This
is only implemented on Windows and macOS.
* `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on
some GTK+3 desktop environments. Default is `false`.
* `transparent` boolean (optional) - Makes the window [transparent](../tutorial/window-customization.md#create-transparent-windows).
Default is `false`. On Windows, does not work unless the window is frameless.
* `type` string (optional) - The type of window, default is normal window. See more about
this below.
* `visualEffectState` string (optional) _macOS_ - Specify how the material
appearance should reflect window activity state on macOS. Must be used
with the `vibrancy` property. Possible values are:
* `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default.
* `active` - The backdrop should always appear active.
* `inactive` - The backdrop should always appear inactive.
* `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar.
Default is `default`. Possible values are:
* `default` - Results in the standard title bar for macOS or Windows respectively.
* `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown.
* `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar
with an alternative look where the traffic light buttons are slightly
more inset from the window edge.
* `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden
title bar and a full size content window, the traffic light buttons will
display when being hovered over in the top left of the window.
**Note:** This option is currently experimental.
* `trafficLightPosition` [Point](structures/point.md) (optional) _macOS_ -
Set a custom position for the traffic light buttons in frameless windows.
* `roundedCorners` boolean (optional) _macOS_ - Whether frameless window
should have rounded corners on macOS. Default is `true`. Setting this property
to `false` will prevent the window from being fullscreenable.
* `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows
the title in the title bar in full screen mode on macOS for `hiddenInset`
titleBarStyle. Default is `false`.
* `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
window shadow and window animations. Default is `true`.
* `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to
the window, only on macOS. Can be `appearance-based`, `light`, `dark`,
`titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`,
`ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`,
`tooltip`, `content`, `under-window`, or `under-page`. Please note that
`appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are
deprecated and have been removed in macOS Catalina (10.15).
* `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on
macOS when option-clicking the green stoplight button on the toolbar or by
clicking the Window > Zoom menu item. If `true`, the window will grow to
the preferred width of the web page when zoomed, `false` will cause it to
zoom to the width of the screen. This will also affect the behavior when
calling `maximize()` directly. Default is `false`.
* `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows
opening the window as a native tab on macOS 10.12+. Windows with the same
tabbing identifier will be grouped together. This also adds a native new
tab button to your window's tab bar and allows your `app` and window to
receive the `new-window-for-tab` event.
* `webPreferences` Object (optional) - Settings of web page's features.
* `devTools` boolean (optional) - Whether to enable DevTools. If it is set to `false`, can not use `BrowserWindow.webContents.openDevTools()` to open DevTools. Default is `true`.
* `nodeIntegration` boolean (optional) - Whether node integration is enabled.
Default is `false`.
* `nodeIntegrationInWorker` boolean (optional) - Whether node integration is
enabled in web workers. Default is `false`. More about this can be found
in [Multithreading](../tutorial/multithreading.md).
* `nodeIntegrationInSubFrames` boolean (optional) - Experimental option for
enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for
every iframe, you can use `process.isMainFrame` to determine if you are
in the main frame or not.
* `preload` string (optional) - Specifies a script that will be loaded before other
scripts run in the page. This script will always have access to node APIs
no matter whether node integration is turned on or off. The value should
be the absolute file path to the script.
When node integration is turned off, the preload script can reintroduce
Node global symbols back to the global scope. See example
[here](context-bridge.md#exposing-node-global-symbols).
* `sandbox` boolean (optional) - If set, this will sandbox the renderer
associated with the window, making it compatible with the Chromium
OS-level sandbox and disabling the Node.js engine. This is not the same as
the `nodeIntegration` option and the APIs available to the preload script
are more limited. Read more about the option [here](../tutorial/sandbox.md).
* `session` [Session](session.md#class-session) (optional) - Sets the session used by the
page. Instead of passing the Session object directly, you can also choose to
use the `partition` option instead, which accepts a partition string. When
both `session` and `partition` are provided, `session` will be preferred.
Default is the default session.
* `partition` string (optional) - Sets the session used by the page according to the
session's partition string. If `partition` starts with `persist:`, the page
will use a persistent session available to all pages in the app with the
same `partition`. If there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. Default is the default session.
* `zoomFactor` number (optional) - The default zoom factor of the page, `3.0` represents
`300%`. Default is `1.0`.
* `javascript` boolean (optional) - Enables JavaScript support. Default is `true`.
* `webSecurity` boolean (optional) - When `false`, it will disable the
same-origin policy (usually using testing websites by people), and set
`allowRunningInsecureContent` to `true` if this options has not been set
by user. Default is `true`.
* `allowRunningInsecureContent` boolean (optional) - Allow an https page to run
JavaScript, CSS or plugins from http URLs. Default is `false`.
* `images` boolean (optional) - Enables image support. Default is `true`.
* `imageAnimationPolicy` string (optional) - Specifies how to run image animations (E.g. GIFs). Can be `animate`, `animateOnce` or `noAnimation`. Default is `animate`.
* `textAreasAreResizable` boolean (optional) - Make TextArea elements resizable. Default
is `true`.
* `webgl` boolean (optional) - Enables WebGL support. Default is `true`.
* `plugins` boolean (optional) - Whether plugins should be enabled. Default is `false`.
* `experimentalFeatures` boolean (optional) - Enables Chromium's experimental features.
Default is `false`.
* `scrollBounce` boolean (optional) _macOS_ - Enables scroll bounce
(rubber banding) effect on macOS. Default is `false`.
* `enableBlinkFeatures` string (optional) - A list of feature strings separated by `,`, like
`CSSVariables,KeyboardEventKey` to enable. The full list of supported feature
strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features]
file.
* `disableBlinkFeatures` string (optional) - A list of feature strings separated by `,`,
like `CSSVariables,KeyboardEventKey` to disable. The full list of supported
feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
* `defaultFontFamily` Object (optional) - Sets the default font for the font-family.
* `standard` string (optional) - Defaults to `Times New Roman`.
* `serif` string (optional) - Defaults to `Times New Roman`.
* `sansSerif` string (optional) - Defaults to `Arial`.
* `monospace` string (optional) - Defaults to `Courier New`.
* `cursive` string (optional) - Defaults to `Script`.
* `fantasy` string (optional) - Defaults to `Impact`.
* `defaultFontSize` Integer (optional) - Defaults to `16`.
* `defaultMonospaceFontSize` Integer (optional) - Defaults to `13`.
* `minimumFontSize` Integer (optional) - Defaults to `0`.
* `defaultEncoding` string (optional) - Defaults to `ISO-8859-1`.
* `backgroundThrottling` boolean (optional) - Whether to throttle animations and timers
when the page becomes background. This also affects the
[Page Visibility API](#page-visibility). Defaults to `true`.
* `offscreen` boolean (optional) - Whether to enable offscreen rendering for the browser
window. Defaults to `false`. See the
[offscreen rendering tutorial](../tutorial/offscreen-rendering.md) for
more details.
* `contextIsolation` boolean (optional) - Whether to run Electron APIs and
the specified `preload` script in a separate JavaScript context. Defaults
to `true`. The context that the `preload` script runs in will only have
access to its own dedicated `document` and `window` globals, as well as
its own set of JavaScript builtins (`Array`, `Object`, `JSON`, etc.),
which are all invisible to the loaded content. The Electron API will only
be available in the `preload` script and not the loaded page. This option
should be used when loading potentially untrusted remote content to ensure
the loaded content cannot tamper with the `preload` script and any
Electron APIs being used. This option uses the same technique used by
[Chrome Content Scripts][chrome-content-scripts]. You can access this
context in the dev tools by selecting the 'Electron Isolated Context'
entry in the combo box at the top of the Console tab.
* `webviewTag` boolean (optional) - Whether to enable the [`<webview>` tag](webview-tag.md).
Defaults to `false`. **Note:** The
`preload` script configured for the `<webview>` will have node integration
enabled when it is executed so you should ensure remote/untrusted content
is not able to create a `<webview>` tag with a possibly malicious `preload`
script. You can use the `will-attach-webview` event on [webContents](web-contents.md)
to strip away the `preload` script and to validate or alter the
`<webview>`'s initial settings.
* `additionalArguments` string[] (optional) - A list of strings that will be appended
to `process.argv` in the renderer process of this app. Useful for passing small
bits of data down to renderer process preload scripts.
* `safeDialogs` boolean (optional) - Whether to enable browser style
consecutive dialog protection. Default is `false`.
* `safeDialogsMessage` string (optional) - The message to display when
consecutive dialog protection is triggered. If not defined the default
message would be used, note that currently the default message is in
English and not localized.
* `disableDialogs` boolean (optional) - Whether to disable dialogs
completely. Overrides `safeDialogs`. Default is `false`.
* `navigateOnDragDrop` boolean (optional) - Whether dragging and dropping a
file or link onto the page causes a navigation. Default is `false`.
* `autoplayPolicy` string (optional) - Autoplay policy to apply to
content in the window, can be `no-user-gesture-required`,
`user-gesture-required`, `document-user-activation-required`. Defaults to
`no-user-gesture-required`.
* `disableHtmlFullscreenWindowResize` boolean (optional) - Whether to
prevent the window from resizing when entering HTML Fullscreen. Default
is `false`.
* `accessibleTitle` string (optional) - An alternative title string provided only
to accessibility tools such as screen readers. This string is not directly
visible to users.
* `spellcheck` boolean (optional) - Whether to enable the builtin spellchecker.
Default is `true`.
* `enableWebSQL` boolean (optional) - Whether to enable the [WebSQL api](https://www.w3.org/TR/webdatabase/).
Default is `true`.
* `v8CacheOptions` string (optional) - Enforces the v8 code caching policy
used by blink. Accepted values are
* `none` - Disables code caching
* `code` - Heuristic based code caching
* `bypassHeatCheck` - Bypass code caching heuristics but with lazy compilation
* `bypassHeatCheckAndEagerCompile` - Same as above except compilation is eager.
Default policy is `code`.
* `enablePreferredSizeMode` boolean (optional) - Whether to enable
preferred size mode. The preferred size is the minimum size needed to
contain the layout of the document—without requiring scrolling. Enabling
this will cause the `preferred-size-changed` event to be emitted on the
`WebContents` when the preferred size changes. Default is `false`.
* `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`.
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color.
* `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
passing a size that does not follow size constraints to `setBounds`/`setSize` or
to the constructor of `BrowserWindow`.
The possible values and behaviors of the `type` option are platform dependent.
Possible values are:
* On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`,
`notification`.
* On macOS, possible types are `desktop`, `textured`, `panel`.
* The `textured` type adds metal gradient appearance
(`NSWindowStyleMaskTexturedBackground`).
* The `desktop` type places the window at the desktop background window level
(`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive
focus, keyboard or mouse events, but you can use `globalShortcut` to receive
input sparingly.
* The `panel` type enables the window to float on top of full-screened apps
by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally
reserved for NSPanel, at runtime. Also, the window will appear on all
spaces (desktops).
* On Windows, possible type is `toolbar`.
### Instance Events
Objects created with `new BrowserWindow` emit the following events:
**Note:** Some events are only available on specific operating systems and are
labeled as such.
#### Event: 'page-title-updated'
Returns:
* `event` Event
* `title` string
* `explicitSet` boolean
Emitted when the document changed its title, calling `event.preventDefault()`
will prevent the native window's title from changing.
`explicitSet` is false when title is synthesized from file URL.
#### Event: 'close'
Returns:
* `event` Event
Emitted when the window is going to be closed. It's emitted before the
`beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()`
will cancel the close.
Usually you would want to use the `beforeunload` handler to decide whether the
window should be closed, which will also be called when the window is
reloaded. In Electron, returning any value other than `undefined` would cancel the
close. For example:
```javascript
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
// Unlike usual browsers that a message box will be prompted to users, returning
// a non-void value will silently cancel the close.
// It is recommended to use the dialog API to let the user confirm closing the
// application.
e.returnValue = false
}
```
_**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._
#### Event: 'closed'
Emitted when the window is closed. After you have received this event you should
remove the reference to the window and avoid using it any more.
#### Event: 'session-end' _Windows_
Emitted when window session is going to end due to force shutdown or machine restart
or session log off.
#### Event: 'unresponsive'
Emitted when the web page becomes unresponsive.
#### Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
#### Event: 'blur'
Emitted when the window loses focus.
#### Event: 'focus'
Emitted when the window gains focus.
#### Event: 'show'
Emitted when the window is shown.
#### Event: 'hide'
Emitted when the window is hidden.
#### Event: 'ready-to-show'
Emitted when the web page has been rendered (while not being shown) and window can be displayed without
a visual flash.
Please note that using this event implies that the renderer will be considered "visible" and
paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false`
#### Event: 'maximize'
Emitted when window is maximized.
#### Event: 'unmaximize'
Emitted when the window exits from a maximized state.
#### Event: 'minimize'
Emitted when the window is minimized.
#### Event: 'restore'
Emitted when the window is restored from a minimized state.
#### Event: 'will-resize' _macOS_ _Windows_
Returns:
* `event` Event
* `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to.
* `details` Object
* `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`.
Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized.
Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event.
The possible values and behaviors of the `edge` option are platform dependent. Possible values are:
* On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`.
* On macOS, possible values are `bottom` and `right`.
* The value `bottom` is used to denote vertical resizing.
* The value `right` is used to denote horizontal resizing.
#### Event: 'resize'
Emitted after the window has been resized.
#### Event: 'resized' _macOS_ _Windows_
Emitted once when the window has finished being resized.
This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished.
#### Event: 'will-move' _macOS_ _Windows_
Returns:
* `event` Event
* `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to.
Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved.
Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event.
#### Event: 'move'
Emitted when the window is being moved to a new position.
#### Event: 'moved' _macOS_ _Windows_
Emitted once when the window is moved to a new position.
__Note__: On macOS this event is an alias of `move`.
#### Event: 'enter-full-screen'
Emitted when the window enters a full-screen state.
#### Event: 'leave-full-screen'
Emitted when the window leaves a full-screen state.
#### Event: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
#### Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
#### Event: 'always-on-top-changed'
Returns:
* `event` Event
* `isAlwaysOnTop` boolean
Emitted when the window is set or unset to show always on top of other windows.
#### Event: 'app-command' _Windows_ _Linux_
Returns:
* `event` Event
* `command` string
Emitted when an [App Command](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx)
is invoked. These are typically related to keyboard media keys or browser
commands, as well as the "Back" button built into some mice on Windows.
Commands are lowercased, underscores are replaced with hyphens, and the
`APPCOMMAND_` prefix is stripped off.
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
```
The following app commands are explicitly supported on Linux:
* `browser-backward`
* `browser-forward`
#### Event: 'scroll-touch-begin' _macOS_ _Deprecated_
Emitted when scroll wheel event phase has begun.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'scroll-touch-end' _macOS_ _Deprecated_
Emitted when scroll wheel event phase has ended.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'scroll-touch-edge' _macOS_ _Deprecated_
Emitted when scroll wheel event phase filed upon reaching the edge of element.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'swipe' _macOS_
Returns:
* `event` Event
* `direction` string
Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`.
The method underlying this event is built to handle older macOS-style trackpad swiping,
where the content on the screen doesn't move with the swipe. Most macOS trackpads are not
configured to allow this kind of swiping anymore, so in order for it to emit properly the
'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be
set to 'Swipe with two or three fingers'.
#### Event: 'rotate-gesture' _macOS_
Returns:
* `event` Event
* `rotation` Float
Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is
ended. The `rotation` value on each emission is the angle in degrees rotated since
the last emission. The last emitted event upon a rotation gesture will always be of
value `0`. Counter-clockwise rotation values are positive, while clockwise ones are
negative.
#### Event: 'sheet-begin' _macOS_
Emitted when the window opens a sheet.
#### Event: 'sheet-end' _macOS_
Emitted when the window has closed a sheet.
#### Event: 'new-window-for-tab' _macOS_
Emitted when the native new tab button is clicked.
#### Event: 'system-context-menu' _Windows_
Returns:
* `event` Event
* `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at
Emitted when the system context menu is triggered on the window, this is
normally only triggered when the user right clicks on the non-client area
of your window. This is the window titlebar or any area you have declared
as `-webkit-app-region: drag` in a frameless window.
Calling `event.preventDefault()` will prevent the menu from being displayed.
### Static Methods
The `BrowserWindow` class has the following static methods:
#### `BrowserWindow.getAllWindows()`
Returns `BrowserWindow[]` - An array of all opened browser windows.
#### `BrowserWindow.getFocusedWindow()`
Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`.
#### `BrowserWindow.fromWebContents(webContents)`
* `webContents` [WebContents](web-contents.md)
Returns `BrowserWindow | null` - The window that owns the given `webContents`
or `null` if the contents are not owned by a window.
#### `BrowserWindow.fromBrowserView(browserView)`
* `browserView` [BrowserView](browser-view.md)
Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`.
#### `BrowserWindow.fromId(id)`
* `id` Integer
Returns `BrowserWindow | null` - The window with the given `id`.
### Instance Properties
Objects created with `new BrowserWindow` have the following properties:
```javascript
const { BrowserWindow } = require('electron')
// In this example `win` is our instance
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
```
#### `win.webContents` _Readonly_
A `WebContents` object this window owns. All web page related events and
operations will be done via it.
See the [`webContents` documentation](web-contents.md) for its methods and
events.
#### `win.id` _Readonly_
A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application.
#### `win.autoHideMenuBar`
A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key.
If the menu bar is already visible, setting this property to `true` won't
hide it immediately.
#### `win.simpleFullScreen`
A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode.
#### `win.fullScreen`
A `boolean` property that determines whether the window is in fullscreen mode.
#### `win.focusable` _Windows_ _macOS_
A `boolean` property that determines whether the window is focusable.
#### `win.visibleOnAllWorkspaces` _macOS_ _Linux_
A `boolean` property that determines whether the window is visible on all workspaces.
**Note:** Always returns false on Windows.
#### `win.shadow`
A `boolean` property that determines whether the window has a shadow.
#### `win.menuBarVisible` _Windows_ _Linux_
A `boolean` property that determines whether the menu bar should be visible.
**Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
#### `win.kiosk`
A `boolean` property that determines whether the window is in kiosk mode.
#### `win.documentEdited` _macOS_
A `boolean` property that specifies whether the window’s document has been edited.
The icon in title bar will become gray when set to `true`.
#### `win.representedFilename` _macOS_
A `string` property that determines the pathname of the file the window represents,
and the icon of the file will show in window's title bar.
#### `win.title`
A `string` property that determines the title of the native window.
**Note:** The title of the web page can be different from the title of the native window.
#### `win.minimizable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually minimized by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.maximizable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually maximized by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.fullScreenable`
A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or
maximizes the window.
#### `win.resizable`
A `boolean` property that determines whether the window can be manually resized by user.
#### `win.closable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually closed by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.movable` _macOS_ _Windows_
A `boolean` property that determines Whether the window can be moved by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.excludedFromShownWindowsMenu` _macOS_
A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default.
```js
const win = new BrowserWindow({ height: 600, width: 600 })
const template = [
{
role: 'windowmenu'
}
]
win.excludedFromShownWindowsMenu = true
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
```
#### `win.accessibleTitle`
A `string` property that defines an alternative title provided only to
accessibility tools such as screen readers. This string is not directly
visible to users.
### Instance Methods
Objects created with `new BrowserWindow` have the following instance methods:
**Note:** Some methods are only available on specific operating systems and are
labeled as such.
#### `win.destroy()`
Force closing the window, the `unload` and `beforeunload` event won't be emitted
for the web page, and `close` event will also not be emitted
for this window, but it guarantees the `closed` event will be emitted.
#### `win.close()`
Try to close the window. This has the same effect as a user manually clicking
the close button of the window. The web page may cancel the close though. See
the [close event](#event-close).
#### `win.focus()`
Focuses on the window.
#### `win.blur()`
Removes focus from the window.
#### `win.isFocused()`
Returns `boolean` - Whether the window is focused.
#### `win.isDestroyed()`
Returns `boolean` - Whether the window is destroyed.
#### `win.show()`
Shows and gives focus to the window.
#### `win.showInactive()`
Shows the window but doesn't focus on it.
#### `win.hide()`
Hides the window.
#### `win.isVisible()`
Returns `boolean` - Whether the window is visible to the user.
#### `win.isModal()`
Returns `boolean` - Whether current window is a modal window.
#### `win.maximize()`
Maximizes the window. This will also show (but not focus) the window if it
isn't being displayed already.
#### `win.unmaximize()`
Unmaximizes the window.
#### `win.isMaximized()`
Returns `boolean` - Whether the window is maximized.
#### `win.minimize()`
Minimizes the window. On some platforms the minimized window will be shown in
the Dock.
#### `win.restore()`
Restores the window from minimized state to its previous state.
#### `win.isMinimized()`
Returns `boolean` - Whether the window is minimized.
#### `win.setFullScreen(flag)`
* `flag` boolean
Sets whether the window should be in fullscreen mode.
#### `win.isFullScreen()`
Returns `boolean` - Whether the window is in fullscreen mode.
#### `win.setSimpleFullScreen(flag)` _macOS_
* `flag` boolean
Enters or leaves simple fullscreen mode.
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).
#### `win.isSimpleFullScreen()` _macOS_
Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode.
#### `win.isNormal()`
Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).
#### `win.setAspectRatio(aspectRatio[, extraSize])`
* `aspectRatio` Float - The aspect ratio to maintain for some portion of the
content view.
* `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while
maintaining the aspect ratio.
This will make a window maintain an aspect ratio. The extra size allows a
developer to have space, specified in pixels, not included within the aspect
ratio calculations. This API already takes into account the difference between a
window's size and its content size.
Consider a normal window with an HD video player and associated controls.
Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls
on the right edge and 50 pixels of controls below the player. In order to
maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within
the player itself we would call this function with arguments of 16/9 and
{ width: 40, height: 50 }. The second argument doesn't care where the extra width and height
are within the content view--only that they exist. Sum any extra width and
height areas you have within the overall content view.
The aspect ratio is not respected when window is resized programmatically with
APIs like `win.setSize`.
#### `win.setBackgroundColor(backgroundColor)`
* `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.
Examples of valid `backgroundColor` values:
* Hex
* #fff (shorthand RGB)
* #ffff (shorthand ARGB)
* #ffffff (RGB)
* #ffffffff (ARGB)
* RGB
* rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)
* e.g. rgb(255, 255, 255)
* RGBA
* rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)
* e.g. rgba(255, 255, 255, 1.0)
* HSL
* hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)
* e.g. hsl(200, 20%, 50%)
* HSLA
* hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)
* e.g. hsla(200, 20%, 50%, 0.5)
* Color name
* Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148)
* Similar to CSS Color Module Level 3 keywords, but case-sensitive.
* e.g. `blueviolet` or `red`
Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property).
#### `win.previewFile(path[, displayName])` _macOS_
* `path` string - The absolute path to the file to preview with QuickLook. This
is important as Quick Look uses the file name and file extension on the path
to determine the content type of the file to open.
* `displayName` string (optional) - The name of the file to display on the
Quick Look modal view. This is purely visual and does not affect the content
type of the file. Defaults to `path`.
Uses [Quick Look][quick-look] to preview a file at a given path.
#### `win.closeFilePreview()` _macOS_
Closes the currently open [Quick Look][quick-look] panel.
#### `win.setBounds(bounds[, animate])`
* `bounds` Partial<[Rectangle](structures/rectangle.md)>
* `animate` boolean (optional) _macOS_
Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// set all bounds properties
win.setBounds({ x: 440, y: 225, width: 800, height: 600 })
// set a single bounds property
win.setBounds({ width: 100 })
// { x: 440, y: 225, width: 100, height: 600 }
console.log(win.getBounds())
```
#### `win.getBounds()`
Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`.
#### `win.getBackgroundColor()`
Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format.
See [Setting `backgroundColor`](#setting-the-backgroundcolor-property).
**Note:** The alpha value is _not_ returned alongside the red, green, and blue values.
#### `win.setContentBounds(bounds[, animate])`
* `bounds` [Rectangle](structures/rectangle.md)
* `animate` boolean (optional) _macOS_
Resizes and moves the window's client area (e.g. the web page) to
the supplied bounds.
#### `win.getContentBounds()`
Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`.
#### `win.getNormalBounds()`
Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state
**Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md).
#### `win.setEnabled(enable)`
* `enable` boolean
Disable or enable the window.
#### `win.isEnabled()`
Returns `boolean` - whether the window is enabled.
#### `win.setSize(width, height[, animate])`
* `width` Integer
* `height` Integer
* `animate` boolean (optional) _macOS_
Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size.
#### `win.getSize()`
Returns `Integer[]` - Contains the window's width and height.
#### `win.setContentSize(width, height[, animate])`
* `width` Integer
* `height` Integer
* `animate` boolean (optional) _macOS_
Resizes the window's client area (e.g. the web page) to `width` and `height`.
#### `win.getContentSize()`
Returns `Integer[]` - Contains the window's client area's width and height.
#### `win.setMinimumSize(width, height)`
* `width` Integer
* `height` Integer
Sets the minimum size of window to `width` and `height`.
#### `win.getMinimumSize()`
Returns `Integer[]` - Contains the window's minimum width and height.
#### `win.setMaximumSize(width, height)`
* `width` Integer
* `height` Integer
Sets the maximum size of window to `width` and `height`.
#### `win.getMaximumSize()`
Returns `Integer[]` - Contains the window's maximum width and height.
#### `win.setResizable(resizable)`
* `resizable` boolean
Sets whether the window can be manually resized by the user.
#### `win.isResizable()`
Returns `boolean` - Whether the window can be manually resized by the user.
#### `win.setMovable(movable)` _macOS_ _Windows_
* `movable` boolean
Sets whether the window can be moved by user. On Linux does nothing.
#### `win.isMovable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be moved by user.
On Linux always returns `true`.
#### `win.setMinimizable(minimizable)` _macOS_ _Windows_
* `minimizable` boolean
Sets whether the window can be manually minimized by user. On Linux does nothing.
#### `win.isMinimizable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually minimized by the user.
On Linux always returns `true`.
#### `win.setMaximizable(maximizable)` _macOS_ _Windows_
* `maximizable` boolean
Sets whether the window can be manually maximized by user. On Linux does nothing.
#### `win.isMaximizable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually maximized by user.
On Linux always returns `true`.
#### `win.setFullScreenable(fullscreenable)`
* `fullscreenable` boolean
Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
#### `win.isFullScreenable()`
Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
#### `win.setClosable(closable)` _macOS_ _Windows_
* `closable` boolean
Sets whether the window can be manually closed by user. On Linux does nothing.
#### `win.isClosable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually closed by user.
On Linux always returns `true`.
#### `win.setHiddenInMissionControl(hidden)` _macOS_
* `hidden` boolean
Sets whether the window will be hidden when the user toggles into mission control.
#### `win.isHiddenInMissionControl()` _macOS_
Returns `boolean` - Whether the window will be hidden when the user toggles into mission control.
#### `win.setAlwaysOnTop(flag[, level][, relativeLevel])`
* `flag` boolean
* `level` string (optional) _macOS_ _Windows_ - Values include `normal`,
`floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`,
`pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is
`floating` when `flag` is true. The `level` is reset to `normal` when the
flag is false. Note that from `floating` to `status` included, the window is
placed below the Dock on macOS and below the taskbar on Windows. From
`pop-up-menu` to a higher it is shown above the Dock on macOS and above the
taskbar on Windows. See the [macOS docs][window-levels] for more details.
* `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set
this window relative to the given `level`. The default is `0`. Note that Apple
discourages setting levels higher than 1 above `screen-saver`.
Sets whether the window should show always on top of other windows. After
setting this, the window is still a normal window, not a toolbox window which
can not be focused on.
#### `win.isAlwaysOnTop()`
Returns `boolean` - Whether the window is always on top of other windows.
#### `win.moveAbove(mediaSourceId)`
* `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0".
Moves window above the source window in the sense of z-order. If the
`mediaSourceId` is not of type window or if the window does not exist then
this method throws an error.
#### `win.moveTop()`
Moves window to top(z-order) regardless of focus
#### `win.center()`
Moves window to the center of the screen.
#### `win.setPosition(x, y[, animate])`
* `x` Integer
* `y` Integer
* `animate` boolean (optional) _macOS_
Moves window to `x` and `y`.
#### `win.getPosition()`
Returns `Integer[]` - Contains the window's current position.
#### `win.setTitle(title)`
* `title` string
Changes the title of native window to `title`.
#### `win.getTitle()`
Returns `string` - The title of the native window.
**Note:** The title of the web page can be different from the title of the native
window.
#### `win.setSheetOffset(offsetY[, offsetX])` _macOS_
* `offsetY` Float
* `offsetX` Float (optional)
Changes the attachment point for sheets on macOS. By default, sheets are
attached just below the window frame, but you may want to display them beneath
a HTML-rendered toolbar. For example:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
```
#### `win.flashFrame(flag)`
* `flag` boolean
Starts or stops flashing the window to attract user's attention.
#### `win.setSkipTaskbar(skip)` _macOS_ _Windows_
* `skip` boolean
Makes the window not show in the taskbar.
#### `win.setKiosk(flag)`
* `flag` boolean
Enters or leaves kiosk mode.
#### `win.isKiosk()`
Returns `boolean` - Whether the window is in kiosk mode.
#### `win.isTabletMode()` _Windows_
Returns `boolean` - Whether the window is in Windows 10 tablet mode.
Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet),
under this mode apps can choose to optimize their UI for tablets, such as
enlarging the titlebar and hiding titlebar buttons.
This API returns whether the window is in tablet mode, and the `resize` event
can be be used to listen to changes to tablet mode.
#### `win.getMediaSourceId()`
Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0".
More precisely the format is `window:id:other_id` where `id` is `HWND` on
Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on
Linux. `other_id` is used to identify web contents (tabs) so within the same
top level window.
#### `win.getNativeWindowHandle()`
Returns `Buffer` - The platform-specific handle of the window.
The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and
`Window` (`unsigned long`) on Linux.
#### `win.hookWindowMessage(message, callback)` _Windows_
* `message` Integer
* `callback` Function
* `wParam` any - The `wParam` provided to the WndProc
* `lParam` any - The `lParam` provided to the WndProc
Hooks a windows message. The `callback` is called when
the message is received in the WndProc.
#### `win.isWindowMessageHooked(message)` _Windows_
* `message` Integer
Returns `boolean` - `true` or `false` depending on whether the message is hooked.
#### `win.unhookWindowMessage(message)` _Windows_
* `message` Integer
Unhook the window message.
#### `win.unhookAllWindowMessages()` _Windows_
Unhooks all of the window messages.
#### `win.setRepresentedFilename(filename)` _macOS_
* `filename` string
Sets the pathname of the file the window represents, and the icon of the file
will show in window's title bar.
#### `win.getRepresentedFilename()` _macOS_
Returns `string` - The pathname of the file the window represents.
#### `win.setDocumentEdited(edited)` _macOS_
* `edited` boolean
Specifies whether the window’s document has been edited, and the icon in title
bar will become gray when set to `true`.
#### `win.isDocumentEdited()` _macOS_
Returns `boolean` - Whether the window's document has been edited.
#### `win.focusOnWebView()`
#### `win.blurWebView()`
#### `win.capturePage([rect, opts])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `opts` Object (optional)
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
#### `win.loadURL(url[, options])`
* `url` string
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n"
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options).
The `url` can be a remote address (e.g. `http://`) or a path to a local
HTML file using the `file://` protocol.
To ensure that file URLs are properly formatted, it is recommended to use
Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject)
method:
```javascript
const url = require('url').format({
protocol: 'file',
slashes: true,
pathname: require('path').join(__dirname, 'index.html')
})
win.loadURL(url)
```
You can load a URL using a `POST` request with URL-encoded data by doing
the following:
```javascript
win.loadURL('http://localhost:8000/post', {
postData: [{
type: 'rawData',
bytes: Buffer.from('hello=world')
}],
extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})
```
#### `win.loadFile(filePath[, options])`
* `filePath` string
* `options` Object (optional)
* `query` Record<string, string> (optional) - Passed to `url.format()`.
* `search` string (optional) - Passed to `url.format()`.
* `hash` string (optional) - Passed to `url.format()`.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Same as `webContents.loadFile`, `filePath` should be a path to an HTML
file relative to the root of your application. See the `webContents` docs
for more information.
#### `win.reload()`
Same as `webContents.reload`.
#### `win.setMenu(menu)` _Linux_ _Windows_
* `menu` Menu | null
Sets the `menu` as the window's menu bar.
#### `win.removeMenu()` _Linux_ _Windows_
Remove the window's menu bar.
#### `win.setProgressBar(progress[, options])`
* `progress` Double
* `options` Object (optional)
* `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`.
Sets progress value in progress bar. Valid range is [0, 1.0].
Remove progress bar when progress < 0;
Change to indeterminate mode when progress > 1.
On Linux platform, only supports Unity desktop environment, you need to specify
the `*.desktop` file name to `desktopName` field in `package.json`. By default,
it will assume `{app.name}.desktop`.
On Windows, a mode can be passed. Accepted values are `none`, `normal`,
`indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a
mode set (but with a value within the valid range), `normal` will be assumed.
#### `win.setOverlayIcon(overlay, description)` _Windows_
* `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom
right corner of the taskbar icon. If this parameter is `null`, the overlay is
cleared
* `description` string - a description that will be provided to Accessibility
screen readers
Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to
convey some sort of application status or to passively notify the user.
#### `win.setHasShadow(hasShadow)`
* `hasShadow` boolean
Sets whether the window should have a shadow.
#### `win.hasShadow()`
Returns `boolean` - Whether the window has a shadow.
#### `win.setOpacity(opacity)` _Windows_ _macOS_
* `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque)
Sets the opacity of the window. On Linux, does nothing. Out of bound number
values are clamped to the [0, 1] range.
#### `win.getOpacity()`
Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On
Linux, always returns 1.
#### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_
* `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window.
Passing an empty list reverts the window to being rectangular.
Setting a window shape determines the area within the window where the system
permits drawing and user interaction. Outside of the given region, no pixels
will be drawn and no mouse events will be registered. Mouse events outside of
the region will not be received by that window, but will fall through to
whatever is behind the window.
#### `win.setThumbarButtons(buttons)` _Windows_
* `buttons` [ThumbarButton[]](structures/thumbar-button.md)
Returns `boolean` - Whether the buttons were added successfully
Add a thumbnail toolbar with a specified set of buttons to the thumbnail image
of a window in a taskbar button layout. Returns a `boolean` object indicates
whether the thumbnail has been added successfully.
The number of buttons in thumbnail toolbar should be no greater than 7 due to
the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be
removed due to the platform's limitation. But you can call the API with an empty
array to clean the buttons.
The `buttons` is an array of `Button` objects:
* `Button` Object
* `icon` [NativeImage](native-image.md) - The icon showing in thumbnail
toolbar.
* `click` Function
* `tooltip` string (optional) - The text of the button's tooltip.
* `flags` string[] (optional) - Control specific states and behaviors of the
button. By default, it is `['enabled']`.
The `flags` is an array that can include following `string`s:
* `enabled` - The button is active and available to the user.
* `disabled` - The button is disabled. It is present, but has a visual state
indicating it will not respond to user action.
* `dismissonclick` - When the button is clicked, the thumbnail window closes
immediately.
* `nobackground` - Do not draw a button border, use only the image.
* `hidden` - The button is not shown to the user.
* `noninteractive` - The button is enabled but not interactive; no pressed
button state is drawn. This value is intended for instances where the button
is used in a notification.
#### `win.setThumbnailClip(region)` _Windows_
* `region` [Rectangle](structures/rectangle.md) - Region of the window
Sets the region of the window to show as the thumbnail image displayed when
hovering over the window in the taskbar. You can reset the thumbnail to be
the entire window by specifying an empty region:
`{ x: 0, y: 0, width: 0, height: 0 }`.
#### `win.setThumbnailToolTip(toolTip)` _Windows_
* `toolTip` string
Sets the toolTip that is displayed when hovering over the window thumbnail
in the taskbar.
#### `win.setAppDetails(options)` _Windows_
* `options` Object
* `appId` string (optional) - Window's [App User Model ID](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391569(v=vs.85).aspx).
It has to be set, otherwise the other options will have no effect.
* `appIconPath` string (optional) - Window's [Relaunch Icon](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391573(v=vs.85).aspx).
* `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`.
Ignored when `appIconPath` is not set. Default is `0`.
* `relaunchCommand` string (optional) - Window's [Relaunch Command](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391571(v=vs.85).aspx).
* `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391572(v=vs.85).aspx).
Sets the properties for the window's taskbar button.
**Note:** `relaunchCommand` and `relaunchDisplayName` must always be set
together. If one of those properties is not set, then neither will be used.
#### `win.showDefinitionForSelection()` _macOS_
Same as `webContents.showDefinitionForSelection()`.
#### `win.setIcon(icon)` _Windows_ _Linux_
* `icon` [NativeImage](native-image.md) | string
Changes window icon.
#### `win.setWindowButtonVisibility(visible)` _macOS_
* `visible` boolean
Sets whether the window traffic light buttons should be visible.
#### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_
* `hide` boolean
Sets whether the window menu bar should hide itself automatically. Once set the
menu bar will only show when users press the single `Alt` key.
If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately.
#### `win.isMenuBarAutoHide()` _Windows_ _Linux_
Returns `boolean` - Whether menu bar automatically hides itself.
#### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` boolean
Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
#### `win.isMenuBarVisible()` _Windows_ _Linux_
Returns `boolean` - Whether the menu bar is visible.
#### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_
* `visible` boolean
* `options` Object (optional)
* `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether
the window should be visible above fullscreen windows.
* `skipTransformProcessType` boolean (optional) _macOS_ - Calling
setVisibleOnAllWorkspaces will by default transform the process
type between UIElementApplication and ForegroundApplication to
ensure the correct behavior. However, this will hide the window
and dock for a short time every time it is called. If your window
is already of type UIElementApplication, you can bypass this
transformation by passing true to skipTransformProcessType.
Sets whether the window should be visible on all workspaces.
**Note:** This API does nothing on Windows.
#### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_
Returns `boolean` - Whether the window is visible on all workspaces.
**Note:** This API always returns false on Windows.
#### `win.setIgnoreMouseEvents(ignore[, options])`
* `ignore` boolean
* `options` Object (optional)
* `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move
messages to Chromium, enabling mouse related events such as `mouseleave`.
Only used when `ignore` is true. If `ignore` is false, forwarding is always
disabled regardless of this value.
Makes the window ignore all mouse events.
All mouse events happened in this window will be passed to the window below
this window, but if this window has focus, it will still receive keyboard
events.
#### `win.setContentProtection(enable)` _macOS_ _Windows_
* `enable` boolean
Prevents the window contents from being captured by other apps.
On macOS it sets the NSWindow's sharingType to NSWindowSharingNone.
On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`.
For Windows 10 version 2004 and up the window will be removed from capture entirely,
older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window.
#### `win.setFocusable(focusable)` _macOS_ _Windows_
* `focusable` boolean
Changes whether the window can be focused.
On macOS it does not remove the focus from the window.
#### `win.isFocusable()` _macOS_ _Windows_
Returns whether the window can be focused.
#### `win.setParentWindow(parent)`
* `parent` BrowserWindow | null
Sets `parent` as current window's parent window, passing `null` will turn
current window into a top-level window.
#### `win.getParentWindow()`
Returns `BrowserWindow | null` - The parent window or `null` if there is no parent.
#### `win.getChildWindows()`
Returns `BrowserWindow[]` - All child windows.
#### `win.setAutoHideCursor(autoHide)` _macOS_
* `autoHide` boolean
Controls whether to hide cursor when typing.
#### `win.selectPreviousTab()` _macOS_
Selects the previous tab when native tabs are enabled and there are other
tabs in the window.
#### `win.selectNextTab()` _macOS_
Selects the next tab when native tabs are enabled and there are other
tabs in the window.
#### `win.mergeAllWindows()` _macOS_
Merges all windows into one window with multiple tabs when native tabs
are enabled and there is more than one open window.
#### `win.moveTabToNewWindow()` _macOS_
Moves the current tab into a new window if native tabs are enabled and
there is more than one tab in the current window.
#### `win.toggleTabBar()` _macOS_
Toggles the visibility of the tab bar if native tabs are enabled and
there is only one tab in the current window.
#### `win.addTabbedWindow(browserWindow)` _macOS_
* `browserWindow` BrowserWindow
Adds a window as a tab on this window, after the tab for the window instance.
#### `win.setVibrancy(type)` _macOS_
* `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`,
`selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See
the [macOS documentation][vibrancy-docs] for more details.
Adds a vibrancy effect to the browser window. Passing `null` or an empty string
will remove the vibrancy effect on the window.
Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been
deprecated and will be removed in an upcoming version of macOS.
#### `win.setTrafficLightPosition(position)` _macOS_
* `position` [Point](structures/point.md)
Set a custom position for the traffic light buttons in frameless window.
#### `win.getTrafficLightPosition()` _macOS_
Returns `Point` - The custom position for the traffic light buttons in
frameless window.
#### `win.setTouchBar(touchBar)` _macOS_
* `touchBar` TouchBar | null
Sets the touchBar layout for the current window. Specifying `null` or
`undefined` clears the touch bar. This method only has an effect if the
machine has a touch bar and is running on macOS 10.12.1+.
**Note:** The TouchBar API is currently experimental and may change or be
removed in future Electron releases.
#### `win.setBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`.
If there are other `BrowserView`s attached, they will be removed from
this window.
#### `win.getBrowserView()` _Experimental_
Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null`
if one is not attached. Throws an error if multiple `BrowserView`s are attached.
#### `win.addBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
Replacement API for setBrowserView supporting work with multi browser views.
#### `win.removeBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
#### `win.setTopBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
Raises `browserView` above other `BrowserView`s attached to `win`.
Throws an error if `browserView` is not attached to `win`.
#### `win.getBrowserViews()` _Experimental_
Returns `BrowserView[]` - an array of all BrowserViews that have been attached
with `addBrowserView` or `setBrowserView`.
**Note:** The BrowserView API is currently experimental and may change or be
removed in future Electron releases.
#### `win.setTitleBarOverlay(options)` _Windows_
* `options` Object
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled.
* `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels.
On a Window with Window Controls Overlay already enabled, this method updates
the style of the title bar overlay.
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
[page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look
[vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc
[window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level
[chrome-content-scripts]: https://developer.chrome.com/extensions/content_scripts#execution-environment
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/api/electron_api_base_window.cc
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_base_window.h"
#include <string>
#include <utility>
#include <vector>
#include "electron/buildflags/buildflags.h"
#include "gin/dictionary.h"
#include "shell/browser/api/electron_api_browser_view.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/api/electron_api_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/native_window_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#if defined(TOOLKIT_VIEWS)
#include "shell/browser/native_window_views.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/ui/win/taskbar_host.h"
#include "ui/base/win/shell.h"
#endif
#if BUILDFLAG(IS_WIN)
namespace gin {
template <>
struct Converter<electron::TaskbarHost::ThumbarButton> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::TaskbarHost::ThumbarButton* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("click", &(out->clicked_callback));
dict.Get("tooltip", &(out->tooltip));
dict.Get("flags", &out->flags);
return dict.Get("icon", &(out->icon));
}
};
} // namespace gin
#endif
namespace electron::api {
namespace {
// Converts binary data to Buffer.
v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size);
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
} // namespace
BaseWindow::BaseWindow(v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
// The parent window.
gin::Handle<BaseWindow> parent;
if (options.Get("parent", &parent) && !parent.IsEmpty())
parent_window_.Reset(isolate, parent.ToV8());
#if BUILDFLAG(ENABLE_OSR)
// Offscreen windows are always created frameless.
gin_helper::Dictionary web_preferences;
bool offscreen;
if (options.Get(options::kWebPreferences, &web_preferences) &&
web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) {
const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false);
}
#endif
// Creates NativeWindow.
window_.reset(NativeWindow::Create(
options, parent.IsEmpty() ? nullptr : parent->window_.get()));
window_->AddObserver(this);
#if defined(TOOLKIT_VIEWS)
v8::Local<v8::Value> icon;
if (options.Get(options::kIcon, &icon)) {
SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn);
}
#endif
}
BaseWindow::BaseWindow(gin_helper::Arguments* args,
const gin_helper::Dictionary& options)
: BaseWindow(args->isolate(), options) {
InitWithArgs(args);
// Init window after everything has been setup.
window()->InitFromOptions(options);
}
BaseWindow::~BaseWindow() {
CloseImmediately();
// Destroy the native window in next tick because the native code might be
// iterating all windows.
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, window_.release());
// Remove global reference so the JS object can be garbage collected.
self_ref_.Reset();
}
void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
AttachAsUserData(window_.get());
gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper);
// We can only append this window to parent window's child windows after this
// window's JS wrapper gets initialized.
if (!parent_window_.IsEmpty()) {
gin::Handle<BaseWindow> parent;
gin::ConvertFromV8(isolate, GetParentWindow(), &parent);
DCHECK(!parent.IsEmpty());
parent->child_windows_.Set(isolate, weak_map_id(), wrapper);
}
// Reference this object in case it got garbage collected.
self_ref_.Reset(isolate, wrapper);
}
void BaseWindow::WillCloseWindow(bool* prevent_default) {
if (Emit("close")) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowClosed() {
// Invalidate weak ptrs before the Javascript object is destroyed,
// there might be some delayed emit events which shouldn't be
// triggered after this.
weak_factory_.InvalidateWeakPtrs();
RemoveFromWeakMap();
window_->RemoveObserver(this);
// We can not call Destroy here because we need to call Emit first, but we
// also do not want any method to be used, so just mark as destroyed here.
MarkDestroyed();
Emit("closed");
RemoveFromParentChildWindows();
BaseWindow::ResetBrowserViews();
// Destroy the native class when window is closed.
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, GetDestroyClosure());
}
void BaseWindow::OnWindowEndSession() {
Emit("session-end");
}
void BaseWindow::OnWindowBlur() {
EmitEventSoon("blur");
}
void BaseWindow::OnWindowFocus() {
EmitEventSoon("focus");
}
void BaseWindow::OnWindowShow() {
Emit("show");
}
void BaseWindow::OnWindowHide() {
Emit("hide");
}
void BaseWindow::OnWindowMaximize() {
Emit("maximize");
}
void BaseWindow::OnWindowUnmaximize() {
Emit("unmaximize");
}
void BaseWindow::OnWindowMinimize() {
Emit("minimize");
}
void BaseWindow::OnWindowRestore() {
Emit("restore");
}
void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate);
info.Set("edge", edge);
if (Emit("will-resize", new_bounds, info)) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowResize() {
Emit("resize");
}
void BaseWindow::OnWindowResized() {
Emit("resized");
}
void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
if (Emit("will-move", new_bounds)) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowMove() {
Emit("move");
}
void BaseWindow::OnWindowMoved() {
Emit("moved");
}
void BaseWindow::OnWindowEnterFullScreen() {
Emit("enter-full-screen");
}
void BaseWindow::OnWindowLeaveFullScreen() {
Emit("leave-full-screen");
}
void BaseWindow::OnWindowSwipe(const std::string& direction) {
Emit("swipe", direction);
}
void BaseWindow::OnWindowRotateGesture(float rotation) {
Emit("rotate-gesture", rotation);
}
void BaseWindow::OnWindowSheetBegin() {
Emit("sheet-begin");
}
void BaseWindow::OnWindowSheetEnd() {
Emit("sheet-end");
}
void BaseWindow::OnWindowEnterHtmlFullScreen() {
Emit("enter-html-full-screen");
}
void BaseWindow::OnWindowLeaveHtmlFullScreen() {
Emit("leave-html-full-screen");
}
void BaseWindow::OnWindowAlwaysOnTopChanged() {
Emit("always-on-top-changed", IsAlwaysOnTop());
}
void BaseWindow::OnExecuteAppCommand(const std::string& command_name) {
Emit("app-command", command_name);
}
void BaseWindow::OnTouchBarItemResult(const std::string& item_id,
const base::Value::Dict& details) {
Emit("-touch-bar-interaction", item_id, details);
}
void BaseWindow::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) {
if (Emit("system-context-menu", gfx::Point(x, y))) {
*prevent_default = true;
}
}
#if BUILDFLAG(IS_WIN)
void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) {
if (IsWindowMessageHooked(message)) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
messages_callback_map_[message].Run(
ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)),
ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM)));
}
}
#endif
void BaseWindow::SetContentView(gin::Handle<View> view) {
ResetBrowserViews();
content_view_.Reset(isolate(), view.ToV8());
window_->SetContentView(view->view());
}
void BaseWindow::CloseImmediately() {
if (!window_->IsClosed())
window_->CloseImmediately();
}
void BaseWindow::Close() {
window_->Close();
}
void BaseWindow::Focus() {
window_->Focus(true);
}
void BaseWindow::Blur() {
window_->Focus(false);
}
bool BaseWindow::IsFocused() {
return window_->IsFocused();
}
void BaseWindow::Show() {
window_->Show();
}
void BaseWindow::ShowInactive() {
// This method doesn't make sense for modal window.
if (IsModal())
return;
window_->ShowInactive();
}
void BaseWindow::Hide() {
window_->Hide();
}
bool BaseWindow::IsVisible() {
return window_->IsVisible();
}
bool BaseWindow::IsEnabled() {
return window_->IsEnabled();
}
void BaseWindow::SetEnabled(bool enable) {
window_->SetEnabled(enable);
}
void BaseWindow::Maximize() {
window_->Maximize();
}
void BaseWindow::Unmaximize() {
window_->Unmaximize();
}
bool BaseWindow::IsMaximized() {
return window_->IsMaximized();
}
void BaseWindow::Minimize() {
window_->Minimize();
}
void BaseWindow::Restore() {
window_->Restore();
}
bool BaseWindow::IsMinimized() {
return window_->IsMinimized();
}
void BaseWindow::SetFullScreen(bool fullscreen) {
window_->SetFullScreen(fullscreen);
}
bool BaseWindow::IsFullscreen() {
return window_->IsFullscreen();
}
void BaseWindow::SetBounds(const gfx::Rect& bounds,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetBounds(bounds, animate);
}
gfx::Rect BaseWindow::GetBounds() {
return window_->GetBounds();
}
bool BaseWindow::IsNormal() {
return window_->IsNormal();
}
gfx::Rect BaseWindow::GetNormalBounds() {
return window_->GetNormalBounds();
}
void BaseWindow::SetContentBounds(const gfx::Rect& bounds,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentBounds(bounds, animate);
}
gfx::Rect BaseWindow::GetContentBounds() {
return window_->GetContentBounds();
}
void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) {
bool animate = false;
gfx::Size size = window_->GetMinimumSize();
size.SetToMax(gfx::Size(width, height));
args->GetNext(&animate);
window_->SetSize(size, animate);
}
std::vector<int> BaseWindow::GetSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetContentSize(int width,
int height,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentSize(gfx::Size(width, height), animate);
}
std::vector<int> BaseWindow::GetContentSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetContentSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetMinimumSize(int width, int height) {
window_->SetMinimumSize(gfx::Size(width, height));
}
std::vector<int> BaseWindow::GetMinimumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMinimumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetMaximumSize(int width, int height) {
window_->SetMaximumSize(gfx::Size(width, height));
}
std::vector<int> BaseWindow::GetMaximumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMaximumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) {
double offsetX = 0.0;
args->GetNext(&offsetX);
window_->SetSheetOffset(offsetX, offsetY);
}
void BaseWindow::SetResizable(bool resizable) {
window_->SetResizable(resizable);
}
bool BaseWindow::IsResizable() {
return window_->IsResizable();
}
void BaseWindow::SetMovable(bool movable) {
window_->SetMovable(movable);
}
bool BaseWindow::IsMovable() {
return window_->IsMovable();
}
void BaseWindow::SetMinimizable(bool minimizable) {
window_->SetMinimizable(minimizable);
}
bool BaseWindow::IsMinimizable() {
return window_->IsMinimizable();
}
void BaseWindow::SetMaximizable(bool maximizable) {
window_->SetMaximizable(maximizable);
}
bool BaseWindow::IsMaximizable() {
return window_->IsMaximizable();
}
void BaseWindow::SetFullScreenable(bool fullscreenable) {
window_->SetFullScreenable(fullscreenable);
}
bool BaseWindow::IsFullScreenable() {
return window_->IsFullScreenable();
}
void BaseWindow::SetClosable(bool closable) {
window_->SetClosable(closable);
}
bool BaseWindow::IsClosable() {
return window_->IsClosable();
}
void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) {
std::string level = "floating";
int relative_level = 0;
args->GetNext(&level);
args->GetNext(&relative_level);
ui::ZOrderLevel z_order =
top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal;
window_->SetAlwaysOnTop(z_order, level, relative_level);
}
bool BaseWindow::IsAlwaysOnTop() {
return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal;
}
void BaseWindow::Center() {
window_->Center();
}
void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetPosition(gfx::Point(x, y), animate);
}
std::vector<int> BaseWindow::GetPosition() {
std::vector<int> result(2);
gfx::Point pos = window_->GetPosition();
result[0] = pos.x();
result[1] = pos.y();
return result;
}
void BaseWindow::MoveAbove(const std::string& sourceId,
gin_helper::Arguments* args) {
#if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
if (!window_->MoveAbove(sourceId))
args->ThrowError("Invalid media source id");
#else
args->ThrowError("enable_desktop_capturer=true to use this feature");
#endif
}
void BaseWindow::MoveTop() {
window_->MoveTop();
}
void BaseWindow::SetTitle(const std::string& title) {
window_->SetTitle(title);
}
std::string BaseWindow::GetTitle() {
return window_->GetTitle();
}
void BaseWindow::SetAccessibleTitle(const std::string& title) {
window_->SetAccessibleTitle(title);
}
std::string BaseWindow::GetAccessibleTitle() {
return window_->GetAccessibleTitle();
}
void BaseWindow::FlashFrame(bool flash) {
window_->FlashFrame(flash);
}
void BaseWindow::SetSkipTaskbar(bool skip) {
window_->SetSkipTaskbar(skip);
}
void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) {
window_->SetExcludedFromShownWindowsMenu(excluded);
}
bool BaseWindow::IsExcludedFromShownWindowsMenu() {
return window_->IsExcludedFromShownWindowsMenu();
}
void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) {
window_->SetSimpleFullScreen(simple_fullscreen);
}
bool BaseWindow::IsSimpleFullScreen() {
return window_->IsSimpleFullScreen();
}
void BaseWindow::SetKiosk(bool kiosk) {
window_->SetKiosk(kiosk);
}
bool BaseWindow::IsKiosk() {
return window_->IsKiosk();
}
bool BaseWindow::IsTabletMode() const {
return window_->IsTabletMode();
}
void BaseWindow::SetBackgroundColor(const std::string& color_name) {
SkColor color = ParseCSSColor(color_name);
window_->SetBackgroundColor(color);
}
std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) {
return ToRGBHex(window_->GetBackgroundColor());
}
void BaseWindow::SetHasShadow(bool has_shadow) {
window_->SetHasShadow(has_shadow);
}
bool BaseWindow::HasShadow() {
return window_->HasShadow();
}
void BaseWindow::SetOpacity(const double opacity) {
window_->SetOpacity(opacity);
}
double BaseWindow::GetOpacity() {
return window_->GetOpacity();
}
void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) {
window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects));
}
void BaseWindow::SetRepresentedFilename(const std::string& filename) {
window_->SetRepresentedFilename(filename);
}
std::string BaseWindow::GetRepresentedFilename() {
return window_->GetRepresentedFilename();
}
void BaseWindow::SetDocumentEdited(bool edited) {
window_->SetDocumentEdited(edited);
}
bool BaseWindow::IsDocumentEdited() {
return window_->IsDocumentEdited();
}
void BaseWindow::SetIgnoreMouseEvents(bool ignore,
gin_helper::Arguments* args) {
gin_helper::Dictionary options;
bool forward = false;
args->GetNext(&options) && options.Get("forward", &forward);
return window_->SetIgnoreMouseEvents(ignore, forward);
}
void BaseWindow::SetContentProtection(bool enable) {
return window_->SetContentProtection(enable);
}
void BaseWindow::SetFocusable(bool focusable) {
return window_->SetFocusable(focusable);
}
bool BaseWindow::IsFocusable() {
return window_->IsFocusable();
}
void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) {
auto context = isolate->GetCurrentContext();
gin::Handle<Menu> menu;
v8::Local<v8::Object> object;
if (value->IsObject() && value->ToObject(context).ToLocal(&object) &&
gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) {
menu_.Reset(isolate, menu.ToV8());
// We only want to update the menu if the menu has a non-zero item count,
// or we risk crashes.
if (menu->model()->GetItemCount() == 0) {
RemoveMenu();
} else {
window_->SetMenu(menu->model());
}
} else if (value->IsNull()) {
RemoveMenu();
} else {
isolate->ThrowException(
v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu")));
}
}
void BaseWindow::RemoveMenu() {
menu_.Reset();
window_->SetMenu(nullptr);
}
void BaseWindow::SetParentWindow(v8::Local<v8::Value> value,
gin_helper::Arguments* args) {
if (IsModal()) {
args->ThrowError("Can not be called for modal window");
return;
}
gin::Handle<BaseWindow> parent;
if (value->IsNull() || value->IsUndefined()) {
RemoveFromParentChildWindows();
parent_window_.Reset();
window_->SetParentWindow(nullptr);
} else if (gin::ConvertFromV8(isolate(), value, &parent)) {
RemoveFromParentChildWindows();
parent_window_.Reset(isolate(), value);
window_->SetParentWindow(parent->window_.get());
parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper());
} else {
args->ThrowError("Must pass BaseWindow instance or null");
}
}
void BaseWindow::SetBrowserView(
absl::optional<gin::Handle<BrowserView>> browser_view) {
ResetBrowserViews();
if (browser_view)
AddBrowserView(*browser_view);
}
void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) {
auto iter = browser_views_.find(browser_view->ID());
if (iter == browser_views_.end()) {
// If we're reparenting a BrowserView, ensure that it's detached from
// its previous owner window.
BaseWindow* owner_window = browser_view->owner_window();
if (owner_window) {
// iter == browser_views_.end() should imply owner_window != this.
DCHECK_NE(owner_window, this);
owner_window->RemoveBrowserView(browser_view);
browser_view->SetOwnerWindow(nullptr);
}
window_->AddBrowserView(browser_view->view());
window_->AddDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(this);
browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8());
}
}
void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) {
auto iter = browser_views_.find(browser_view->ID());
if (iter != browser_views_.end()) {
window_->RemoveBrowserView(browser_view->view());
window_->RemoveDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(nullptr);
iter->second.Reset();
browser_views_.erase(iter);
}
}
void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view,
gin_helper::Arguments* args) {
BaseWindow* owner_window = browser_view->owner_window();
auto iter = browser_views_.find(browser_view->ID());
if (iter == browser_views_.end() || (owner_window && owner_window != this)) {
args->ThrowError("Given BrowserView is not attached to the window");
return;
}
window_->SetTopBrowserView(browser_view->view());
}
std::string BaseWindow::GetMediaSourceId() const {
return window_->GetDesktopMediaID().ToString();
}
v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() {
// TODO(MarshallOfSound): Replace once
// https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has
// landed
NativeWindowHandle handle = window_->GetNativeWindowHandle();
return ToBuffer(isolate(), &handle, sizeof(handle));
}
void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) {
gin_helper::Dictionary options;
std::string mode;
args->GetNext(&options) && options.Get("mode", &mode);
NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal;
if (mode == "error")
state = NativeWindow::ProgressState::kError;
else if (mode == "paused")
state = NativeWindow::ProgressState::kPaused;
else if (mode == "indeterminate")
state = NativeWindow::ProgressState::kIndeterminate;
else if (mode == "none")
state = NativeWindow::ProgressState::kNone;
window_->SetProgressBar(progress, state);
}
void BaseWindow::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {
window_->SetOverlayIcon(overlay, description);
}
void BaseWindow::SetVisibleOnAllWorkspaces(bool visible,
gin_helper::Arguments* args) {
gin_helper::Dictionary options;
bool visibleOnFullScreen = false;
bool skipTransformProcessType = false;
if (args->GetNext(&options)) {
options.Get("visibleOnFullScreen", &visibleOnFullScreen);
options.Get("skipTransformProcessType", &skipTransformProcessType);
}
return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen,
skipTransformProcessType);
}
bool BaseWindow::IsVisibleOnAllWorkspaces() {
return window_->IsVisibleOnAllWorkspaces();
}
void BaseWindow::SetAutoHideCursor(bool auto_hide) {
window_->SetAutoHideCursor(auto_hide);
}
void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) {
std::string type = gin::V8ToString(isolate, value);
window_->SetVibrancy(type);
}
#if BUILDFLAG(IS_MAC)
std::string BaseWindow::GetAlwaysOnTopLevel() {
return window_->GetAlwaysOnTopLevel();
}
void BaseWindow::SetWindowButtonVisibility(bool visible) {
window_->SetWindowButtonVisibility(visible);
}
bool BaseWindow::GetWindowButtonVisibility() const {
return window_->GetWindowButtonVisibility();
}
void BaseWindow::SetTrafficLightPosition(const gfx::Point& position) {
// For backward compatibility we treat (0, 0) as resetting to default.
if (position.IsOrigin())
window_->SetTrafficLightPosition(absl::nullopt);
else
window_->SetTrafficLightPosition(position);
}
gfx::Point BaseWindow::GetTrafficLightPosition() const {
// For backward compatibility we treat default value as (0, 0).
return window_->GetTrafficLightPosition().value_or(gfx::Point());
}
#endif
#if BUILDFLAG(IS_MAC)
bool BaseWindow::IsHiddenInMissionControl() {
return window_->IsHiddenInMissionControl();
}
void BaseWindow::SetHiddenInMissionControl(bool hidden) {
window_->SetHiddenInMissionControl(hidden);
}
#endif
void BaseWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
window_->SetTouchBar(std::move(items));
}
void BaseWindow::RefreshTouchBarItem(const std::string& item_id) {
window_->RefreshTouchBarItem(item_id);
}
void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) {
window_->SetEscapeTouchBarItem(std::move(item));
}
void BaseWindow::SelectPreviousTab() {
window_->SelectPreviousTab();
}
void BaseWindow::SelectNextTab() {
window_->SelectNextTab();
}
void BaseWindow::MergeAllWindows() {
window_->MergeAllWindows();
}
void BaseWindow::MoveTabToNewWindow() {
window_->MoveTabToNewWindow();
}
void BaseWindow::ToggleTabBar() {
window_->ToggleTabBar();
}
void BaseWindow::AddTabbedWindow(NativeWindow* window,
gin_helper::Arguments* args) {
if (!window_->AddTabbedWindow(window))
args->ThrowError("AddTabbedWindow cannot be called by a window on itself.");
}
void BaseWindow::SetAutoHideMenuBar(bool auto_hide) {
window_->SetAutoHideMenuBar(auto_hide);
}
bool BaseWindow::IsMenuBarAutoHide() {
return window_->IsMenuBarAutoHide();
}
void BaseWindow::SetMenuBarVisibility(bool visible) {
window_->SetMenuBarVisibility(visible);
}
bool BaseWindow::IsMenuBarVisible() {
return window_->IsMenuBarVisible();
}
void BaseWindow::SetAspectRatio(double aspect_ratio,
gin_helper::Arguments* args) {
gfx::Size extra_size;
args->GetNext(&extra_size);
window_->SetAspectRatio(aspect_ratio, extra_size);
}
void BaseWindow::PreviewFile(const std::string& path,
gin_helper::Arguments* args) {
std::string display_name;
if (!args->GetNext(&display_name))
display_name = path;
window_->PreviewFile(path, display_name);
}
void BaseWindow::CloseFilePreview() {
window_->CloseFilePreview();
}
void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) {
window_->SetGTKDarkThemeEnabled(use_dark_theme);
}
v8::Local<v8::Value> BaseWindow::GetContentView() const {
if (content_view_.IsEmpty())
return v8::Null(isolate());
else
return v8::Local<v8::Value>::New(isolate(), content_view_);
}
v8::Local<v8::Value> BaseWindow::GetParentWindow() const {
if (parent_window_.IsEmpty())
return v8::Null(isolate());
else
return v8::Local<v8::Value>::New(isolate(), parent_window_);
}
std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const {
return child_windows_.Values(isolate());
}
v8::Local<v8::Value> BaseWindow::GetBrowserView(
gin_helper::Arguments* args) const {
if (browser_views_.empty()) {
return v8::Null(isolate());
} else if (browser_views_.size() == 1) {
auto first_view = browser_views_.begin();
return v8::Local<v8::Value>::New(isolate(), (*first_view).second);
} else {
args->ThrowError(
"BrowserWindow have multiple BrowserViews, "
"Use getBrowserViews() instead");
return v8::Null(isolate());
}
}
std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const {
std::vector<v8::Local<v8::Value>> ret;
for (auto const& views_iter : browser_views_) {
ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second));
}
return ret;
}
bool BaseWindow::IsModal() const {
return window_->is_modal();
}
bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) {
#if BUILDFLAG(IS_WIN)
std::vector<TaskbarHost::ThumbarButton> buttons;
if (!args->GetNext(&buttons)) {
args->ThrowError();
return false;
}
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbarButtons(
window_->GetAcceleratedWidget(), buttons);
#else
return false;
#endif
}
#if defined(TOOLKIT_VIEWS)
void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow);
}
void BaseWindow::SetIconImpl(v8::Isolate* isolate,
v8::Local<v8::Value> icon,
NativeImage::OnConvertError on_error) {
NativeImage* native_image = nullptr;
if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image,
on_error))
return;
#if BUILDFLAG(IS_WIN)
static_cast<NativeWindowViews*>(window_.get())
->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)),
native_image->GetHICON(GetSystemMetrics(SM_CXICON)));
#elif BUILDFLAG(IS_LINUX)
static_cast<NativeWindowViews*>(window_.get())
->SetIcon(native_image->image().AsImageSkia());
#endif
}
#endif
#if BUILDFLAG(IS_WIN)
bool BaseWindow::HookWindowMessage(UINT message,
const MessageCallback& callback) {
messages_callback_map_[message] = callback;
return true;
}
void BaseWindow::UnhookWindowMessage(UINT message) {
messages_callback_map_.erase(message);
}
bool BaseWindow::IsWindowMessageHooked(UINT message) {
return base::Contains(messages_callback_map_, message);
}
void BaseWindow::UnhookAllWindowMessages() {
messages_callback_map_.clear();
}
bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) {
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailClip(
window_->GetAcceleratedWidget(), region);
}
bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) {
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailToolTip(
window_->GetAcceleratedWidget(), tooltip);
}
void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) {
std::wstring app_id;
base::FilePath app_icon_path;
int app_icon_index = 0;
std::wstring relaunch_command;
std::wstring relaunch_display_name;
options.Get("appId", &app_id);
options.Get("appIconPath", &app_icon_path);
options.Get("appIconIndex", &app_icon_index);
options.Get("relaunchCommand", &relaunch_command);
options.Get("relaunchDisplayName", &relaunch_display_name);
ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index,
relaunch_command, relaunch_display_name,
window_->GetAcceleratedWidget());
}
#endif
int32_t BaseWindow::GetID() const {
return weak_map_id();
}
void BaseWindow::ResetBrowserViews() {
v8::HandleScope scope(isolate());
for (auto& item : browser_views_) {
gin::Handle<BrowserView> browser_view;
if (gin::ConvertFromV8(isolate(),
v8::Local<v8::Value>::New(isolate(), item.second),
&browser_view) &&
!browser_view.IsEmpty()) {
// There's a chance that the BrowserView may have been reparented - only
// reset if the owner window is *this* window.
BaseWindow* owner_window = browser_view->owner_window();
DCHECK_EQ(owner_window, this);
browser_view->SetOwnerWindow(nullptr);
window_->RemoveBrowserView(browser_view->view());
window_->RemoveDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(nullptr);
}
item.second.Reset();
}
browser_views_.clear();
}
void BaseWindow::RemoveFromParentChildWindows() {
if (parent_window_.IsEmpty())
return;
gin::Handle<BaseWindow> parent;
if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) ||
parent.IsEmpty()) {
return;
}
parent->child_windows_.Remove(weak_map_id());
}
// static
gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
return new BaseWindow(args, options);
}
// static
void BaseWindow::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow"));
gin_helper::Destroyable::MakeDestroyable(isolate, prototype);
gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("setContentView", &BaseWindow::SetContentView)
.SetMethod("close", &BaseWindow::Close)
.SetMethod("focus", &BaseWindow::Focus)
.SetMethod("blur", &BaseWindow::Blur)
.SetMethod("isFocused", &BaseWindow::IsFocused)
.SetMethod("show", &BaseWindow::Show)
.SetMethod("showInactive", &BaseWindow::ShowInactive)
.SetMethod("hide", &BaseWindow::Hide)
.SetMethod("isVisible", &BaseWindow::IsVisible)
.SetMethod("isEnabled", &BaseWindow::IsEnabled)
.SetMethod("setEnabled", &BaseWindow::SetEnabled)
.SetMethod("maximize", &BaseWindow::Maximize)
.SetMethod("unmaximize", &BaseWindow::Unmaximize)
.SetMethod("isMaximized", &BaseWindow::IsMaximized)
.SetMethod("minimize", &BaseWindow::Minimize)
.SetMethod("restore", &BaseWindow::Restore)
.SetMethod("isMinimized", &BaseWindow::IsMinimized)
.SetMethod("setFullScreen", &BaseWindow::SetFullScreen)
.SetMethod("isFullScreen", &BaseWindow::IsFullscreen)
.SetMethod("setBounds", &BaseWindow::SetBounds)
.SetMethod("getBounds", &BaseWindow::GetBounds)
.SetMethod("isNormal", &BaseWindow::IsNormal)
.SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds)
.SetMethod("setSize", &BaseWindow::SetSize)
.SetMethod("getSize", &BaseWindow::GetSize)
.SetMethod("setContentBounds", &BaseWindow::SetContentBounds)
.SetMethod("getContentBounds", &BaseWindow::GetContentBounds)
.SetMethod("setContentSize", &BaseWindow::SetContentSize)
.SetMethod("getContentSize", &BaseWindow::GetContentSize)
.SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize)
.SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize)
.SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize)
.SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize)
.SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset)
.SetMethod("moveAbove", &BaseWindow::MoveAbove)
.SetMethod("moveTop", &BaseWindow::MoveTop)
.SetMethod("setResizable", &BaseWindow::SetResizable)
.SetMethod("isResizable", &BaseWindow::IsResizable)
.SetMethod("setMovable", &BaseWindow::SetMovable)
.SetMethod("isMovable", &BaseWindow::IsMovable)
.SetMethod("setMinimizable", &BaseWindow::SetMinimizable)
.SetMethod("isMinimizable", &BaseWindow::IsMinimizable)
.SetMethod("setMaximizable", &BaseWindow::SetMaximizable)
.SetMethod("isMaximizable", &BaseWindow::IsMaximizable)
.SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable)
.SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable)
.SetMethod("setClosable", &BaseWindow::SetClosable)
.SetMethod("isClosable", &BaseWindow::IsClosable)
.SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop)
.SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop)
.SetMethod("center", &BaseWindow::Center)
.SetMethod("setPosition", &BaseWindow::SetPosition)
.SetMethod("getPosition", &BaseWindow::GetPosition)
.SetMethod("setTitle", &BaseWindow::SetTitle)
.SetMethod("getTitle", &BaseWindow::GetTitle)
.SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle,
&BaseWindow::SetAccessibleTitle)
.SetMethod("flashFrame", &BaseWindow::FlashFrame)
.SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar)
.SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen)
.SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen)
.SetMethod("setKiosk", &BaseWindow::SetKiosk)
.SetMethod("isKiosk", &BaseWindow::IsKiosk)
.SetMethod("isTabletMode", &BaseWindow::IsTabletMode)
.SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor)
.SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor)
.SetMethod("setHasShadow", &BaseWindow::SetHasShadow)
.SetMethod("hasShadow", &BaseWindow::HasShadow)
.SetMethod("setOpacity", &BaseWindow::SetOpacity)
.SetMethod("getOpacity", &BaseWindow::GetOpacity)
.SetMethod("setShape", &BaseWindow::SetShape)
.SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename)
.SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename)
.SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited)
.SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited)
.SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents)
.SetMethod("setContentProtection", &BaseWindow::SetContentProtection)
.SetMethod("setFocusable", &BaseWindow::SetFocusable)
.SetMethod("isFocusable", &BaseWindow::IsFocusable)
.SetMethod("setMenu", &BaseWindow::SetMenu)
.SetMethod("removeMenu", &BaseWindow::RemoveMenu)
.SetMethod("setParentWindow", &BaseWindow::SetParentWindow)
.SetMethod("setBrowserView", &BaseWindow::SetBrowserView)
.SetMethod("addBrowserView", &BaseWindow::AddBrowserView)
.SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView)
.SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView)
.SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId)
.SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle)
.SetMethod("setProgressBar", &BaseWindow::SetProgressBar)
.SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon)
.SetMethod("setVisibleOnAllWorkspaces",
&BaseWindow::SetVisibleOnAllWorkspaces)
.SetMethod("isVisibleOnAllWorkspaces",
&BaseWindow::IsVisibleOnAllWorkspaces)
#if BUILDFLAG(IS_MAC)
.SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel)
.SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor)
#endif
.SetMethod("setVibrancy", &BaseWindow::SetVibrancy)
#if BUILDFLAG(IS_MAC)
.SetMethod("setTrafficLightPosition",
&BaseWindow::SetTrafficLightPosition)
.SetMethod("getTrafficLightPosition",
&BaseWindow::GetTrafficLightPosition)
#endif
#if BUILDFLAG(IS_MAC)
.SetMethod("isHiddenInMissionControl",
&BaseWindow::IsHiddenInMissionControl)
.SetMethod("setHiddenInMissionControl",
&BaseWindow::SetHiddenInMissionControl)
#endif
.SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar)
.SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem)
.SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem)
#if BUILDFLAG(IS_MAC)
.SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab)
.SetMethod("selectNextTab", &BaseWindow::SelectNextTab)
.SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows)
.SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow)
.SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar)
.SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow)
.SetMethod("setWindowButtonVisibility",
&BaseWindow::SetWindowButtonVisibility)
.SetMethod("_getWindowButtonVisibility",
&BaseWindow::GetWindowButtonVisibility)
.SetProperty("excludedFromShownWindowsMenu",
&BaseWindow::IsExcludedFromShownWindowsMenu,
&BaseWindow::SetExcludedFromShownWindowsMenu)
#endif
.SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar)
.SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide)
.SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility)
.SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible)
.SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio)
.SetMethod("previewFile", &BaseWindow::PreviewFile)
.SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview)
.SetMethod("getContentView", &BaseWindow::GetContentView)
.SetMethod("getParentWindow", &BaseWindow::GetParentWindow)
.SetMethod("getChildWindows", &BaseWindow::GetChildWindows)
.SetMethod("getBrowserView", &BaseWindow::GetBrowserView)
.SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews)
.SetMethod("isModal", &BaseWindow::IsModal)
.SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons)
#if defined(TOOLKIT_VIEWS)
.SetMethod("setIcon", &BaseWindow::SetIcon)
#endif
#if BUILDFLAG(IS_WIN)
.SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage)
.SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked)
.SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage)
.SetMethod("unhookAllWindowMessages",
&BaseWindow::UnhookAllWindowMessages)
.SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip)
.SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip)
.SetMethod("setAppDetails", &BaseWindow::SetAppDetails)
#endif
.SetProperty("id", &BaseWindow::GetID);
}
} // namespace electron::api
namespace {
using electron::api::BaseWindow;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New));
gin_helper::Dictionary constructor(isolate,
BaseWindow::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID);
constructor.SetMethod("getAllWindows", &BaseWindow::GetAll);
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BaseWindow", constructor);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_base_window, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/api/electron_api_base_window.h
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "gin/handle.h"
#include "shell/browser/native_window.h"
#include "shell/browser/native_window_observer.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/trackable_object.h"
namespace electron::api {
class View;
class BrowserView;
class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
public NativeWindowObserver {
public:
static gin_helper::WrappableBase* New(gin_helper::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
NativeWindow* window() const { return window_.get(); }
protected:
// Common constructor.
BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options);
// Creating independent BaseWindow instance.
BaseWindow(gin_helper::Arguments* args,
const gin_helper::Dictionary& options);
~BaseWindow() override;
// TrackableObject:
void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override;
// NativeWindowObserver:
void WillCloseWindow(bool* prevent_default) override;
void OnWindowClosed() override;
void OnWindowEndSession() override;
void OnWindowBlur() override;
void OnWindowFocus() override;
void OnWindowShow() override;
void OnWindowHide() override;
void OnWindowMaximize() override;
void OnWindowUnmaximize() override;
void OnWindowMinimize() override;
void OnWindowRestore() override;
void OnWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) override;
void OnWindowResize() override;
void OnWindowResized() override;
void OnWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) override;
void OnWindowMove() override;
void OnWindowMoved() override;
void OnWindowSwipe(const std::string& direction) override;
void OnWindowRotateGesture(float rotation) override;
void OnWindowSheetBegin() override;
void OnWindowSheetEnd() override;
void OnWindowEnterFullScreen() override;
void OnWindowLeaveFullScreen() override;
void OnWindowEnterHtmlFullScreen() override;
void OnWindowLeaveHtmlFullScreen() override;
void OnWindowAlwaysOnTopChanged() override;
void OnExecuteAppCommand(const std::string& command_name) override;
void OnTouchBarItemResult(const std::string& item_id,
const base::Value::Dict& details) override;
void OnNewWindowForTab() override;
void OnSystemContextMenu(int x, int y, bool* prevent_default) override;
#if BUILDFLAG(IS_WIN)
void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override;
#endif
// Public APIs of NativeWindow.
void SetContentView(gin::Handle<View> view);
void Close();
virtual void CloseImmediately();
virtual void Focus();
virtual void Blur();
bool IsFocused();
void Show();
void ShowInactive();
void Hide();
bool IsVisible();
bool IsEnabled();
void SetEnabled(bool enable);
void Maximize();
void Unmaximize();
bool IsMaximized();
void Minimize();
void Restore();
bool IsMinimized();
void SetFullScreen(bool fullscreen);
bool IsFullscreen();
void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args);
gfx::Rect GetBounds();
void SetSize(int width, int height, gin_helper::Arguments* args);
std::vector<int> GetSize();
void SetContentSize(int width, int height, gin_helper::Arguments* args);
std::vector<int> GetContentSize();
void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args);
gfx::Rect GetContentBounds();
bool IsNormal();
gfx::Rect GetNormalBounds();
void SetMinimumSize(int width, int height);
std::vector<int> GetMinimumSize();
void SetMaximumSize(int width, int height);
std::vector<int> GetMaximumSize();
void SetSheetOffset(double offsetY, gin_helper::Arguments* args);
void SetResizable(bool resizable);
bool IsResizable();
void SetMovable(bool movable);
void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args);
void MoveTop();
bool IsMovable();
void SetMinimizable(bool minimizable);
bool IsMinimizable();
void SetMaximizable(bool maximizable);
bool IsMaximizable();
void SetFullScreenable(bool fullscreenable);
bool IsFullScreenable();
void SetClosable(bool closable);
bool IsClosable();
void SetAlwaysOnTop(bool top, gin_helper::Arguments* args);
bool IsAlwaysOnTop();
void Center();
void SetPosition(int x, int y, gin_helper::Arguments* args);
std::vector<int> GetPosition();
void SetTitle(const std::string& title);
std::string GetTitle();
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
void FlashFrame(bool flash);
void SetSkipTaskbar(bool skip);
void SetExcludedFromShownWindowsMenu(bool excluded);
bool IsExcludedFromShownWindowsMenu();
void SetSimpleFullScreen(bool simple_fullscreen);
bool IsSimpleFullScreen();
void SetKiosk(bool kiosk);
bool IsKiosk();
bool IsTabletMode() const;
virtual void SetBackgroundColor(const std::string& color_name);
std::string GetBackgroundColor(gin_helper::Arguments* args);
void SetHasShadow(bool has_shadow);
bool HasShadow();
void SetOpacity(const double opacity);
double GetOpacity();
void SetShape(const std::vector<gfx::Rect>& rects);
void SetRepresentedFilename(const std::string& filename);
std::string GetRepresentedFilename();
void SetDocumentEdited(bool edited);
bool IsDocumentEdited();
void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args);
void SetContentProtection(bool enable);
void SetFocusable(bool focusable);
bool IsFocusable();
void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu);
void RemoveMenu();
void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args);
virtual void SetBrowserView(
absl::optional<gin::Handle<BrowserView>> browser_view);
virtual void AddBrowserView(gin::Handle<BrowserView> browser_view);
virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view);
virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view,
gin_helper::Arguments* args);
virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const;
virtual void ResetBrowserViews();
std::string GetMediaSourceId() const;
v8::Local<v8::Value> GetNativeWindowHandle();
void SetProgressBar(double progress, gin_helper::Arguments* args);
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description);
void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args);
bool IsVisibleOnAllWorkspaces();
void SetAutoHideCursor(bool auto_hide);
virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value);
#if BUILDFLAG(IS_MAC)
std::string GetAlwaysOnTopLevel();
void SetWindowButtonVisibility(bool visible);
bool GetWindowButtonVisibility() const;
void SetTrafficLightPosition(const gfx::Point& position);
gfx::Point GetTrafficLightPosition() const;
#endif
#if BUILDFLAG(IS_MAC)
bool IsHiddenInMissionControl();
void SetHiddenInMissionControl(bool hidden);
#endif
void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
void RefreshTouchBarItem(const std::string& item_id);
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
void SelectPreviousTab();
void SelectNextTab();
void MergeAllWindows();
void MoveTabToNewWindow();
void ToggleTabBar();
void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args);
void SetAutoHideMenuBar(bool auto_hide);
bool IsMenuBarAutoHide();
void SetMenuBarVisibility(bool visible);
bool IsMenuBarVisible();
void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args);
void PreviewFile(const std::string& path, gin_helper::Arguments* args);
void CloseFilePreview();
void SetGTKDarkThemeEnabled(bool use_dark_theme);
// Public getters of NativeWindow.
v8::Local<v8::Value> GetContentView() const;
v8::Local<v8::Value> GetParentWindow() const;
std::vector<v8::Local<v8::Object>> GetChildWindows() const;
v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const;
bool IsModal() const;
// Extra APIs added in JS.
bool SetThumbarButtons(gin_helper::Arguments* args);
#if defined(TOOLKIT_VIEWS)
void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
void SetIconImpl(v8::Isolate* isolate,
v8::Local<v8::Value> icon,
NativeImage::OnConvertError on_error);
#endif
#if BUILDFLAG(IS_WIN)
typedef base::RepeatingCallback<void(v8::Local<v8::Value>,
v8::Local<v8::Value>)>
MessageCallback;
bool HookWindowMessage(UINT message, const MessageCallback& callback);
bool IsWindowMessageHooked(UINT message);
void UnhookWindowMessage(UINT message);
void UnhookAllWindowMessages();
bool SetThumbnailClip(const gfx::Rect& region);
bool SetThumbnailToolTip(const std::string& tooltip);
void SetAppDetails(const gin_helper::Dictionary& options);
#endif
int32_t GetID() const;
// Helpers.
// Remove BrowserView.
void ResetBrowserView();
// Remove this window from parent window's |child_windows_|.
void RemoveFromParentChildWindows();
template <typename... Args>
void EmitEventSoon(base::StringPiece eventName) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>),
weak_factory_.GetWeakPtr(), eventName));
}
#if BUILDFLAG(IS_WIN)
typedef std::map<UINT, MessageCallback> MessageCallbackMap;
MessageCallbackMap messages_callback_map_;
#endif
v8::Global<v8::Value> content_view_;
std::map<int32_t, v8::Global<v8::Value>> browser_views_;
v8::Global<v8::Value> menu_;
v8::Global<v8::Value> parent_window_;
KeyWeakMap<int> child_windows_;
std::unique_ptr<NativeWindow> window_;
// Reference to JS wrapper to prevent garbage collection.
v8::Global<v8::Value> self_ref_;
base::WeakPtrFactory<BaseWindow> weak_factory_{this};
};
} // namespace electron::api
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent() || !ui::win::IsAeroGlassEnabled())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
if (have_max_width && max_width <= 0)
max_width = INT_MAX;
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
if (have_max_height && max_height <= 0)
max_height = INT_MAX;
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (std::find(draggable_region_providers_.begin(),
draggable_region_providers_.end(),
provider) == draggable_region_providers_.end()) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::NONE);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#include <list>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/supports_user_data.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/web_contents_user_data.h"
#include "extensions/browser/app_window/size_constraints.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_observer.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/widget/widget_delegate.h"
class SkRegion;
namespace base {
class DictionaryValue;
}
namespace content {
struct NativeWebKeyboardEvent;
}
namespace gfx {
class Image;
class Point;
class Rect;
enum class ResizeEdge;
class Size;
} // namespace gfx
namespace gin_helper {
class Dictionary;
class PersistentDictionary;
} // namespace gin_helper
namespace electron {
class ElectronMenuModel;
class NativeBrowserView;
namespace api {
class BrowserView;
}
#if BUILDFLAG(IS_MAC)
typedef NSView* NativeWindowHandle;
#else
typedef gfx::AcceleratedWidget NativeWindowHandle;
#endif
class NativeWindow : public base::SupportsUserData,
public views::WidgetDelegate {
public:
~NativeWindow() override;
// disable copy
NativeWindow(const NativeWindow&) = delete;
NativeWindow& operator=(const NativeWindow&) = delete;
// Create window with existing WebContents, the caller is responsible for
// managing the window's live.
static NativeWindow* Create(const gin_helper::Dictionary& options,
NativeWindow* parent = nullptr);
void InitFromOptions(const gin_helper::Dictionary& options);
virtual void SetContentView(views::View* view) = 0;
virtual void Close() = 0;
virtual void CloseImmediately() = 0;
virtual bool IsClosed() const;
virtual void Focus(bool focus) = 0;
virtual bool IsFocused() = 0;
virtual void Show() = 0;
virtual void ShowInactive() = 0;
virtual void Hide() = 0;
virtual bool IsVisible() = 0;
virtual bool IsEnabled() = 0;
virtual void SetEnabled(bool enable) = 0;
virtual void Maximize() = 0;
virtual void Unmaximize() = 0;
virtual bool IsMaximized() = 0;
virtual void Minimize() = 0;
virtual void Restore() = 0;
virtual bool IsMinimized() = 0;
virtual void SetFullScreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0;
virtual gfx::Rect GetBounds() = 0;
virtual void SetSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetSize();
virtual void SetPosition(const gfx::Point& position, bool animate = false);
virtual gfx::Point GetPosition();
virtual void SetContentSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetContentSize();
virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false);
virtual gfx::Rect GetContentBounds();
virtual bool IsNormal();
virtual gfx::Rect GetNormalBounds() = 0;
virtual void SetSizeConstraints(
const extensions::SizeConstraints& window_constraints);
virtual extensions::SizeConstraints GetSizeConstraints() const;
virtual void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints);
virtual extensions::SizeConstraints GetContentSizeConstraints() const;
virtual void SetMinimumSize(const gfx::Size& size);
virtual gfx::Size GetMinimumSize() const;
virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize() const;
virtual gfx::Size GetContentMinimumSize() const;
virtual gfx::Size GetContentMaximumSize() const;
virtual void SetSheetOffset(const double offsetX, const double offsetY);
virtual double GetSheetOffsetX();
virtual double GetSheetOffsetY();
virtual void SetResizable(bool resizable) = 0;
virtual bool MoveAbove(const std::string& sourceId) = 0;
virtual void MoveTop() = 0;
virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0;
virtual bool IsMovable() = 0;
virtual void SetMinimizable(bool minimizable) = 0;
virtual bool IsMinimizable() = 0;
virtual void SetMaximizable(bool maximizable) = 0;
virtual bool IsMaximizable() = 0;
virtual void SetFullScreenable(bool fullscreenable) = 0;
virtual bool IsFullScreenable() = 0;
virtual void SetClosable(bool closable) = 0;
virtual bool IsClosable() = 0;
virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level = "floating",
int relativeLevel = 0) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() = 0;
virtual void Center() = 0;
virtual void Invalidate() = 0;
virtual void SetTitle(const std::string& title) = 0;
virtual std::string GetTitle() = 0;
#if BUILDFLAG(IS_MAC)
virtual std::string GetAlwaysOnTopLevel() = 0;
virtual void SetActive(bool is_key) = 0;
virtual bool IsActive() const = 0;
#endif
// Ability to augment the window title for the screen readers.
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
virtual void FlashFrame(bool flash) = 0;
virtual void SetSkipTaskbar(bool skip) = 0;
virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0;
virtual bool IsExcludedFromShownWindowsMenu() = 0;
virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0;
virtual bool IsSimpleFullScreen() = 0;
virtual void SetKiosk(bool kiosk) = 0;
virtual bool IsKiosk() = 0;
virtual bool IsTabletMode() const;
virtual void SetBackgroundColor(SkColor color) = 0;
virtual SkColor GetBackgroundColor() = 0;
virtual void SetHasShadow(bool has_shadow) = 0;
virtual bool HasShadow() = 0;
virtual void SetOpacity(const double opacity) = 0;
virtual double GetOpacity() = 0;
virtual void SetRepresentedFilename(const std::string& filename);
virtual std::string GetRepresentedFilename();
virtual void SetDocumentEdited(bool edited);
virtual bool IsDocumentEdited();
virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0;
virtual void SetContentProtection(bool enable) = 0;
virtual void SetFocusable(bool focusable);
virtual bool IsFocusable();
virtual void SetMenu(ElectronMenuModel* menu);
virtual void SetParentWindow(NativeWindow* parent);
virtual void AddBrowserView(NativeBrowserView* browser_view) = 0;
virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0;
virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0;
virtual content::DesktopMediaID GetDesktopMediaID() const = 0;
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0;
virtual NativeWindowHandle GetNativeWindowHandle() const = 0;
// Taskbar/Dock APIs.
enum class ProgressState {
kNone, // no progress, no marking
kIndeterminate, // progress, indeterminate
kError, // progress, errored (red)
kPaused, // progress, paused (yellow)
kNormal, // progress, not marked (green)
};
virtual void SetProgressBar(double progress, const ProgressState state) = 0;
virtual void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) = 0;
// Workspace APIs.
virtual void SetVisibleOnAllWorkspaces(
bool visible,
bool visibleOnFullScreen = false,
bool skipTransformProcessType = false) = 0;
virtual bool IsVisibleOnAllWorkspaces() = 0;
virtual void SetAutoHideCursor(bool auto_hide);
// Vibrancy API
virtual void SetVibrancy(const std::string& type);
// Traffic Light API
#if BUILDFLAG(IS_MAC)
virtual void SetWindowButtonVisibility(bool visible) = 0;
virtual bool GetWindowButtonVisibility() const = 0;
virtual void SetTrafficLightPosition(absl::optional<gfx::Point> position) = 0;
virtual absl::optional<gfx::Point> GetTrafficLightPosition() const = 0;
virtual void RedrawTrafficLights() = 0;
virtual void UpdateFrame() = 0;
#endif
// whether windows should be ignored by mission control
#if BUILDFLAG(IS_MAC)
virtual bool IsHiddenInMissionControl() = 0;
virtual void SetHiddenInMissionControl(bool hidden) = 0;
#endif
// Touchbar API
virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
virtual void RefreshTouchBarItem(const std::string& item_id);
virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
// Native Tab API
virtual void SelectPreviousTab();
virtual void SelectNextTab();
virtual void MergeAllWindows();
virtual void MoveTabToNewWindow();
virtual void ToggleTabBar();
virtual bool AddTabbedWindow(NativeWindow* window);
// Toggle the menu bar.
virtual void SetAutoHideMenuBar(bool auto_hide);
virtual bool IsMenuBarAutoHide();
virtual void SetMenuBarVisibility(bool visible);
virtual bool IsMenuBarVisible();
// Set the aspect ratio when resizing window.
double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize();
virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
// File preview APIs.
virtual void PreviewFile(const std::string& path,
const std::string& display_name);
virtual void CloseFilePreview();
virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {}
// Converts between content bounds and window bounds.
virtual gfx::Rect ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const = 0;
virtual gfx::Rect WindowBoundsToContentBounds(
const gfx::Rect& bounds) const = 0;
base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
virtual gfx::Rect GetWindowControlsOverlayRect();
virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect);
// Methods called by the WebContents.
virtual void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {}
// Public API used by platform-dependent delegates and observers to send UI
// related notifications.
void NotifyWindowRequestPreferredWidth(int* width);
void NotifyWindowCloseButtonClicked();
void NotifyWindowClosed();
void NotifyWindowEndSession();
void NotifyWindowBlur();
void NotifyWindowFocus();
void NotifyWindowShow();
void NotifyWindowIsKeyChanged(bool is_key);
void NotifyWindowHide();
void NotifyWindowMaximize();
void NotifyWindowUnmaximize();
void NotifyWindowMinimize();
void NotifyWindowRestore();
void NotifyWindowMove();
void NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default);
void NotifyWindowResize();
void NotifyWindowResized();
void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default);
void NotifyWindowMoved();
void NotifyWindowSwipe(const std::string& direction);
void NotifyWindowRotateGesture(float rotation);
void NotifyWindowSheetBegin();
void NotifyWindowSheetEnd();
virtual void NotifyWindowEnterFullScreen();
virtual void NotifyWindowLeaveFullScreen();
void NotifyWindowEnterHtmlFullScreen();
void NotifyWindowLeaveHtmlFullScreen();
void NotifyWindowAlwaysOnTopChanged();
void NotifyWindowExecuteAppCommand(const std::string& command);
void NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details);
void NotifyNewWindowForTab();
void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default);
void NotifyLayoutWindowControlsOverlay();
#if BUILDFLAG(IS_WIN)
void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param);
#endif
void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(NativeWindowObserver* obs) {
observers_.RemoveObserver(obs);
}
// Handle fullscreen transitions.
void HandlePendingFullscreenTransitions();
enum class FullScreenTransitionState { ENTERING, EXITING, NONE };
void set_fullscreen_transition_state(FullScreenTransitionState state) {
fullscreen_transition_state_ = state;
}
FullScreenTransitionState fullscreen_transition_state() const {
return fullscreen_transition_state_;
}
enum class FullScreenTransitionType { HTML, NATIVE, NONE };
void set_fullscreen_transition_type(FullScreenTransitionType type) {
fullscreen_transition_type_ = type;
}
FullScreenTransitionType fullscreen_transition_type() const {
return fullscreen_transition_type_;
}
views::Widget* widget() const { return widget_.get(); }
views::View* content_view() const { return content_view_; }
enum class TitleBarStyle {
kNormal,
kHidden,
kHiddenInset,
kCustomButtonsOnHover,
};
TitleBarStyle title_bar_style() const { return title_bar_style_; }
int titlebar_overlay_height() const { return titlebar_overlay_height_; }
void set_titlebar_overlay_height(int height) {
titlebar_overlay_height_ = height;
}
bool titlebar_overlay_enabled() const { return titlebar_overlay_; }
bool has_frame() const { return has_frame_; }
void set_has_frame(bool has_frame) { has_frame_ = has_frame; }
bool has_client_frame() const { return has_client_frame_; }
bool transparent() const { return transparent_; }
bool enable_larger_than_screen() const { return enable_larger_than_screen_; }
NativeWindow* parent() const { return parent_; }
bool is_modal() const { return is_modal_; }
std::list<NativeBrowserView*> browser_views() const { return browser_views_; }
int32_t window_id() const { return next_id_; }
int NonClientHitTest(const gfx::Point& point);
void AddDraggableRegionProvider(DraggableRegionProvider* provider);
void RemoveDraggableRegionProvider(DraggableRegionProvider* provider);
protected:
friend class api::BrowserView;
NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent);
// views::WidgetDelegate:
views::Widget* GetWidget() override;
const views::Widget* GetWidget() const override;
std::u16string GetAccessibleWindowTitle() const override;
void set_content_view(views::View* view) { content_view_ = view; }
void add_browser_view(NativeBrowserView* browser_view) {
browser_views_.push_back(browser_view);
}
void remove_browser_view(NativeBrowserView* browser_view) {
browser_views_.remove_if(
[&browser_view](NativeBrowserView* n) { return (n == browser_view); });
}
// The boolean parsing of the "titleBarOverlay" option
bool titlebar_overlay_ = false;
// The custom height parsed from the "height" option in a Object
// "titleBarOverlay"
int titlebar_overlay_height_ = 0;
// The "titleBarStyle" option.
TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal;
std::queue<bool> pending_transitions_;
FullScreenTransitionState fullscreen_transition_state_ =
FullScreenTransitionState::NONE;
FullScreenTransitionType fullscreen_transition_type_ =
FullScreenTransitionType::NONE;
private:
std::unique_ptr<views::Widget> widget_;
static int32_t next_id_;
// The content view, weak ref.
views::View* content_view_ = nullptr;
// Whether window has standard frame.
bool has_frame_ = true;
// Whether window has standard frame, but it's drawn by Electron (the client
// application) instead of the OS. Currently only has meaning on Linux for
// Wayland hosts.
bool has_client_frame_ = false;
// Whether window is transparent.
bool transparent_ = false;
// Minimum and maximum size, stored as content size.
extensions::SizeConstraints size_constraints_;
// Whether window can be resized larger than screen.
bool enable_larger_than_screen_ = false;
// The windows has been closed.
bool is_closed_ = false;
// Used to display sheets at the appropriate horizontal and vertical offsets
// on macOS.
double sheet_offset_x_ = 0.0;
double sheet_offset_y_ = 0.0;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_ = 0.0;
gfx::Size aspect_ratio_extraSize_;
// The parent window, it is guaranteed to be valid during this window's life.
NativeWindow* parent_ = nullptr;
// Is this a modal window.
bool is_modal_ = false;
// The browser view layer.
std::list<NativeBrowserView*> browser_views_;
std::list<DraggableRegionProvider*> draggable_region_providers_;
// Observers of this window.
base::ObserverList<NativeWindowObserver> observers_;
// Accessible title.
std::u16string accessible_title_;
gfx::Rect overlay_rect_;
base::WeakPtrFactory<NativeWindow> weak_factory_{this};
};
// This class provides a hook to get a NativeWindow from a WebContents.
class NativeWindowRelay
: public content::WebContentsUserData<NativeWindowRelay> {
public:
static void CreateForWebContents(content::WebContents*,
base::WeakPtr<NativeWindow>);
~NativeWindowRelay() override;
NativeWindow* GetNativeWindow() const { return native_window_.get(); }
WEB_CONTENTS_USER_DATA_KEY_DECL();
private:
friend class content::WebContentsUserData<NativeWindow>;
explicit NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window);
base::WeakPtr<NativeWindow> native_window_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window_mac.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#import <Cocoa/Cocoa.h>
#include <memory>
#include <string>
#include <vector>
#include "base/mac/scoped_nsobject.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "ui/display/display_observer.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/controls/native/native_view_host.h"
@class ElectronNSWindow;
@class ElectronNSWindowDelegate;
@class ElectronPreviewItem;
@class ElectronTouchBar;
@class WindowButtonsProxy;
namespace electron {
class RootViewMac;
class NativeWindowMac : public NativeWindow,
public ui::NativeThemeObserver,
public display::DisplayObserver {
public:
NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent);
~NativeWindowMac() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate = false) override;
gfx::Rect GetBounds() override;
bool IsNormal() override;
gfx::Rect GetNormalBounds() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relative_level) override;
std::string GetAlwaysOnTopLevel() override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
void SetBackgroundColor(SkColor color) override;
SkColor GetBackgroundColor() override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetRepresentedFilename(const std::string& filename) override;
std::string GetRepresentedFilename() override;
void SetDocumentEdited(bool edited) override;
bool IsDocumentEdited() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
bool IsHiddenInMissionControl() override;
void SetHiddenInMissionControl(bool hidden) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetAutoHideCursor(bool auto_hide) override;
void SetVibrancy(const std::string& type) override;
void SetWindowButtonVisibility(bool visible) override;
bool GetWindowButtonVisibility() const override;
void SetTrafficLightPosition(absl::optional<gfx::Point> position) override;
absl::optional<gfx::Point> GetTrafficLightPosition() const override;
void RedrawTrafficLights() override;
void UpdateFrame() override;
void SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) override;
void RefreshTouchBarItem(const std::string& item_id) override;
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override;
void SelectPreviousTab() override;
void SelectNextTab() override;
void MergeAllWindows() override;
void MoveTabToNewWindow() override;
void ToggleTabBar() override;
bool AddTabbedWindow(NativeWindow* window) override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void PreviewFile(const std::string& path,
const std::string& display_name) override;
void CloseFilePreview() override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
gfx::Rect GetWindowControlsOverlayRect() override;
void NotifyWindowEnterFullScreen() override;
void NotifyWindowLeaveFullScreen() override;
void SetActive(bool is_key) override;
bool IsActive() const override;
void NotifyWindowWillEnterFullScreen();
void NotifyWindowWillLeaveFullScreen();
// Cleanup observers when window is getting closed. Note that the destructor
// can be called much later after window gets closed, so we should not do
// cleanup in destructor.
void Cleanup();
void UpdateVibrancyRadii(bool fullscreen);
void UpdateWindowOriginalFrame();
// Set the attribute of NSWindow while work around a bug of zoom button.
bool HasStyleMask(NSUInteger flag) const;
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
void SetWindowLevel(int level);
bool HandleDeferredClose();
void SetHasDeferredWindowClose(bool defer_close) {
has_deferred_window_close_ = defer_close;
}
enum class VisualEffectState {
kFollowWindow,
kActive,
kInactive,
};
ElectronPreviewItem* preview_item() const { return preview_item_.get(); }
ElectronTouchBar* touch_bar() const { return touch_bar_.get(); }
bool zoom_to_page_width() const { return zoom_to_page_width_; }
bool always_simple_fullscreen() const { return always_simple_fullscreen_; }
// We need to save the result of windowWillUseStandardFrame:defaultFrame
// because macOS calls it with what it refers to as the "best fit" frame for a
// zoom. This means that even if an aspect ratio is set, macOS might adjust it
// to better fit the screen.
//
// Thus, we can't just calculate the maximized aspect ratio'd sizing from
// the current visible screen and compare that to the current window's frame
// to determine whether a window is maximized.
NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; }
void set_default_frame_for_zoom(NSRect frame) {
default_frame_for_zoom_ = frame;
}
protected:
// views::WidgetDelegate:
views::View* GetContentsView() override;
bool CanMaximize() const override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
// display::DisplayObserver:
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
private:
// Add custom layers to the content view.
void AddContentViewLayers();
void InternalSetWindowButtonVisibility(bool visible);
void InternalSetParentWindow(NativeWindow* parent, bool attach);
void SetForwardMouseMessages(bool forward);
ElectronNSWindow* window_; // Weak ref, managed by widget_.
base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_;
base::scoped_nsobject<ElectronPreviewItem> preview_item_;
base::scoped_nsobject<ElectronTouchBar> touch_bar_;
// The views::View that fills the client area.
std::unique_ptr<RootViewMac> root_view_;
bool is_kiosk_ = false;
bool zoom_to_page_width_ = false;
absl::optional<gfx::Point> traffic_light_position_;
// Trying to close an NSWindow during a fullscreen transition will cause the
// window to lock up. Use this to track if CloseWindow was called during a
// fullscreen transition, to defer the -[NSWindow close] call until the
// transition is complete.
bool has_deferred_window_close_ = false;
NSInteger attention_request_id_ = 0; // identifier from requestUserAttention
// The presentation options before entering kiosk mode.
NSApplicationPresentationOptions kiosk_options_;
// The "visualEffectState" option.
VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow;
// The visibility mode of window button controls when explicitly set through
// setWindowButtonVisibility().
absl::optional<bool> window_button_visibility_;
// Controls the position and visibility of window buttons.
base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_;
std::unique_ptr<SkRegion> draggable_region_;
// Maximizable window state; necessary for persistence through redraws.
bool maximizable_ = true;
bool user_set_bounds_maximized_ = false;
// Simple (pre-Lion) Fullscreen Settings
bool always_simple_fullscreen_ = false;
bool is_simple_fullscreen_ = false;
bool was_maximizable_ = false;
bool was_movable_ = false;
bool is_active_ = false;
NSRect original_frame_;
NSInteger original_level_;
NSUInteger simple_fullscreen_mask_;
NSRect default_frame_for_zoom_;
std::string vibrancy_type_;
// The presentation options before entering simple fullscreen mode.
NSApplicationPresentationOptions simple_fullscreen_options_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// Removing NSWindowStyleMaskTitled removes window title, which removes
// rounded corners of window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
// Hide all children of the current window before hiding the window.
// components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
// expects this when window visibility changes.
if ([window_ childWindows]) {
for (NSWindow* child in [window_ childWindows]) {
[child orderOut:nil];
}
}
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
// For a window to be visible, it must be visible to the user in the
// foreground of the app, which means that it should not be minimized or
// occluded
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::ENTERING
: FullScreenTransitionState::EXITING;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::NONE;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
[NSApp setPresentationOptions:kiosk_options_];
is_kiosk_ = false;
SetFullScreen(false);
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = base::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to functionally
// mimic app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
ProcessSerialNumber psn = {0, kCurrentProcess};
if (visibleOnFullScreen) {
[window_ setCanHide:NO];
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
} else {
[window_ setCanHide:YES];
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetTrafficLightPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
[[window_ parentWindow] removeChildWindow:window_];
// Set new parent window.
// Note that this method will force the window to become visible.
if (parent && attach) {
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[parent->GetNativeWindow().GetNativeNSWindow()
addChildWindow:window_
ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
docs/api/browser-window.md
|
# BrowserWindow
> Create and control browser windows.
Process: [Main](../glossary.md#main-process)
This module cannot be used until the `ready` event of the `app`
module is emitted.
```javascript
// In the main process.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
// Load a remote URL
win.loadURL('https://github.com')
// Or load a local HTML file
win.loadFile('index.html')
```
## Window customization
The `BrowserWindow` class exposes various ways to modify the look and behavior of
your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md)
tutorial.
## Showing the window gracefully
When loading a page in the window directly, users may see the page load incrementally,
which is not a good experience for a native app. To make the window display
without a visual flash, there are two solutions for different situations.
### Using the `ready-to-show` event
While loading the page, the `ready-to-show` event will be emitted when the renderer
process has rendered the page for the first time if the window has not been shown yet. Showing
the window after this event will have no visual flash:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
```
This event is usually emitted after the `did-finish-load` event, but for
pages with many remote resources, it may be emitted before the `did-finish-load`
event.
Please note that using this event implies that the renderer will be considered "visible" and
paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false`
### Setting the `backgroundColor` property
For a complex app, the `ready-to-show` event could be emitted too late, making
the app feel slow. In this case, it is recommended to show the window
immediately, and use a `backgroundColor` close to your app's background:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
```
Note that even for apps that use `ready-to-show` event, it is still recommended
to set `backgroundColor` to make the app feel more native.
Some examples of valid `backgroundColor` values include:
```js
const win = new BrowserWindow()
win.setBackgroundColor('hsl(230, 100%, 50%)')
win.setBackgroundColor('rgb(255, 145, 145)')
win.setBackgroundColor('#ff00a3')
win.setBackgroundColor('blueviolet')
```
For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor).
## Parent and child windows
By using `parent` option, you can create child windows:
```javascript
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
```
The `child` window will always show on top of the `top` window.
## Modal windows
A modal window is a child window that disables parent window, to create a modal
window, you have to set both `parent` and `modal` options:
```javascript
const { BrowserWindow } = require('electron')
const child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})
```
## Page visibility
The [Page Visibility API][page-visibility-api] works as follows:
* On all platforms, the visibility state tracks whether the window is
hidden/minimized or not.
* Additionally, on macOS, the visibility state also tracks the window
occlusion state. If the window is occluded (i.e. fully covered) by another
window, the visibility state will be `hidden`. On other platforms, the
visibility state will be `hidden` only when the window is minimized or
explicitly hidden with `win.hide()`.
* If a `BrowserWindow` is created with `show: false`, the initial visibility
state will be `visible` despite the window actually being hidden.
* If `backgroundThrottling` is disabled, the visibility state will remain
`visible` even if the window is minimized, occluded, or hidden.
It is recommended that you pause expensive operations when the visibility
state is `hidden` in order to minimize power consumption.
## Platform notices
* On macOS modal windows will be displayed as sheets attached to the parent window.
* On macOS the child windows will keep the relative position to parent window
when parent window moves, while on Windows and Linux child windows will not
move.
* On Linux the type of modal windows will be changed to `dialog`.
* On Linux many desktop environments do not support hiding a modal window.
## Class: BrowserWindow
> Create and control browser windows.
Process: [Main](../glossary.md#main-process)
`BrowserWindow` is an [EventEmitter][event-emitter].
It creates a new `BrowserWindow` with native properties as set by the `options`.
### `new BrowserWindow([options])`
* `options` Object (optional)
* `width` Integer (optional) - Window's width in pixels. Default is `800`.
* `height` Integer (optional) - Window's height in pixels. Default is `600`.
* `x` Integer (optional) - (**required** if y is used) Window's left offset from screen.
Default is to center the window.
* `y` Integer (optional) - (**required** if x is used) Window's top offset from screen.
Default is to center the window.
* `useContentSize` boolean (optional) - The `width` and `height` would be used as web
page's size, which means the actual window's size will include window
frame's size and be slightly larger. Default is `false`.
* `center` boolean (optional) - Show window in the center of the screen. Default is `false`.
* `minWidth` Integer (optional) - Window's minimum width. Default is `0`.
* `minHeight` Integer (optional) - Window's minimum height. Default is `0`.
* `maxWidth` Integer (optional) - Window's maximum width. Default is no limit.
* `maxHeight` Integer (optional) - Window's maximum height. Default is no limit.
* `resizable` boolean (optional) - Whether window is resizable. Default is `true`.
* `movable` boolean (optional) _macOS_ _Windows_ - Whether window is
movable. This is not implemented on Linux. Default is `true`.
* `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is
minimizable. This is not implemented on Linux. Default is `true`.
* `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is
maximizable. This is not implemented on Linux. Default is `true`.
* `closable` boolean (optional) _macOS_ _Windows_ - Whether window is
closable. This is not implemented on Linux. Default is `true`.
* `focusable` boolean (optional) - Whether the window can be focused. Default is
`true`. On Windows setting `focusable: false` also implies setting
`skipTaskbar: true`. On Linux setting `focusable: false` makes the window
stop interacting with wm, so the window will always stay on top in all
workspaces.
* `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of
other windows. Default is `false`.
* `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When
explicitly set to `false` the fullscreen button will be hidden or disabled
on macOS. Default is `false`.
* `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen
mode. On macOS, also whether the maximize/zoom button should toggle full
screen mode or maximize window. Default is `true`.
* `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on
macOS. Default is `false`.
* `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar.
Default is `false`.
* `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control.
* `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`.
* `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored.
* `icon` ([NativeImage](native-image.md) | string) (optional) - The window icon. On Windows it is
recommended to use `ICO` icons to get best visual effects, you can also
leave it undefined so the executable's icon will be used.
* `show` boolean (optional) - Whether window should be shown when created. Default is
`true`.
* `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`.
* `frame` boolean (optional) - Specify `false` to create a
[frameless window](../tutorial/window-customization.md#create-frameless-windows). Default is `true`.
* `parent` BrowserWindow (optional) - Specify parent window. Default is `null`.
* `modal` boolean (optional) - Whether this is a modal window. This only works when the
window is a child window. Default is `false`.
* `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an
inactive window will also click through to the web contents. Default is
`false` on macOS. This option is not configurable on other platforms.
* `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing.
Default is `false`.
* `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt`
key is pressed. Default is `false`.
* `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to
be resized larger than screen. Only relevant for macOS, as other OSes
allow larger-than-screen windows by default. Default is `false`.
* `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information.
* `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`.
* `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of
the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This
is only implemented on Windows and macOS.
* `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on
some GTK+3 desktop environments. Default is `false`.
* `transparent` boolean (optional) - Makes the window [transparent](../tutorial/window-customization.md#create-transparent-windows).
Default is `false`. On Windows, does not work unless the window is frameless.
* `type` string (optional) - The type of window, default is normal window. See more about
this below.
* `visualEffectState` string (optional) _macOS_ - Specify how the material
appearance should reflect window activity state on macOS. Must be used
with the `vibrancy` property. Possible values are:
* `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default.
* `active` - The backdrop should always appear active.
* `inactive` - The backdrop should always appear inactive.
* `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar.
Default is `default`. Possible values are:
* `default` - Results in the standard title bar for macOS or Windows respectively.
* `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown.
* `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar
with an alternative look where the traffic light buttons are slightly
more inset from the window edge.
* `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden
title bar and a full size content window, the traffic light buttons will
display when being hovered over in the top left of the window.
**Note:** This option is currently experimental.
* `trafficLightPosition` [Point](structures/point.md) (optional) _macOS_ -
Set a custom position for the traffic light buttons in frameless windows.
* `roundedCorners` boolean (optional) _macOS_ - Whether frameless window
should have rounded corners on macOS. Default is `true`. Setting this property
to `false` will prevent the window from being fullscreenable.
* `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows
the title in the title bar in full screen mode on macOS for `hiddenInset`
titleBarStyle. Default is `false`.
* `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
window shadow and window animations. Default is `true`.
* `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to
the window, only on macOS. Can be `appearance-based`, `light`, `dark`,
`titlebar`, `selection`, `menu`, `popover`, `sidebar`, `medium-light`,
`ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`,
`tooltip`, `content`, `under-window`, or `under-page`. Please note that
`appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are
deprecated and have been removed in macOS Catalina (10.15).
* `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on
macOS when option-clicking the green stoplight button on the toolbar or by
clicking the Window > Zoom menu item. If `true`, the window will grow to
the preferred width of the web page when zoomed, `false` will cause it to
zoom to the width of the screen. This will also affect the behavior when
calling `maximize()` directly. Default is `false`.
* `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows
opening the window as a native tab on macOS 10.12+. Windows with the same
tabbing identifier will be grouped together. This also adds a native new
tab button to your window's tab bar and allows your `app` and window to
receive the `new-window-for-tab` event.
* `webPreferences` Object (optional) - Settings of web page's features.
* `devTools` boolean (optional) - Whether to enable DevTools. If it is set to `false`, can not use `BrowserWindow.webContents.openDevTools()` to open DevTools. Default is `true`.
* `nodeIntegration` boolean (optional) - Whether node integration is enabled.
Default is `false`.
* `nodeIntegrationInWorker` boolean (optional) - Whether node integration is
enabled in web workers. Default is `false`. More about this can be found
in [Multithreading](../tutorial/multithreading.md).
* `nodeIntegrationInSubFrames` boolean (optional) - Experimental option for
enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for
every iframe, you can use `process.isMainFrame` to determine if you are
in the main frame or not.
* `preload` string (optional) - Specifies a script that will be loaded before other
scripts run in the page. This script will always have access to node APIs
no matter whether node integration is turned on or off. The value should
be the absolute file path to the script.
When node integration is turned off, the preload script can reintroduce
Node global symbols back to the global scope. See example
[here](context-bridge.md#exposing-node-global-symbols).
* `sandbox` boolean (optional) - If set, this will sandbox the renderer
associated with the window, making it compatible with the Chromium
OS-level sandbox and disabling the Node.js engine. This is not the same as
the `nodeIntegration` option and the APIs available to the preload script
are more limited. Read more about the option [here](../tutorial/sandbox.md).
* `session` [Session](session.md#class-session) (optional) - Sets the session used by the
page. Instead of passing the Session object directly, you can also choose to
use the `partition` option instead, which accepts a partition string. When
both `session` and `partition` are provided, `session` will be preferred.
Default is the default session.
* `partition` string (optional) - Sets the session used by the page according to the
session's partition string. If `partition` starts with `persist:`, the page
will use a persistent session available to all pages in the app with the
same `partition`. If there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. Default is the default session.
* `zoomFactor` number (optional) - The default zoom factor of the page, `3.0` represents
`300%`. Default is `1.0`.
* `javascript` boolean (optional) - Enables JavaScript support. Default is `true`.
* `webSecurity` boolean (optional) - When `false`, it will disable the
same-origin policy (usually using testing websites by people), and set
`allowRunningInsecureContent` to `true` if this options has not been set
by user. Default is `true`.
* `allowRunningInsecureContent` boolean (optional) - Allow an https page to run
JavaScript, CSS or plugins from http URLs. Default is `false`.
* `images` boolean (optional) - Enables image support. Default is `true`.
* `imageAnimationPolicy` string (optional) - Specifies how to run image animations (E.g. GIFs). Can be `animate`, `animateOnce` or `noAnimation`. Default is `animate`.
* `textAreasAreResizable` boolean (optional) - Make TextArea elements resizable. Default
is `true`.
* `webgl` boolean (optional) - Enables WebGL support. Default is `true`.
* `plugins` boolean (optional) - Whether plugins should be enabled. Default is `false`.
* `experimentalFeatures` boolean (optional) - Enables Chromium's experimental features.
Default is `false`.
* `scrollBounce` boolean (optional) _macOS_ - Enables scroll bounce
(rubber banding) effect on macOS. Default is `false`.
* `enableBlinkFeatures` string (optional) - A list of feature strings separated by `,`, like
`CSSVariables,KeyboardEventKey` to enable. The full list of supported feature
strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features]
file.
* `disableBlinkFeatures` string (optional) - A list of feature strings separated by `,`,
like `CSSVariables,KeyboardEventKey` to disable. The full list of supported
feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
* `defaultFontFamily` Object (optional) - Sets the default font for the font-family.
* `standard` string (optional) - Defaults to `Times New Roman`.
* `serif` string (optional) - Defaults to `Times New Roman`.
* `sansSerif` string (optional) - Defaults to `Arial`.
* `monospace` string (optional) - Defaults to `Courier New`.
* `cursive` string (optional) - Defaults to `Script`.
* `fantasy` string (optional) - Defaults to `Impact`.
* `defaultFontSize` Integer (optional) - Defaults to `16`.
* `defaultMonospaceFontSize` Integer (optional) - Defaults to `13`.
* `minimumFontSize` Integer (optional) - Defaults to `0`.
* `defaultEncoding` string (optional) - Defaults to `ISO-8859-1`.
* `backgroundThrottling` boolean (optional) - Whether to throttle animations and timers
when the page becomes background. This also affects the
[Page Visibility API](#page-visibility). Defaults to `true`.
* `offscreen` boolean (optional) - Whether to enable offscreen rendering for the browser
window. Defaults to `false`. See the
[offscreen rendering tutorial](../tutorial/offscreen-rendering.md) for
more details.
* `contextIsolation` boolean (optional) - Whether to run Electron APIs and
the specified `preload` script in a separate JavaScript context. Defaults
to `true`. The context that the `preload` script runs in will only have
access to its own dedicated `document` and `window` globals, as well as
its own set of JavaScript builtins (`Array`, `Object`, `JSON`, etc.),
which are all invisible to the loaded content. The Electron API will only
be available in the `preload` script and not the loaded page. This option
should be used when loading potentially untrusted remote content to ensure
the loaded content cannot tamper with the `preload` script and any
Electron APIs being used. This option uses the same technique used by
[Chrome Content Scripts][chrome-content-scripts]. You can access this
context in the dev tools by selecting the 'Electron Isolated Context'
entry in the combo box at the top of the Console tab.
* `webviewTag` boolean (optional) - Whether to enable the [`<webview>` tag](webview-tag.md).
Defaults to `false`. **Note:** The
`preload` script configured for the `<webview>` will have node integration
enabled when it is executed so you should ensure remote/untrusted content
is not able to create a `<webview>` tag with a possibly malicious `preload`
script. You can use the `will-attach-webview` event on [webContents](web-contents.md)
to strip away the `preload` script and to validate or alter the
`<webview>`'s initial settings.
* `additionalArguments` string[] (optional) - A list of strings that will be appended
to `process.argv` in the renderer process of this app. Useful for passing small
bits of data down to renderer process preload scripts.
* `safeDialogs` boolean (optional) - Whether to enable browser style
consecutive dialog protection. Default is `false`.
* `safeDialogsMessage` string (optional) - The message to display when
consecutive dialog protection is triggered. If not defined the default
message would be used, note that currently the default message is in
English and not localized.
* `disableDialogs` boolean (optional) - Whether to disable dialogs
completely. Overrides `safeDialogs`. Default is `false`.
* `navigateOnDragDrop` boolean (optional) - Whether dragging and dropping a
file or link onto the page causes a navigation. Default is `false`.
* `autoplayPolicy` string (optional) - Autoplay policy to apply to
content in the window, can be `no-user-gesture-required`,
`user-gesture-required`, `document-user-activation-required`. Defaults to
`no-user-gesture-required`.
* `disableHtmlFullscreenWindowResize` boolean (optional) - Whether to
prevent the window from resizing when entering HTML Fullscreen. Default
is `false`.
* `accessibleTitle` string (optional) - An alternative title string provided only
to accessibility tools such as screen readers. This string is not directly
visible to users.
* `spellcheck` boolean (optional) - Whether to enable the builtin spellchecker.
Default is `true`.
* `enableWebSQL` boolean (optional) - Whether to enable the [WebSQL api](https://www.w3.org/TR/webdatabase/).
Default is `true`.
* `v8CacheOptions` string (optional) - Enforces the v8 code caching policy
used by blink. Accepted values are
* `none` - Disables code caching
* `code` - Heuristic based code caching
* `bypassHeatCheck` - Bypass code caching heuristics but with lazy compilation
* `bypassHeatCheckAndEagerCompile` - Same as above except compilation is eager.
Default policy is `code`.
* `enablePreferredSizeMode` boolean (optional) - Whether to enable
preferred size mode. The preferred size is the minimum size needed to
contain the layout of the document—without requiring scrolling. Enabling
this will cause the `preferred-size-changed` event to be emitted on the
`WebContents` when the preferred size changes. Default is `false`.
* `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`.
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color.
* `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
passing a size that does not follow size constraints to `setBounds`/`setSize` or
to the constructor of `BrowserWindow`.
The possible values and behaviors of the `type` option are platform dependent.
Possible values are:
* On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`,
`notification`.
* On macOS, possible types are `desktop`, `textured`, `panel`.
* The `textured` type adds metal gradient appearance
(`NSWindowStyleMaskTexturedBackground`).
* The `desktop` type places the window at the desktop background window level
(`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive
focus, keyboard or mouse events, but you can use `globalShortcut` to receive
input sparingly.
* The `panel` type enables the window to float on top of full-screened apps
by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally
reserved for NSPanel, at runtime. Also, the window will appear on all
spaces (desktops).
* On Windows, possible type is `toolbar`.
### Instance Events
Objects created with `new BrowserWindow` emit the following events:
**Note:** Some events are only available on specific operating systems and are
labeled as such.
#### Event: 'page-title-updated'
Returns:
* `event` Event
* `title` string
* `explicitSet` boolean
Emitted when the document changed its title, calling `event.preventDefault()`
will prevent the native window's title from changing.
`explicitSet` is false when title is synthesized from file URL.
#### Event: 'close'
Returns:
* `event` Event
Emitted when the window is going to be closed. It's emitted before the
`beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()`
will cancel the close.
Usually you would want to use the `beforeunload` handler to decide whether the
window should be closed, which will also be called when the window is
reloaded. In Electron, returning any value other than `undefined` would cancel the
close. For example:
```javascript
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
// Unlike usual browsers that a message box will be prompted to users, returning
// a non-void value will silently cancel the close.
// It is recommended to use the dialog API to let the user confirm closing the
// application.
e.returnValue = false
}
```
_**Note**: There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and `window.addEventListener('beforeunload', handler)`. It is recommended to always set the `event.returnValue` explicitly, instead of only returning a value, as the former works more consistently within Electron._
#### Event: 'closed'
Emitted when the window is closed. After you have received this event you should
remove the reference to the window and avoid using it any more.
#### Event: 'session-end' _Windows_
Emitted when window session is going to end due to force shutdown or machine restart
or session log off.
#### Event: 'unresponsive'
Emitted when the web page becomes unresponsive.
#### Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
#### Event: 'blur'
Emitted when the window loses focus.
#### Event: 'focus'
Emitted when the window gains focus.
#### Event: 'show'
Emitted when the window is shown.
#### Event: 'hide'
Emitted when the window is hidden.
#### Event: 'ready-to-show'
Emitted when the web page has been rendered (while not being shown) and window can be displayed without
a visual flash.
Please note that using this event implies that the renderer will be considered "visible" and
paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false`
#### Event: 'maximize'
Emitted when window is maximized.
#### Event: 'unmaximize'
Emitted when the window exits from a maximized state.
#### Event: 'minimize'
Emitted when the window is minimized.
#### Event: 'restore'
Emitted when the window is restored from a minimized state.
#### Event: 'will-resize' _macOS_ _Windows_
Returns:
* `event` Event
* `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to.
* `details` Object
* `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`.
Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized.
Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event.
The possible values and behaviors of the `edge` option are platform dependent. Possible values are:
* On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`.
* On macOS, possible values are `bottom` and `right`.
* The value `bottom` is used to denote vertical resizing.
* The value `right` is used to denote horizontal resizing.
#### Event: 'resize'
Emitted after the window has been resized.
#### Event: 'resized' _macOS_ _Windows_
Emitted once when the window has finished being resized.
This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished.
#### Event: 'will-move' _macOS_ _Windows_
Returns:
* `event` Event
* `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to.
Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved.
Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event.
#### Event: 'move'
Emitted when the window is being moved to a new position.
#### Event: 'moved' _macOS_ _Windows_
Emitted once when the window is moved to a new position.
__Note__: On macOS this event is an alias of `move`.
#### Event: 'enter-full-screen'
Emitted when the window enters a full-screen state.
#### Event: 'leave-full-screen'
Emitted when the window leaves a full-screen state.
#### Event: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
#### Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
#### Event: 'always-on-top-changed'
Returns:
* `event` Event
* `isAlwaysOnTop` boolean
Emitted when the window is set or unset to show always on top of other windows.
#### Event: 'app-command' _Windows_ _Linux_
Returns:
* `event` Event
* `command` string
Emitted when an [App Command](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx)
is invoked. These are typically related to keyboard media keys or browser
commands, as well as the "Back" button built into some mice on Windows.
Commands are lowercased, underscores are replaced with hyphens, and the
`APPCOMMAND_` prefix is stripped off.
e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
```
The following app commands are explicitly supported on Linux:
* `browser-backward`
* `browser-forward`
#### Event: 'scroll-touch-begin' _macOS_ _Deprecated_
Emitted when scroll wheel event phase has begun.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'scroll-touch-end' _macOS_ _Deprecated_
Emitted when scroll wheel event phase has ended.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'scroll-touch-edge' _macOS_ _Deprecated_
Emitted when scroll wheel event phase filed upon reaching the edge of element.
> **Note**
> This event is deprecated beginning in Electron 22.0.0. See [Breaking
> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
> for details of how to migrate to using the [WebContents
> `input-event`](api/web-contents.md#event-input-event) event.
#### Event: 'swipe' _macOS_
Returns:
* `event` Event
* `direction` string
Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`.
The method underlying this event is built to handle older macOS-style trackpad swiping,
where the content on the screen doesn't move with the swipe. Most macOS trackpads are not
configured to allow this kind of swiping anymore, so in order for it to emit properly the
'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be
set to 'Swipe with two or three fingers'.
#### Event: 'rotate-gesture' _macOS_
Returns:
* `event` Event
* `rotation` Float
Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is
ended. The `rotation` value on each emission is the angle in degrees rotated since
the last emission. The last emitted event upon a rotation gesture will always be of
value `0`. Counter-clockwise rotation values are positive, while clockwise ones are
negative.
#### Event: 'sheet-begin' _macOS_
Emitted when the window opens a sheet.
#### Event: 'sheet-end' _macOS_
Emitted when the window has closed a sheet.
#### Event: 'new-window-for-tab' _macOS_
Emitted when the native new tab button is clicked.
#### Event: 'system-context-menu' _Windows_
Returns:
* `event` Event
* `point` [Point](structures/point.md) - The screen coordinates the context menu was triggered at
Emitted when the system context menu is triggered on the window, this is
normally only triggered when the user right clicks on the non-client area
of your window. This is the window titlebar or any area you have declared
as `-webkit-app-region: drag` in a frameless window.
Calling `event.preventDefault()` will prevent the menu from being displayed.
### Static Methods
The `BrowserWindow` class has the following static methods:
#### `BrowserWindow.getAllWindows()`
Returns `BrowserWindow[]` - An array of all opened browser windows.
#### `BrowserWindow.getFocusedWindow()`
Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`.
#### `BrowserWindow.fromWebContents(webContents)`
* `webContents` [WebContents](web-contents.md)
Returns `BrowserWindow | null` - The window that owns the given `webContents`
or `null` if the contents are not owned by a window.
#### `BrowserWindow.fromBrowserView(browserView)`
* `browserView` [BrowserView](browser-view.md)
Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`.
#### `BrowserWindow.fromId(id)`
* `id` Integer
Returns `BrowserWindow | null` - The window with the given `id`.
### Instance Properties
Objects created with `new BrowserWindow` have the following properties:
```javascript
const { BrowserWindow } = require('electron')
// In this example `win` is our instance
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
```
#### `win.webContents` _Readonly_
A `WebContents` object this window owns. All web page related events and
operations will be done via it.
See the [`webContents` documentation](web-contents.md) for its methods and
events.
#### `win.id` _Readonly_
A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application.
#### `win.autoHideMenuBar`
A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key.
If the menu bar is already visible, setting this property to `true` won't
hide it immediately.
#### `win.simpleFullScreen`
A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode.
#### `win.fullScreen`
A `boolean` property that determines whether the window is in fullscreen mode.
#### `win.focusable` _Windows_ _macOS_
A `boolean` property that determines whether the window is focusable.
#### `win.visibleOnAllWorkspaces` _macOS_ _Linux_
A `boolean` property that determines whether the window is visible on all workspaces.
**Note:** Always returns false on Windows.
#### `win.shadow`
A `boolean` property that determines whether the window has a shadow.
#### `win.menuBarVisible` _Windows_ _Linux_
A `boolean` property that determines whether the menu bar should be visible.
**Note:** If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
#### `win.kiosk`
A `boolean` property that determines whether the window is in kiosk mode.
#### `win.documentEdited` _macOS_
A `boolean` property that specifies whether the window’s document has been edited.
The icon in title bar will become gray when set to `true`.
#### `win.representedFilename` _macOS_
A `string` property that determines the pathname of the file the window represents,
and the icon of the file will show in window's title bar.
#### `win.title`
A `string` property that determines the title of the native window.
**Note:** The title of the web page can be different from the title of the native window.
#### `win.minimizable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually minimized by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.maximizable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually maximized by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.fullScreenable`
A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or
maximizes the window.
#### `win.resizable`
A `boolean` property that determines whether the window can be manually resized by user.
#### `win.closable` _macOS_ _Windows_
A `boolean` property that determines whether the window can be manually closed by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.movable` _macOS_ _Windows_
A `boolean` property that determines Whether the window can be moved by user.
On Linux the setter is a no-op, although the getter returns `true`.
#### `win.excludedFromShownWindowsMenu` _macOS_
A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default.
```js
const win = new BrowserWindow({ height: 600, width: 600 })
const template = [
{
role: 'windowmenu'
}
]
win.excludedFromShownWindowsMenu = true
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
```
#### `win.accessibleTitle`
A `string` property that defines an alternative title provided only to
accessibility tools such as screen readers. This string is not directly
visible to users.
### Instance Methods
Objects created with `new BrowserWindow` have the following instance methods:
**Note:** Some methods are only available on specific operating systems and are
labeled as such.
#### `win.destroy()`
Force closing the window, the `unload` and `beforeunload` event won't be emitted
for the web page, and `close` event will also not be emitted
for this window, but it guarantees the `closed` event will be emitted.
#### `win.close()`
Try to close the window. This has the same effect as a user manually clicking
the close button of the window. The web page may cancel the close though. See
the [close event](#event-close).
#### `win.focus()`
Focuses on the window.
#### `win.blur()`
Removes focus from the window.
#### `win.isFocused()`
Returns `boolean` - Whether the window is focused.
#### `win.isDestroyed()`
Returns `boolean` - Whether the window is destroyed.
#### `win.show()`
Shows and gives focus to the window.
#### `win.showInactive()`
Shows the window but doesn't focus on it.
#### `win.hide()`
Hides the window.
#### `win.isVisible()`
Returns `boolean` - Whether the window is visible to the user.
#### `win.isModal()`
Returns `boolean` - Whether current window is a modal window.
#### `win.maximize()`
Maximizes the window. This will also show (but not focus) the window if it
isn't being displayed already.
#### `win.unmaximize()`
Unmaximizes the window.
#### `win.isMaximized()`
Returns `boolean` - Whether the window is maximized.
#### `win.minimize()`
Minimizes the window. On some platforms the minimized window will be shown in
the Dock.
#### `win.restore()`
Restores the window from minimized state to its previous state.
#### `win.isMinimized()`
Returns `boolean` - Whether the window is minimized.
#### `win.setFullScreen(flag)`
* `flag` boolean
Sets whether the window should be in fullscreen mode.
#### `win.isFullScreen()`
Returns `boolean` - Whether the window is in fullscreen mode.
#### `win.setSimpleFullScreen(flag)` _macOS_
* `flag` boolean
Enters or leaves simple fullscreen mode.
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).
#### `win.isSimpleFullScreen()` _macOS_
Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode.
#### `win.isNormal()`
Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).
#### `win.setAspectRatio(aspectRatio[, extraSize])`
* `aspectRatio` Float - The aspect ratio to maintain for some portion of the
content view.
* `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while
maintaining the aspect ratio.
This will make a window maintain an aspect ratio. The extra size allows a
developer to have space, specified in pixels, not included within the aspect
ratio calculations. This API already takes into account the difference between a
window's size and its content size.
Consider a normal window with an HD video player and associated controls.
Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls
on the right edge and 50 pixels of controls below the player. In order to
maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within
the player itself we would call this function with arguments of 16/9 and
{ width: 40, height: 50 }. The second argument doesn't care where the extra width and height
are within the content view--only that they exist. Sum any extra width and
height areas you have within the overall content view.
The aspect ratio is not respected when window is resized programmatically with
APIs like `win.setSize`.
#### `win.setBackgroundColor(backgroundColor)`
* `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.
Examples of valid `backgroundColor` values:
* Hex
* #fff (shorthand RGB)
* #ffff (shorthand ARGB)
* #ffffff (RGB)
* #ffffffff (ARGB)
* RGB
* rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)
* e.g. rgb(255, 255, 255)
* RGBA
* rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)
* e.g. rgba(255, 255, 255, 1.0)
* HSL
* hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)
* e.g. hsl(200, 20%, 50%)
* HSLA
* hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)
* e.g. hsla(200, 20%, 50%, 0.5)
* Color name
* Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148)
* Similar to CSS Color Module Level 3 keywords, but case-sensitive.
* e.g. `blueviolet` or `red`
Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property).
#### `win.previewFile(path[, displayName])` _macOS_
* `path` string - The absolute path to the file to preview with QuickLook. This
is important as Quick Look uses the file name and file extension on the path
to determine the content type of the file to open.
* `displayName` string (optional) - The name of the file to display on the
Quick Look modal view. This is purely visual and does not affect the content
type of the file. Defaults to `path`.
Uses [Quick Look][quick-look] to preview a file at a given path.
#### `win.closeFilePreview()` _macOS_
Closes the currently open [Quick Look][quick-look] panel.
#### `win.setBounds(bounds[, animate])`
* `bounds` Partial<[Rectangle](structures/rectangle.md)>
* `animate` boolean (optional) _macOS_
Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// set all bounds properties
win.setBounds({ x: 440, y: 225, width: 800, height: 600 })
// set a single bounds property
win.setBounds({ width: 100 })
// { x: 440, y: 225, width: 100, height: 600 }
console.log(win.getBounds())
```
#### `win.getBounds()`
Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`.
#### `win.getBackgroundColor()`
Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format.
See [Setting `backgroundColor`](#setting-the-backgroundcolor-property).
**Note:** The alpha value is _not_ returned alongside the red, green, and blue values.
#### `win.setContentBounds(bounds[, animate])`
* `bounds` [Rectangle](structures/rectangle.md)
* `animate` boolean (optional) _macOS_
Resizes and moves the window's client area (e.g. the web page) to
the supplied bounds.
#### `win.getContentBounds()`
Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`.
#### `win.getNormalBounds()`
Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state
**Note:** whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md).
#### `win.setEnabled(enable)`
* `enable` boolean
Disable or enable the window.
#### `win.isEnabled()`
Returns `boolean` - whether the window is enabled.
#### `win.setSize(width, height[, animate])`
* `width` Integer
* `height` Integer
* `animate` boolean (optional) _macOS_
Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size.
#### `win.getSize()`
Returns `Integer[]` - Contains the window's width and height.
#### `win.setContentSize(width, height[, animate])`
* `width` Integer
* `height` Integer
* `animate` boolean (optional) _macOS_
Resizes the window's client area (e.g. the web page) to `width` and `height`.
#### `win.getContentSize()`
Returns `Integer[]` - Contains the window's client area's width and height.
#### `win.setMinimumSize(width, height)`
* `width` Integer
* `height` Integer
Sets the minimum size of window to `width` and `height`.
#### `win.getMinimumSize()`
Returns `Integer[]` - Contains the window's minimum width and height.
#### `win.setMaximumSize(width, height)`
* `width` Integer
* `height` Integer
Sets the maximum size of window to `width` and `height`.
#### `win.getMaximumSize()`
Returns `Integer[]` - Contains the window's maximum width and height.
#### `win.setResizable(resizable)`
* `resizable` boolean
Sets whether the window can be manually resized by the user.
#### `win.isResizable()`
Returns `boolean` - Whether the window can be manually resized by the user.
#### `win.setMovable(movable)` _macOS_ _Windows_
* `movable` boolean
Sets whether the window can be moved by user. On Linux does nothing.
#### `win.isMovable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be moved by user.
On Linux always returns `true`.
#### `win.setMinimizable(minimizable)` _macOS_ _Windows_
* `minimizable` boolean
Sets whether the window can be manually minimized by user. On Linux does nothing.
#### `win.isMinimizable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually minimized by the user.
On Linux always returns `true`.
#### `win.setMaximizable(maximizable)` _macOS_ _Windows_
* `maximizable` boolean
Sets whether the window can be manually maximized by user. On Linux does nothing.
#### `win.isMaximizable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually maximized by user.
On Linux always returns `true`.
#### `win.setFullScreenable(fullscreenable)`
* `fullscreenable` boolean
Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
#### `win.isFullScreenable()`
Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
#### `win.setClosable(closable)` _macOS_ _Windows_
* `closable` boolean
Sets whether the window can be manually closed by user. On Linux does nothing.
#### `win.isClosable()` _macOS_ _Windows_
Returns `boolean` - Whether the window can be manually closed by user.
On Linux always returns `true`.
#### `win.setHiddenInMissionControl(hidden)` _macOS_
* `hidden` boolean
Sets whether the window will be hidden when the user toggles into mission control.
#### `win.isHiddenInMissionControl()` _macOS_
Returns `boolean` - Whether the window will be hidden when the user toggles into mission control.
#### `win.setAlwaysOnTop(flag[, level][, relativeLevel])`
* `flag` boolean
* `level` string (optional) _macOS_ _Windows_ - Values include `normal`,
`floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`,
`pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is
`floating` when `flag` is true. The `level` is reset to `normal` when the
flag is false. Note that from `floating` to `status` included, the window is
placed below the Dock on macOS and below the taskbar on Windows. From
`pop-up-menu` to a higher it is shown above the Dock on macOS and above the
taskbar on Windows. See the [macOS docs][window-levels] for more details.
* `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set
this window relative to the given `level`. The default is `0`. Note that Apple
discourages setting levels higher than 1 above `screen-saver`.
Sets whether the window should show always on top of other windows. After
setting this, the window is still a normal window, not a toolbox window which
can not be focused on.
#### `win.isAlwaysOnTop()`
Returns `boolean` - Whether the window is always on top of other windows.
#### `win.moveAbove(mediaSourceId)`
* `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0".
Moves window above the source window in the sense of z-order. If the
`mediaSourceId` is not of type window or if the window does not exist then
this method throws an error.
#### `win.moveTop()`
Moves window to top(z-order) regardless of focus
#### `win.center()`
Moves window to the center of the screen.
#### `win.setPosition(x, y[, animate])`
* `x` Integer
* `y` Integer
* `animate` boolean (optional) _macOS_
Moves window to `x` and `y`.
#### `win.getPosition()`
Returns `Integer[]` - Contains the window's current position.
#### `win.setTitle(title)`
* `title` string
Changes the title of native window to `title`.
#### `win.getTitle()`
Returns `string` - The title of the native window.
**Note:** The title of the web page can be different from the title of the native
window.
#### `win.setSheetOffset(offsetY[, offsetX])` _macOS_
* `offsetY` Float
* `offsetX` Float (optional)
Changes the attachment point for sheets on macOS. By default, sheets are
attached just below the window frame, but you may want to display them beneath
a HTML-rendered toolbar. For example:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
```
#### `win.flashFrame(flag)`
* `flag` boolean
Starts or stops flashing the window to attract user's attention.
#### `win.setSkipTaskbar(skip)` _macOS_ _Windows_
* `skip` boolean
Makes the window not show in the taskbar.
#### `win.setKiosk(flag)`
* `flag` boolean
Enters or leaves kiosk mode.
#### `win.isKiosk()`
Returns `boolean` - Whether the window is in kiosk mode.
#### `win.isTabletMode()` _Windows_
Returns `boolean` - Whether the window is in Windows 10 tablet mode.
Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet),
under this mode apps can choose to optimize their UI for tablets, such as
enlarging the titlebar and hiding titlebar buttons.
This API returns whether the window is in tablet mode, and the `resize` event
can be be used to listen to changes to tablet mode.
#### `win.getMediaSourceId()`
Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0".
More precisely the format is `window:id:other_id` where `id` is `HWND` on
Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on
Linux. `other_id` is used to identify web contents (tabs) so within the same
top level window.
#### `win.getNativeWindowHandle()`
Returns `Buffer` - The platform-specific handle of the window.
The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and
`Window` (`unsigned long`) on Linux.
#### `win.hookWindowMessage(message, callback)` _Windows_
* `message` Integer
* `callback` Function
* `wParam` any - The `wParam` provided to the WndProc
* `lParam` any - The `lParam` provided to the WndProc
Hooks a windows message. The `callback` is called when
the message is received in the WndProc.
#### `win.isWindowMessageHooked(message)` _Windows_
* `message` Integer
Returns `boolean` - `true` or `false` depending on whether the message is hooked.
#### `win.unhookWindowMessage(message)` _Windows_
* `message` Integer
Unhook the window message.
#### `win.unhookAllWindowMessages()` _Windows_
Unhooks all of the window messages.
#### `win.setRepresentedFilename(filename)` _macOS_
* `filename` string
Sets the pathname of the file the window represents, and the icon of the file
will show in window's title bar.
#### `win.getRepresentedFilename()` _macOS_
Returns `string` - The pathname of the file the window represents.
#### `win.setDocumentEdited(edited)` _macOS_
* `edited` boolean
Specifies whether the window’s document has been edited, and the icon in title
bar will become gray when set to `true`.
#### `win.isDocumentEdited()` _macOS_
Returns `boolean` - Whether the window's document has been edited.
#### `win.focusOnWebView()`
#### `win.blurWebView()`
#### `win.capturePage([rect, opts])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `opts` Object (optional)
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
#### `win.loadURL(url[, options])`
* `url` string
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n"
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options).
The `url` can be a remote address (e.g. `http://`) or a path to a local
HTML file using the `file://` protocol.
To ensure that file URLs are properly formatted, it is recommended to use
Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject)
method:
```javascript
const url = require('url').format({
protocol: 'file',
slashes: true,
pathname: require('path').join(__dirname, 'index.html')
})
win.loadURL(url)
```
You can load a URL using a `POST` request with URL-encoded data by doing
the following:
```javascript
win.loadURL('http://localhost:8000/post', {
postData: [{
type: 'rawData',
bytes: Buffer.from('hello=world')
}],
extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})
```
#### `win.loadFile(filePath[, options])`
* `filePath` string
* `options` Object (optional)
* `query` Record<string, string> (optional) - Passed to `url.format()`.
* `search` string (optional) - Passed to `url.format()`.
* `hash` string (optional) - Passed to `url.format()`.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Same as `webContents.loadFile`, `filePath` should be a path to an HTML
file relative to the root of your application. See the `webContents` docs
for more information.
#### `win.reload()`
Same as `webContents.reload`.
#### `win.setMenu(menu)` _Linux_ _Windows_
* `menu` Menu | null
Sets the `menu` as the window's menu bar.
#### `win.removeMenu()` _Linux_ _Windows_
Remove the window's menu bar.
#### `win.setProgressBar(progress[, options])`
* `progress` Double
* `options` Object (optional)
* `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`.
Sets progress value in progress bar. Valid range is [0, 1.0].
Remove progress bar when progress < 0;
Change to indeterminate mode when progress > 1.
On Linux platform, only supports Unity desktop environment, you need to specify
the `*.desktop` file name to `desktopName` field in `package.json`. By default,
it will assume `{app.name}.desktop`.
On Windows, a mode can be passed. Accepted values are `none`, `normal`,
`indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a
mode set (but with a value within the valid range), `normal` will be assumed.
#### `win.setOverlayIcon(overlay, description)` _Windows_
* `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom
right corner of the taskbar icon. If this parameter is `null`, the overlay is
cleared
* `description` string - a description that will be provided to Accessibility
screen readers
Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to
convey some sort of application status or to passively notify the user.
#### `win.setHasShadow(hasShadow)`
* `hasShadow` boolean
Sets whether the window should have a shadow.
#### `win.hasShadow()`
Returns `boolean` - Whether the window has a shadow.
#### `win.setOpacity(opacity)` _Windows_ _macOS_
* `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque)
Sets the opacity of the window. On Linux, does nothing. Out of bound number
values are clamped to the [0, 1] range.
#### `win.getOpacity()`
Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On
Linux, always returns 1.
#### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_
* `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window.
Passing an empty list reverts the window to being rectangular.
Setting a window shape determines the area within the window where the system
permits drawing and user interaction. Outside of the given region, no pixels
will be drawn and no mouse events will be registered. Mouse events outside of
the region will not be received by that window, but will fall through to
whatever is behind the window.
#### `win.setThumbarButtons(buttons)` _Windows_
* `buttons` [ThumbarButton[]](structures/thumbar-button.md)
Returns `boolean` - Whether the buttons were added successfully
Add a thumbnail toolbar with a specified set of buttons to the thumbnail image
of a window in a taskbar button layout. Returns a `boolean` object indicates
whether the thumbnail has been added successfully.
The number of buttons in thumbnail toolbar should be no greater than 7 due to
the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be
removed due to the platform's limitation. But you can call the API with an empty
array to clean the buttons.
The `buttons` is an array of `Button` objects:
* `Button` Object
* `icon` [NativeImage](native-image.md) - The icon showing in thumbnail
toolbar.
* `click` Function
* `tooltip` string (optional) - The text of the button's tooltip.
* `flags` string[] (optional) - Control specific states and behaviors of the
button. By default, it is `['enabled']`.
The `flags` is an array that can include following `string`s:
* `enabled` - The button is active and available to the user.
* `disabled` - The button is disabled. It is present, but has a visual state
indicating it will not respond to user action.
* `dismissonclick` - When the button is clicked, the thumbnail window closes
immediately.
* `nobackground` - Do not draw a button border, use only the image.
* `hidden` - The button is not shown to the user.
* `noninteractive` - The button is enabled but not interactive; no pressed
button state is drawn. This value is intended for instances where the button
is used in a notification.
#### `win.setThumbnailClip(region)` _Windows_
* `region` [Rectangle](structures/rectangle.md) - Region of the window
Sets the region of the window to show as the thumbnail image displayed when
hovering over the window in the taskbar. You can reset the thumbnail to be
the entire window by specifying an empty region:
`{ x: 0, y: 0, width: 0, height: 0 }`.
#### `win.setThumbnailToolTip(toolTip)` _Windows_
* `toolTip` string
Sets the toolTip that is displayed when hovering over the window thumbnail
in the taskbar.
#### `win.setAppDetails(options)` _Windows_
* `options` Object
* `appId` string (optional) - Window's [App User Model ID](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391569(v=vs.85).aspx).
It has to be set, otherwise the other options will have no effect.
* `appIconPath` string (optional) - Window's [Relaunch Icon](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391573(v=vs.85).aspx).
* `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`.
Ignored when `appIconPath` is not set. Default is `0`.
* `relaunchCommand` string (optional) - Window's [Relaunch Command](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391571(v=vs.85).aspx).
* `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://msdn.microsoft.com/en-us/library/windows/desktop/dd391572(v=vs.85).aspx).
Sets the properties for the window's taskbar button.
**Note:** `relaunchCommand` and `relaunchDisplayName` must always be set
together. If one of those properties is not set, then neither will be used.
#### `win.showDefinitionForSelection()` _macOS_
Same as `webContents.showDefinitionForSelection()`.
#### `win.setIcon(icon)` _Windows_ _Linux_
* `icon` [NativeImage](native-image.md) | string
Changes window icon.
#### `win.setWindowButtonVisibility(visible)` _macOS_
* `visible` boolean
Sets whether the window traffic light buttons should be visible.
#### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_
* `hide` boolean
Sets whether the window menu bar should hide itself automatically. Once set the
menu bar will only show when users press the single `Alt` key.
If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately.
#### `win.isMenuBarAutoHide()` _Windows_ _Linux_
Returns `boolean` - Whether menu bar automatically hides itself.
#### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` boolean
Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key.
#### `win.isMenuBarVisible()` _Windows_ _Linux_
Returns `boolean` - Whether the menu bar is visible.
#### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_
* `visible` boolean
* `options` Object (optional)
* `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether
the window should be visible above fullscreen windows.
* `skipTransformProcessType` boolean (optional) _macOS_ - Calling
setVisibleOnAllWorkspaces will by default transform the process
type between UIElementApplication and ForegroundApplication to
ensure the correct behavior. However, this will hide the window
and dock for a short time every time it is called. If your window
is already of type UIElementApplication, you can bypass this
transformation by passing true to skipTransformProcessType.
Sets whether the window should be visible on all workspaces.
**Note:** This API does nothing on Windows.
#### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_
Returns `boolean` - Whether the window is visible on all workspaces.
**Note:** This API always returns false on Windows.
#### `win.setIgnoreMouseEvents(ignore[, options])`
* `ignore` boolean
* `options` Object (optional)
* `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move
messages to Chromium, enabling mouse related events such as `mouseleave`.
Only used when `ignore` is true. If `ignore` is false, forwarding is always
disabled regardless of this value.
Makes the window ignore all mouse events.
All mouse events happened in this window will be passed to the window below
this window, but if this window has focus, it will still receive keyboard
events.
#### `win.setContentProtection(enable)` _macOS_ _Windows_
* `enable` boolean
Prevents the window contents from being captured by other apps.
On macOS it sets the NSWindow's sharingType to NSWindowSharingNone.
On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`.
For Windows 10 version 2004 and up the window will be removed from capture entirely,
older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window.
#### `win.setFocusable(focusable)` _macOS_ _Windows_
* `focusable` boolean
Changes whether the window can be focused.
On macOS it does not remove the focus from the window.
#### `win.isFocusable()` _macOS_ _Windows_
Returns whether the window can be focused.
#### `win.setParentWindow(parent)`
* `parent` BrowserWindow | null
Sets `parent` as current window's parent window, passing `null` will turn
current window into a top-level window.
#### `win.getParentWindow()`
Returns `BrowserWindow | null` - The parent window or `null` if there is no parent.
#### `win.getChildWindows()`
Returns `BrowserWindow[]` - All child windows.
#### `win.setAutoHideCursor(autoHide)` _macOS_
* `autoHide` boolean
Controls whether to hide cursor when typing.
#### `win.selectPreviousTab()` _macOS_
Selects the previous tab when native tabs are enabled and there are other
tabs in the window.
#### `win.selectNextTab()` _macOS_
Selects the next tab when native tabs are enabled and there are other
tabs in the window.
#### `win.mergeAllWindows()` _macOS_
Merges all windows into one window with multiple tabs when native tabs
are enabled and there is more than one open window.
#### `win.moveTabToNewWindow()` _macOS_
Moves the current tab into a new window if native tabs are enabled and
there is more than one tab in the current window.
#### `win.toggleTabBar()` _macOS_
Toggles the visibility of the tab bar if native tabs are enabled and
there is only one tab in the current window.
#### `win.addTabbedWindow(browserWindow)` _macOS_
* `browserWindow` BrowserWindow
Adds a window as a tab on this window, after the tab for the window instance.
#### `win.setVibrancy(type)` _macOS_
* `type` string | null - Can be `appearance-based`, `light`, `dark`, `titlebar`,
`selection`, `menu`, `popover`, `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See
the [macOS documentation][vibrancy-docs] for more details.
Adds a vibrancy effect to the browser window. Passing `null` or an empty string
will remove the vibrancy effect on the window.
Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been
deprecated and will be removed in an upcoming version of macOS.
#### `win.setTrafficLightPosition(position)` _macOS_
* `position` [Point](structures/point.md)
Set a custom position for the traffic light buttons in frameless window.
#### `win.getTrafficLightPosition()` _macOS_
Returns `Point` - The custom position for the traffic light buttons in
frameless window.
#### `win.setTouchBar(touchBar)` _macOS_
* `touchBar` TouchBar | null
Sets the touchBar layout for the current window. Specifying `null` or
`undefined` clears the touch bar. This method only has an effect if the
machine has a touch bar and is running on macOS 10.12.1+.
**Note:** The TouchBar API is currently experimental and may change or be
removed in future Electron releases.
#### `win.setBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`.
If there are other `BrowserView`s attached, they will be removed from
this window.
#### `win.getBrowserView()` _Experimental_
Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null`
if one is not attached. Throws an error if multiple `BrowserView`s are attached.
#### `win.addBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
Replacement API for setBrowserView supporting work with multi browser views.
#### `win.removeBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
#### `win.setTopBrowserView(browserView)` _Experimental_
* `browserView` [BrowserView](browser-view.md)
Raises `browserView` above other `BrowserView`s attached to `win`.
Throws an error if `browserView` is not attached to `win`.
#### `win.getBrowserViews()` _Experimental_
Returns `BrowserView[]` - an array of all BrowserViews that have been attached
with `addBrowserView` or `setBrowserView`.
**Note:** The BrowserView API is currently experimental and may change or be
removed in future Electron releases.
#### `win.setTitleBarOverlay(options)` _Windows_
* `options` Object
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled.
* `height` Integer (optional) _Windows_ - The height of the title bar and Window Controls Overlay in pixels.
On a Window with Window Controls Overlay already enabled, this method updates
the style of the title bar overlay.
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
[page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look
[vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc
[window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level
[chrome-content-scripts]: https://developer.chrome.com/extensions/content_scripts#execution-environment
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/api/electron_api_base_window.cc
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_base_window.h"
#include <string>
#include <utility>
#include <vector>
#include "electron/buildflags/buildflags.h"
#include "gin/dictionary.h"
#include "shell/browser/api/electron_api_browser_view.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/api/electron_api_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/native_window_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#if defined(TOOLKIT_VIEWS)
#include "shell/browser/native_window_views.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/ui/win/taskbar_host.h"
#include "ui/base/win/shell.h"
#endif
#if BUILDFLAG(IS_WIN)
namespace gin {
template <>
struct Converter<electron::TaskbarHost::ThumbarButton> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::TaskbarHost::ThumbarButton* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("click", &(out->clicked_callback));
dict.Get("tooltip", &(out->tooltip));
dict.Get("flags", &out->flags);
return dict.Get("icon", &(out->icon));
}
};
} // namespace gin
#endif
namespace electron::api {
namespace {
// Converts binary data to Buffer.
v8::Local<v8::Value> ToBuffer(v8::Isolate* isolate, void* val, int size) {
auto buffer = node::Buffer::Copy(isolate, static_cast<char*>(val), size);
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
} // namespace
BaseWindow::BaseWindow(v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
// The parent window.
gin::Handle<BaseWindow> parent;
if (options.Get("parent", &parent) && !parent.IsEmpty())
parent_window_.Reset(isolate, parent.ToV8());
#if BUILDFLAG(ENABLE_OSR)
// Offscreen windows are always created frameless.
gin_helper::Dictionary web_preferences;
bool offscreen;
if (options.Get(options::kWebPreferences, &web_preferences) &&
web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) {
const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false);
}
#endif
// Creates NativeWindow.
window_.reset(NativeWindow::Create(
options, parent.IsEmpty() ? nullptr : parent->window_.get()));
window_->AddObserver(this);
#if defined(TOOLKIT_VIEWS)
v8::Local<v8::Value> icon;
if (options.Get(options::kIcon, &icon)) {
SetIconImpl(isolate, icon, NativeImage::OnConvertError::kWarn);
}
#endif
}
BaseWindow::BaseWindow(gin_helper::Arguments* args,
const gin_helper::Dictionary& options)
: BaseWindow(args->isolate(), options) {
InitWithArgs(args);
// Init window after everything has been setup.
window()->InitFromOptions(options);
}
BaseWindow::~BaseWindow() {
CloseImmediately();
// Destroy the native window in next tick because the native code might be
// iterating all windows.
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, window_.release());
// Remove global reference so the JS object can be garbage collected.
self_ref_.Reset();
}
void BaseWindow::InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
AttachAsUserData(window_.get());
gin_helper::TrackableObject<BaseWindow>::InitWith(isolate, wrapper);
// We can only append this window to parent window's child windows after this
// window's JS wrapper gets initialized.
if (!parent_window_.IsEmpty()) {
gin::Handle<BaseWindow> parent;
gin::ConvertFromV8(isolate, GetParentWindow(), &parent);
DCHECK(!parent.IsEmpty());
parent->child_windows_.Set(isolate, weak_map_id(), wrapper);
}
// Reference this object in case it got garbage collected.
self_ref_.Reset(isolate, wrapper);
}
void BaseWindow::WillCloseWindow(bool* prevent_default) {
if (Emit("close")) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowClosed() {
// Invalidate weak ptrs before the Javascript object is destroyed,
// there might be some delayed emit events which shouldn't be
// triggered after this.
weak_factory_.InvalidateWeakPtrs();
RemoveFromWeakMap();
window_->RemoveObserver(this);
// We can not call Destroy here because we need to call Emit first, but we
// also do not want any method to be used, so just mark as destroyed here.
MarkDestroyed();
Emit("closed");
RemoveFromParentChildWindows();
BaseWindow::ResetBrowserViews();
// Destroy the native class when window is closed.
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, GetDestroyClosure());
}
void BaseWindow::OnWindowEndSession() {
Emit("session-end");
}
void BaseWindow::OnWindowBlur() {
EmitEventSoon("blur");
}
void BaseWindow::OnWindowFocus() {
EmitEventSoon("focus");
}
void BaseWindow::OnWindowShow() {
Emit("show");
}
void BaseWindow::OnWindowHide() {
Emit("hide");
}
void BaseWindow::OnWindowMaximize() {
Emit("maximize");
}
void BaseWindow::OnWindowUnmaximize() {
Emit("unmaximize");
}
void BaseWindow::OnWindowMinimize() {
Emit("minimize");
}
void BaseWindow::OnWindowRestore() {
Emit("restore");
}
void BaseWindow::OnWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary info = gin::Dictionary::CreateEmpty(isolate);
info.Set("edge", edge);
if (Emit("will-resize", new_bounds, info)) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowResize() {
Emit("resize");
}
void BaseWindow::OnWindowResized() {
Emit("resized");
}
void BaseWindow::OnWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
if (Emit("will-move", new_bounds)) {
*prevent_default = true;
}
}
void BaseWindow::OnWindowMove() {
Emit("move");
}
void BaseWindow::OnWindowMoved() {
Emit("moved");
}
void BaseWindow::OnWindowEnterFullScreen() {
Emit("enter-full-screen");
}
void BaseWindow::OnWindowLeaveFullScreen() {
Emit("leave-full-screen");
}
void BaseWindow::OnWindowSwipe(const std::string& direction) {
Emit("swipe", direction);
}
void BaseWindow::OnWindowRotateGesture(float rotation) {
Emit("rotate-gesture", rotation);
}
void BaseWindow::OnWindowSheetBegin() {
Emit("sheet-begin");
}
void BaseWindow::OnWindowSheetEnd() {
Emit("sheet-end");
}
void BaseWindow::OnWindowEnterHtmlFullScreen() {
Emit("enter-html-full-screen");
}
void BaseWindow::OnWindowLeaveHtmlFullScreen() {
Emit("leave-html-full-screen");
}
void BaseWindow::OnWindowAlwaysOnTopChanged() {
Emit("always-on-top-changed", IsAlwaysOnTop());
}
void BaseWindow::OnExecuteAppCommand(const std::string& command_name) {
Emit("app-command", command_name);
}
void BaseWindow::OnTouchBarItemResult(const std::string& item_id,
const base::Value::Dict& details) {
Emit("-touch-bar-interaction", item_id, details);
}
void BaseWindow::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
void BaseWindow::OnSystemContextMenu(int x, int y, bool* prevent_default) {
if (Emit("system-context-menu", gfx::Point(x, y))) {
*prevent_default = true;
}
}
#if BUILDFLAG(IS_WIN)
void BaseWindow::OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) {
if (IsWindowMessageHooked(message)) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
messages_callback_map_[message].Run(
ToBuffer(isolate, static_cast<void*>(&w_param), sizeof(WPARAM)),
ToBuffer(isolate, static_cast<void*>(&l_param), sizeof(LPARAM)));
}
}
#endif
void BaseWindow::SetContentView(gin::Handle<View> view) {
ResetBrowserViews();
content_view_.Reset(isolate(), view.ToV8());
window_->SetContentView(view->view());
}
void BaseWindow::CloseImmediately() {
if (!window_->IsClosed())
window_->CloseImmediately();
}
void BaseWindow::Close() {
window_->Close();
}
void BaseWindow::Focus() {
window_->Focus(true);
}
void BaseWindow::Blur() {
window_->Focus(false);
}
bool BaseWindow::IsFocused() {
return window_->IsFocused();
}
void BaseWindow::Show() {
window_->Show();
}
void BaseWindow::ShowInactive() {
// This method doesn't make sense for modal window.
if (IsModal())
return;
window_->ShowInactive();
}
void BaseWindow::Hide() {
window_->Hide();
}
bool BaseWindow::IsVisible() {
return window_->IsVisible();
}
bool BaseWindow::IsEnabled() {
return window_->IsEnabled();
}
void BaseWindow::SetEnabled(bool enable) {
window_->SetEnabled(enable);
}
void BaseWindow::Maximize() {
window_->Maximize();
}
void BaseWindow::Unmaximize() {
window_->Unmaximize();
}
bool BaseWindow::IsMaximized() {
return window_->IsMaximized();
}
void BaseWindow::Minimize() {
window_->Minimize();
}
void BaseWindow::Restore() {
window_->Restore();
}
bool BaseWindow::IsMinimized() {
return window_->IsMinimized();
}
void BaseWindow::SetFullScreen(bool fullscreen) {
window_->SetFullScreen(fullscreen);
}
bool BaseWindow::IsFullscreen() {
return window_->IsFullscreen();
}
void BaseWindow::SetBounds(const gfx::Rect& bounds,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetBounds(bounds, animate);
}
gfx::Rect BaseWindow::GetBounds() {
return window_->GetBounds();
}
bool BaseWindow::IsNormal() {
return window_->IsNormal();
}
gfx::Rect BaseWindow::GetNormalBounds() {
return window_->GetNormalBounds();
}
void BaseWindow::SetContentBounds(const gfx::Rect& bounds,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentBounds(bounds, animate);
}
gfx::Rect BaseWindow::GetContentBounds() {
return window_->GetContentBounds();
}
void BaseWindow::SetSize(int width, int height, gin_helper::Arguments* args) {
bool animate = false;
gfx::Size size = window_->GetMinimumSize();
size.SetToMax(gfx::Size(width, height));
args->GetNext(&animate);
window_->SetSize(size, animate);
}
std::vector<int> BaseWindow::GetSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetContentSize(int width,
int height,
gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetContentSize(gfx::Size(width, height), animate);
}
std::vector<int> BaseWindow::GetContentSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetContentSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetMinimumSize(int width, int height) {
window_->SetMinimumSize(gfx::Size(width, height));
}
std::vector<int> BaseWindow::GetMinimumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMinimumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetMaximumSize(int width, int height) {
window_->SetMaximumSize(gfx::Size(width, height));
}
std::vector<int> BaseWindow::GetMaximumSize() {
std::vector<int> result(2);
gfx::Size size = window_->GetMaximumSize();
result[0] = size.width();
result[1] = size.height();
return result;
}
void BaseWindow::SetSheetOffset(double offsetY, gin_helper::Arguments* args) {
double offsetX = 0.0;
args->GetNext(&offsetX);
window_->SetSheetOffset(offsetX, offsetY);
}
void BaseWindow::SetResizable(bool resizable) {
window_->SetResizable(resizable);
}
bool BaseWindow::IsResizable() {
return window_->IsResizable();
}
void BaseWindow::SetMovable(bool movable) {
window_->SetMovable(movable);
}
bool BaseWindow::IsMovable() {
return window_->IsMovable();
}
void BaseWindow::SetMinimizable(bool minimizable) {
window_->SetMinimizable(minimizable);
}
bool BaseWindow::IsMinimizable() {
return window_->IsMinimizable();
}
void BaseWindow::SetMaximizable(bool maximizable) {
window_->SetMaximizable(maximizable);
}
bool BaseWindow::IsMaximizable() {
return window_->IsMaximizable();
}
void BaseWindow::SetFullScreenable(bool fullscreenable) {
window_->SetFullScreenable(fullscreenable);
}
bool BaseWindow::IsFullScreenable() {
return window_->IsFullScreenable();
}
void BaseWindow::SetClosable(bool closable) {
window_->SetClosable(closable);
}
bool BaseWindow::IsClosable() {
return window_->IsClosable();
}
void BaseWindow::SetAlwaysOnTop(bool top, gin_helper::Arguments* args) {
std::string level = "floating";
int relative_level = 0;
args->GetNext(&level);
args->GetNext(&relative_level);
ui::ZOrderLevel z_order =
top ? ui::ZOrderLevel::kFloatingWindow : ui::ZOrderLevel::kNormal;
window_->SetAlwaysOnTop(z_order, level, relative_level);
}
bool BaseWindow::IsAlwaysOnTop() {
return window_->GetZOrderLevel() != ui::ZOrderLevel::kNormal;
}
void BaseWindow::Center() {
window_->Center();
}
void BaseWindow::SetPosition(int x, int y, gin_helper::Arguments* args) {
bool animate = false;
args->GetNext(&animate);
window_->SetPosition(gfx::Point(x, y), animate);
}
std::vector<int> BaseWindow::GetPosition() {
std::vector<int> result(2);
gfx::Point pos = window_->GetPosition();
result[0] = pos.x();
result[1] = pos.y();
return result;
}
void BaseWindow::MoveAbove(const std::string& sourceId,
gin_helper::Arguments* args) {
#if BUILDFLAG(ENABLE_DESKTOP_CAPTURER)
if (!window_->MoveAbove(sourceId))
args->ThrowError("Invalid media source id");
#else
args->ThrowError("enable_desktop_capturer=true to use this feature");
#endif
}
void BaseWindow::MoveTop() {
window_->MoveTop();
}
void BaseWindow::SetTitle(const std::string& title) {
window_->SetTitle(title);
}
std::string BaseWindow::GetTitle() {
return window_->GetTitle();
}
void BaseWindow::SetAccessibleTitle(const std::string& title) {
window_->SetAccessibleTitle(title);
}
std::string BaseWindow::GetAccessibleTitle() {
return window_->GetAccessibleTitle();
}
void BaseWindow::FlashFrame(bool flash) {
window_->FlashFrame(flash);
}
void BaseWindow::SetSkipTaskbar(bool skip) {
window_->SetSkipTaskbar(skip);
}
void BaseWindow::SetExcludedFromShownWindowsMenu(bool excluded) {
window_->SetExcludedFromShownWindowsMenu(excluded);
}
bool BaseWindow::IsExcludedFromShownWindowsMenu() {
return window_->IsExcludedFromShownWindowsMenu();
}
void BaseWindow::SetSimpleFullScreen(bool simple_fullscreen) {
window_->SetSimpleFullScreen(simple_fullscreen);
}
bool BaseWindow::IsSimpleFullScreen() {
return window_->IsSimpleFullScreen();
}
void BaseWindow::SetKiosk(bool kiosk) {
window_->SetKiosk(kiosk);
}
bool BaseWindow::IsKiosk() {
return window_->IsKiosk();
}
bool BaseWindow::IsTabletMode() const {
return window_->IsTabletMode();
}
void BaseWindow::SetBackgroundColor(const std::string& color_name) {
SkColor color = ParseCSSColor(color_name);
window_->SetBackgroundColor(color);
}
std::string BaseWindow::GetBackgroundColor(gin_helper::Arguments* args) {
return ToRGBHex(window_->GetBackgroundColor());
}
void BaseWindow::SetHasShadow(bool has_shadow) {
window_->SetHasShadow(has_shadow);
}
bool BaseWindow::HasShadow() {
return window_->HasShadow();
}
void BaseWindow::SetOpacity(const double opacity) {
window_->SetOpacity(opacity);
}
double BaseWindow::GetOpacity() {
return window_->GetOpacity();
}
void BaseWindow::SetShape(const std::vector<gfx::Rect>& rects) {
window_->widget()->SetShape(std::make_unique<std::vector<gfx::Rect>>(rects));
}
void BaseWindow::SetRepresentedFilename(const std::string& filename) {
window_->SetRepresentedFilename(filename);
}
std::string BaseWindow::GetRepresentedFilename() {
return window_->GetRepresentedFilename();
}
void BaseWindow::SetDocumentEdited(bool edited) {
window_->SetDocumentEdited(edited);
}
bool BaseWindow::IsDocumentEdited() {
return window_->IsDocumentEdited();
}
void BaseWindow::SetIgnoreMouseEvents(bool ignore,
gin_helper::Arguments* args) {
gin_helper::Dictionary options;
bool forward = false;
args->GetNext(&options) && options.Get("forward", &forward);
return window_->SetIgnoreMouseEvents(ignore, forward);
}
void BaseWindow::SetContentProtection(bool enable) {
return window_->SetContentProtection(enable);
}
void BaseWindow::SetFocusable(bool focusable) {
return window_->SetFocusable(focusable);
}
bool BaseWindow::IsFocusable() {
return window_->IsFocusable();
}
void BaseWindow::SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> value) {
auto context = isolate->GetCurrentContext();
gin::Handle<Menu> menu;
v8::Local<v8::Object> object;
if (value->IsObject() && value->ToObject(context).ToLocal(&object) &&
gin::ConvertFromV8(isolate, value, &menu) && !menu.IsEmpty()) {
menu_.Reset(isolate, menu.ToV8());
// We only want to update the menu if the menu has a non-zero item count,
// or we risk crashes.
if (menu->model()->GetItemCount() == 0) {
RemoveMenu();
} else {
window_->SetMenu(menu->model());
}
} else if (value->IsNull()) {
RemoveMenu();
} else {
isolate->ThrowException(
v8::Exception::TypeError(gin::StringToV8(isolate, "Invalid Menu")));
}
}
void BaseWindow::RemoveMenu() {
menu_.Reset();
window_->SetMenu(nullptr);
}
void BaseWindow::SetParentWindow(v8::Local<v8::Value> value,
gin_helper::Arguments* args) {
if (IsModal()) {
args->ThrowError("Can not be called for modal window");
return;
}
gin::Handle<BaseWindow> parent;
if (value->IsNull() || value->IsUndefined()) {
RemoveFromParentChildWindows();
parent_window_.Reset();
window_->SetParentWindow(nullptr);
} else if (gin::ConvertFromV8(isolate(), value, &parent)) {
RemoveFromParentChildWindows();
parent_window_.Reset(isolate(), value);
window_->SetParentWindow(parent->window_.get());
parent->child_windows_.Set(isolate(), weak_map_id(), GetWrapper());
} else {
args->ThrowError("Must pass BaseWindow instance or null");
}
}
void BaseWindow::SetBrowserView(
absl::optional<gin::Handle<BrowserView>> browser_view) {
ResetBrowserViews();
if (browser_view)
AddBrowserView(*browser_view);
}
void BaseWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) {
auto iter = browser_views_.find(browser_view->ID());
if (iter == browser_views_.end()) {
// If we're reparenting a BrowserView, ensure that it's detached from
// its previous owner window.
BaseWindow* owner_window = browser_view->owner_window();
if (owner_window) {
// iter == browser_views_.end() should imply owner_window != this.
DCHECK_NE(owner_window, this);
owner_window->RemoveBrowserView(browser_view);
browser_view->SetOwnerWindow(nullptr);
}
window_->AddBrowserView(browser_view->view());
window_->AddDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(this);
browser_views_[browser_view->ID()].Reset(isolate(), browser_view.ToV8());
}
}
void BaseWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) {
auto iter = browser_views_.find(browser_view->ID());
if (iter != browser_views_.end()) {
window_->RemoveBrowserView(browser_view->view());
window_->RemoveDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(nullptr);
iter->second.Reset();
browser_views_.erase(iter);
}
}
void BaseWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view,
gin_helper::Arguments* args) {
BaseWindow* owner_window = browser_view->owner_window();
auto iter = browser_views_.find(browser_view->ID());
if (iter == browser_views_.end() || (owner_window && owner_window != this)) {
args->ThrowError("Given BrowserView is not attached to the window");
return;
}
window_->SetTopBrowserView(browser_view->view());
}
std::string BaseWindow::GetMediaSourceId() const {
return window_->GetDesktopMediaID().ToString();
}
v8::Local<v8::Value> BaseWindow::GetNativeWindowHandle() {
// TODO(MarshallOfSound): Replace once
// https://chromium-review.googlesource.com/c/chromium/src/+/1253094/ has
// landed
NativeWindowHandle handle = window_->GetNativeWindowHandle();
return ToBuffer(isolate(), &handle, sizeof(handle));
}
void BaseWindow::SetProgressBar(double progress, gin_helper::Arguments* args) {
gin_helper::Dictionary options;
std::string mode;
args->GetNext(&options) && options.Get("mode", &mode);
NativeWindow::ProgressState state = NativeWindow::ProgressState::kNormal;
if (mode == "error")
state = NativeWindow::ProgressState::kError;
else if (mode == "paused")
state = NativeWindow::ProgressState::kPaused;
else if (mode == "indeterminate")
state = NativeWindow::ProgressState::kIndeterminate;
else if (mode == "none")
state = NativeWindow::ProgressState::kNone;
window_->SetProgressBar(progress, state);
}
void BaseWindow::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {
window_->SetOverlayIcon(overlay, description);
}
void BaseWindow::SetVisibleOnAllWorkspaces(bool visible,
gin_helper::Arguments* args) {
gin_helper::Dictionary options;
bool visibleOnFullScreen = false;
bool skipTransformProcessType = false;
if (args->GetNext(&options)) {
options.Get("visibleOnFullScreen", &visibleOnFullScreen);
options.Get("skipTransformProcessType", &skipTransformProcessType);
}
return window_->SetVisibleOnAllWorkspaces(visible, visibleOnFullScreen,
skipTransformProcessType);
}
bool BaseWindow::IsVisibleOnAllWorkspaces() {
return window_->IsVisibleOnAllWorkspaces();
}
void BaseWindow::SetAutoHideCursor(bool auto_hide) {
window_->SetAutoHideCursor(auto_hide);
}
void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) {
std::string type = gin::V8ToString(isolate, value);
window_->SetVibrancy(type);
}
#if BUILDFLAG(IS_MAC)
std::string BaseWindow::GetAlwaysOnTopLevel() {
return window_->GetAlwaysOnTopLevel();
}
void BaseWindow::SetWindowButtonVisibility(bool visible) {
window_->SetWindowButtonVisibility(visible);
}
bool BaseWindow::GetWindowButtonVisibility() const {
return window_->GetWindowButtonVisibility();
}
void BaseWindow::SetTrafficLightPosition(const gfx::Point& position) {
// For backward compatibility we treat (0, 0) as resetting to default.
if (position.IsOrigin())
window_->SetTrafficLightPosition(absl::nullopt);
else
window_->SetTrafficLightPosition(position);
}
gfx::Point BaseWindow::GetTrafficLightPosition() const {
// For backward compatibility we treat default value as (0, 0).
return window_->GetTrafficLightPosition().value_or(gfx::Point());
}
#endif
#if BUILDFLAG(IS_MAC)
bool BaseWindow::IsHiddenInMissionControl() {
return window_->IsHiddenInMissionControl();
}
void BaseWindow::SetHiddenInMissionControl(bool hidden) {
window_->SetHiddenInMissionControl(hidden);
}
#endif
void BaseWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
window_->SetTouchBar(std::move(items));
}
void BaseWindow::RefreshTouchBarItem(const std::string& item_id) {
window_->RefreshTouchBarItem(item_id);
}
void BaseWindow::SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) {
window_->SetEscapeTouchBarItem(std::move(item));
}
void BaseWindow::SelectPreviousTab() {
window_->SelectPreviousTab();
}
void BaseWindow::SelectNextTab() {
window_->SelectNextTab();
}
void BaseWindow::MergeAllWindows() {
window_->MergeAllWindows();
}
void BaseWindow::MoveTabToNewWindow() {
window_->MoveTabToNewWindow();
}
void BaseWindow::ToggleTabBar() {
window_->ToggleTabBar();
}
void BaseWindow::AddTabbedWindow(NativeWindow* window,
gin_helper::Arguments* args) {
if (!window_->AddTabbedWindow(window))
args->ThrowError("AddTabbedWindow cannot be called by a window on itself.");
}
void BaseWindow::SetAutoHideMenuBar(bool auto_hide) {
window_->SetAutoHideMenuBar(auto_hide);
}
bool BaseWindow::IsMenuBarAutoHide() {
return window_->IsMenuBarAutoHide();
}
void BaseWindow::SetMenuBarVisibility(bool visible) {
window_->SetMenuBarVisibility(visible);
}
bool BaseWindow::IsMenuBarVisible() {
return window_->IsMenuBarVisible();
}
void BaseWindow::SetAspectRatio(double aspect_ratio,
gin_helper::Arguments* args) {
gfx::Size extra_size;
args->GetNext(&extra_size);
window_->SetAspectRatio(aspect_ratio, extra_size);
}
void BaseWindow::PreviewFile(const std::string& path,
gin_helper::Arguments* args) {
std::string display_name;
if (!args->GetNext(&display_name))
display_name = path;
window_->PreviewFile(path, display_name);
}
void BaseWindow::CloseFilePreview() {
window_->CloseFilePreview();
}
void BaseWindow::SetGTKDarkThemeEnabled(bool use_dark_theme) {
window_->SetGTKDarkThemeEnabled(use_dark_theme);
}
v8::Local<v8::Value> BaseWindow::GetContentView() const {
if (content_view_.IsEmpty())
return v8::Null(isolate());
else
return v8::Local<v8::Value>::New(isolate(), content_view_);
}
v8::Local<v8::Value> BaseWindow::GetParentWindow() const {
if (parent_window_.IsEmpty())
return v8::Null(isolate());
else
return v8::Local<v8::Value>::New(isolate(), parent_window_);
}
std::vector<v8::Local<v8::Object>> BaseWindow::GetChildWindows() const {
return child_windows_.Values(isolate());
}
v8::Local<v8::Value> BaseWindow::GetBrowserView(
gin_helper::Arguments* args) const {
if (browser_views_.empty()) {
return v8::Null(isolate());
} else if (browser_views_.size() == 1) {
auto first_view = browser_views_.begin();
return v8::Local<v8::Value>::New(isolate(), (*first_view).second);
} else {
args->ThrowError(
"BrowserWindow have multiple BrowserViews, "
"Use getBrowserViews() instead");
return v8::Null(isolate());
}
}
std::vector<v8::Local<v8::Value>> BaseWindow::GetBrowserViews() const {
std::vector<v8::Local<v8::Value>> ret;
for (auto const& views_iter : browser_views_) {
ret.push_back(v8::Local<v8::Value>::New(isolate(), views_iter.second));
}
return ret;
}
bool BaseWindow::IsModal() const {
return window_->is_modal();
}
bool BaseWindow::SetThumbarButtons(gin_helper::Arguments* args) {
#if BUILDFLAG(IS_WIN)
std::vector<TaskbarHost::ThumbarButton> buttons;
if (!args->GetNext(&buttons)) {
args->ThrowError();
return false;
}
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbarButtons(
window_->GetAcceleratedWidget(), buttons);
#else
return false;
#endif
}
#if defined(TOOLKIT_VIEWS)
void BaseWindow::SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
SetIconImpl(isolate, icon, NativeImage::OnConvertError::kThrow);
}
void BaseWindow::SetIconImpl(v8::Isolate* isolate,
v8::Local<v8::Value> icon,
NativeImage::OnConvertError on_error) {
NativeImage* native_image = nullptr;
if (!NativeImage::TryConvertNativeImage(isolate, icon, &native_image,
on_error))
return;
#if BUILDFLAG(IS_WIN)
static_cast<NativeWindowViews*>(window_.get())
->SetIcon(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON)),
native_image->GetHICON(GetSystemMetrics(SM_CXICON)));
#elif BUILDFLAG(IS_LINUX)
static_cast<NativeWindowViews*>(window_.get())
->SetIcon(native_image->image().AsImageSkia());
#endif
}
#endif
#if BUILDFLAG(IS_WIN)
bool BaseWindow::HookWindowMessage(UINT message,
const MessageCallback& callback) {
messages_callback_map_[message] = callback;
return true;
}
void BaseWindow::UnhookWindowMessage(UINT message) {
messages_callback_map_.erase(message);
}
bool BaseWindow::IsWindowMessageHooked(UINT message) {
return base::Contains(messages_callback_map_, message);
}
void BaseWindow::UnhookAllWindowMessages() {
messages_callback_map_.clear();
}
bool BaseWindow::SetThumbnailClip(const gfx::Rect& region) {
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailClip(
window_->GetAcceleratedWidget(), region);
}
bool BaseWindow::SetThumbnailToolTip(const std::string& tooltip) {
auto* window = static_cast<NativeWindowViews*>(window_.get());
return window->taskbar_host().SetThumbnailToolTip(
window_->GetAcceleratedWidget(), tooltip);
}
void BaseWindow::SetAppDetails(const gin_helper::Dictionary& options) {
std::wstring app_id;
base::FilePath app_icon_path;
int app_icon_index = 0;
std::wstring relaunch_command;
std::wstring relaunch_display_name;
options.Get("appId", &app_id);
options.Get("appIconPath", &app_icon_path);
options.Get("appIconIndex", &app_icon_index);
options.Get("relaunchCommand", &relaunch_command);
options.Get("relaunchDisplayName", &relaunch_display_name);
ui::win::SetAppDetailsForWindow(app_id, app_icon_path, app_icon_index,
relaunch_command, relaunch_display_name,
window_->GetAcceleratedWidget());
}
#endif
int32_t BaseWindow::GetID() const {
return weak_map_id();
}
void BaseWindow::ResetBrowserViews() {
v8::HandleScope scope(isolate());
for (auto& item : browser_views_) {
gin::Handle<BrowserView> browser_view;
if (gin::ConvertFromV8(isolate(),
v8::Local<v8::Value>::New(isolate(), item.second),
&browser_view) &&
!browser_view.IsEmpty()) {
// There's a chance that the BrowserView may have been reparented - only
// reset if the owner window is *this* window.
BaseWindow* owner_window = browser_view->owner_window();
DCHECK_EQ(owner_window, this);
browser_view->SetOwnerWindow(nullptr);
window_->RemoveBrowserView(browser_view->view());
window_->RemoveDraggableRegionProvider(browser_view.get());
browser_view->SetOwnerWindow(nullptr);
}
item.second.Reset();
}
browser_views_.clear();
}
void BaseWindow::RemoveFromParentChildWindows() {
if (parent_window_.IsEmpty())
return;
gin::Handle<BaseWindow> parent;
if (!gin::ConvertFromV8(isolate(), GetParentWindow(), &parent) ||
parent.IsEmpty()) {
return;
}
parent->child_windows_.Remove(weak_map_id());
}
// static
gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
return new BaseWindow(args, options);
}
// static
void BaseWindow::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(gin::StringToV8(isolate, "BaseWindow"));
gin_helper::Destroyable::MakeDestroyable(isolate, prototype);
gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod("setContentView", &BaseWindow::SetContentView)
.SetMethod("close", &BaseWindow::Close)
.SetMethod("focus", &BaseWindow::Focus)
.SetMethod("blur", &BaseWindow::Blur)
.SetMethod("isFocused", &BaseWindow::IsFocused)
.SetMethod("show", &BaseWindow::Show)
.SetMethod("showInactive", &BaseWindow::ShowInactive)
.SetMethod("hide", &BaseWindow::Hide)
.SetMethod("isVisible", &BaseWindow::IsVisible)
.SetMethod("isEnabled", &BaseWindow::IsEnabled)
.SetMethod("setEnabled", &BaseWindow::SetEnabled)
.SetMethod("maximize", &BaseWindow::Maximize)
.SetMethod("unmaximize", &BaseWindow::Unmaximize)
.SetMethod("isMaximized", &BaseWindow::IsMaximized)
.SetMethod("minimize", &BaseWindow::Minimize)
.SetMethod("restore", &BaseWindow::Restore)
.SetMethod("isMinimized", &BaseWindow::IsMinimized)
.SetMethod("setFullScreen", &BaseWindow::SetFullScreen)
.SetMethod("isFullScreen", &BaseWindow::IsFullscreen)
.SetMethod("setBounds", &BaseWindow::SetBounds)
.SetMethod("getBounds", &BaseWindow::GetBounds)
.SetMethod("isNormal", &BaseWindow::IsNormal)
.SetMethod("getNormalBounds", &BaseWindow::GetNormalBounds)
.SetMethod("setSize", &BaseWindow::SetSize)
.SetMethod("getSize", &BaseWindow::GetSize)
.SetMethod("setContentBounds", &BaseWindow::SetContentBounds)
.SetMethod("getContentBounds", &BaseWindow::GetContentBounds)
.SetMethod("setContentSize", &BaseWindow::SetContentSize)
.SetMethod("getContentSize", &BaseWindow::GetContentSize)
.SetMethod("setMinimumSize", &BaseWindow::SetMinimumSize)
.SetMethod("getMinimumSize", &BaseWindow::GetMinimumSize)
.SetMethod("setMaximumSize", &BaseWindow::SetMaximumSize)
.SetMethod("getMaximumSize", &BaseWindow::GetMaximumSize)
.SetMethod("setSheetOffset", &BaseWindow::SetSheetOffset)
.SetMethod("moveAbove", &BaseWindow::MoveAbove)
.SetMethod("moveTop", &BaseWindow::MoveTop)
.SetMethod("setResizable", &BaseWindow::SetResizable)
.SetMethod("isResizable", &BaseWindow::IsResizable)
.SetMethod("setMovable", &BaseWindow::SetMovable)
.SetMethod("isMovable", &BaseWindow::IsMovable)
.SetMethod("setMinimizable", &BaseWindow::SetMinimizable)
.SetMethod("isMinimizable", &BaseWindow::IsMinimizable)
.SetMethod("setMaximizable", &BaseWindow::SetMaximizable)
.SetMethod("isMaximizable", &BaseWindow::IsMaximizable)
.SetMethod("setFullScreenable", &BaseWindow::SetFullScreenable)
.SetMethod("isFullScreenable", &BaseWindow::IsFullScreenable)
.SetMethod("setClosable", &BaseWindow::SetClosable)
.SetMethod("isClosable", &BaseWindow::IsClosable)
.SetMethod("setAlwaysOnTop", &BaseWindow::SetAlwaysOnTop)
.SetMethod("isAlwaysOnTop", &BaseWindow::IsAlwaysOnTop)
.SetMethod("center", &BaseWindow::Center)
.SetMethod("setPosition", &BaseWindow::SetPosition)
.SetMethod("getPosition", &BaseWindow::GetPosition)
.SetMethod("setTitle", &BaseWindow::SetTitle)
.SetMethod("getTitle", &BaseWindow::GetTitle)
.SetProperty("accessibleTitle", &BaseWindow::GetAccessibleTitle,
&BaseWindow::SetAccessibleTitle)
.SetMethod("flashFrame", &BaseWindow::FlashFrame)
.SetMethod("setSkipTaskbar", &BaseWindow::SetSkipTaskbar)
.SetMethod("setSimpleFullScreen", &BaseWindow::SetSimpleFullScreen)
.SetMethod("isSimpleFullScreen", &BaseWindow::IsSimpleFullScreen)
.SetMethod("setKiosk", &BaseWindow::SetKiosk)
.SetMethod("isKiosk", &BaseWindow::IsKiosk)
.SetMethod("isTabletMode", &BaseWindow::IsTabletMode)
.SetMethod("setBackgroundColor", &BaseWindow::SetBackgroundColor)
.SetMethod("getBackgroundColor", &BaseWindow::GetBackgroundColor)
.SetMethod("setHasShadow", &BaseWindow::SetHasShadow)
.SetMethod("hasShadow", &BaseWindow::HasShadow)
.SetMethod("setOpacity", &BaseWindow::SetOpacity)
.SetMethod("getOpacity", &BaseWindow::GetOpacity)
.SetMethod("setShape", &BaseWindow::SetShape)
.SetMethod("setRepresentedFilename", &BaseWindow::SetRepresentedFilename)
.SetMethod("getRepresentedFilename", &BaseWindow::GetRepresentedFilename)
.SetMethod("setDocumentEdited", &BaseWindow::SetDocumentEdited)
.SetMethod("isDocumentEdited", &BaseWindow::IsDocumentEdited)
.SetMethod("setIgnoreMouseEvents", &BaseWindow::SetIgnoreMouseEvents)
.SetMethod("setContentProtection", &BaseWindow::SetContentProtection)
.SetMethod("setFocusable", &BaseWindow::SetFocusable)
.SetMethod("isFocusable", &BaseWindow::IsFocusable)
.SetMethod("setMenu", &BaseWindow::SetMenu)
.SetMethod("removeMenu", &BaseWindow::RemoveMenu)
.SetMethod("setParentWindow", &BaseWindow::SetParentWindow)
.SetMethod("setBrowserView", &BaseWindow::SetBrowserView)
.SetMethod("addBrowserView", &BaseWindow::AddBrowserView)
.SetMethod("removeBrowserView", &BaseWindow::RemoveBrowserView)
.SetMethod("setTopBrowserView", &BaseWindow::SetTopBrowserView)
.SetMethod("getMediaSourceId", &BaseWindow::GetMediaSourceId)
.SetMethod("getNativeWindowHandle", &BaseWindow::GetNativeWindowHandle)
.SetMethod("setProgressBar", &BaseWindow::SetProgressBar)
.SetMethod("setOverlayIcon", &BaseWindow::SetOverlayIcon)
.SetMethod("setVisibleOnAllWorkspaces",
&BaseWindow::SetVisibleOnAllWorkspaces)
.SetMethod("isVisibleOnAllWorkspaces",
&BaseWindow::IsVisibleOnAllWorkspaces)
#if BUILDFLAG(IS_MAC)
.SetMethod("_getAlwaysOnTopLevel", &BaseWindow::GetAlwaysOnTopLevel)
.SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor)
#endif
.SetMethod("setVibrancy", &BaseWindow::SetVibrancy)
#if BUILDFLAG(IS_MAC)
.SetMethod("setTrafficLightPosition",
&BaseWindow::SetTrafficLightPosition)
.SetMethod("getTrafficLightPosition",
&BaseWindow::GetTrafficLightPosition)
#endif
#if BUILDFLAG(IS_MAC)
.SetMethod("isHiddenInMissionControl",
&BaseWindow::IsHiddenInMissionControl)
.SetMethod("setHiddenInMissionControl",
&BaseWindow::SetHiddenInMissionControl)
#endif
.SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar)
.SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem)
.SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem)
#if BUILDFLAG(IS_MAC)
.SetMethod("selectPreviousTab", &BaseWindow::SelectPreviousTab)
.SetMethod("selectNextTab", &BaseWindow::SelectNextTab)
.SetMethod("mergeAllWindows", &BaseWindow::MergeAllWindows)
.SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow)
.SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar)
.SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow)
.SetMethod("setWindowButtonVisibility",
&BaseWindow::SetWindowButtonVisibility)
.SetMethod("_getWindowButtonVisibility",
&BaseWindow::GetWindowButtonVisibility)
.SetProperty("excludedFromShownWindowsMenu",
&BaseWindow::IsExcludedFromShownWindowsMenu,
&BaseWindow::SetExcludedFromShownWindowsMenu)
#endif
.SetMethod("setAutoHideMenuBar", &BaseWindow::SetAutoHideMenuBar)
.SetMethod("isMenuBarAutoHide", &BaseWindow::IsMenuBarAutoHide)
.SetMethod("setMenuBarVisibility", &BaseWindow::SetMenuBarVisibility)
.SetMethod("isMenuBarVisible", &BaseWindow::IsMenuBarVisible)
.SetMethod("setAspectRatio", &BaseWindow::SetAspectRatio)
.SetMethod("previewFile", &BaseWindow::PreviewFile)
.SetMethod("closeFilePreview", &BaseWindow::CloseFilePreview)
.SetMethod("getContentView", &BaseWindow::GetContentView)
.SetMethod("getParentWindow", &BaseWindow::GetParentWindow)
.SetMethod("getChildWindows", &BaseWindow::GetChildWindows)
.SetMethod("getBrowserView", &BaseWindow::GetBrowserView)
.SetMethod("getBrowserViews", &BaseWindow::GetBrowserViews)
.SetMethod("isModal", &BaseWindow::IsModal)
.SetMethod("setThumbarButtons", &BaseWindow::SetThumbarButtons)
#if defined(TOOLKIT_VIEWS)
.SetMethod("setIcon", &BaseWindow::SetIcon)
#endif
#if BUILDFLAG(IS_WIN)
.SetMethod("hookWindowMessage", &BaseWindow::HookWindowMessage)
.SetMethod("isWindowMessageHooked", &BaseWindow::IsWindowMessageHooked)
.SetMethod("unhookWindowMessage", &BaseWindow::UnhookWindowMessage)
.SetMethod("unhookAllWindowMessages",
&BaseWindow::UnhookAllWindowMessages)
.SetMethod("setThumbnailClip", &BaseWindow::SetThumbnailClip)
.SetMethod("setThumbnailToolTip", &BaseWindow::SetThumbnailToolTip)
.SetMethod("setAppDetails", &BaseWindow::SetAppDetails)
#endif
.SetProperty("id", &BaseWindow::GetID);
}
} // namespace electron::api
namespace {
using electron::api::BaseWindow;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
BaseWindow::SetConstructor(isolate, base::BindRepeating(&BaseWindow::New));
gin_helper::Dictionary constructor(isolate,
BaseWindow::GetConstructor(isolate)
->GetFunction(context)
.ToLocalChecked());
constructor.SetMethod("fromId", &BaseWindow::FromWeakMapID);
constructor.SetMethod("getAllWindows", &BaseWindow::GetAll);
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BaseWindow", constructor);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_base_window, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/api/electron_api_base_window.h
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "gin/handle.h"
#include "shell/browser/native_window.h"
#include "shell/browser/native_window_observer.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/trackable_object.h"
namespace electron::api {
class View;
class BrowserView;
class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
public NativeWindowObserver {
public:
static gin_helper::WrappableBase* New(gin_helper::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
base::WeakPtr<BaseWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
NativeWindow* window() const { return window_.get(); }
protected:
// Common constructor.
BaseWindow(v8::Isolate* isolate, const gin_helper::Dictionary& options);
// Creating independent BaseWindow instance.
BaseWindow(gin_helper::Arguments* args,
const gin_helper::Dictionary& options);
~BaseWindow() override;
// TrackableObject:
void InitWith(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) override;
// NativeWindowObserver:
void WillCloseWindow(bool* prevent_default) override;
void OnWindowClosed() override;
void OnWindowEndSession() override;
void OnWindowBlur() override;
void OnWindowFocus() override;
void OnWindowShow() override;
void OnWindowHide() override;
void OnWindowMaximize() override;
void OnWindowUnmaximize() override;
void OnWindowMinimize() override;
void OnWindowRestore() override;
void OnWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) override;
void OnWindowResize() override;
void OnWindowResized() override;
void OnWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) override;
void OnWindowMove() override;
void OnWindowMoved() override;
void OnWindowSwipe(const std::string& direction) override;
void OnWindowRotateGesture(float rotation) override;
void OnWindowSheetBegin() override;
void OnWindowSheetEnd() override;
void OnWindowEnterFullScreen() override;
void OnWindowLeaveFullScreen() override;
void OnWindowEnterHtmlFullScreen() override;
void OnWindowLeaveHtmlFullScreen() override;
void OnWindowAlwaysOnTopChanged() override;
void OnExecuteAppCommand(const std::string& command_name) override;
void OnTouchBarItemResult(const std::string& item_id,
const base::Value::Dict& details) override;
void OnNewWindowForTab() override;
void OnSystemContextMenu(int x, int y, bool* prevent_default) override;
#if BUILDFLAG(IS_WIN)
void OnWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) override;
#endif
// Public APIs of NativeWindow.
void SetContentView(gin::Handle<View> view);
void Close();
virtual void CloseImmediately();
virtual void Focus();
virtual void Blur();
bool IsFocused();
void Show();
void ShowInactive();
void Hide();
bool IsVisible();
bool IsEnabled();
void SetEnabled(bool enable);
void Maximize();
void Unmaximize();
bool IsMaximized();
void Minimize();
void Restore();
bool IsMinimized();
void SetFullScreen(bool fullscreen);
bool IsFullscreen();
void SetBounds(const gfx::Rect& bounds, gin_helper::Arguments* args);
gfx::Rect GetBounds();
void SetSize(int width, int height, gin_helper::Arguments* args);
std::vector<int> GetSize();
void SetContentSize(int width, int height, gin_helper::Arguments* args);
std::vector<int> GetContentSize();
void SetContentBounds(const gfx::Rect& bounds, gin_helper::Arguments* args);
gfx::Rect GetContentBounds();
bool IsNormal();
gfx::Rect GetNormalBounds();
void SetMinimumSize(int width, int height);
std::vector<int> GetMinimumSize();
void SetMaximumSize(int width, int height);
std::vector<int> GetMaximumSize();
void SetSheetOffset(double offsetY, gin_helper::Arguments* args);
void SetResizable(bool resizable);
bool IsResizable();
void SetMovable(bool movable);
void MoveAbove(const std::string& sourceId, gin_helper::Arguments* args);
void MoveTop();
bool IsMovable();
void SetMinimizable(bool minimizable);
bool IsMinimizable();
void SetMaximizable(bool maximizable);
bool IsMaximizable();
void SetFullScreenable(bool fullscreenable);
bool IsFullScreenable();
void SetClosable(bool closable);
bool IsClosable();
void SetAlwaysOnTop(bool top, gin_helper::Arguments* args);
bool IsAlwaysOnTop();
void Center();
void SetPosition(int x, int y, gin_helper::Arguments* args);
std::vector<int> GetPosition();
void SetTitle(const std::string& title);
std::string GetTitle();
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
void FlashFrame(bool flash);
void SetSkipTaskbar(bool skip);
void SetExcludedFromShownWindowsMenu(bool excluded);
bool IsExcludedFromShownWindowsMenu();
void SetSimpleFullScreen(bool simple_fullscreen);
bool IsSimpleFullScreen();
void SetKiosk(bool kiosk);
bool IsKiosk();
bool IsTabletMode() const;
virtual void SetBackgroundColor(const std::string& color_name);
std::string GetBackgroundColor(gin_helper::Arguments* args);
void SetHasShadow(bool has_shadow);
bool HasShadow();
void SetOpacity(const double opacity);
double GetOpacity();
void SetShape(const std::vector<gfx::Rect>& rects);
void SetRepresentedFilename(const std::string& filename);
std::string GetRepresentedFilename();
void SetDocumentEdited(bool edited);
bool IsDocumentEdited();
void SetIgnoreMouseEvents(bool ignore, gin_helper::Arguments* args);
void SetContentProtection(bool enable);
void SetFocusable(bool focusable);
bool IsFocusable();
void SetMenu(v8::Isolate* isolate, v8::Local<v8::Value> menu);
void RemoveMenu();
void SetParentWindow(v8::Local<v8::Value> value, gin_helper::Arguments* args);
virtual void SetBrowserView(
absl::optional<gin::Handle<BrowserView>> browser_view);
virtual void AddBrowserView(gin::Handle<BrowserView> browser_view);
virtual void RemoveBrowserView(gin::Handle<BrowserView> browser_view);
virtual void SetTopBrowserView(gin::Handle<BrowserView> browser_view,
gin_helper::Arguments* args);
virtual std::vector<v8::Local<v8::Value>> GetBrowserViews() const;
virtual void ResetBrowserViews();
std::string GetMediaSourceId() const;
v8::Local<v8::Value> GetNativeWindowHandle();
void SetProgressBar(double progress, gin_helper::Arguments* args);
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description);
void SetVisibleOnAllWorkspaces(bool visible, gin_helper::Arguments* args);
bool IsVisibleOnAllWorkspaces();
void SetAutoHideCursor(bool auto_hide);
virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value);
#if BUILDFLAG(IS_MAC)
std::string GetAlwaysOnTopLevel();
void SetWindowButtonVisibility(bool visible);
bool GetWindowButtonVisibility() const;
void SetTrafficLightPosition(const gfx::Point& position);
gfx::Point GetTrafficLightPosition() const;
#endif
#if BUILDFLAG(IS_MAC)
bool IsHiddenInMissionControl();
void SetHiddenInMissionControl(bool hidden);
#endif
void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
void RefreshTouchBarItem(const std::string& item_id);
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
void SelectPreviousTab();
void SelectNextTab();
void MergeAllWindows();
void MoveTabToNewWindow();
void ToggleTabBar();
void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args);
void SetAutoHideMenuBar(bool auto_hide);
bool IsMenuBarAutoHide();
void SetMenuBarVisibility(bool visible);
bool IsMenuBarVisible();
void SetAspectRatio(double aspect_ratio, gin_helper::Arguments* args);
void PreviewFile(const std::string& path, gin_helper::Arguments* args);
void CloseFilePreview();
void SetGTKDarkThemeEnabled(bool use_dark_theme);
// Public getters of NativeWindow.
v8::Local<v8::Value> GetContentView() const;
v8::Local<v8::Value> GetParentWindow() const;
std::vector<v8::Local<v8::Object>> GetChildWindows() const;
v8::Local<v8::Value> GetBrowserView(gin_helper::Arguments* args) const;
bool IsModal() const;
// Extra APIs added in JS.
bool SetThumbarButtons(gin_helper::Arguments* args);
#if defined(TOOLKIT_VIEWS)
void SetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
void SetIconImpl(v8::Isolate* isolate,
v8::Local<v8::Value> icon,
NativeImage::OnConvertError on_error);
#endif
#if BUILDFLAG(IS_WIN)
typedef base::RepeatingCallback<void(v8::Local<v8::Value>,
v8::Local<v8::Value>)>
MessageCallback;
bool HookWindowMessage(UINT message, const MessageCallback& callback);
bool IsWindowMessageHooked(UINT message);
void UnhookWindowMessage(UINT message);
void UnhookAllWindowMessages();
bool SetThumbnailClip(const gfx::Rect& region);
bool SetThumbnailToolTip(const std::string& tooltip);
void SetAppDetails(const gin_helper::Dictionary& options);
#endif
int32_t GetID() const;
// Helpers.
// Remove BrowserView.
void ResetBrowserView();
// Remove this window from parent window's |child_windows_|.
void RemoveFromParentChildWindows();
template <typename... Args>
void EmitEventSoon(base::StringPiece eventName) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>),
weak_factory_.GetWeakPtr(), eventName));
}
#if BUILDFLAG(IS_WIN)
typedef std::map<UINT, MessageCallback> MessageCallbackMap;
MessageCallbackMap messages_callback_map_;
#endif
v8::Global<v8::Value> content_view_;
std::map<int32_t, v8::Global<v8::Value>> browser_views_;
v8::Global<v8::Value> menu_;
v8::Global<v8::Value> parent_window_;
KeyWeakMap<int> child_windows_;
std::unique_ptr<NativeWindow> window_;
// Reference to JS wrapper to prevent garbage collection.
v8::Global<v8::Value> self_ref_;
base::WeakPtrFactory<BaseWindow> weak_factory_{this};
};
} // namespace electron::api
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BASE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent() || !ui::win::IsAeroGlassEnabled())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
if (have_max_width && max_width <= 0)
max_width = INT_MAX;
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
if (have_max_height && max_height <= 0)
max_height = INT_MAX;
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (std::find(draggable_region_providers_.begin(),
draggable_region_providers_.end(),
provider) == draggable_region_providers_.end()) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::NONE);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#include <list>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/supports_user_data.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/web_contents_user_data.h"
#include "extensions/browser/app_window/size_constraints.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_observer.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/widget/widget_delegate.h"
class SkRegion;
namespace base {
class DictionaryValue;
}
namespace content {
struct NativeWebKeyboardEvent;
}
namespace gfx {
class Image;
class Point;
class Rect;
enum class ResizeEdge;
class Size;
} // namespace gfx
namespace gin_helper {
class Dictionary;
class PersistentDictionary;
} // namespace gin_helper
namespace electron {
class ElectronMenuModel;
class NativeBrowserView;
namespace api {
class BrowserView;
}
#if BUILDFLAG(IS_MAC)
typedef NSView* NativeWindowHandle;
#else
typedef gfx::AcceleratedWidget NativeWindowHandle;
#endif
class NativeWindow : public base::SupportsUserData,
public views::WidgetDelegate {
public:
~NativeWindow() override;
// disable copy
NativeWindow(const NativeWindow&) = delete;
NativeWindow& operator=(const NativeWindow&) = delete;
// Create window with existing WebContents, the caller is responsible for
// managing the window's live.
static NativeWindow* Create(const gin_helper::Dictionary& options,
NativeWindow* parent = nullptr);
void InitFromOptions(const gin_helper::Dictionary& options);
virtual void SetContentView(views::View* view) = 0;
virtual void Close() = 0;
virtual void CloseImmediately() = 0;
virtual bool IsClosed() const;
virtual void Focus(bool focus) = 0;
virtual bool IsFocused() = 0;
virtual void Show() = 0;
virtual void ShowInactive() = 0;
virtual void Hide() = 0;
virtual bool IsVisible() = 0;
virtual bool IsEnabled() = 0;
virtual void SetEnabled(bool enable) = 0;
virtual void Maximize() = 0;
virtual void Unmaximize() = 0;
virtual bool IsMaximized() = 0;
virtual void Minimize() = 0;
virtual void Restore() = 0;
virtual bool IsMinimized() = 0;
virtual void SetFullScreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0;
virtual gfx::Rect GetBounds() = 0;
virtual void SetSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetSize();
virtual void SetPosition(const gfx::Point& position, bool animate = false);
virtual gfx::Point GetPosition();
virtual void SetContentSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetContentSize();
virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false);
virtual gfx::Rect GetContentBounds();
virtual bool IsNormal();
virtual gfx::Rect GetNormalBounds() = 0;
virtual void SetSizeConstraints(
const extensions::SizeConstraints& window_constraints);
virtual extensions::SizeConstraints GetSizeConstraints() const;
virtual void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints);
virtual extensions::SizeConstraints GetContentSizeConstraints() const;
virtual void SetMinimumSize(const gfx::Size& size);
virtual gfx::Size GetMinimumSize() const;
virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize() const;
virtual gfx::Size GetContentMinimumSize() const;
virtual gfx::Size GetContentMaximumSize() const;
virtual void SetSheetOffset(const double offsetX, const double offsetY);
virtual double GetSheetOffsetX();
virtual double GetSheetOffsetY();
virtual void SetResizable(bool resizable) = 0;
virtual bool MoveAbove(const std::string& sourceId) = 0;
virtual void MoveTop() = 0;
virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0;
virtual bool IsMovable() = 0;
virtual void SetMinimizable(bool minimizable) = 0;
virtual bool IsMinimizable() = 0;
virtual void SetMaximizable(bool maximizable) = 0;
virtual bool IsMaximizable() = 0;
virtual void SetFullScreenable(bool fullscreenable) = 0;
virtual bool IsFullScreenable() = 0;
virtual void SetClosable(bool closable) = 0;
virtual bool IsClosable() = 0;
virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level = "floating",
int relativeLevel = 0) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() = 0;
virtual void Center() = 0;
virtual void Invalidate() = 0;
virtual void SetTitle(const std::string& title) = 0;
virtual std::string GetTitle() = 0;
#if BUILDFLAG(IS_MAC)
virtual std::string GetAlwaysOnTopLevel() = 0;
virtual void SetActive(bool is_key) = 0;
virtual bool IsActive() const = 0;
#endif
// Ability to augment the window title for the screen readers.
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
virtual void FlashFrame(bool flash) = 0;
virtual void SetSkipTaskbar(bool skip) = 0;
virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0;
virtual bool IsExcludedFromShownWindowsMenu() = 0;
virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0;
virtual bool IsSimpleFullScreen() = 0;
virtual void SetKiosk(bool kiosk) = 0;
virtual bool IsKiosk() = 0;
virtual bool IsTabletMode() const;
virtual void SetBackgroundColor(SkColor color) = 0;
virtual SkColor GetBackgroundColor() = 0;
virtual void SetHasShadow(bool has_shadow) = 0;
virtual bool HasShadow() = 0;
virtual void SetOpacity(const double opacity) = 0;
virtual double GetOpacity() = 0;
virtual void SetRepresentedFilename(const std::string& filename);
virtual std::string GetRepresentedFilename();
virtual void SetDocumentEdited(bool edited);
virtual bool IsDocumentEdited();
virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0;
virtual void SetContentProtection(bool enable) = 0;
virtual void SetFocusable(bool focusable);
virtual bool IsFocusable();
virtual void SetMenu(ElectronMenuModel* menu);
virtual void SetParentWindow(NativeWindow* parent);
virtual void AddBrowserView(NativeBrowserView* browser_view) = 0;
virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0;
virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0;
virtual content::DesktopMediaID GetDesktopMediaID() const = 0;
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0;
virtual NativeWindowHandle GetNativeWindowHandle() const = 0;
// Taskbar/Dock APIs.
enum class ProgressState {
kNone, // no progress, no marking
kIndeterminate, // progress, indeterminate
kError, // progress, errored (red)
kPaused, // progress, paused (yellow)
kNormal, // progress, not marked (green)
};
virtual void SetProgressBar(double progress, const ProgressState state) = 0;
virtual void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) = 0;
// Workspace APIs.
virtual void SetVisibleOnAllWorkspaces(
bool visible,
bool visibleOnFullScreen = false,
bool skipTransformProcessType = false) = 0;
virtual bool IsVisibleOnAllWorkspaces() = 0;
virtual void SetAutoHideCursor(bool auto_hide);
// Vibrancy API
virtual void SetVibrancy(const std::string& type);
// Traffic Light API
#if BUILDFLAG(IS_MAC)
virtual void SetWindowButtonVisibility(bool visible) = 0;
virtual bool GetWindowButtonVisibility() const = 0;
virtual void SetTrafficLightPosition(absl::optional<gfx::Point> position) = 0;
virtual absl::optional<gfx::Point> GetTrafficLightPosition() const = 0;
virtual void RedrawTrafficLights() = 0;
virtual void UpdateFrame() = 0;
#endif
// whether windows should be ignored by mission control
#if BUILDFLAG(IS_MAC)
virtual bool IsHiddenInMissionControl() = 0;
virtual void SetHiddenInMissionControl(bool hidden) = 0;
#endif
// Touchbar API
virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
virtual void RefreshTouchBarItem(const std::string& item_id);
virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
// Native Tab API
virtual void SelectPreviousTab();
virtual void SelectNextTab();
virtual void MergeAllWindows();
virtual void MoveTabToNewWindow();
virtual void ToggleTabBar();
virtual bool AddTabbedWindow(NativeWindow* window);
// Toggle the menu bar.
virtual void SetAutoHideMenuBar(bool auto_hide);
virtual bool IsMenuBarAutoHide();
virtual void SetMenuBarVisibility(bool visible);
virtual bool IsMenuBarVisible();
// Set the aspect ratio when resizing window.
double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize();
virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
// File preview APIs.
virtual void PreviewFile(const std::string& path,
const std::string& display_name);
virtual void CloseFilePreview();
virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {}
// Converts between content bounds and window bounds.
virtual gfx::Rect ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const = 0;
virtual gfx::Rect WindowBoundsToContentBounds(
const gfx::Rect& bounds) const = 0;
base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
virtual gfx::Rect GetWindowControlsOverlayRect();
virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect);
// Methods called by the WebContents.
virtual void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {}
// Public API used by platform-dependent delegates and observers to send UI
// related notifications.
void NotifyWindowRequestPreferredWidth(int* width);
void NotifyWindowCloseButtonClicked();
void NotifyWindowClosed();
void NotifyWindowEndSession();
void NotifyWindowBlur();
void NotifyWindowFocus();
void NotifyWindowShow();
void NotifyWindowIsKeyChanged(bool is_key);
void NotifyWindowHide();
void NotifyWindowMaximize();
void NotifyWindowUnmaximize();
void NotifyWindowMinimize();
void NotifyWindowRestore();
void NotifyWindowMove();
void NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default);
void NotifyWindowResize();
void NotifyWindowResized();
void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default);
void NotifyWindowMoved();
void NotifyWindowSwipe(const std::string& direction);
void NotifyWindowRotateGesture(float rotation);
void NotifyWindowSheetBegin();
void NotifyWindowSheetEnd();
virtual void NotifyWindowEnterFullScreen();
virtual void NotifyWindowLeaveFullScreen();
void NotifyWindowEnterHtmlFullScreen();
void NotifyWindowLeaveHtmlFullScreen();
void NotifyWindowAlwaysOnTopChanged();
void NotifyWindowExecuteAppCommand(const std::string& command);
void NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details);
void NotifyNewWindowForTab();
void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default);
void NotifyLayoutWindowControlsOverlay();
#if BUILDFLAG(IS_WIN)
void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param);
#endif
void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(NativeWindowObserver* obs) {
observers_.RemoveObserver(obs);
}
// Handle fullscreen transitions.
void HandlePendingFullscreenTransitions();
enum class FullScreenTransitionState { ENTERING, EXITING, NONE };
void set_fullscreen_transition_state(FullScreenTransitionState state) {
fullscreen_transition_state_ = state;
}
FullScreenTransitionState fullscreen_transition_state() const {
return fullscreen_transition_state_;
}
enum class FullScreenTransitionType { HTML, NATIVE, NONE };
void set_fullscreen_transition_type(FullScreenTransitionType type) {
fullscreen_transition_type_ = type;
}
FullScreenTransitionType fullscreen_transition_type() const {
return fullscreen_transition_type_;
}
views::Widget* widget() const { return widget_.get(); }
views::View* content_view() const { return content_view_; }
enum class TitleBarStyle {
kNormal,
kHidden,
kHiddenInset,
kCustomButtonsOnHover,
};
TitleBarStyle title_bar_style() const { return title_bar_style_; }
int titlebar_overlay_height() const { return titlebar_overlay_height_; }
void set_titlebar_overlay_height(int height) {
titlebar_overlay_height_ = height;
}
bool titlebar_overlay_enabled() const { return titlebar_overlay_; }
bool has_frame() const { return has_frame_; }
void set_has_frame(bool has_frame) { has_frame_ = has_frame; }
bool has_client_frame() const { return has_client_frame_; }
bool transparent() const { return transparent_; }
bool enable_larger_than_screen() const { return enable_larger_than_screen_; }
NativeWindow* parent() const { return parent_; }
bool is_modal() const { return is_modal_; }
std::list<NativeBrowserView*> browser_views() const { return browser_views_; }
int32_t window_id() const { return next_id_; }
int NonClientHitTest(const gfx::Point& point);
void AddDraggableRegionProvider(DraggableRegionProvider* provider);
void RemoveDraggableRegionProvider(DraggableRegionProvider* provider);
protected:
friend class api::BrowserView;
NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent);
// views::WidgetDelegate:
views::Widget* GetWidget() override;
const views::Widget* GetWidget() const override;
std::u16string GetAccessibleWindowTitle() const override;
void set_content_view(views::View* view) { content_view_ = view; }
void add_browser_view(NativeBrowserView* browser_view) {
browser_views_.push_back(browser_view);
}
void remove_browser_view(NativeBrowserView* browser_view) {
browser_views_.remove_if(
[&browser_view](NativeBrowserView* n) { return (n == browser_view); });
}
// The boolean parsing of the "titleBarOverlay" option
bool titlebar_overlay_ = false;
// The custom height parsed from the "height" option in a Object
// "titleBarOverlay"
int titlebar_overlay_height_ = 0;
// The "titleBarStyle" option.
TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal;
std::queue<bool> pending_transitions_;
FullScreenTransitionState fullscreen_transition_state_ =
FullScreenTransitionState::NONE;
FullScreenTransitionType fullscreen_transition_type_ =
FullScreenTransitionType::NONE;
private:
std::unique_ptr<views::Widget> widget_;
static int32_t next_id_;
// The content view, weak ref.
views::View* content_view_ = nullptr;
// Whether window has standard frame.
bool has_frame_ = true;
// Whether window has standard frame, but it's drawn by Electron (the client
// application) instead of the OS. Currently only has meaning on Linux for
// Wayland hosts.
bool has_client_frame_ = false;
// Whether window is transparent.
bool transparent_ = false;
// Minimum and maximum size, stored as content size.
extensions::SizeConstraints size_constraints_;
// Whether window can be resized larger than screen.
bool enable_larger_than_screen_ = false;
// The windows has been closed.
bool is_closed_ = false;
// Used to display sheets at the appropriate horizontal and vertical offsets
// on macOS.
double sheet_offset_x_ = 0.0;
double sheet_offset_y_ = 0.0;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_ = 0.0;
gfx::Size aspect_ratio_extraSize_;
// The parent window, it is guaranteed to be valid during this window's life.
NativeWindow* parent_ = nullptr;
// Is this a modal window.
bool is_modal_ = false;
// The browser view layer.
std::list<NativeBrowserView*> browser_views_;
std::list<DraggableRegionProvider*> draggable_region_providers_;
// Observers of this window.
base::ObserverList<NativeWindowObserver> observers_;
// Accessible title.
std::u16string accessible_title_;
gfx::Rect overlay_rect_;
base::WeakPtrFactory<NativeWindow> weak_factory_{this};
};
// This class provides a hook to get a NativeWindow from a WebContents.
class NativeWindowRelay
: public content::WebContentsUserData<NativeWindowRelay> {
public:
static void CreateForWebContents(content::WebContents*,
base::WeakPtr<NativeWindow>);
~NativeWindowRelay() override;
NativeWindow* GetNativeWindow() const { return native_window_.get(); }
WEB_CONTENTS_USER_DATA_KEY_DECL();
private:
friend class content::WebContentsUserData<NativeWindow>;
explicit NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window);
base::WeakPtr<NativeWindow> native_window_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window_mac.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#import <Cocoa/Cocoa.h>
#include <memory>
#include <string>
#include <vector>
#include "base/mac/scoped_nsobject.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "ui/display/display_observer.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/controls/native/native_view_host.h"
@class ElectronNSWindow;
@class ElectronNSWindowDelegate;
@class ElectronPreviewItem;
@class ElectronTouchBar;
@class WindowButtonsProxy;
namespace electron {
class RootViewMac;
class NativeWindowMac : public NativeWindow,
public ui::NativeThemeObserver,
public display::DisplayObserver {
public:
NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent);
~NativeWindowMac() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate = false) override;
gfx::Rect GetBounds() override;
bool IsNormal() override;
gfx::Rect GetNormalBounds() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relative_level) override;
std::string GetAlwaysOnTopLevel() override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
void SetBackgroundColor(SkColor color) override;
SkColor GetBackgroundColor() override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetRepresentedFilename(const std::string& filename) override;
std::string GetRepresentedFilename() override;
void SetDocumentEdited(bool edited) override;
bool IsDocumentEdited() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
bool IsHiddenInMissionControl() override;
void SetHiddenInMissionControl(bool hidden) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetAutoHideCursor(bool auto_hide) override;
void SetVibrancy(const std::string& type) override;
void SetWindowButtonVisibility(bool visible) override;
bool GetWindowButtonVisibility() const override;
void SetTrafficLightPosition(absl::optional<gfx::Point> position) override;
absl::optional<gfx::Point> GetTrafficLightPosition() const override;
void RedrawTrafficLights() override;
void UpdateFrame() override;
void SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) override;
void RefreshTouchBarItem(const std::string& item_id) override;
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override;
void SelectPreviousTab() override;
void SelectNextTab() override;
void MergeAllWindows() override;
void MoveTabToNewWindow() override;
void ToggleTabBar() override;
bool AddTabbedWindow(NativeWindow* window) override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void PreviewFile(const std::string& path,
const std::string& display_name) override;
void CloseFilePreview() override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
gfx::Rect GetWindowControlsOverlayRect() override;
void NotifyWindowEnterFullScreen() override;
void NotifyWindowLeaveFullScreen() override;
void SetActive(bool is_key) override;
bool IsActive() const override;
void NotifyWindowWillEnterFullScreen();
void NotifyWindowWillLeaveFullScreen();
// Cleanup observers when window is getting closed. Note that the destructor
// can be called much later after window gets closed, so we should not do
// cleanup in destructor.
void Cleanup();
void UpdateVibrancyRadii(bool fullscreen);
void UpdateWindowOriginalFrame();
// Set the attribute of NSWindow while work around a bug of zoom button.
bool HasStyleMask(NSUInteger flag) const;
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
void SetWindowLevel(int level);
bool HandleDeferredClose();
void SetHasDeferredWindowClose(bool defer_close) {
has_deferred_window_close_ = defer_close;
}
enum class VisualEffectState {
kFollowWindow,
kActive,
kInactive,
};
ElectronPreviewItem* preview_item() const { return preview_item_.get(); }
ElectronTouchBar* touch_bar() const { return touch_bar_.get(); }
bool zoom_to_page_width() const { return zoom_to_page_width_; }
bool always_simple_fullscreen() const { return always_simple_fullscreen_; }
// We need to save the result of windowWillUseStandardFrame:defaultFrame
// because macOS calls it with what it refers to as the "best fit" frame for a
// zoom. This means that even if an aspect ratio is set, macOS might adjust it
// to better fit the screen.
//
// Thus, we can't just calculate the maximized aspect ratio'd sizing from
// the current visible screen and compare that to the current window's frame
// to determine whether a window is maximized.
NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; }
void set_default_frame_for_zoom(NSRect frame) {
default_frame_for_zoom_ = frame;
}
protected:
// views::WidgetDelegate:
views::View* GetContentsView() override;
bool CanMaximize() const override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
// display::DisplayObserver:
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
private:
// Add custom layers to the content view.
void AddContentViewLayers();
void InternalSetWindowButtonVisibility(bool visible);
void InternalSetParentWindow(NativeWindow* parent, bool attach);
void SetForwardMouseMessages(bool forward);
ElectronNSWindow* window_; // Weak ref, managed by widget_.
base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_;
base::scoped_nsobject<ElectronPreviewItem> preview_item_;
base::scoped_nsobject<ElectronTouchBar> touch_bar_;
// The views::View that fills the client area.
std::unique_ptr<RootViewMac> root_view_;
bool is_kiosk_ = false;
bool zoom_to_page_width_ = false;
absl::optional<gfx::Point> traffic_light_position_;
// Trying to close an NSWindow during a fullscreen transition will cause the
// window to lock up. Use this to track if CloseWindow was called during a
// fullscreen transition, to defer the -[NSWindow close] call until the
// transition is complete.
bool has_deferred_window_close_ = false;
NSInteger attention_request_id_ = 0; // identifier from requestUserAttention
// The presentation options before entering kiosk mode.
NSApplicationPresentationOptions kiosk_options_;
// The "visualEffectState" option.
VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow;
// The visibility mode of window button controls when explicitly set through
// setWindowButtonVisibility().
absl::optional<bool> window_button_visibility_;
// Controls the position and visibility of window buttons.
base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_;
std::unique_ptr<SkRegion> draggable_region_;
// Maximizable window state; necessary for persistence through redraws.
bool maximizable_ = true;
bool user_set_bounds_maximized_ = false;
// Simple (pre-Lion) Fullscreen Settings
bool always_simple_fullscreen_ = false;
bool is_simple_fullscreen_ = false;
bool was_maximizable_ = false;
bool was_movable_ = false;
bool is_active_ = false;
NSRect original_frame_;
NSInteger original_level_;
NSUInteger simple_fullscreen_mask_;
NSRect default_frame_for_zoom_;
std::string vibrancy_type_;
// The presentation options before entering simple fullscreen mode.
NSApplicationPresentationOptions simple_fullscreen_options_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 32,450 |
[Bug]: macOS transparent window font shadow residual
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
13.x/14.x/15.x/16.x
### What operating system are you using?
macOS
### Operating System Version
macOS 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
MAC OS transparent windows should not have font shadow residue
### Actual Behavior
On the Mac OS platform, there will be font shadow residue on transparent windows
### Testcase Gist URL
https://gist.github.com/5112851712bcd11e7045921fee1cbbf7
### Additional Information
This is a long-standing issue, previously related issue:
- https://github.com/electron/electron/issues/14304
- https://github.com/electron/electron/issues/21173

|
https://github.com/electron/electron/issues/32450
|
https://github.com/electron/electron/pull/32452
|
35a7c07306249854c34609b1782ed0dc2318f429
|
d092e6bda4c7ba840f76ef835135f6ac94e02803
| 2022-01-13T05:05:22Z |
c++
| 2022-12-01T18:24:44Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// Removing NSWindowStyleMaskTitled removes window title, which removes
// rounded corners of window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
// Hide all children of the current window before hiding the window.
// components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
// expects this when window visibility changes.
if ([window_ childWindows]) {
for (NSWindow* child in [window_ childWindows]) {
[child orderOut:nil];
}
}
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
// For a window to be visible, it must be visible to the user in the
// foreground of the app, which means that it should not be minimized or
// occluded
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::ENTERING
: FullScreenTransitionState::EXITING;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::NONE;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
[NSApp setPresentationOptions:kiosk_options_];
is_kiosk_ = false;
SetFullScreen(false);
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = base::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to functionally
// mimic app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
ProcessSerialNumber psn = {0, kCurrentProcess};
if (visibleOnFullScreen) {
[window_ setCanHide:NO];
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
} else {
[window_ setCanHide:YES];
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetTrafficLightPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
[[window_ parentWindow] removeChildWindow:window_];
// Set new parent window.
// Note that this method will force the window to become visible.
if (parent && attach) {
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[parent->GetNativeWindow().GetNativeNSWindow()
addChildWindow:window_
ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
script/node-disabled-tests.json
|
[
"abort/test-abort-backtrace",
"async-hooks/test-crypto-pbkdf2",
"async-hooks/test-crypto-randomBytes",
"parallel/test-bootstrap-modules",
"parallel/test-child-process-fork-exec-path",
"parallel/test-cli-node-print-help",
"parallel/test-cluster-bind-privileged-port",
"parallel/test-cluster-shared-handle-bind-privileged-port",
"parallel/test-code-cache",
"parallel/test-crypto-aes-wrap",
"parallel/test-crypto-authenticated-stream",
"parallel/test-crypto-des3-wrap",
"parallel/test-crypto-modp1-error",
"parallel/test-crypto-dh-modp2",
"parallel/test-crypto-dh-modp2-views",
"parallel/test-crypto-dh-stateless",
"parallel/test-crypto-ecb",
"parallel/test-crypto-fips",
"parallel/test-crypto-keygen",
"parallel/test-crypto-keygen-deprecation",
"parallel/test-crypto-key-objects",
"parallel/test-crypto-padding-aes256",
"parallel/test-crypto-secure-heap",
"parallel/test-fs-utimes-y2K38",
"parallel/test-heapsnapshot-near-heap-limit-worker",
"parallel/test-http2-clean-output",
"parallel/test-https-agent-session-reuse",
"parallel/test-https-options-boolean-check",
"parallel/test-icu-minimum-version",
"parallel/test-icu-env",
"parallel/test-inspector-multisession-ws",
"parallel/test-inspector-port-zero-cluster",
"parallel/test-inspector-tracing-domain",
"parallel/test-module-loading-globalpaths",
"parallel/test-module-version",
"parallel/test-openssl-ca-options",
"parallel/test-process-env-allowed-flags-are-documented",
"parallel/test-process-versions",
"parallel/test-repl",
"parallel/test-repl-underscore",
"parallel/test-snapshot-api",
"parallel/test-snapshot-basic",
"parallel/test-snapshot-console",
"parallel/test-snapshot-cjs-main",
"parallel/test-snapshot-dns-lookup-localhost",
"parallel/test-snapshot-dns-lookup-localhost-promise",
"parallel/test-snapshot-dns-resolve-localhost",
"parallel/test-snapshot-dns-resolve-localhost-promise",
"parallel/test-snapshot-error",
"parallel/test-snapshot-gzip",
"parallel/test-snapshot-umd",
"parallel/test-snapshot-eval",
"parallel/test-snapshot-warning",
"parallel/test-snapshot-typescript",
"parallel/test-stdout-close-catch",
"parallel/test-tls-cert-chains-concat",
"parallel/test-tls-cert-chains-in-ca",
"parallel/test-tls-cli-max-version-1.2",
"parallel/test-tls-cli-max-version-1.3",
"parallel/test-tls-cli-min-version-1.1",
"parallel/test-tls-cli-min-version-1.2",
"parallel/test-tls-cli-min-version-1.3",
"parallel/test-tls-client-auth",
"parallel/test-tls-client-getephemeralkeyinfo",
"parallel/test-tls-client-mindhsize",
"parallel/test-tls-client-reject",
"parallel/test-tls-client-renegotiation-13",
"parallel/test-tls-cnnic-whitelist",
"parallel/test-tls-disable-renegotiation",
"parallel/test-tls-empty-sni-context",
"parallel/test-tls-env-bad-extra-ca",
"parallel/test-tls-env-extra-ca",
"parallel/test-tls-finished",
"parallel/test-tls-generic-stream",
"parallel/test-tls-getcipher",
"parallel/test-tls-handshake-error",
"parallel/test-tls-handshake-exception",
"parallel/test-tls-hello-parser-failure",
"parallel/test-tls-honorcipherorder",
"parallel/test-tls-junk-closes-server",
"parallel/test-tls-junk-server",
"parallel/test-tls-key-mismatch",
"parallel/test-tls-max-send-fragment",
"parallel/test-tls-min-max-version",
"parallel/test-tls-multi-key",
"parallel/test-tls-multi-pfx",
"parallel/test-tls-no-cert-required",
"parallel/test-tls-options-boolean-check",
"parallel/test-tls-passphrase",
"parallel/test-tls-peer-certificate",
"parallel/test-tls-pfx-authorizationerror",
"parallel/test-tls-psk-circuit",
"parallel/test-tls-root-certificates",
"parallel/test-tls-server-failed-handshake-emits-clienterror",
"parallel/test-tls-set-ciphers",
"parallel/test-tls-set-ciphers-error",
"parallel/test-tls-set-sigalgs",
"parallel/test-tls-socket-allow-half-open-option",
"parallel/test-tls-socket-failed-handshake-emits-error",
"parallel/test-tls-ticket",
"parallel/test-tls-ticket-cluster",
"parallel/test-trace-events-all",
"parallel/test-trace-events-async-hooks",
"parallel/test-trace-events-binding",
"parallel/test-trace-events-bootstrap",
"parallel/test-trace-events-category-used",
"parallel/test-trace-events-console",
"parallel/test-trace-events-dynamic-enable",
"parallel/test-trace-events-dynamic-enable-workers-disabled",
"parallel/test-trace-events-environment",
"parallel/test-trace-events-file-pattern",
"parallel/test-trace-events-fs-async",
"parallel/test-trace-events-fs-sync",
"parallel/test-trace-events-http",
"parallel/test-trace-events-metadata",
"parallel/test-trace-events-net",
"parallel/test-trace-events-none",
"parallel/test-trace-events-process-exit",
"parallel/test-trace-events-promises",
"parallel/test-trace-events-v8",
"parallel/test-trace-events-vm",
"parallel/test-trace-events-worker-metadata",
"parallel/test-wasm-web-api",
"parallel/test-webcrypto-derivebits-cfrg",
"parallel/test-webcrypto-derivekey-cfrg",
"parallel/test-webcrypto-encrypt-decrypt",
"parallel/test-webcrypto-encrypt-decrypt-aes",
"parallel/test-webcrypto-encrypt-decrypt-rsa",
"parallel/test-webcrypto-export-import-cfrg",
"parallel/test-webcrypto-keygen",
"parallel/test-webcrypto-sign-verify-eddsa",
"parallel/test-worker-debug",
"parallel/test-worker-stdio",
"parallel/test-v8-serialize-leak",
"parallel/test-zlib-unused-weak",
"report/test-report-fatalerror-oomerror-set",
"report/test-report-fatalerror-oomerror-directory",
"report/test-report-fatalerror-oomerror-filename",
"report/test-report-fatalerror-oomerror-compact",
"report/test-report-getreport",
"report/test-report-signal",
"report/test-report-uncaught-exception",
"report/test-report-uncaught-exception-compat",
"report/test-report-uv-handles",
"report/test-report-worker",
"report/test-report-writereport",
"sequential/test-cpu-prof-kill",
"sequential/test-diagnostic-dir-cpu-prof",
"sequential/test-cpu-prof-drained",
"sequential/test-tls-connect",
"wpt/test-webcrypto"
]
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/app/node_main.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/app/node_main.h"
#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/content_switches.h"
#include "electron/electron_version.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#include "shell/app/uv_task_runner.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#if BUILDFLAG(IS_WIN)
#include "chrome/child/v8_crashpad_support_win.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "base/posix/global_descriptors.h"
#include "base/strings/string_number_conversions.h"
#include "components/crash/core/app/crash_switches.h" // nogncheck
#include "content/public/common/content_descriptors.h"
#endif
#if !IS_MAS_BUILD()
#include "components/crash/core/app/crashpad.h" // nogncheck
#include "shell/app/electron_crash_reporter_client.h"
#include "shell/common/crash_keys.h"
#endif
namespace {
// Initialize Node.js cli options to pass to Node.js
// See https://nodejs.org/api/cli.html#cli_options
int SetNodeCliFlags() {
// Options that are unilaterally disallowed
const std::unordered_set<base::StringPiece, base::StringPieceHash>
disallowed = {"--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
"--force-fips", "--enable-fips"};
const auto argv = base::CommandLine::ForCurrentProcess()->argv();
std::vector<std::string> args;
// TODO(codebytere): We need to set the first entry in args to the
// process name owing to src/node_options-inl.h#L286-L290 but this is
// redundant and so should be refactored upstream.
args.reserve(argv.size() + 1);
args.emplace_back("electron");
for (const auto& arg : argv) {
#if BUILDFLAG(IS_WIN)
const auto& option = base::WideToUTF8(arg);
#else
const auto& option = arg;
#endif
const auto stripped = base::StringPiece(option).substr(0, option.find('='));
if (disallowed.count(stripped) != 0) {
LOG(ERROR) << "The Node.js cli flag " << stripped
<< " is not supported in Electron";
// Node.js returns 9 from ProcessGlobalArgs for any errors encountered
// when setting up cli flags and env vars. Since we're outlawing these
// flags (making them errors) return 9 here for consistency.
return 9;
} else {
args.push_back(option);
}
}
std::vector<std::string> errors;
// Node.js itself will output parsing errors to
// console so we don't need to handle that ourselves
return ProcessGlobalArgs(&args, nullptr, &errors,
node::kDisallowedInEnvironment);
}
#if IS_MAS_BUILD()
void SetCrashKeyStub(const std::string& key, const std::string& value) {}
void ClearCrashKeyStub(const std::string& key) {}
#endif
} // namespace
namespace electron {
v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
std::map<std::string, std::string> keys;
#if !IS_MAS_BUILD()
electron::crash_keys::GetCrashKeys(&keys);
#endif
return gin::ConvertToV8(isolate, keys);
}
int NodeMain(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
#if BUILDFLAG(IS_WIN)
v8_crashpad_support::SetUp();
#endif
#if BUILDFLAG(IS_LINUX)
auto os_env = base::Environment::Create();
std::string fd_string, pid_string;
if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) &&
os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) {
int fd = -1, pid = -1;
DCHECK(base::StringToInt(fd_string, &fd));
DCHECK(base::StringToInt(pid_string, &pid));
base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd);
// Following API is unsafe in multi-threaded scenario, but at this point
// we are still single threaded.
os_env->UnSetVar("CRASHDUMP_SIGNAL_FD");
os_env->UnSetVar("CRASHPAD_HANDLER_PID");
}
#endif
int exit_code = 1;
{
// Feed gin::PerIsolateData with a task runner.
uv_loop_t* loop = uv_default_loop();
auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
// Explicitly register electron's builtin modules.
NodeBindings::RegisterBuiltinModules();
// Parse and set Node.js cli flags.
int flags_exit_code = SetNodeCliFlags();
if (flags_exit_code != 0)
exit(flags_exit_code);
// Hack around with the argv pointer. Used for process.title = "blah".
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
for (const std::string& error : result->errors())
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (result->early_return() != 0) {
return result->exit_code();
}
#if BUILDFLAG(IS_LINUX)
// On Linux, initialize crashpad after Nodejs init phase so that
// crash and termination signal handlers can be set by the crashpad client.
if (!pid_string.empty()) {
auto* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitchASCII(
crash_reporter::switches::kCrashpadHandlerPid, pid_string);
ElectronCrashReporterClient::Create();
crash_reporter::InitializeCrashpad(false, "node");
crash_keys::SetCrashKeysFromCommandLine(
*base::CommandLine::ForCurrentProcess());
crash_keys::SetPlatformCrashKey();
// Ensure the flags and env variable does not propagate to userland.
command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
}
#elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
ElectronCrashReporterClient::Create();
crash_reporter::InitializeCrashpad(false, "node");
crash_keys::SetCrashKeysFromCommandLine(
*base::CommandLine::ForCurrentProcess());
crash_keys::SetPlatformCrashKey();
#endif
gin::V8Initializer::LoadV8Snapshot(
gin::V8SnapshotFileType::kWithAdditionalContext);
// V8 requires a task scheduler.
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
// Allow Node.js to track the amount of time the event loop has spent
// idle in the kernel’s event provider .
uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env(loop);
v8::Isolate* isolate = gin_env.isolate();
v8::Isolate::Scope isolate_scope(isolate);
v8::Locker locker(isolate);
node::Environment* env = nullptr;
node::IsolateData* isolate_data = nullptr;
{
v8::HandleScope scope(isolate);
isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
CHECK_NE(nullptr, isolate_data);
uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
node::EnvironmentFlags::kHideConsoleWindows;
env = node::CreateEnvironment(
isolate_data, gin_env.context(), result->args(), result->exec_args(),
static_cast<node::EnvironmentFlags::Flags>(env_flags));
CHECK_NE(nullptr, env);
node::IsolateSettings is;
node::SetIsolateUpForNode(isolate, is);
gin_helper::Dictionary process(isolate, env->process_object());
process.SetMethod("crash", &ElectronBindings::Crash);
// Setup process.crashReporter in child node processes
gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
reporter.SetMethod("getParameters", &GetParameters);
#if IS_MAS_BUILD()
reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
#else
reporter.SetMethod("addExtraParameter",
&electron::crash_keys::SetCrashKey);
reporter.SetMethod("removeExtraParameter",
&electron::crash_keys::ClearCrashKey);
#endif
process.Set("crashReporter", reporter);
gin_helper::Dictionary versions;
if (process.Get("versions", &versions)) {
versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
}
}
v8::HandleScope scope(isolate);
node::LoadEnvironment(env, node::StartExecutionCallback{});
env->set_trace_sync_io(env->options()->trace_sync_io);
{
v8::SealHandleScope seal(isolate);
bool more;
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
do {
uv_run(env->event_loop(), UV_RUN_DEFAULT);
gin_env.platform()->DrainTasks(isolate);
more = uv_loop_alive(env->event_loop());
if (more && !env->is_stopping())
continue;
if (!uv_loop_alive(env->event_loop())) {
EmitBeforeExit(env);
}
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
} while (more && !env->is_stopping());
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
}
env->set_trace_sync_io(false);
exit_code = node::EmitExit(env);
node::ResetStdio();
node::Stop(env);
node::FreeEnvironment(env);
node::FreeIsolateData(isolate_data);
}
// According to "src/gin/shell/gin_main.cc":
//
// gin::IsolateHolder waits for tasks running in ThreadPool in its
// destructor and thus must be destroyed before ThreadPool starts skipping
// CONTINUE_ON_SHUTDOWN tasks.
base::ThreadPoolInstance::Get()->Shutdown();
v8::V8::Dispose();
return exit_code;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/browser/javascript_environment.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/javascript_environment.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include "base/allocator/partition_alloc_features.h"
#include "base/allocator/partition_allocator/partition_alloc.h"
#include "base/bits.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool/initialization_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"
#include "shell/browser/microtasks_runner.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/node_includes.h"
#include "third_party/blink/public/common/switches.h"
namespace {
v8::Isolate* g_isolate;
}
namespace gin {
class ConvertableToTraceFormatWrapper final
: public base::trace_event::ConvertableToTraceFormat {
public:
explicit ConvertableToTraceFormatWrapper(
std::unique_ptr<v8::ConvertableToTraceFormat> inner)
: inner_(std::move(inner)) {}
~ConvertableToTraceFormatWrapper() override = default;
// disable copy
ConvertableToTraceFormatWrapper(const ConvertableToTraceFormatWrapper&) =
delete;
ConvertableToTraceFormatWrapper& operator=(
const ConvertableToTraceFormatWrapper&) = delete;
void AppendAsTraceFormat(std::string* out) const final {
inner_->AppendAsTraceFormat(out);
}
private:
std::unique_ptr<v8::ConvertableToTraceFormat> inner_;
};
} // namespace gin
// Allow std::unique_ptr<v8::ConvertableToTraceFormat> to be a valid
// initialization value for trace macros.
template <>
struct base::trace_event::TraceValue::Helper<
std::unique_ptr<v8::ConvertableToTraceFormat>> {
static constexpr unsigned char kType = TRACE_VALUE_TYPE_CONVERTABLE;
static inline void SetValue(
TraceValue* v,
std::unique_ptr<v8::ConvertableToTraceFormat> value) {
// NOTE: |as_convertable| is an owning pointer, so using new here
// is acceptable.
v->as_convertable =
new gin::ConvertableToTraceFormatWrapper(std::move(value));
}
};
namespace electron {
JavascriptEnvironment::JavascriptEnvironment(uv_loop_t* event_loop)
: isolate_(Initialize(event_loop)),
isolate_holder_(base::ThreadTaskRunnerHandle::Get(),
gin::IsolateHolder::kSingleThread,
gin::IsolateHolder::kAllowAtomicsWait,
gin::IsolateHolder::IsolateType::kUtility,
gin::IsolateHolder::IsolateCreationMode::kNormal,
nullptr,
nullptr,
isolate_),
locker_(isolate_) {
isolate_->Enter();
v8::HandleScope scope(isolate_);
auto context = node::NewContext(isolate_);
context_ = v8::Global<v8::Context>(isolate_, context);
context->Enter();
}
JavascriptEnvironment::~JavascriptEnvironment() {
DCHECK_NE(platform_, nullptr);
platform_->DrainTasks(isolate_);
{
v8::HandleScope scope(isolate_);
context_.Get(isolate_)->Exit();
}
isolate_->Exit();
g_isolate = nullptr;
platform_->UnregisterIsolate(isolate_);
}
class EnabledStateObserverImpl final
: public base::trace_event::TraceLog::EnabledStateObserver {
public:
EnabledStateObserverImpl() {
base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
}
~EnabledStateObserverImpl() override {
base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(
this);
}
// disable copy
EnabledStateObserverImpl(const EnabledStateObserverImpl&) = delete;
EnabledStateObserverImpl& operator=(const EnabledStateObserverImpl&) = delete;
void OnTraceLogEnabled() final {
base::AutoLock lock(mutex_);
for (auto* o : observers_) {
o->OnTraceEnabled();
}
}
void OnTraceLogDisabled() final {
base::AutoLock lock(mutex_);
for (auto* o : observers_) {
o->OnTraceDisabled();
}
}
void AddObserver(v8::TracingController::TraceStateObserver* observer) {
{
base::AutoLock lock(mutex_);
DCHECK(!observers_.count(observer));
observers_.insert(observer);
}
// Fire the observer if recording is already in progress.
if (base::trace_event::TraceLog::GetInstance()->IsEnabled())
observer->OnTraceEnabled();
}
void RemoveObserver(v8::TracingController::TraceStateObserver* observer) {
base::AutoLock lock(mutex_);
DCHECK_EQ(observers_.count(observer), 1lu);
observers_.erase(observer);
}
private:
base::Lock mutex_;
std::unordered_set<v8::TracingController::TraceStateObserver*> observers_;
};
base::LazyInstance<EnabledStateObserverImpl>::Leaky g_trace_state_dispatcher =
LAZY_INSTANCE_INITIALIZER;
class TracingControllerImpl : public node::tracing::TracingController {
public:
TracingControllerImpl() = default;
~TracingControllerImpl() override = default;
// disable copy
TracingControllerImpl(const TracingControllerImpl&) = delete;
TracingControllerImpl& operator=(const TracingControllerImpl&) = delete;
// TracingController implementation.
const uint8_t* GetCategoryGroupEnabled(const char* name) override {
return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(name);
}
uint64_t AddTraceEvent(
char phase,
const uint8_t* category_enabled_flag,
const char* name,
const char* scope,
uint64_t id,
uint64_t bind_id,
int32_t num_args,
const char** arg_names,
const uint8_t* arg_types,
const uint64_t* arg_values,
std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables,
unsigned int flags) override {
base::trace_event::TraceArguments args(
num_args, arg_names, arg_types,
reinterpret_cast<const unsigned long long*>( // NOLINT(runtime/int)
arg_values),
arg_convertables);
DCHECK_LE(num_args, 2);
base::trace_event::TraceEventHandle handle =
TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_BIND_ID(
phase, category_enabled_flag, name, scope, id, bind_id, &args,
flags);
uint64_t result;
memcpy(&result, &handle, sizeof(result));
return result;
}
uint64_t AddTraceEventWithTimestamp(
char phase,
const uint8_t* category_enabled_flag,
const char* name,
const char* scope,
uint64_t id,
uint64_t bind_id,
int32_t num_args,
const char** arg_names,
const uint8_t* arg_types,
const uint64_t* arg_values,
std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables,
unsigned int flags,
int64_t timestampMicroseconds) override {
base::trace_event::TraceArguments args(
num_args, arg_names, arg_types,
reinterpret_cast<const unsigned long long*>( // NOLINT(runtime/int)
arg_values),
arg_convertables);
DCHECK_LE(num_args, 2);
base::TimeTicks timestamp =
base::TimeTicks() + base::Microseconds(timestampMicroseconds);
base::trace_event::TraceEventHandle handle =
TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(
phase, category_enabled_flag, name, scope, id, bind_id,
TRACE_EVENT_API_CURRENT_THREAD_ID, timestamp, &args, flags);
uint64_t result;
memcpy(&result, &handle, sizeof(result));
return result;
}
void UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
const char* name,
uint64_t handle) override {
base::trace_event::TraceEventHandle traceEventHandle;
memcpy(&traceEventHandle, &handle, sizeof(handle));
TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(category_enabled_flag, name,
traceEventHandle);
}
void AddTraceStateObserver(TraceStateObserver* observer) override {
g_trace_state_dispatcher.Get().AddObserver(observer);
}
void RemoveTraceStateObserver(TraceStateObserver* observer) override {
g_trace_state_dispatcher.Get().RemoveObserver(observer);
}
};
v8::Isolate* JavascriptEnvironment::Initialize(uv_loop_t* event_loop) {
auto* cmd = base::CommandLine::ForCurrentProcess();
// --js-flags.
std::string js_flags =
cmd->GetSwitchValueASCII(blink::switches::kJavaScriptFlags);
js_flags.append(" --no-freeze-flags-after-init");
if (!js_flags.empty())
v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size());
// The V8Platform of gin relies on Chromium's task schedule, which has not
// been started at this point, so we have to rely on Node's V8Platform.
auto* tracing_agent = node::CreateAgent();
auto* tracing_controller = new TracingControllerImpl();
node::tracing::TraceEventHelper::SetAgent(tracing_agent);
platform_ = node::MultiIsolatePlatform::Create(
base::RecommendedMaxNumberOfThreadsInThreadGroup(3, 8, 0.1, 0),
tracing_controller, gin::V8Platform::PageAllocator());
v8::V8::InitializePlatform(platform_.get());
gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
gin::ArrayBufferAllocator::SharedInstance(),
nullptr /* external_reference_table */,
js_flags, nullptr /* fatal_error_callback */,
nullptr /* oom_error_callback */,
false /* create_v8_platform */);
v8::Isolate* isolate = v8::Isolate::Allocate();
platform_->RegisterIsolate(isolate, event_loop);
g_isolate = isolate;
return isolate;
}
// static
v8::Isolate* JavascriptEnvironment::GetIsolate() {
CHECK(g_isolate);
return g_isolate;
}
void JavascriptEnvironment::CreateMicrotasksRunner() {
DCHECK(!microtasks_runner_);
microtasks_runner_ = std::make_unique<MicrotasksRunner>(isolate());
base::CurrentThread::Get()->AddTaskObserver(microtasks_runner_.get());
}
void JavascriptEnvironment::DestroyMicrotasksRunner() {
DCHECK(microtasks_runner_);
{
v8::HandleScope scope(isolate_);
gin_helper::CleanedUpAtExit::DoCleanup();
}
base::CurrentThread::Get()->RemoveTaskObserver(microtasks_runner_.get());
}
NodeEnvironment::NodeEnvironment(node::Environment* env) : env_(env) {}
NodeEnvironment::~NodeEnvironment() {
auto* isolate_data = env_->isolate_data();
node::FreeEnvironment(env_);
node::FreeIsolateData(isolate_data);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/browser/javascript_environment.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
#define ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
#include <memory>
#include "gin/public/isolate_holder.h"
#include "uv.h" // NOLINT(build/include_directory)
#include "v8/include/v8-locker.h"
namespace node {
class Environment;
class MultiIsolatePlatform;
} // namespace node
namespace electron {
class MicrotasksRunner;
// Manage the V8 isolate and context automatically.
class JavascriptEnvironment {
public:
explicit JavascriptEnvironment(uv_loop_t* event_loop);
~JavascriptEnvironment();
// disable copy
JavascriptEnvironment(const JavascriptEnvironment&) = delete;
JavascriptEnvironment& operator=(const JavascriptEnvironment&) = delete;
void CreateMicrotasksRunner();
void DestroyMicrotasksRunner();
node::MultiIsolatePlatform* platform() const { return platform_.get(); }
v8::Isolate* isolate() const { return isolate_; }
v8::Local<v8::Context> context() const {
return v8::Local<v8::Context>::New(isolate_, context_);
}
static v8::Isolate* GetIsolate();
private:
v8::Isolate* Initialize(uv_loop_t* event_loop);
std::unique_ptr<node::MultiIsolatePlatform> platform_;
v8::Isolate* isolate_;
gin::IsolateHolder isolate_holder_;
v8::Locker locker_;
v8::Global<v8::Context> context_;
std::unique_ptr<MicrotasksRunner> microtasks_runner_;
};
// Manage the Node Environment automatically.
class NodeEnvironment {
public:
explicit NodeEnvironment(node::Environment* env);
~NodeEnvironment();
// disable copy
NodeEnvironment(const NodeEnvironment&) = delete;
NodeEnvironment& operator=(const NodeEnvironment&) = delete;
node::Environment* env() { return env_; }
private:
node::Environment* env_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
script/node-disabled-tests.json
|
[
"abort/test-abort-backtrace",
"async-hooks/test-crypto-pbkdf2",
"async-hooks/test-crypto-randomBytes",
"parallel/test-bootstrap-modules",
"parallel/test-child-process-fork-exec-path",
"parallel/test-cli-node-print-help",
"parallel/test-cluster-bind-privileged-port",
"parallel/test-cluster-shared-handle-bind-privileged-port",
"parallel/test-code-cache",
"parallel/test-crypto-aes-wrap",
"parallel/test-crypto-authenticated-stream",
"parallel/test-crypto-des3-wrap",
"parallel/test-crypto-modp1-error",
"parallel/test-crypto-dh-modp2",
"parallel/test-crypto-dh-modp2-views",
"parallel/test-crypto-dh-stateless",
"parallel/test-crypto-ecb",
"parallel/test-crypto-fips",
"parallel/test-crypto-keygen",
"parallel/test-crypto-keygen-deprecation",
"parallel/test-crypto-key-objects",
"parallel/test-crypto-padding-aes256",
"parallel/test-crypto-secure-heap",
"parallel/test-fs-utimes-y2K38",
"parallel/test-heapsnapshot-near-heap-limit-worker",
"parallel/test-http2-clean-output",
"parallel/test-https-agent-session-reuse",
"parallel/test-https-options-boolean-check",
"parallel/test-icu-minimum-version",
"parallel/test-icu-env",
"parallel/test-inspector-multisession-ws",
"parallel/test-inspector-port-zero-cluster",
"parallel/test-inspector-tracing-domain",
"parallel/test-module-loading-globalpaths",
"parallel/test-module-version",
"parallel/test-openssl-ca-options",
"parallel/test-process-env-allowed-flags-are-documented",
"parallel/test-process-versions",
"parallel/test-repl",
"parallel/test-repl-underscore",
"parallel/test-snapshot-api",
"parallel/test-snapshot-basic",
"parallel/test-snapshot-console",
"parallel/test-snapshot-cjs-main",
"parallel/test-snapshot-dns-lookup-localhost",
"parallel/test-snapshot-dns-lookup-localhost-promise",
"parallel/test-snapshot-dns-resolve-localhost",
"parallel/test-snapshot-dns-resolve-localhost-promise",
"parallel/test-snapshot-error",
"parallel/test-snapshot-gzip",
"parallel/test-snapshot-umd",
"parallel/test-snapshot-eval",
"parallel/test-snapshot-warning",
"parallel/test-snapshot-typescript",
"parallel/test-stdout-close-catch",
"parallel/test-tls-cert-chains-concat",
"parallel/test-tls-cert-chains-in-ca",
"parallel/test-tls-cli-max-version-1.2",
"parallel/test-tls-cli-max-version-1.3",
"parallel/test-tls-cli-min-version-1.1",
"parallel/test-tls-cli-min-version-1.2",
"parallel/test-tls-cli-min-version-1.3",
"parallel/test-tls-client-auth",
"parallel/test-tls-client-getephemeralkeyinfo",
"parallel/test-tls-client-mindhsize",
"parallel/test-tls-client-reject",
"parallel/test-tls-client-renegotiation-13",
"parallel/test-tls-cnnic-whitelist",
"parallel/test-tls-disable-renegotiation",
"parallel/test-tls-empty-sni-context",
"parallel/test-tls-env-bad-extra-ca",
"parallel/test-tls-env-extra-ca",
"parallel/test-tls-finished",
"parallel/test-tls-generic-stream",
"parallel/test-tls-getcipher",
"parallel/test-tls-handshake-error",
"parallel/test-tls-handshake-exception",
"parallel/test-tls-hello-parser-failure",
"parallel/test-tls-honorcipherorder",
"parallel/test-tls-junk-closes-server",
"parallel/test-tls-junk-server",
"parallel/test-tls-key-mismatch",
"parallel/test-tls-max-send-fragment",
"parallel/test-tls-min-max-version",
"parallel/test-tls-multi-key",
"parallel/test-tls-multi-pfx",
"parallel/test-tls-no-cert-required",
"parallel/test-tls-options-boolean-check",
"parallel/test-tls-passphrase",
"parallel/test-tls-peer-certificate",
"parallel/test-tls-pfx-authorizationerror",
"parallel/test-tls-psk-circuit",
"parallel/test-tls-root-certificates",
"parallel/test-tls-server-failed-handshake-emits-clienterror",
"parallel/test-tls-set-ciphers",
"parallel/test-tls-set-ciphers-error",
"parallel/test-tls-set-sigalgs",
"parallel/test-tls-socket-allow-half-open-option",
"parallel/test-tls-socket-failed-handshake-emits-error",
"parallel/test-tls-ticket",
"parallel/test-tls-ticket-cluster",
"parallel/test-trace-events-all",
"parallel/test-trace-events-async-hooks",
"parallel/test-trace-events-binding",
"parallel/test-trace-events-bootstrap",
"parallel/test-trace-events-category-used",
"parallel/test-trace-events-console",
"parallel/test-trace-events-dynamic-enable",
"parallel/test-trace-events-dynamic-enable-workers-disabled",
"parallel/test-trace-events-environment",
"parallel/test-trace-events-file-pattern",
"parallel/test-trace-events-fs-async",
"parallel/test-trace-events-fs-sync",
"parallel/test-trace-events-http",
"parallel/test-trace-events-metadata",
"parallel/test-trace-events-net",
"parallel/test-trace-events-none",
"parallel/test-trace-events-process-exit",
"parallel/test-trace-events-promises",
"parallel/test-trace-events-v8",
"parallel/test-trace-events-vm",
"parallel/test-trace-events-worker-metadata",
"parallel/test-wasm-web-api",
"parallel/test-webcrypto-derivebits-cfrg",
"parallel/test-webcrypto-derivekey-cfrg",
"parallel/test-webcrypto-encrypt-decrypt",
"parallel/test-webcrypto-encrypt-decrypt-aes",
"parallel/test-webcrypto-encrypt-decrypt-rsa",
"parallel/test-webcrypto-export-import-cfrg",
"parallel/test-webcrypto-keygen",
"parallel/test-webcrypto-sign-verify-eddsa",
"parallel/test-worker-debug",
"parallel/test-worker-stdio",
"parallel/test-v8-serialize-leak",
"parallel/test-zlib-unused-weak",
"report/test-report-fatalerror-oomerror-set",
"report/test-report-fatalerror-oomerror-directory",
"report/test-report-fatalerror-oomerror-filename",
"report/test-report-fatalerror-oomerror-compact",
"report/test-report-getreport",
"report/test-report-signal",
"report/test-report-uncaught-exception",
"report/test-report-uncaught-exception-compat",
"report/test-report-uv-handles",
"report/test-report-worker",
"report/test-report-writereport",
"sequential/test-cpu-prof-kill",
"sequential/test-diagnostic-dir-cpu-prof",
"sequential/test-cpu-prof-drained",
"sequential/test-tls-connect",
"wpt/test-webcrypto"
]
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/app/node_main.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/app/node_main.h"
#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/content_switches.h"
#include "electron/electron_version.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#include "shell/app/uv_task_runner.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#if BUILDFLAG(IS_WIN)
#include "chrome/child/v8_crashpad_support_win.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "base/posix/global_descriptors.h"
#include "base/strings/string_number_conversions.h"
#include "components/crash/core/app/crash_switches.h" // nogncheck
#include "content/public/common/content_descriptors.h"
#endif
#if !IS_MAS_BUILD()
#include "components/crash/core/app/crashpad.h" // nogncheck
#include "shell/app/electron_crash_reporter_client.h"
#include "shell/common/crash_keys.h"
#endif
namespace {
// Initialize Node.js cli options to pass to Node.js
// See https://nodejs.org/api/cli.html#cli_options
int SetNodeCliFlags() {
// Options that are unilaterally disallowed
const std::unordered_set<base::StringPiece, base::StringPieceHash>
disallowed = {"--openssl-config", "--use-bundled-ca", "--use-openssl-ca",
"--force-fips", "--enable-fips"};
const auto argv = base::CommandLine::ForCurrentProcess()->argv();
std::vector<std::string> args;
// TODO(codebytere): We need to set the first entry in args to the
// process name owing to src/node_options-inl.h#L286-L290 but this is
// redundant and so should be refactored upstream.
args.reserve(argv.size() + 1);
args.emplace_back("electron");
for (const auto& arg : argv) {
#if BUILDFLAG(IS_WIN)
const auto& option = base::WideToUTF8(arg);
#else
const auto& option = arg;
#endif
const auto stripped = base::StringPiece(option).substr(0, option.find('='));
if (disallowed.count(stripped) != 0) {
LOG(ERROR) << "The Node.js cli flag " << stripped
<< " is not supported in Electron";
// Node.js returns 9 from ProcessGlobalArgs for any errors encountered
// when setting up cli flags and env vars. Since we're outlawing these
// flags (making them errors) return 9 here for consistency.
return 9;
} else {
args.push_back(option);
}
}
std::vector<std::string> errors;
// Node.js itself will output parsing errors to
// console so we don't need to handle that ourselves
return ProcessGlobalArgs(&args, nullptr, &errors,
node::kDisallowedInEnvironment);
}
#if IS_MAS_BUILD()
void SetCrashKeyStub(const std::string& key, const std::string& value) {}
void ClearCrashKeyStub(const std::string& key) {}
#endif
} // namespace
namespace electron {
v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
std::map<std::string, std::string> keys;
#if !IS_MAS_BUILD()
electron::crash_keys::GetCrashKeys(&keys);
#endif
return gin::ConvertToV8(isolate, keys);
}
int NodeMain(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
#if BUILDFLAG(IS_WIN)
v8_crashpad_support::SetUp();
#endif
#if BUILDFLAG(IS_LINUX)
auto os_env = base::Environment::Create();
std::string fd_string, pid_string;
if (os_env->GetVar("CRASHDUMP_SIGNAL_FD", &fd_string) &&
os_env->GetVar("CRASHPAD_HANDLER_PID", &pid_string)) {
int fd = -1, pid = -1;
DCHECK(base::StringToInt(fd_string, &fd));
DCHECK(base::StringToInt(pid_string, &pid));
base::GlobalDescriptors::GetInstance()->Set(kCrashDumpSignal, fd);
// Following API is unsafe in multi-threaded scenario, but at this point
// we are still single threaded.
os_env->UnSetVar("CRASHDUMP_SIGNAL_FD");
os_env->UnSetVar("CRASHPAD_HANDLER_PID");
}
#endif
int exit_code = 1;
{
// Feed gin::PerIsolateData with a task runner.
uv_loop_t* loop = uv_default_loop();
auto uv_task_runner = base::MakeRefCounted<UvTaskRunner>(loop);
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
auto feature_list = std::make_unique<base::FeatureList>();
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
// Explicitly register electron's builtin modules.
NodeBindings::RegisterBuiltinModules();
// Parse and set Node.js cli flags.
int flags_exit_code = SetNodeCliFlags();
if (flags_exit_code != 0)
exit(flags_exit_code);
// Hack around with the argv pointer. Used for process.title = "blah".
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
for (const std::string& error : result->errors())
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (result->early_return() != 0) {
return result->exit_code();
}
#if BUILDFLAG(IS_LINUX)
// On Linux, initialize crashpad after Nodejs init phase so that
// crash and termination signal handlers can be set by the crashpad client.
if (!pid_string.empty()) {
auto* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitchASCII(
crash_reporter::switches::kCrashpadHandlerPid, pid_string);
ElectronCrashReporterClient::Create();
crash_reporter::InitializeCrashpad(false, "node");
crash_keys::SetCrashKeysFromCommandLine(
*base::CommandLine::ForCurrentProcess());
crash_keys::SetPlatformCrashKey();
// Ensure the flags and env variable does not propagate to userland.
command_line->RemoveSwitch(crash_reporter::switches::kCrashpadHandlerPid);
}
#elif BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !IS_MAS_BUILD())
ElectronCrashReporterClient::Create();
crash_reporter::InitializeCrashpad(false, "node");
crash_keys::SetCrashKeysFromCommandLine(
*base::CommandLine::ForCurrentProcess());
crash_keys::SetPlatformCrashKey();
#endif
gin::V8Initializer::LoadV8Snapshot(
gin::V8SnapshotFileType::kWithAdditionalContext);
// V8 requires a task scheduler.
base::ThreadPoolInstance::CreateAndStartWithDefaultParams("Electron");
// Allow Node.js to track the amount of time the event loop has spent
// idle in the kernel’s event provider .
uv_loop_configure(loop, UV_METRICS_IDLE_TIME);
// Initialize gin::IsolateHolder.
JavascriptEnvironment gin_env(loop);
v8::Isolate* isolate = gin_env.isolate();
v8::Isolate::Scope isolate_scope(isolate);
v8::Locker locker(isolate);
node::Environment* env = nullptr;
node::IsolateData* isolate_data = nullptr;
{
v8::HandleScope scope(isolate);
isolate_data = node::CreateIsolateData(isolate, loop, gin_env.platform());
CHECK_NE(nullptr, isolate_data);
uint64_t env_flags = node::EnvironmentFlags::kDefaultFlags |
node::EnvironmentFlags::kHideConsoleWindows;
env = node::CreateEnvironment(
isolate_data, gin_env.context(), result->args(), result->exec_args(),
static_cast<node::EnvironmentFlags::Flags>(env_flags));
CHECK_NE(nullptr, env);
node::IsolateSettings is;
node::SetIsolateUpForNode(isolate, is);
gin_helper::Dictionary process(isolate, env->process_object());
process.SetMethod("crash", &ElectronBindings::Crash);
// Setup process.crashReporter in child node processes
gin_helper::Dictionary reporter = gin::Dictionary::CreateEmpty(isolate);
reporter.SetMethod("getParameters", &GetParameters);
#if IS_MAS_BUILD()
reporter.SetMethod("addExtraParameter", &SetCrashKeyStub);
reporter.SetMethod("removeExtraParameter", &ClearCrashKeyStub);
#else
reporter.SetMethod("addExtraParameter",
&electron::crash_keys::SetCrashKey);
reporter.SetMethod("removeExtraParameter",
&electron::crash_keys::ClearCrashKey);
#endif
process.Set("crashReporter", reporter);
gin_helper::Dictionary versions;
if (process.Get("versions", &versions)) {
versions.SetReadOnly(ELECTRON_PROJECT_NAME, ELECTRON_VERSION_STRING);
}
}
v8::HandleScope scope(isolate);
node::LoadEnvironment(env, node::StartExecutionCallback{});
env->set_trace_sync_io(env->options()->trace_sync_io);
{
v8::SealHandleScope seal(isolate);
bool more;
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START);
do {
uv_run(env->event_loop(), UV_RUN_DEFAULT);
gin_env.platform()->DrainTasks(isolate);
more = uv_loop_alive(env->event_loop());
if (more && !env->is_stopping())
continue;
if (!uv_loop_alive(env->event_loop())) {
EmitBeforeExit(env);
}
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
} while (more && !env->is_stopping());
env->performance_state()->Mark(
node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT);
}
env->set_trace_sync_io(false);
exit_code = node::EmitExit(env);
node::ResetStdio();
node::Stop(env);
node::FreeEnvironment(env);
node::FreeIsolateData(isolate_data);
}
// According to "src/gin/shell/gin_main.cc":
//
// gin::IsolateHolder waits for tasks running in ThreadPool in its
// destructor and thus must be destroyed before ThreadPool starts skipping
// CONTINUE_ON_SHUTDOWN tasks.
base::ThreadPoolInstance::Get()->Shutdown();
v8::V8::Dispose();
return exit_code;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/browser/javascript_environment.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/javascript_environment.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <utility>
#include "base/allocator/partition_alloc_features.h"
#include "base/allocator/partition_allocator/partition_alloc.h"
#include "base/bits.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool/initialization_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/trace_event/trace_event.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"
#include "shell/browser/microtasks_runner.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/node_includes.h"
#include "third_party/blink/public/common/switches.h"
namespace {
v8::Isolate* g_isolate;
}
namespace gin {
class ConvertableToTraceFormatWrapper final
: public base::trace_event::ConvertableToTraceFormat {
public:
explicit ConvertableToTraceFormatWrapper(
std::unique_ptr<v8::ConvertableToTraceFormat> inner)
: inner_(std::move(inner)) {}
~ConvertableToTraceFormatWrapper() override = default;
// disable copy
ConvertableToTraceFormatWrapper(const ConvertableToTraceFormatWrapper&) =
delete;
ConvertableToTraceFormatWrapper& operator=(
const ConvertableToTraceFormatWrapper&) = delete;
void AppendAsTraceFormat(std::string* out) const final {
inner_->AppendAsTraceFormat(out);
}
private:
std::unique_ptr<v8::ConvertableToTraceFormat> inner_;
};
} // namespace gin
// Allow std::unique_ptr<v8::ConvertableToTraceFormat> to be a valid
// initialization value for trace macros.
template <>
struct base::trace_event::TraceValue::Helper<
std::unique_ptr<v8::ConvertableToTraceFormat>> {
static constexpr unsigned char kType = TRACE_VALUE_TYPE_CONVERTABLE;
static inline void SetValue(
TraceValue* v,
std::unique_ptr<v8::ConvertableToTraceFormat> value) {
// NOTE: |as_convertable| is an owning pointer, so using new here
// is acceptable.
v->as_convertable =
new gin::ConvertableToTraceFormatWrapper(std::move(value));
}
};
namespace electron {
JavascriptEnvironment::JavascriptEnvironment(uv_loop_t* event_loop)
: isolate_(Initialize(event_loop)),
isolate_holder_(base::ThreadTaskRunnerHandle::Get(),
gin::IsolateHolder::kSingleThread,
gin::IsolateHolder::kAllowAtomicsWait,
gin::IsolateHolder::IsolateType::kUtility,
gin::IsolateHolder::IsolateCreationMode::kNormal,
nullptr,
nullptr,
isolate_),
locker_(isolate_) {
isolate_->Enter();
v8::HandleScope scope(isolate_);
auto context = node::NewContext(isolate_);
context_ = v8::Global<v8::Context>(isolate_, context);
context->Enter();
}
JavascriptEnvironment::~JavascriptEnvironment() {
DCHECK_NE(platform_, nullptr);
platform_->DrainTasks(isolate_);
{
v8::HandleScope scope(isolate_);
context_.Get(isolate_)->Exit();
}
isolate_->Exit();
g_isolate = nullptr;
platform_->UnregisterIsolate(isolate_);
}
class EnabledStateObserverImpl final
: public base::trace_event::TraceLog::EnabledStateObserver {
public:
EnabledStateObserverImpl() {
base::trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
}
~EnabledStateObserverImpl() override {
base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(
this);
}
// disable copy
EnabledStateObserverImpl(const EnabledStateObserverImpl&) = delete;
EnabledStateObserverImpl& operator=(const EnabledStateObserverImpl&) = delete;
void OnTraceLogEnabled() final {
base::AutoLock lock(mutex_);
for (auto* o : observers_) {
o->OnTraceEnabled();
}
}
void OnTraceLogDisabled() final {
base::AutoLock lock(mutex_);
for (auto* o : observers_) {
o->OnTraceDisabled();
}
}
void AddObserver(v8::TracingController::TraceStateObserver* observer) {
{
base::AutoLock lock(mutex_);
DCHECK(!observers_.count(observer));
observers_.insert(observer);
}
// Fire the observer if recording is already in progress.
if (base::trace_event::TraceLog::GetInstance()->IsEnabled())
observer->OnTraceEnabled();
}
void RemoveObserver(v8::TracingController::TraceStateObserver* observer) {
base::AutoLock lock(mutex_);
DCHECK_EQ(observers_.count(observer), 1lu);
observers_.erase(observer);
}
private:
base::Lock mutex_;
std::unordered_set<v8::TracingController::TraceStateObserver*> observers_;
};
base::LazyInstance<EnabledStateObserverImpl>::Leaky g_trace_state_dispatcher =
LAZY_INSTANCE_INITIALIZER;
class TracingControllerImpl : public node::tracing::TracingController {
public:
TracingControllerImpl() = default;
~TracingControllerImpl() override = default;
// disable copy
TracingControllerImpl(const TracingControllerImpl&) = delete;
TracingControllerImpl& operator=(const TracingControllerImpl&) = delete;
// TracingController implementation.
const uint8_t* GetCategoryGroupEnabled(const char* name) override {
return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(name);
}
uint64_t AddTraceEvent(
char phase,
const uint8_t* category_enabled_flag,
const char* name,
const char* scope,
uint64_t id,
uint64_t bind_id,
int32_t num_args,
const char** arg_names,
const uint8_t* arg_types,
const uint64_t* arg_values,
std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables,
unsigned int flags) override {
base::trace_event::TraceArguments args(
num_args, arg_names, arg_types,
reinterpret_cast<const unsigned long long*>( // NOLINT(runtime/int)
arg_values),
arg_convertables);
DCHECK_LE(num_args, 2);
base::trace_event::TraceEventHandle handle =
TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_BIND_ID(
phase, category_enabled_flag, name, scope, id, bind_id, &args,
flags);
uint64_t result;
memcpy(&result, &handle, sizeof(result));
return result;
}
uint64_t AddTraceEventWithTimestamp(
char phase,
const uint8_t* category_enabled_flag,
const char* name,
const char* scope,
uint64_t id,
uint64_t bind_id,
int32_t num_args,
const char** arg_names,
const uint8_t* arg_types,
const uint64_t* arg_values,
std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables,
unsigned int flags,
int64_t timestampMicroseconds) override {
base::trace_event::TraceArguments args(
num_args, arg_names, arg_types,
reinterpret_cast<const unsigned long long*>( // NOLINT(runtime/int)
arg_values),
arg_convertables);
DCHECK_LE(num_args, 2);
base::TimeTicks timestamp =
base::TimeTicks() + base::Microseconds(timestampMicroseconds);
base::trace_event::TraceEventHandle handle =
TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(
phase, category_enabled_flag, name, scope, id, bind_id,
TRACE_EVENT_API_CURRENT_THREAD_ID, timestamp, &args, flags);
uint64_t result;
memcpy(&result, &handle, sizeof(result));
return result;
}
void UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
const char* name,
uint64_t handle) override {
base::trace_event::TraceEventHandle traceEventHandle;
memcpy(&traceEventHandle, &handle, sizeof(handle));
TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(category_enabled_flag, name,
traceEventHandle);
}
void AddTraceStateObserver(TraceStateObserver* observer) override {
g_trace_state_dispatcher.Get().AddObserver(observer);
}
void RemoveTraceStateObserver(TraceStateObserver* observer) override {
g_trace_state_dispatcher.Get().RemoveObserver(observer);
}
};
v8::Isolate* JavascriptEnvironment::Initialize(uv_loop_t* event_loop) {
auto* cmd = base::CommandLine::ForCurrentProcess();
// --js-flags.
std::string js_flags =
cmd->GetSwitchValueASCII(blink::switches::kJavaScriptFlags);
js_flags.append(" --no-freeze-flags-after-init");
if (!js_flags.empty())
v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size());
// The V8Platform of gin relies on Chromium's task schedule, which has not
// been started at this point, so we have to rely on Node's V8Platform.
auto* tracing_agent = node::CreateAgent();
auto* tracing_controller = new TracingControllerImpl();
node::tracing::TraceEventHelper::SetAgent(tracing_agent);
platform_ = node::MultiIsolatePlatform::Create(
base::RecommendedMaxNumberOfThreadsInThreadGroup(3, 8, 0.1, 0),
tracing_controller, gin::V8Platform::PageAllocator());
v8::V8::InitializePlatform(platform_.get());
gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
gin::ArrayBufferAllocator::SharedInstance(),
nullptr /* external_reference_table */,
js_flags, nullptr /* fatal_error_callback */,
nullptr /* oom_error_callback */,
false /* create_v8_platform */);
v8::Isolate* isolate = v8::Isolate::Allocate();
platform_->RegisterIsolate(isolate, event_loop);
g_isolate = isolate;
return isolate;
}
// static
v8::Isolate* JavascriptEnvironment::GetIsolate() {
CHECK(g_isolate);
return g_isolate;
}
void JavascriptEnvironment::CreateMicrotasksRunner() {
DCHECK(!microtasks_runner_);
microtasks_runner_ = std::make_unique<MicrotasksRunner>(isolate());
base::CurrentThread::Get()->AddTaskObserver(microtasks_runner_.get());
}
void JavascriptEnvironment::DestroyMicrotasksRunner() {
DCHECK(microtasks_runner_);
{
v8::HandleScope scope(isolate_);
gin_helper::CleanedUpAtExit::DoCleanup();
}
base::CurrentThread::Get()->RemoveTaskObserver(microtasks_runner_.get());
}
NodeEnvironment::NodeEnvironment(node::Environment* env) : env_(env) {}
NodeEnvironment::~NodeEnvironment() {
auto* isolate_data = env_->isolate_data();
node::FreeEnvironment(env_);
node::FreeIsolateData(isolate_data);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,282 |
Enable `WebAssembly.{compileStreaming|instantiateStreaming}` in Node.js
|
Refs https://github.com/electron/electron/pull/35999.
Refs https://github.com/nodejs/node/pull/42701.
Node.js added support for `WebAssembly.compileStreaming` and `WebAssembly.instantiateStreaming` but they don't work within Electron at the moment.
This is happening because Node.js' logic for enabling them [here](https://github.com/nodejs/node/pull/42701/files#diff-5f2fc380364ef43210af4a28c08f9a0c7ec5f85e3ec1f5c1df5e0204eb9dc721R261) is called via `node::SetIsolateUpForNode`, which by necessity can only be called on an existing isolate. However, the switch to enable it [here](https://source.chromium.org/chromium/chromium/src/+/main:v8/src/wasm/wasm-js.cc;l=2983-2988?q=wasm_streaming_callback&ss=chromium%2Fchromium%2Fsrc) is called by gin during [its own isolate initialization](https://github.com/electron/electron/blob/f2c341b655406434b5a44bc8b1e2418d664c319b/shell/app/node_main.cc#L162), which means that it ends up being undefined. Look into a good way to fix this.
|
https://github.com/electron/electron/issues/36282
|
https://github.com/electron/electron/pull/36420
|
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
|
b90a5baa6dc7f745bf8779dd79d51229a3f8593d
| 2022-11-08T10:43:02Z |
c++
| 2022-12-05T17:07:49Z |
shell/browser/javascript_environment.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
#define ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
#include <memory>
#include "gin/public/isolate_holder.h"
#include "uv.h" // NOLINT(build/include_directory)
#include "v8/include/v8-locker.h"
namespace node {
class Environment;
class MultiIsolatePlatform;
} // namespace node
namespace electron {
class MicrotasksRunner;
// Manage the V8 isolate and context automatically.
class JavascriptEnvironment {
public:
explicit JavascriptEnvironment(uv_loop_t* event_loop);
~JavascriptEnvironment();
// disable copy
JavascriptEnvironment(const JavascriptEnvironment&) = delete;
JavascriptEnvironment& operator=(const JavascriptEnvironment&) = delete;
void CreateMicrotasksRunner();
void DestroyMicrotasksRunner();
node::MultiIsolatePlatform* platform() const { return platform_.get(); }
v8::Isolate* isolate() const { return isolate_; }
v8::Local<v8::Context> context() const {
return v8::Local<v8::Context>::New(isolate_, context_);
}
static v8::Isolate* GetIsolate();
private:
v8::Isolate* Initialize(uv_loop_t* event_loop);
std::unique_ptr<node::MultiIsolatePlatform> platform_;
v8::Isolate* isolate_;
gin::IsolateHolder isolate_holder_;
v8::Locker locker_;
v8::Global<v8::Context> context_;
std::unique_ptr<MicrotasksRunner> microtasks_runner_;
};
// Manage the Node Environment automatically.
class NodeEnvironment {
public:
explicit NodeEnvironment(node::Environment* env);
~NodeEnvironment();
// disable copy
NodeEnvironment(const NodeEnvironment&) = delete;
NodeEnvironment& operator=(const NodeEnvironment&) = delete;
node::Environment* env() { return env_; }
private:
node::Environment* env_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,548 |
[Bug]: Documentation for net.request doesn't clearly show constructor options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
The documentation for net.request should include documentation of the options that the function takes: https://www.electronjs.org/docs/latest/api/net#netrequestoptions
### Actual Behavior
Instead, that documentation exists at https://www.electronjs.org/docs/latest/api/client-request, which is not obvious from the net.request docs
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36548
|
https://github.com/electron/electron/pull/36556
|
8acf6039e78725918af5797fad6fc4f7cf1e177c
|
e1e66fc8ac52af3f951404a647cb82a8389528c3
| 2022-12-04T21:18:48Z |
c++
| 2022-12-05T23:17:37Z |
docs/api/net.md
|
# net
> Issue HTTP/HTTPS requests using Chromium's native networking library
Process: [Main](../glossary.md#main-process)
The `net` module is a client-side API for issuing HTTP(S) requests. It is
similar to the [HTTP](https://nodejs.org/api/http.html) and
[HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses
Chromium's native networking library instead of the Node.js implementation,
offering better support for web proxies. It also supports checking network status.
The following is a non-exhaustive list of why you may consider using the `net`
module instead of the native Node.js modules:
* Automatic management of system proxy configuration, support of the wpad
protocol and proxy pac configuration files.
* Automatic tunneling of HTTPS requests.
* Support for authenticating proxies using basic, digest, NTLM, Kerberos or
negotiate authentication schemes.
* Support for traffic monitoring proxies: Fiddler-like proxies used for access
control and monitoring.
The API components (including classes, methods, properties and event names) are similar to those used in
Node.js.
Example usage:
```javascript
const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
```
The `net` API can be used only after the application emits the `ready` event.
Trying to use the module before the `ready` event will throw an error.
## Methods
The `net` module has the following methods:
### `net.request(options)`
* `options` (ClientRequestConstructorOptions | string) - The `ClientRequest` constructor options.
Returns [`ClientRequest`](./client-request.md)
Creates a [`ClientRequest`](./client-request.md) instance using the provided
`options` which are directly forwarded to the `ClientRequest` constructor.
The `net.request` method would be used to issue both secure and insecure HTTP
requests according to the specified protocol scheme in the `options` object.
### `net.isOnline()`
Returns `boolean` - Whether there is currently internet connection.
A return value of `false` is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
`true` is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
## Properties
### `net.online` _Readonly_
A `boolean` property. Whether there is currently internet connection.
A return value of `false` is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
`true` is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,548 |
[Bug]: Documentation for net.request doesn't clearly show constructor options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
The documentation for net.request should include documentation of the options that the function takes: https://www.electronjs.org/docs/latest/api/net#netrequestoptions
### Actual Behavior
Instead, that documentation exists at https://www.electronjs.org/docs/latest/api/client-request, which is not obvious from the net.request docs
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36548
|
https://github.com/electron/electron/pull/36556
|
8acf6039e78725918af5797fad6fc4f7cf1e177c
|
e1e66fc8ac52af3f951404a647cb82a8389528c3
| 2022-12-04T21:18:48Z |
c++
| 2022-12-05T23:17:37Z |
docs/api/net.md
|
# net
> Issue HTTP/HTTPS requests using Chromium's native networking library
Process: [Main](../glossary.md#main-process)
The `net` module is a client-side API for issuing HTTP(S) requests. It is
similar to the [HTTP](https://nodejs.org/api/http.html) and
[HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses
Chromium's native networking library instead of the Node.js implementation,
offering better support for web proxies. It also supports checking network status.
The following is a non-exhaustive list of why you may consider using the `net`
module instead of the native Node.js modules:
* Automatic management of system proxy configuration, support of the wpad
protocol and proxy pac configuration files.
* Automatic tunneling of HTTPS requests.
* Support for authenticating proxies using basic, digest, NTLM, Kerberos or
negotiate authentication schemes.
* Support for traffic monitoring proxies: Fiddler-like proxies used for access
control and monitoring.
The API components (including classes, methods, properties and event names) are similar to those used in
Node.js.
Example usage:
```javascript
const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
```
The `net` API can be used only after the application emits the `ready` event.
Trying to use the module before the `ready` event will throw an error.
## Methods
The `net` module has the following methods:
### `net.request(options)`
* `options` (ClientRequestConstructorOptions | string) - The `ClientRequest` constructor options.
Returns [`ClientRequest`](./client-request.md)
Creates a [`ClientRequest`](./client-request.md) instance using the provided
`options` which are directly forwarded to the `ClientRequest` constructor.
The `net.request` method would be used to issue both secure and insecure HTTP
requests according to the specified protocol scheme in the `options` object.
### `net.isOnline()`
Returns `boolean` - Whether there is currently internet connection.
A return value of `false` is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
`true` is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
## Properties
### `net.online` _Readonly_
A `boolean` property. Whether there is currently internet connection.
A return value of `false` is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
`true` is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,597 |
[Bug]: memory leak when a worker accesses a file in the asar archive package for the first time
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
After a worker ends, the memory usage falls back to before the worker starts.
### Actual Behavior
Each time a worker is created, the memory usage will be increased a little. Even if the worker is finished, the memory usage will not be reduced.

### Testcase Gist URL
https://gist.github.com/xuwanghu/d61b511abf80aa691375cdfd30a8474e
### Additional Information
The purpose of adding so many dependencies is to make the ASAR file large enough so that the memory leaks are more noticeable.
**How to Reproduce:**
it's on windows:
1. npm install
2. yarn dist
3. run the /dist/win-unpacked/test_leak_for_worker.exe
4. use the Performance Monitor to monitor its working set.
|
https://github.com/electron/electron/issues/36597
|
https://github.com/electron/electron/pull/36600
|
ab890fb8c3883ca60af514546245bf6a000686f1
|
f72e6551f093e7f9f02531c6a69f390521463bf8
| 2022-12-07T05:42:31Z |
c++
| 2022-12-14T17:37:28Z |
shell/common/api/electron_api_asar.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <vector>
#include "gin/handle.h"
#include "shell/common/asar/archive.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
namespace {
class Archive : public node::ObjectWrap {
public:
static v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
v8::Isolate* isolate) {
auto tpl = v8::FunctionTemplate::New(isolate, Archive::New);
tpl->SetClassName(
v8::String::NewFromUtf8(isolate, "Archive").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "getFileInfo", &Archive::GetFileInfo);
NODE_SET_PROTOTYPE_METHOD(tpl, "stat", &Archive::Stat);
NODE_SET_PROTOTYPE_METHOD(tpl, "readdir", &Archive::Readdir);
NODE_SET_PROTOTYPE_METHOD(tpl, "realpath", &Archive::Realpath);
NODE_SET_PROTOTYPE_METHOD(tpl, "copyFileOut", &Archive::CopyFileOut);
NODE_SET_PROTOTYPE_METHOD(tpl, "getFdAndValidateIntegrityLater",
&Archive::GetFD);
return tpl;
}
// disable copy
Archive(const Archive&) = delete;
Archive& operator=(const Archive&) = delete;
protected:
explicit Archive(std::unique_ptr<asar::Archive> archive)
: archive_(std::move(archive)) {}
static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
isolate->ThrowException(v8::Exception::Error(node::FIXED_ONE_BYTE_STRING(
isolate, "failed to convert path to V8")));
return;
}
auto archive = std::make_unique<asar::Archive>(path);
if (!archive->Init()) {
isolate->ThrowException(v8::Exception::Error(node::FIXED_ONE_BYTE_STRING(
isolate, "failed to initialize archive")));
return;
}
auto* archive_wrap = new Archive(std::move(archive));
archive_wrap->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
// Reads the offset and size of file.
static void GetFileInfo(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
asar::Archive::FileInfo info;
if (!wrap->archive_ || !wrap->archive_->GetFileInfo(path, &info)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("size", info.size);
dict.Set("unpacked", info.unpacked);
dict.Set("offset", info.offset);
if (info.integrity.has_value()) {
gin_helper::Dictionary integrity(isolate, v8::Object::New(isolate));
asar::HashAlgorithm algorithm = info.integrity.value().algorithm;
switch (algorithm) {
case asar::HashAlgorithm::SHA256:
integrity.Set("algorithm", "SHA256");
break;
case asar::HashAlgorithm::NONE:
CHECK(false);
break;
}
integrity.Set("hash", info.integrity.value().hash);
dict.Set("integrity", integrity);
}
args.GetReturnValue().Set(dict.GetHandle());
}
// Returns a fake result of fs.stat(path).
static void Stat(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
asar::Archive::Stats stats;
if (!wrap->archive_ || !wrap->archive_->Stat(path, &stats)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("size", stats.size);
dict.Set("offset", stats.offset);
dict.Set("isFile", stats.is_file);
dict.Set("isDirectory", stats.is_directory);
dict.Set("isLink", stats.is_link);
args.GetReturnValue().Set(dict.GetHandle());
}
// Returns all files under a directory.
static void Readdir(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
std::vector<base::FilePath> files;
if (!wrap->archive_ || !wrap->archive_->Readdir(path, &files)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, files));
}
// Returns the path of file with symbol link resolved.
static void Realpath(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
base::FilePath realpath;
if (!wrap->archive_ || !wrap->archive_->Realpath(path, &realpath)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, realpath));
}
// Copy the file out into a temporary file and returns the new path.
static void CopyFileOut(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
base::FilePath new_path;
if (!wrap->archive_ || !wrap->archive_->CopyFileOut(path, &new_path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, new_path));
}
// Return the file descriptor.
static void GetFD(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
args.GetReturnValue().Set(gin::ConvertToV8(
isolate, wrap->archive_ ? wrap->archive_->GetUnsafeFD() : -1));
}
std::unique_ptr<asar::Archive> archive_;
};
static void InitAsarSupport(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto require = args[0];
// Evaluate asar_bundle.js.
std::vector<v8::Local<v8::String>> asar_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "require")};
std::vector<v8::Local<v8::Value>> asar_bundle_args = {require};
electron::util::CompileAndCall(
isolate->GetCurrentContext(), "electron/js2c/asar_bundle",
&asar_bundle_params, &asar_bundle_args, nullptr);
}
static void SplitPath(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
base::FilePath asar_path, file_path;
if (asar::GetAsarArchivePath(path, &asar_path, &file_path, true)) {
dict.Set("isAsar", true);
dict.Set("asarPath", asar_path);
dict.Set("filePath", file_path);
} else {
dict.Set("isAsar", false);
}
args.GetReturnValue().Set(dict.GetHandle());
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
auto* isolate = exports->GetIsolate();
auto cons = Archive::CreateFunctionTemplate(isolate)
->GetFunction(context)
.ToLocalChecked();
cons->SetName(node::FIXED_ONE_BYTE_STRING(isolate, "Archive"));
exports->Set(context, node::FIXED_ONE_BYTE_STRING(isolate, "Archive"), cons)
.Check();
NODE_SET_METHOD(exports, "splitPath", &SplitPath);
NODE_SET_METHOD(exports, "initAsarSupport", &InitAsarSupport);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_common_asar, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,597 |
[Bug]: memory leak when a worker accesses a file in the asar archive package for the first time
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
After a worker ends, the memory usage falls back to before the worker starts.
### Actual Behavior
Each time a worker is created, the memory usage will be increased a little. Even if the worker is finished, the memory usage will not be reduced.

### Testcase Gist URL
https://gist.github.com/xuwanghu/d61b511abf80aa691375cdfd30a8474e
### Additional Information
The purpose of adding so many dependencies is to make the ASAR file large enough so that the memory leaks are more noticeable.
**How to Reproduce:**
it's on windows:
1. npm install
2. yarn dist
3. run the /dist/win-unpacked/test_leak_for_worker.exe
4. use the Performance Monitor to monitor its working set.
|
https://github.com/electron/electron/issues/36597
|
https://github.com/electron/electron/pull/36600
|
ab890fb8c3883ca60af514546245bf6a000686f1
|
f72e6551f093e7f9f02531c6a69f390521463bf8
| 2022-12-07T05:42:31Z |
c++
| 2022-12-14T17:37:28Z |
shell/common/api/electron_api_asar.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <vector>
#include "gin/handle.h"
#include "shell/common/asar/archive.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
namespace {
class Archive : public node::ObjectWrap {
public:
static v8::Local<v8::FunctionTemplate> CreateFunctionTemplate(
v8::Isolate* isolate) {
auto tpl = v8::FunctionTemplate::New(isolate, Archive::New);
tpl->SetClassName(
v8::String::NewFromUtf8(isolate, "Archive").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "getFileInfo", &Archive::GetFileInfo);
NODE_SET_PROTOTYPE_METHOD(tpl, "stat", &Archive::Stat);
NODE_SET_PROTOTYPE_METHOD(tpl, "readdir", &Archive::Readdir);
NODE_SET_PROTOTYPE_METHOD(tpl, "realpath", &Archive::Realpath);
NODE_SET_PROTOTYPE_METHOD(tpl, "copyFileOut", &Archive::CopyFileOut);
NODE_SET_PROTOTYPE_METHOD(tpl, "getFdAndValidateIntegrityLater",
&Archive::GetFD);
return tpl;
}
// disable copy
Archive(const Archive&) = delete;
Archive& operator=(const Archive&) = delete;
protected:
explicit Archive(std::unique_ptr<asar::Archive> archive)
: archive_(std::move(archive)) {}
static void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
isolate->ThrowException(v8::Exception::Error(node::FIXED_ONE_BYTE_STRING(
isolate, "failed to convert path to V8")));
return;
}
auto archive = std::make_unique<asar::Archive>(path);
if (!archive->Init()) {
isolate->ThrowException(v8::Exception::Error(node::FIXED_ONE_BYTE_STRING(
isolate, "failed to initialize archive")));
return;
}
auto* archive_wrap = new Archive(std::move(archive));
archive_wrap->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
// Reads the offset and size of file.
static void GetFileInfo(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
asar::Archive::FileInfo info;
if (!wrap->archive_ || !wrap->archive_->GetFileInfo(path, &info)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("size", info.size);
dict.Set("unpacked", info.unpacked);
dict.Set("offset", info.offset);
if (info.integrity.has_value()) {
gin_helper::Dictionary integrity(isolate, v8::Object::New(isolate));
asar::HashAlgorithm algorithm = info.integrity.value().algorithm;
switch (algorithm) {
case asar::HashAlgorithm::SHA256:
integrity.Set("algorithm", "SHA256");
break;
case asar::HashAlgorithm::NONE:
CHECK(false);
break;
}
integrity.Set("hash", info.integrity.value().hash);
dict.Set("integrity", integrity);
}
args.GetReturnValue().Set(dict.GetHandle());
}
// Returns a fake result of fs.stat(path).
static void Stat(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
asar::Archive::Stats stats;
if (!wrap->archive_ || !wrap->archive_->Stat(path, &stats)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("size", stats.size);
dict.Set("offset", stats.offset);
dict.Set("isFile", stats.is_file);
dict.Set("isDirectory", stats.is_directory);
dict.Set("isLink", stats.is_link);
args.GetReturnValue().Set(dict.GetHandle());
}
// Returns all files under a directory.
static void Readdir(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
std::vector<base::FilePath> files;
if (!wrap->archive_ || !wrap->archive_->Readdir(path, &files)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, files));
}
// Returns the path of file with symbol link resolved.
static void Realpath(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
base::FilePath realpath;
if (!wrap->archive_ || !wrap->archive_->Realpath(path, &realpath)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, realpath));
}
// Copy the file out into a temporary file and returns the new path.
static void CopyFileOut(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
base::FilePath new_path;
if (!wrap->archive_ || !wrap->archive_->CopyFileOut(path, &new_path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
args.GetReturnValue().Set(gin::ConvertToV8(isolate, new_path));
}
// Return the file descriptor.
static void GetFD(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto* wrap = node::ObjectWrap::Unwrap<Archive>(args.Holder());
args.GetReturnValue().Set(gin::ConvertToV8(
isolate, wrap->archive_ ? wrap->archive_->GetUnsafeFD() : -1));
}
std::unique_ptr<asar::Archive> archive_;
};
static void InitAsarSupport(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
auto require = args[0];
// Evaluate asar_bundle.js.
std::vector<v8::Local<v8::String>> asar_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "require")};
std::vector<v8::Local<v8::Value>> asar_bundle_args = {require};
electron::util::CompileAndCall(
isolate->GetCurrentContext(), "electron/js2c/asar_bundle",
&asar_bundle_params, &asar_bundle_args, nullptr);
}
static void SplitPath(const v8::FunctionCallbackInfo<v8::Value>& args) {
auto* isolate = args.GetIsolate();
base::FilePath path;
if (!gin::ConvertFromV8(isolate, args[0], &path)) {
args.GetReturnValue().Set(v8::False(isolate));
return;
}
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
base::FilePath asar_path, file_path;
if (asar::GetAsarArchivePath(path, &asar_path, &file_path, true)) {
dict.Set("isAsar", true);
dict.Set("asarPath", asar_path);
dict.Set("filePath", file_path);
} else {
dict.Set("isAsar", false);
}
args.GetReturnValue().Set(dict.GetHandle());
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
auto* isolate = exports->GetIsolate();
auto cons = Archive::CreateFunctionTemplate(isolate)
->GetFunction(context)
.ToLocalChecked();
cons->SetName(node::FIXED_ONE_BYTE_STRING(isolate, "Archive"));
exports->Set(context, node::FIXED_ONE_BYTE_STRING(isolate, "Archive"), cons)
.Check();
NODE_SET_METHOD(exports, "splitPath", &SplitPath);
NODE_SET_METHOD(exports, "initAsarSupport", &InitAsarSupport);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_common_asar, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
lib/browser/api/net.ts
|
import * as url from 'url';
import { Readable, Writable } from 'stream';
import { app } from 'electron/main';
import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
const {
isOnline,
isValidHeaderName,
isValidHeaderValue,
createURLLoader
} = process._linkedBinding('electron_browser_net');
const kSupportedProtocols = new Set(['http:', 'https:']);
// set of headers that Node.js discards duplicates for
// see https://nodejs.org/api/http.html#http_message_headers
const discardableDuplicateHeaders = new Set([
'content-type',
'content-length',
'user-agent',
'referer',
'host',
'authorization',
'proxy-authorization',
'if-modified-since',
'if-unmodified-since',
'from',
'location',
'max-forwards',
'retry-after',
'etag',
'last-modified',
'server',
'age',
'expires'
]);
class IncomingMessage extends Readable {
_shouldPush: boolean = false;
_data: (Buffer | null)[] = [];
_responseHead: NodeJS.ResponseHead;
_resume: (() => void) | null = null;
constructor (responseHead: NodeJS.ResponseHead) {
super();
this._responseHead = responseHead;
}
get statusCode () {
return this._responseHead.statusCode;
}
get statusMessage () {
return this._responseHead.statusMessage;
}
get headers () {
const filteredHeaders: Record<string, string | string[]> = {};
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
const keyLowerCase = header.key.toLowerCase();
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase) &&
discardableDuplicateHeaders.has(keyLowerCase)) {
// do nothing with discardable duplicate headers
} else {
if (keyLowerCase === 'set-cookie') {
// keep set-cookie as an array per Node.js rules
// see https://nodejs.org/api/http.html#http_message_headers
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) {
(filteredHeaders[keyLowerCase] as string[]).push(header.value);
} else {
filteredHeaders[keyLowerCase] = [header.value];
}
} else {
// for non-cookie headers, the values are joined together with ', '
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) {
filteredHeaders[keyLowerCase] += `, ${header.value}`;
} else {
filteredHeaders[keyLowerCase] = header.value;
}
}
}
});
return filteredHeaders;
}
get rawHeaders () {
const rawHeadersArr: string[] = [];
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
rawHeadersArr.push(header.key, header.value);
});
return rawHeadersArr;
}
get httpVersion () {
return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
}
get httpVersionMajor () {
return this._responseHead.httpVersion.major;
}
get httpVersionMinor () {
return this._responseHead.httpVersion.minor;
}
get rawTrailers () {
throw new Error('HTTP trailers are not supported');
}
get trailers () {
throw new Error('HTTP trailers are not supported');
}
_storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
// save the network callback for use in _pushInternalData
this._resume = resume;
this._data.push(chunk);
this._pushInternalData();
}
_pushInternalData () {
while (this._shouldPush && this._data.length > 0) {
const chunk = this._data.shift();
this._shouldPush = this.push(chunk);
}
if (this._shouldPush && this._resume) {
// Reset the callback, so that a new one is used for each
// batch of throttled data. Do this before calling resume to avoid a
// potential race-condition
const resume = this._resume;
this._resume = null;
resume();
}
}
_read () {
this._shouldPush = true;
this._pushInternalData();
}
}
/** Writable stream that buffers up everything written to it. */
class SlurpStream extends Writable {
_data: Buffer;
constructor () {
super();
this._data = Buffer.alloc(0);
}
_write (chunk: Buffer, encoding: string, callback: () => void) {
this._data = Buffer.concat([this._data, chunk]);
callback();
}
data () { return this._data; }
}
class ChunkedBodyStream extends Writable {
_pendingChunk: Buffer | undefined;
_downstream?: NodeJS.DataPipe;
_pendingCallback?: (error?: Error) => void;
_clientRequest: ClientRequest;
constructor (clientRequest: ClientRequest) {
super();
this._clientRequest = clientRequest;
}
_write (chunk: Buffer, encoding: string, callback: () => void) {
if (this._downstream) {
this._downstream.write(chunk).then(callback, callback);
} else {
// the contract of _write is that we won't be called again until we call
// the callback, so we're good to just save a single chunk.
this._pendingChunk = chunk;
this._pendingCallback = callback;
// The first write to a chunked body stream begins the request.
this._clientRequest._startRequest();
}
}
_final (callback: () => void) {
this._downstream!.done();
callback();
}
startReading (pipe: NodeJS.DataPipe) {
if (this._downstream) {
throw new Error('two startReading calls???');
}
this._downstream = pipe;
if (this._pendingChunk) {
const doneWriting = (maybeError: Error | void) => {
// If the underlying request has been aborted, we honestly don't care about the error
// all work should cease as soon as we abort anyway, this error is probably a
// "mojo pipe disconnected" error (code=9)
if (this._clientRequest._aborted) return;
const cb = this._pendingCallback!;
delete this._pendingCallback;
delete this._pendingChunk;
cb(maybeError || undefined);
};
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
}
}
}
type RedirectPolicy = 'manual' | 'follow' | 'error';
function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } {
const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
let urlStr: string = options.url;
if (!urlStr) {
const urlObj: url.UrlObject = {};
const protocol = options.protocol || 'http:';
if (!kSupportedProtocols.has(protocol)) {
throw new Error('Protocol "' + protocol + '" not supported');
}
urlObj.protocol = protocol;
if (options.host) {
urlObj.host = options.host;
} else {
if (options.hostname) {
urlObj.hostname = options.hostname;
} else {
urlObj.hostname = 'localhost';
}
if (options.port) {
urlObj.port = options.port;
}
}
if (options.path && / /.test(options.path)) {
// The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
// with an additional rule for ignoring percentage-escaped characters
// but that's a) hard to capture in a regular expression that performs
// well, and b) possibly too restrictive for real-world usage. That's
// why it only scans for spaces because those are guaranteed to create
// an invalid request.
throw new TypeError('Request path contains unescaped characters');
}
const pathObj = url.parse(options.path || '/');
urlObj.pathname = pathObj.pathname;
urlObj.search = pathObj.search;
urlObj.hash = pathObj.hash;
urlStr = url.format(urlObj);
}
const redirectPolicy = options.redirect || 'follow';
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
throw new Error('redirect mode should be one of follow, error or manual');
}
if (options.headers != null && typeof options.headers !== 'object') {
throw new TypeError('headers must be an object');
}
const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } = {
method: (options.method || 'GET').toUpperCase(),
url: urlStr,
redirectPolicy,
headers: {},
body: null as any,
useSessionCookies: options.useSessionCookies,
credentials: options.credentials,
origin: options.origin
};
const headers: Record<string, string | string[]> = options.headers || {};
for (const [name, value] of Object.entries(headers)) {
if (!isValidHeaderName(name)) {
throw new Error(`Invalid header name: '${name}'`);
}
if (!isValidHeaderValue(value.toString())) {
throw new Error(`Invalid value for header '${name}': '${value}'`);
}
const key = name.toLowerCase();
urlLoaderOptions.headers[key] = { name, value };
}
if (options.session) {
// Weak check, but it should be enough to catch 99% of accidental misuses.
if (options.session.constructor && options.session.constructor.name === 'Session') {
urlLoaderOptions.session = options.session;
} else {
throw new TypeError('`session` should be an instance of the Session class');
}
} else if (options.partition) {
if (typeof options.partition === 'string') {
urlLoaderOptions.partition = options.partition;
} else {
throw new TypeError('`partition` should be a string');
}
}
return urlLoaderOptions;
}
export class ClientRequest extends Writable implements Electron.ClientRequest {
_started: boolean = false;
_firstWrite: boolean = false;
_aborted: boolean = false;
_chunkedEncoding: boolean | undefined;
_body: Writable | undefined;
_urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
_redirectPolicy: RedirectPolicy;
_followRedirectCb?: () => void;
_uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
_urlLoader?: NodeJS.URLLoader;
_response?: IncomingMessage;
constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
super({ autoDestroy: true });
if (!app.isReady()) {
throw new Error('net module can only be used after app is ready');
}
if (callback) {
this.once('response', callback);
}
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
this._urlLoaderOptions = urlLoaderOptions;
this._redirectPolicy = redirectPolicy;
}
get chunkedEncoding () {
return this._chunkedEncoding || false;
}
set chunkedEncoding (value: boolean) {
if (this._started) {
throw new Error('chunkedEncoding can only be set before the request is started');
}
if (typeof this._chunkedEncoding !== 'undefined') {
throw new Error('chunkedEncoding can only be set once');
}
this._chunkedEncoding = !!value;
if (this._chunkedEncoding) {
this._body = new ChunkedBodyStream(this);
this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
(this._body! as ChunkedBodyStream).startReading(pipe);
};
}
}
setHeader (name: string, value: string) {
if (typeof name !== 'string') {
throw new TypeError('`name` should be a string in setHeader(name, value)');
}
if (value == null) {
throw new Error('`value` required in setHeader("' + name + '", value)');
}
if (this._started || this._firstWrite) {
throw new Error('Can\'t set headers after they are sent');
}
if (!isValidHeaderName(name)) {
throw new Error(`Invalid header name: '${name}'`);
}
if (!isValidHeaderValue(value.toString())) {
throw new Error(`Invalid value for header '${name}': '${value}'`);
}
const key = name.toLowerCase();
this._urlLoaderOptions.headers[key] = { name, value };
}
getHeader (name: string) {
if (name == null) {
throw new Error('`name` is required for getHeader(name)');
}
const key = name.toLowerCase();
const header = this._urlLoaderOptions.headers[key];
return header && header.value as any;
}
removeHeader (name: string) {
if (name == null) {
throw new Error('`name` is required for removeHeader(name)');
}
if (this._started || this._firstWrite) {
throw new Error('Can\'t remove headers after they are sent');
}
const key = name.toLowerCase();
delete this._urlLoaderOptions.headers[key];
}
_write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
this._firstWrite = true;
if (!this._body) {
this._body = new SlurpStream();
this._body.on('finish', () => {
this._urlLoaderOptions.body = (this._body as SlurpStream).data();
this._startRequest();
});
}
// TODO: is this the right way to forward to another stream?
this._body.write(chunk, encoding, callback);
}
_final (callback: () => void) {
if (this._body) {
// TODO: is this the right way to forward to another stream?
this._body.end(callback);
} else {
// end() called without a body, go ahead and start the request
this._startRequest();
callback();
}
}
_startRequest () {
this._started = true;
const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
const ret: Record<string, string> = {};
for (const k of Object.keys(obj)) {
const kv = obj[k];
ret[kv.name] = kv.value.toString();
}
return ret;
};
this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
this._urlLoader = createURLLoader(opts);
this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
const response = this._response = new IncomingMessage(responseHead);
this.emit('response', response);
});
this._urlLoader.on('data', (event, data, resume) => {
this._response!._storeInternalData(Buffer.from(data), resume);
});
this._urlLoader.on('complete', () => {
if (this._response) { this._response._storeInternalData(null, null); }
});
this._urlLoader.on('error', (event, netErrorString) => {
const error = new Error(netErrorString);
if (this._response) this._response.destroy(error);
this._die(error);
});
this._urlLoader.on('login', (event, authInfo, callback) => {
const handled = this.emit('login', authInfo, callback);
if (!handled) {
// If there were no listeners, cancel the authentication request.
callback();
}
});
this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
const { statusCode, newMethod, newUrl } = redirectInfo;
if (this._redirectPolicy === 'error') {
this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
} else if (this._redirectPolicy === 'manual') {
let _followRedirect = false;
this._followRedirectCb = () => { _followRedirect = true; };
try {
this.emit('redirect', statusCode, newMethod, newUrl, headers);
} finally {
this._followRedirectCb = undefined;
if (!_followRedirect && !this._aborted) {
this._die(new Error('Redirect was cancelled'));
}
}
} else if (this._redirectPolicy === 'follow') {
// Calling followRedirect() when the redirect policy is 'follow' is
// allowed but does nothing. (Perhaps it should throw an error
// though...? Since the redirect will happen regardless.)
try {
this._followRedirectCb = () => {};
this.emit('redirect', statusCode, newMethod, newUrl, headers);
} finally {
this._followRedirectCb = undefined;
}
} else {
this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
}
});
this._urlLoader.on('upload-progress', (event, position, total) => {
this._uploadProgress = { active: true, started: true, current: position, total };
this.emit('upload-progress', position, total); // Undocumented, for now
});
this._urlLoader.on('download-progress', (event, current) => {
if (this._response) {
this._response.emit('download-progress', current); // Undocumented, for now
}
});
}
followRedirect () {
if (this._followRedirectCb) {
this._followRedirectCb();
} else {
throw new Error('followRedirect() called, but was not waiting for a redirect');
}
}
abort () {
if (!this._aborted) {
process.nextTick(() => { this.emit('abort'); });
}
this._aborted = true;
this._die();
}
_die (err?: Error) {
// Node.js assumes that any stream which is ended is no longer capable of emitted events
// which is a faulty assumption for the case of an object that is acting like a stream
// (our urlRequest). If we don't emit here, this causes errors since we *do* expect
// that error events can be emitted after urlRequest.end().
if ((this as any)._writableState.destroyed && err) {
this.emit('error', err);
}
this.destroy(err);
if (this._urlLoader) {
this._urlLoader.cancel();
if (this._response) this._response.destroy(err);
}
}
getUploadProgress (): UploadProgress {
return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
}
}
export function request (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
return new ClientRequest(options, callback);
}
exports.isOnline = isOnline;
Object.defineProperty(exports, 'online', {
get: () => isOnline()
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
shell/browser/api/electron_api_url_loader.cc
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_url_loader.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/no_destructor.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "net/base/load_flags.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h"
#include "services/network/public/mojom/http_raw_headers.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
namespace gin {
template <>
struct Converter<network::mojom::HttpRawHeaderPairPtr> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const network::mojom::HttpRawHeaderPairPtr& pair) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("key", pair->key);
dict.Set("value", pair->value);
return dict.GetHandle();
}
};
template <>
struct Converter<network::mojom::CredentialsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::CredentialsMode* out) {
std::string mode;
if (!ConvertFromV8(isolate, val, &mode))
return false;
if (mode == "omit")
*out = network::mojom::CredentialsMode::kOmit;
else if (mode == "include")
*out = network::mojom::CredentialsMode::kInclude;
else
// "same-origin" is technically a member of this enum as well, but it
// doesn't make sense in the context of `net.request()`, so don't convert
// it.
return false;
return true;
}
};
} // namespace gin
namespace electron::api {
namespace {
class BufferDataSource : public mojo::DataPipeProducer::DataSource {
public:
explicit BufferDataSource(base::span<char> buffer) {
buffer_.resize(buffer.size());
memcpy(buffer_.data(), buffer.data(), buffer_.size());
}
~BufferDataSource() override = default;
private:
// mojo::DataPipeProducer::DataSource:
uint64_t GetLength() const override { return buffer_.size(); }
ReadResult Read(uint64_t offset, base::span<char> buffer) override {
ReadResult result;
if (offset <= buffer_.size()) {
size_t readable_size = buffer_.size() - offset;
size_t writable_size = buffer.size();
size_t copyable_size = std::min(readable_size, writable_size);
if (copyable_size > 0) {
memcpy(buffer.data(), &buffer_[offset], copyable_size);
}
result.bytes_read = copyable_size;
} else {
NOTREACHED();
result.result = MOJO_RESULT_OUT_OF_RANGE;
}
return result;
}
std::vector<char> buffer_;
};
class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
public network::mojom::ChunkedDataPipeGetter {
public:
static gin::Handle<JSChunkedDataPipeGetter> Create(
v8::Isolate* isolate,
v8::Local<v8::Function> body_func,
mojo::PendingReceiver<network::mojom::ChunkedDataPipeGetter>
chunked_data_pipe_getter) {
return gin::CreateHandle(
isolate, new JSChunkedDataPipeGetter(
isolate, body_func, std::move(chunked_data_pipe_getter)));
}
// gin::Wrappable
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<JSChunkedDataPipeGetter>::GetObjectTemplateBuilder(
isolate)
.SetMethod("write", &JSChunkedDataPipeGetter::WriteChunk)
.SetMethod("done", &JSChunkedDataPipeGetter::Done);
}
static gin::WrapperInfo kWrapperInfo;
~JSChunkedDataPipeGetter() override = default;
private:
JSChunkedDataPipeGetter(
v8::Isolate* isolate,
v8::Local<v8::Function> body_func,
mojo::PendingReceiver<network::mojom::ChunkedDataPipeGetter>
chunked_data_pipe_getter)
: isolate_(isolate), body_func_(isolate, body_func) {
receiver_.Bind(std::move(chunked_data_pipe_getter));
}
// network::mojom::ChunkedDataPipeGetter:
void GetSize(GetSizeCallback callback) override {
size_callback_ = std::move(callback);
}
void StartReading(mojo::ScopedDataPipeProducerHandle pipe) override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (body_func_.IsEmpty()) {
LOG(ERROR) << "Tried to read twice from a JSChunkedDataPipeGetter";
// Drop the handle on the floor.
return;
}
data_producer_ = std::make_unique<mojo::DataPipeProducer>(std::move(pipe));
v8::HandleScope handle_scope(isolate_);
auto maybe_wrapper = GetWrapper(isolate_);
v8::Local<v8::Value> wrapper;
if (!maybe_wrapper.ToLocal(&wrapper)) {
return;
}
v8::Local<v8::Value> argv[] = {wrapper};
node::Environment* env = node::Environment::GetCurrent(isolate_);
auto global = env->context()->Global();
node::MakeCallback(isolate_, global, body_func_.Get(isolate_),
node::arraysize(argv), argv, {0, 0});
}
v8::Local<v8::Promise> WriteChunk(v8::Local<v8::Value> buffer_val) {
gin_helper::Promise<void> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!buffer_val->IsArrayBufferView()) {
promise.RejectWithErrorMessage("Expected an ArrayBufferView");
return handle;
}
if (is_writing_) {
promise.RejectWithErrorMessage("Only one write can be pending at a time");
return handle;
}
if (!size_callback_) {
promise.RejectWithErrorMessage("Can't write after calling done()");
return handle;
}
auto buffer = buffer_val.As<v8::ArrayBufferView>();
is_writing_ = true;
bytes_written_ += buffer->ByteLength();
auto backing_store = buffer->Buffer()->GetBackingStore();
auto buffer_span = base::make_span(
static_cast<char*>(backing_store->Data()) + buffer->ByteOffset(),
buffer->ByteLength());
auto buffer_source = std::make_unique<BufferDataSource>(buffer_span);
data_producer_->Write(
std::move(buffer_source),
base::BindOnce(&JSChunkedDataPipeGetter::OnWriteChunkComplete,
// We're OK to use Unretained here because we own
// |data_producer_|.
base::Unretained(this), std::move(promise)));
return handle;
}
void OnWriteChunkComplete(gin_helper::Promise<void> promise,
MojoResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
is_writing_ = false;
if (result == MOJO_RESULT_OK) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("mojo result not ok: " +
std::to_string(result));
Finished();
}
}
// TODO(nornagon): accept a net error here to allow the data provider to
// cancel the request with an error.
void Done() {
if (size_callback_) {
std::move(size_callback_).Run(net::OK, bytes_written_);
Finished();
}
}
void Finished() {
body_func_.Reset();
data_producer_.reset();
receiver_.reset();
size_callback_.Reset();
}
GetSizeCallback size_callback_;
mojo::Receiver<network::mojom::ChunkedDataPipeGetter> receiver_{this};
std::unique_ptr<mojo::DataPipeProducer> data_producer_;
bool is_writing_ = false;
uint64_t bytes_written_ = 0;
v8::Isolate* isolate_;
v8::Global<v8::Function> body_func_;
};
gin::WrapperInfo JSChunkedDataPipeGetter::kWrapperInfo = {
gin::kEmbedderNativeGin};
const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("electron_net_module", R"(
semantics {
sender: "Electron Net module"
description:
"Issue HTTP/HTTPS requests using Chromium's native networking "
"library."
trigger: "Using the Net module"
data: "Anything the user wants to send."
destination: OTHER
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting: "This feature cannot be disabled."
})");
} // namespace
gin::WrapperInfo SimpleURLLoaderWrapper::kWrapperInfo = {
gin::kEmbedderNativeGin};
SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
std::unique_ptr<network::ResourceRequest> request,
network::mojom::URLLoaderFactory* url_loader_factory,
int options) {
if (!request->trusted_params)
request->trusted_params = network::ResourceRequest::TrustedParams();
mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
url_loader_network_observer_remote;
url_loader_network_observer_receivers_.Add(
this,
url_loader_network_observer_remote.InitWithNewPipeAndPassReceiver());
request->trusted_params->url_loader_network_observer =
std::move(url_loader_network_observer_remote);
// Chromium filters headers using browser rules, while for net module we have
// every header passed. The following setting will allow us to capture the
// raw headers in the URLLoader.
request->report_raw_headers = true;
// SimpleURLLoader wants to control the request body itself. We have other
// ideas.
auto request_body = std::move(request->request_body);
auto* request_ref = request.get();
loader_ =
network::SimpleURLLoader::Create(std::move(request), kTrafficAnnotation);
if (request_body) {
request_ref->request_body = std::move(request_body);
}
loader_->SetAllowHttpErrorResults(true);
loader_->SetURLLoaderFactoryOptions(options);
loader_->SetOnResponseStartedCallback(base::BindOnce(
&SimpleURLLoaderWrapper::OnResponseStarted, base::Unretained(this)));
loader_->SetOnRedirectCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnRedirect, base::Unretained(this)));
loader_->SetOnUploadProgressCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnUploadProgress, base::Unretained(this)));
loader_->SetOnDownloadProgressCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnDownloadProgress, base::Unretained(this)));
loader_->DownloadAsStream(url_loader_factory, this);
}
void SimpleURLLoaderWrapper::Pin() {
// Prevent ourselves from being GC'd until the request is complete. Must be
// called after gin::CreateHandle, otherwise the wrapper isn't initialized.
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
pinned_wrapper_.Reset(isolate, GetWrapper(isolate).ToLocalChecked());
}
void SimpleURLLoaderWrapper::PinBodyGetter(v8::Local<v8::Value> body_getter) {
pinned_chunk_pipe_getter_.Reset(JavascriptEnvironment::GetIsolate(),
body_getter);
}
SimpleURLLoaderWrapper::~SimpleURLLoaderWrapper() = default;
void SimpleURLLoaderWrapper::OnAuthRequired(
const absl::optional<base::UnguessableToken>& window_id,
uint32_t request_id,
const GURL& url,
bool first_auth_attempt,
const net::AuthChallengeInfo& auth_info,
const scoped_refptr<net::HttpResponseHeaders>& head_headers,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
mojo::Remote<network::mojom::AuthChallengeResponder> auth_responder(
std::move(auth_challenge_responder));
// WeakPtr because if we're Cancel()ed while waiting for auth, and the
// network service also decides to cancel at the same time and kill this
// pipe, we might end up trying to call Cancel again on dead memory.
auth_responder.set_disconnect_handler(base::BindOnce(
&SimpleURLLoaderWrapper::Cancel, weak_factory_.GetWeakPtr()));
auto cb = base::BindOnce(
[](mojo::Remote<network::mojom::AuthChallengeResponder> auth_responder,
gin::Arguments* args) {
std::u16string username_str, password_str;
if (!args->GetNext(&username_str) || !args->GetNext(&password_str)) {
auth_responder->OnAuthCredentials(absl::nullopt);
return;
}
auth_responder->OnAuthCredentials(
net::AuthCredentials(username_str, password_str));
},
std::move(auth_responder));
Emit("login", auth_info, base::AdaptCallbackForRepeating(std::move(cb)));
}
void SimpleURLLoaderWrapper::OnSSLCertificateError(
const GURL& url,
int net_error,
const net::SSLInfo& ssl_info,
bool fatal,
OnSSLCertificateErrorCallback response) {
std::move(response).Run(net_error);
}
void SimpleURLLoaderWrapper::OnClearSiteData(
const GURL& url,
const std::string& header_value,
int32_t load_flags,
const absl::optional<net::CookiePartitionKey>& cookie_partition_key,
OnClearSiteDataCallback callback) {
std::move(callback).Run();
}
void SimpleURLLoaderWrapper::OnLoadingStateUpdate(
network::mojom::LoadInfoPtr info,
OnLoadingStateUpdateCallback callback) {
std::move(callback).Run();
}
void SimpleURLLoaderWrapper::Clone(
mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver>
observer) {
url_loader_network_observer_receivers_.Add(this, std::move(observer));
}
void SimpleURLLoaderWrapper::Cancel() {
loader_.reset();
pinned_wrapper_.Reset();
pinned_chunk_pipe_getter_.Reset();
// This ensures that no further callbacks will be called, so there's no need
// for additional guards.
}
// static
gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
gin::Arguments* args) {
gin_helper::Dictionary opts;
if (!args->GetNext(&opts)) {
args->ThrowTypeError("Expected a dictionary");
return gin::Handle<SimpleURLLoaderWrapper>();
}
auto request = std::make_unique<network::ResourceRequest>();
opts.Get("method", &request->method);
opts.Get("url", &request->url);
request->site_for_cookies = net::SiteForCookies::FromUrl(request->url);
opts.Get("referrer", &request->referrer);
std::string origin;
opts.Get("origin", &origin);
if (!origin.empty()) {
request->request_initiator = url::Origin::Create(GURL(origin));
}
bool has_user_activation;
if (opts.Get("hasUserActivation", &has_user_activation)) {
request->trusted_params = network::ResourceRequest::TrustedParams();
request->trusted_params->has_user_activation = has_user_activation;
}
std::string mode;
if (opts.Get("mode", &mode) && !mode.empty()) {
if (mode == "navigate") {
request->mode = network::mojom::RequestMode::kNavigate;
} else if (mode == "cors") {
request->mode = network::mojom::RequestMode::kCors;
} else if (mode == "no-cors") {
request->mode = network::mojom::RequestMode::kNoCors;
} else if (mode == "same-origin") {
request->mode = network::mojom::RequestMode::kSameOrigin;
}
}
std::string destination;
if (opts.Get("destination", &destination) && !destination.empty()) {
if (destination == "empty") {
request->destination = network::mojom::RequestDestination::kEmpty;
} else if (destination == "audio") {
request->destination = network::mojom::RequestDestination::kAudio;
} else if (destination == "audioworklet") {
request->destination = network::mojom::RequestDestination::kAudioWorklet;
} else if (destination == "document") {
request->destination = network::mojom::RequestDestination::kDocument;
} else if (destination == "embed") {
request->destination = network::mojom::RequestDestination::kEmbed;
} else if (destination == "font") {
request->destination = network::mojom::RequestDestination::kFont;
} else if (destination == "frame") {
request->destination = network::mojom::RequestDestination::kFrame;
} else if (destination == "iframe") {
request->destination = network::mojom::RequestDestination::kIframe;
} else if (destination == "image") {
request->destination = network::mojom::RequestDestination::kImage;
} else if (destination == "manifest") {
request->destination = network::mojom::RequestDestination::kManifest;
} else if (destination == "object") {
request->destination = network::mojom::RequestDestination::kObject;
} else if (destination == "paintworklet") {
request->destination = network::mojom::RequestDestination::kPaintWorklet;
} else if (destination == "report") {
request->destination = network::mojom::RequestDestination::kReport;
} else if (destination == "script") {
request->destination = network::mojom::RequestDestination::kScript;
} else if (destination == "serviceworker") {
request->destination = network::mojom::RequestDestination::kServiceWorker;
} else if (destination == "style") {
request->destination = network::mojom::RequestDestination::kStyle;
} else if (destination == "track") {
request->destination = network::mojom::RequestDestination::kTrack;
} else if (destination == "video") {
request->destination = network::mojom::RequestDestination::kVideo;
} else if (destination == "worker") {
request->destination = network::mojom::RequestDestination::kWorker;
} else if (destination == "xslt") {
request->destination = network::mojom::RequestDestination::kXslt;
}
}
bool credentials_specified =
opts.Get("credentials", &request->credentials_mode);
std::vector<std::pair<std::string, std::string>> extra_headers;
if (opts.Get("extraHeaders", &extra_headers)) {
for (const auto& it : extra_headers) {
if (!net::HttpUtil::IsValidHeaderName(it.first) ||
!net::HttpUtil::IsValidHeaderValue(it.second)) {
args->ThrowTypeError("Invalid header name or value");
return gin::Handle<SimpleURLLoaderWrapper>();
}
request->headers.SetHeader(it.first, it.second);
}
}
bool use_session_cookies = false;
opts.Get("useSessionCookies", &use_session_cookies);
int options = 0;
if (!credentials_specified && !use_session_cookies) {
// This is the default case, as well as the case when credentials is not
// specified and useSessionCookies is false. credentials_mode will be
// kInclude, but cookies will be blocked.
request->credentials_mode = network::mojom::CredentialsMode::kInclude;
options |= network::mojom::kURLLoadOptionBlockAllCookies;
}
v8::Local<v8::Value> body;
v8::Local<v8::Value> chunk_pipe_getter;
if (opts.Get("body", &body)) {
if (body->IsArrayBufferView()) {
auto buffer_body = body.As<v8::ArrayBufferView>();
auto backing_store = buffer_body->Buffer()->GetBackingStore();
request->request_body = network::ResourceRequestBody::CreateFromBytes(
static_cast<char*>(backing_store->Data()) + buffer_body->ByteOffset(),
buffer_body->ByteLength());
} else if (body->IsFunction()) {
auto body_func = body.As<v8::Function>();
mojo::PendingRemote<network::mojom::ChunkedDataPipeGetter>
data_pipe_getter;
chunk_pipe_getter = JSChunkedDataPipeGetter::Create(
args->isolate(), body_func,
data_pipe_getter.InitWithNewPipeAndPassReceiver())
.ToV8();
request->request_body =
base::MakeRefCounted<network::ResourceRequestBody>();
request->request_body->SetToChunkedDataPipe(
std::move(data_pipe_getter),
network::ResourceRequestBody::ReadOnlyOnce(false));
}
}
std::string partition;
gin::Handle<Session> session;
if (!opts.Get("session", &session)) {
if (opts.Get("partition", &partition))
session = Session::FromPartition(args->isolate(), partition);
else // default session
session = Session::FromPartition(args->isolate(), "");
}
auto url_loader_factory = session->browser_context()->GetURLLoaderFactory();
auto ret = gin::CreateHandle(
args->isolate(),
new SimpleURLLoaderWrapper(std::move(request), url_loader_factory.get(),
options));
ret->Pin();
if (!chunk_pipe_getter.IsEmpty()) {
ret->PinBodyGetter(chunk_pipe_getter);
}
return ret;
}
void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece,
base::OnceClosure resume) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto array_buffer = v8::ArrayBuffer::New(isolate, string_piece.size());
auto backing_store = array_buffer->GetBackingStore();
memcpy(backing_store->Data(), string_piece.data(), string_piece.size());
Emit("data", array_buffer,
base::AdaptCallbackForRepeating(std::move(resume)));
}
void SimpleURLLoaderWrapper::OnComplete(bool success) {
if (success) {
Emit("complete");
} else {
Emit("error", net::ErrorToString(loader_->NetError()));
}
loader_.reset();
pinned_wrapper_.Reset();
pinned_chunk_pipe_getter_.Reset();
}
void SimpleURLLoaderWrapper::OnRetry(base::OnceClosure start_retry) {}
void SimpleURLLoaderWrapper::OnResponseStarted(
const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("statusCode", response_head.headers->response_code());
dict.Set("statusMessage", response_head.headers->GetStatusText());
dict.Set("httpVersion", response_head.headers->GetHttpVersion());
// Note that |response_head.headers| are filtered by Chromium and should not
// be used here.
DCHECK(!response_head.raw_response_headers.empty());
dict.Set("rawHeaders", response_head.raw_response_headers);
Emit("response-started", final_url, dict);
}
void SimpleURLLoaderWrapper::OnRedirect(
const net::RedirectInfo& redirect_info,
const network::mojom::URLResponseHead& response_head,
std::vector<std::string>* removed_headers) {
Emit("redirect", redirect_info, response_head.headers.get());
}
void SimpleURLLoaderWrapper::OnUploadProgress(uint64_t position,
uint64_t total) {
Emit("upload-progress", position, total);
}
void SimpleURLLoaderWrapper::OnDownloadProgress(uint64_t current) {
Emit("download-progress", current);
}
// static
gin::ObjectTemplateBuilder SimpleURLLoaderWrapper::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin_helper::EventEmitterMixin<
SimpleURLLoaderWrapper>::GetObjectTemplateBuilder(isolate)
.SetMethod("cancel", &SimpleURLLoaderWrapper::Cancel);
}
const char* SimpleURLLoaderWrapper::GetTypeName() {
return "SimpleURLLoaderWrapper";
}
} // namespace electron::api
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
spec/api-net-spec.ts
|
import { expect } from 'chai';
import * as dns from 'dns';
import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions } from 'electron/main';
import * as http from 'http';
import * as url from 'url';
import { AddressInfo, Socket } from 'net';
import { emittedOnce } from './events-helpers';
import { defer, delay } from './spec-helpers';
// See https://github.com/nodejs/node/issues/40702.
dns.setDefaultResultOrder('ipv4first');
const kOneKiloByte = 1024;
const kOneMegaByte = kOneKiloByte * kOneKiloByte;
function randomBuffer (size: number, start: number = 0, end: number = 255) {
const range = 1 + end - start;
const buffer = Buffer.allocUnsafe(size);
for (let i = 0; i < size; ++i) {
buffer[i] = start + Math.floor(Math.random() * range);
}
return buffer;
}
function randomString (length: number) {
const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
return buffer.toString();
}
async function getResponse (urlRequest: Electron.ClientRequest) {
return new Promise<Electron.IncomingMessage>((resolve, reject) => {
urlRequest.on('error', reject);
urlRequest.on('abort', reject);
urlRequest.on('response', (response) => resolve(response));
urlRequest.end();
});
}
async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
return (await collectStreamBodyBuffer(response)).toString();
}
function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
return new Promise<Buffer>((resolve, reject) => {
response.on('error', reject);
(response as NodeJS.EventEmitter).on('aborted', reject);
const data: Buffer[] = [];
response.on('data', (chunk) => data.push(chunk));
response.on('end', (chunk?: Buffer) => {
if (chunk) data.push(chunk);
resolve(Buffer.concat(data));
});
});
}
function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
return new Promise((resolve) => {
const server = http.createServer((request, response) => {
fn(request, response);
// don't close if a redirect was returned
if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
n--;
server.close();
}
});
server.listen(0, '127.0.0.1', () => {
resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
});
const sockets: Socket[] = [];
server.on('connection', s => sockets.push(s));
defer(() => {
server.close();
sockets.forEach(s => s.destroy());
});
});
}
function respondOnce (fn: http.RequestListener) {
return respondNTimes(fn, 1);
}
let routeFailure = false;
respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
return respondNTimes((request, response) => {
if (Object.prototype.hasOwnProperty.call(routes, request.url || '')) {
(async () => {
await Promise.resolve(routes[request.url || ''](request, response));
})().catch((err) => {
routeFailure = true;
console.error('Route handler failed, this is probably why your test failed', err);
response.statusCode = 500;
response.end();
});
} else {
response.statusCode = 500;
response.end();
expect.fail(`Unexpected URL: ${request.url}`);
}
}, n);
};
respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
return respondNTimes.toRoutes({ [url]: fn }, n);
};
respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
const requestUrl = '/requestUrl';
return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
};
respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
describe('net module', () => {
beforeEach(() => {
routeFailure = false;
});
afterEach(async function () {
await session.defaultSession.clearCache();
if (routeFailure && this.test) {
if (!this.test.isFailed()) {
throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
}
}
});
describe('HTTP basics', () => {
it('should be able to issue a basic GET request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to issue a basic POST request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('POST');
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should fetch correct data in a GET request', async () => {
const expectedBodyData = 'Hello World!';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end(expectedBodyData);
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
const body = await collectStreamBody(response);
expect(body).to.equal(expectedBodyData);
});
it('should post the correct data in a POST request', async () => {
const bodyData = 'Hello World!';
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const postedBodyData = await collectStreamBody(request);
expect(postedBodyData).to.equal(bodyData);
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
urlRequest.write(bodyData);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should support chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.chunkedEncoding = true;
expect(request.method).to.equal('POST');
expect(request.headers['transfer-encoding']).to.equal('chunked');
expect(request.headers['content-length']).to.equal(undefined);
request.on('data', (chunk: Buffer) => {
response.write(chunk);
});
request.on('end', (chunk: Buffer) => {
response.end(chunk);
});
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
let chunkIndex = 0;
const chunkCount = 100;
let sent = Buffer.alloc(0);
urlRequest.chunkedEncoding = true;
while (chunkIndex < chunkCount) {
chunkIndex += 1;
const chunk = randomBuffer(kOneKiloByte);
sent = Buffer.concat([sent, chunk]);
urlRequest.write(chunk);
}
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
const received = await collectStreamBodyBuffer(response);
expect(sent.equals(received)).to.be.true();
expect(chunkIndex).to.be.equal(chunkCount);
});
for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
it('should emit the login event when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
let loginAuthInfo: Electron.AuthInfo;
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
loginAuthInfo = authInfo;
cb(user, pass);
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(200);
expect(loginAuthInfo!.realm).to.equal('Foo');
expect(loginAuthInfo!.scheme).to.equal('basic');
});
it('should receive 401 response when cancelling authentication', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
response.end('unauthenticated');
} else {
response.writeHead(200).end('ok');
}
});
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(401);
expect(body).to.equal('unauthenticated');
});
it('should share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
await collectStreamBody(response);
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should upload body when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200);
request.on('data', (chunk) => response.write(chunk));
request.on('end', () => response.end());
});
const requestData = randomString(kOneKiloByte);
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb(user, pass);
});
request.write(requestData);
const response = await getResponse(request);
const responseData = await collectStreamBody(response);
expect(responseData).to.equal(requestData);
});
});
}
describe('authentication when {"credentials":"omit"}', () => {
it('should not emit the login event when 401', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail('unexpected login event');
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should not share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
});
});
});
describe('ClientRequest API', () => {
it('request/response objects should emit expected events', async () => {
const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end(bodyData);
});
const urlRequest = net.request(serverUrl);
// request close event
const closePromise = emittedOnce(urlRequest, 'close');
// request finish event
const finishPromise = emittedOnce(urlRequest, 'close');
// request "response" event
const response = await getResponse(urlRequest);
response.on('error', (error: Error) => {
expect(error).to.be.an('Error');
});
const statusCode = response.statusCode;
expect(statusCode).to.equal(200);
// response data event
// respond end event
const body = await collectStreamBody(response);
expect(body).to.equal(bodyData);
urlRequest.on('error', (error) => {
expect(error).to.be.an('Error');
});
await Promise.all([closePromise, finishPromise]);
});
it('should be able to set a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set a non-string object as a header value', async () => {
const customHeaderName = 'Some-Integer-Value';
const customHeaderValue = 900;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue as any);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not change the case of header name', async () => {
const customHeaderName = 'X-Header-Name';
const customHeaderValue = 'value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to set a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.write('');
expect(() => {
urlRequest.setHeader(customHeaderName, customHeaderValue);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to remove a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.removeHeader(customHeaderName);
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to remove a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
expect(() => {
urlRequest.removeHeader(customHeaderName);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should keep the order of headers', async () => {
const customHeaderNameA = 'X-Header-100';
const customHeaderNameB = 'X-Header-200';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
const headerNames = Array.from(Object.keys(request.headers));
const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
expect(headerBIndex).to.be.below(headerAIndex);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderNameB, 'b');
urlRequest.setHeader(customHeaderNameA, 'a');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set cookie header line', async () => {
const cookieHeaderName = 'Cookie';
const cookieHeaderValue = 'test=12345';
const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
await customSession.cookies.set({
url: `${serverUrl}`,
name: 'test',
value: '11111',
expirationDate: 0
});
const urlRequest = net.request({
method: 'GET',
url: serverUrl,
session: customSession
});
urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to receive cookies', async () => {
const cookie = ['cookie1', 'cookie2'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', cookie);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.headers['set-cookie']).to.have.same.members(cookie);
});
it('should not use the sessions cookie store by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', `${request.headers.cookie!}`);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
});
for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`when ${JSON.stringify(extraOptions)}`, () => {
it('should be able to use the sessions cookie store', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', request.headers.cookie!);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
});
it('should be able to use the sessions cookie store with set-cookie', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', 'foo=bar');
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
await collectStreamBody(await getResponse(urlRequest));
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'foo',
value: 'bar',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: 'unspecified'
});
});
['Lax', 'Strict'].forEach((mode) => {
it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
response.setHeader('x-cookie', `${request.headers.cookie}`);
response.end();
}, 2);
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
await collectStreamBody(response);
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'same',
value: 'site',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: mode.toLowerCase()
});
const urlRequest2 = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response2 = await getResponse(urlRequest2);
expect(response2.headers['x-cookie']).to.equal('same=site');
});
});
it('should be able to use the sessions cookie store safely across redirects', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
response.statusCode = 302;
response.statusMessage = 'Moved';
const newUrl = await respondOnce.toSingleURL((req, res) => {
res.statusCode = 200;
res.statusMessage = 'OK';
res.setHeader('x-cookie', req.headers.cookie!);
res.end();
});
response.setHeader('x-cookie', request.headers.cookie!);
response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookie127Val = `${Date.now()}-127`;
const cookieLocalVal = `${Date.now()}-local`;
const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
expect(localhostUrl).to.not.equal(serverUrl);
// cookies with lax or strict same-site settings will not
// persist after redirects. no_restriction must be used
await Promise.all([
sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookie127Val
}), sess.cookies.set({
url: localhostUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookieLocalVal
})
]);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
urlRequest.on('redirect', (status, method, url, headers) => {
// The initial redirect response should have received the 127 value here
expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
urlRequest.followRedirect();
});
const response = await getResponse(urlRequest);
// We expect the server to have received the localhost value here
// The original request was to a 127.0.0.1 URL
// That request would have the cookie127Val cookie attached
// The request is then redirect to a localhost URL (different site)
// Because we are using the session cookie store it should do the safe / secure thing
// and attach the cookies for the new target domain
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
});
});
}
describe('when {"credentials":"omit"}', () => {
it('should not send cookies');
it('should not store cookies');
});
it('should set sec-fetch-site to same-origin for request from same origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.setHeader('Origin', serverUrl);
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-site to cross-site for request from other origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('cross-site');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: 'https://not-exists.com'
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should not send sec-fetch-user header by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers).not.to.have.property('sec-fetch-user');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-user to ?1 if requested', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-user']).to.equal('?1');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.setHeader('sec-fetch-user', '?1');
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-mode to no-cors by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => {
it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal(mode);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
urlRequest.setHeader('sec-fetch-mode', mode);
await collectStreamBody(await getResponse(urlRequest));
});
});
it('should set sec-fetch-dest to empty by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal('empty');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
[
'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
'report', 'script', 'serviceworker', 'style', 'track', 'video',
'worker', 'xslt'
].forEach((dest) => {
it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal(dest);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
urlRequest.setHeader('sec-fetch-dest', dest);
await collectStreamBody(await getResponse(urlRequest));
});
});
it('should be able to abort an HTTP request before first write', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
expect.fail('Unexpected request event');
});
const urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('unexpected response event');
});
const aborted = emittedOnce(urlRequest, 'abort');
urlRequest.abort();
urlRequest.write('');
urlRequest.end();
await aborted;
});
it('it should be able to abort an HTTP request before request end', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL(() => {
requestReceivedByServer = true;
urlRequest!.abort();
});
let requestAbortEventEmitted = false;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
expect.fail('Unexpected finish event');
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.on('abort', () => {
requestAbortEventEmitted = true;
});
await emittedOnce(urlRequest, 'close', () => {
urlRequest!.chunkedEncoding = true;
urlRequest!.write(randomString(kOneKiloByte));
});
expect(requestReceivedByServer).to.equal(true);
expect(requestAbortEventEmitted).to.equal(true);
});
it('it should be able to abort an HTTP request after request end and before response', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
requestReceivedByServer = true;
urlRequest!.abort();
process.nextTick(() => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
});
let requestFinishEventEmitted = false;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.equal(true);
expect(requestReceivedByServer).to.equal(true);
});
it('it should be able to abort an HTTP request after response start', async () => {
let requestReceivedByServer = false;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
requestReceivedByServer = true;
response.statusCode = 200;
response.statusMessage = 'OK';
response.write(randomString(kOneKiloByte));
});
let requestFinishEventEmitted = false;
let requestResponseEventEmitted = false;
let responseCloseEventEmitted = false;
const urlRequest = net.request(serverUrl);
urlRequest.on('response', (response) => {
requestResponseEventEmitted = true;
const statusCode = response.statusCode;
expect(statusCode).to.equal(200);
response.on('data', () => {});
response.on('end', () => {
expect.fail('Unexpected end event');
});
response.on('error', () => {
expect.fail('Unexpected error event');
});
response.on('close' as any, () => {
responseCloseEventEmitted = true;
});
urlRequest.abort();
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
expect(requestReceivedByServer).to.be.true('request should be received by the server');
expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
});
it('abort event should be emitted at most once', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL(() => {
requestReceivedByServer = true;
urlRequest!.abort();
urlRequest!.abort();
});
let requestFinishEventEmitted = false;
let abortsEmitted = 0;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.on('abort', () => {
abortsEmitted++;
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
expect(requestReceivedByServer).to.be.true('request should be received by server');
expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
});
it('should allow to read response body from non-2xx response', async () => {
const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 404;
response.end(bodyData);
});
const urlRequest = net.request(serverUrl);
const bodyCheckPromise = getResponse(urlRequest).then(r => {
expect(r.statusCode).to.equal(404);
return r;
}).then(collectStreamBody).then(receivedBodyData => {
expect(receivedBodyData.toString()).to.equal(bodyData);
});
const eventHandlers = Promise.all([
bodyCheckPromise,
emittedOnce(urlRequest, 'close')
]);
urlRequest.end();
await eventHandlers;
});
describe('webRequest', () => {
afterEach(() => {
session.defaultSession.webRequest.onBeforeRequest(null);
});
it('Should throw when invalid filters are passed', () => {
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
});
it('Should not throw when valid filters are passed', () => {
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com/'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.not.throw();
});
it('Requests should be intercepted by webRequest module', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
let requestIsIntercepted = false;
session.defaultSession.webRequest.onBeforeRequest(
(details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request(`${serverUrl}${requestUrl}`);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
it('should to able to create and intercept a request using a custom session object', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
const customPartitionName = `custom-partition-${Math.random()}`;
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
session.defaultSession.webRequest.onBeforeRequest(() => {
expect.fail('Request should not be intercepted by the default session');
});
const customSession = session.fromPartition(customPartitionName, { cache: false });
let requestIsIntercepted = false;
customSession.webRequest.onBeforeRequest((details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`,
session: customSession
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
it('should to able to create and intercept a request using a custom partition name', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
const customPartitionName = `custom-partition-${Math.random()}`;
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
session.defaultSession.webRequest.onBeforeRequest(() => {
expect.fail('Request should not be intercepted by the default session');
});
const customSession = session.fromPartition(customPartitionName, { cache: false });
let requestIsIntercepted = false;
customSession.webRequest.onBeforeRequest((details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`,
partition: customPartitionName
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
});
it('should throw when calling getHeader without a name', () => {
expect(() => {
(net.request({ url: 'https://test' }).getHeader as any)();
}).to.throw(/`name` is required for getHeader\(name\)/);
expect(() => {
net.request({ url: 'https://test' }).getHeader(null as any);
}).to.throw(/`name` is required for getHeader\(name\)/);
});
it('should throw when calling removeHeader without a name', () => {
expect(() => {
(net.request({ url: 'https://test' }).removeHeader as any)();
}).to.throw(/`name` is required for removeHeader\(name\)/);
expect(() => {
net.request({ url: 'https://test' }).removeHeader(null as any);
}).to.throw(/`name` is required for removeHeader\(name\)/);
});
it('should follow redirect when no redirect handler is provided', async () => {
const requestUrl = '/302';
const serverUrl = await respondOnce.toRoutes({
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should follow redirect chain when no redirect handler is provided', async () => {
const serverUrl = await respondOnce.toRoutes({
'/redirectChain': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/302');
response.end();
},
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({
url: `${serverUrl}/redirectChain`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should not follow redirect when request is canceled in redirect handler', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.end();
urlRequest.on('redirect', () => { urlRequest.abort(); });
urlRequest.on('error', () => {});
await emittedOnce(urlRequest, 'abort');
});
it('should not follow redirect when mode is error', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
});
const urlRequest = net.request({
url: serverUrl,
redirect: 'error'
});
urlRequest.end();
await emittedOnce(urlRequest, 'error');
});
it('should follow redirect when handler calls callback', async () => {
const serverUrl = await respondOnce.toRoutes({
'/redirectChain': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/302');
response.end();
},
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
const redirects: string[] = [];
urlRequest.on('redirect', (status, method, url) => {
redirects.push(url);
urlRequest.followRedirect();
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(redirects).to.deep.equal([
`${serverUrl}/302`,
`${serverUrl}/200`
]);
});
it('should throw if given an invalid session option', () => {
expect(() => {
net.request({
url: 'https://foo',
session: 1 as any
});
}).to.throw('`session` should be an instance of the Session class');
});
it('should throw if given an invalid partition option', () => {
expect(() => {
net.request({
url: 'https://foo',
partition: 1 as any
});
}).to.throw('`partition` should be a string');
});
it('should be able to create a request with options', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
expect(request.method).to.equal('GET');
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const serverUrl = url.parse(serverUrlUnparsed);
const options = {
port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
hostname: '127.0.0.1',
headers: { [customHeaderName]: customHeaderValue }
};
const urlRequest = net.request(options);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.be.equal(200);
await collectStreamBody(response);
});
it('should be able to pipe a readable stream into a net request', async () => {
const bodyData = randomString(kOneMegaByte);
let netRequestReceived = false;
let netRequestEnded = false;
const [nodeServerUrl, netServerUrl] = await Promise.all([
respondOnce.toSingleURL((request, response) => response.end(bodyData)),
respondOnce.toSingleURL((request, response) => {
netRequestReceived = true;
let receivedBodyData = '';
request.on('data', (chunk) => {
receivedBodyData += chunk.toString();
});
request.on('end', (chunk: Buffer | undefined) => {
netRequestEnded = true;
if (chunk) {
receivedBodyData += chunk.toString();
}
expect(receivedBodyData).to.be.equal(bodyData);
response.end();
});
})
]);
const nodeRequest = http.request(nodeServerUrl);
const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
const netRequest = net.request(netServerUrl);
const responsePromise = emittedOnce(netRequest, 'response');
// TODO(@MarshallOfSound) - FIXME with #22730
nodeResponse.pipe(netRequest as any);
const [netResponse] = await responsePromise;
expect(netResponse.statusCode).to.equal(200);
await collectStreamBody(netResponse);
expect(netRequestReceived).to.be.true('net request received');
expect(netRequestEnded).to.be.true('net request ended');
});
it('should report upload progress', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const netRequest = net.request({ url: serverUrl, method: 'POST' });
expect(netRequest.getUploadProgress()).to.have.property('active', false);
netRequest.end(Buffer.from('hello'));
const [position, total] = await emittedOnce(netRequest, 'upload-progress');
expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
});
it('should emit error event on server socket destroy', async () => {
const serverUrl = await respondOnce.toSingleURL((request) => {
request.socket.destroy();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
const [error] = await emittedOnce(urlRequest, 'error');
expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
});
it('should emit error event on server request destroy', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
request.destroy();
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end(randomBuffer(kOneMegaByte));
const [error] = await emittedOnce(urlRequest, 'error');
expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
});
it('should not emit any event after close', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
await emittedOnce(urlRequest, 'close');
await new Promise((resolve, reject) => {
['finish', 'abort', 'close', 'error'].forEach(evName => {
urlRequest.on(evName as any, () => {
reject(new Error(`Unexpected ${evName} event`));
});
});
setTimeout(resolve, 50);
});
});
it('should remove the referer header when no referrer url specified', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers.referer).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should set the referer header when a referrer url specified', async () => {
const referrerURL = 'https://www.electronjs.org/';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers.referer).to.equal(referrerURL);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader('referer', referrerURL);
urlRequest.end();
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
});
describe('IncomingMessage API', () => {
it('response object should implement the IncomingMessage API', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader(customHeaderName, customHeaderValue);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
const headerValue = headers[customHeaderName.toLowerCase()];
expect(headerValue).to.equal(customHeaderValue);
const rawHeaders = response.rawHeaders;
expect(rawHeaders).to.be.an('array');
expect(rawHeaders[0]).to.equal(customHeaderName);
expect(rawHeaders[1]).to.equal(customHeaderValue);
const httpVersion = response.httpVersion;
expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
const httpVersionMajor = response.httpVersionMajor;
expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
const httpVersionMinor = response.httpVersionMinor;
expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
await collectStreamBody(response);
});
it('should discard duplicate headers', async () => {
const includedHeader = 'max-forwards';
const discardableHeader = 'Max-Forwards';
const includedHeaderValue = 'max-fwds-val';
const discardableHeaderValue = 'max-fwds-val-two';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader(discardableHeader, discardableHeaderValue);
response.setHeader(includedHeader, includedHeaderValue);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property(includedHeader);
expect(headers).to.not.have.property(discardableHeader);
expect(headers[includedHeader]).to.equal(includedHeaderValue);
await collectStreamBody(response);
});
it('should join repeated non-discardable header values with ,', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('referrer-policy', ['first-text', 'second-text']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('referrer-policy');
expect(headers['referrer-policy']).to.equal('first-text, second-text');
await collectStreamBody(response);
});
it('should not join repeated discardable header values with ,', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('last-modified', ['yesterday', 'today']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('last-modified');
expect(headers['last-modified']).to.equal('yesterday');
await collectStreamBody(response);
});
it('should make set-cookie header an array even if single value', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', 'chocolate-chip');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('set-cookie');
expect(headers['set-cookie']).to.be.an('array');
expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
await collectStreamBody(response);
});
it('should keep set-cookie header an array when an array', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('set-cookie');
expect(headers['set-cookie']).to.be.an('array');
expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
expect(headers['set-cookie'][1]).to.equal('oatmeal');
await collectStreamBody(response);
});
it('should lowercase header keys', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('HEADER-KEY', ['header-value']);
response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
response.setHeader('LAST-modified', 'yesterday');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('header-key');
expect(headers).to.have.property('set-cookie');
expect(headers).to.have.property('referrer-policy');
expect(headers).to.have.property('last-modified');
await collectStreamBody(response);
});
it('should return correct raw headers', async () => {
const customHeaders: [string, string|string[]][] = [
['HEADER-KEY-ONE', 'header-value-one'],
['set-cookie', 'chocolate-chip'],
['header-key-two', 'header-value-two'],
['referrer-policy', ['first-text', 'second-text']],
['HEADER-KEY-THREE', 'header-value-three'],
['last-modified', ['first-text', 'second-text']],
['header-key-four', 'header-value-four']
];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
customHeaders.forEach((headerTuple) => {
response.setHeader(headerTuple[0], headerTuple[1]);
});
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const rawHeaders = response.rawHeaders;
expect(rawHeaders).to.be.an('array');
let rawHeadersIdx = 0;
customHeaders.forEach((headerTuple) => {
const headerKey = headerTuple[0];
const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
headerValues.forEach((headerValue) => {
expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
rawHeadersIdx += 2;
});
});
await collectStreamBody(response);
});
it('should be able to pipe a net response into a writable stream', async () => {
const bodyData = randomString(kOneKiloByte);
let nodeRequestProcessed = false;
const [netServerUrl, nodeServerUrl] = await Promise.all([
respondOnce.toSingleURL((request, response) => response.end(bodyData)),
respondOnce.toSingleURL(async (request, response) => {
const receivedBodyData = await collectStreamBody(request);
expect(receivedBodyData).to.be.equal(bodyData);
nodeRequestProcessed = true;
response.end();
})
]);
const netRequest = net.request(netServerUrl);
const netResponse = await getResponse(netRequest);
const serverUrl = url.parse(nodeServerUrl);
const nodeOptions = {
method: 'POST',
path: serverUrl.path,
port: serverUrl.port
};
const nodeRequest = http.request(nodeOptions);
const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
// TODO(@MarshallOfSound) - FIXME with #22730
(netResponse as any).pipe(nodeRequest);
const [nodeResponse] = await nodeResponsePromise;
netRequest.end();
await collectStreamBody(nodeResponse);
expect(nodeRequestProcessed).to.equal(true);
});
it('should correctly throttle an incoming stream', async () => {
let numChunksSent = 0;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
const data = randomString(kOneMegaByte);
const write = () => {
let ok = true;
do {
numChunksSent++;
if (numChunksSent > 30) return;
ok = response.write(data);
} while (ok);
response.once('drain', write);
};
write();
});
const urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {});
urlRequest.end();
await delay(2000);
// TODO(nornagon): I think this ought to max out at 20, but in practice
// it seems to exceed that sometimes. This is at 25 to avoid test flakes,
// but we should investigate if there's actually something broken here and
// if so fix it and reset this to max at 20, and if not then delete this
// comment.
expect(numChunksSent).to.be.at.most(25);
});
});
describe('net.isOnline', () => {
it('getter returns boolean', () => {
expect(net.isOnline()).to.be.a('boolean');
});
it('property returns boolean', () => {
expect(net.online).to.be.a('boolean');
});
});
describe('Stability and performance', () => {
it('should free unreferenced, never-started request objects without crash', (done) => {
net.request('https://test');
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
done();
});
});
it('should collect on-going requests without crash', async () => {
let finishResponse: (() => void) | null = null;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.write(randomString(kOneKiloByte));
finishResponse = () => {
response.write(randomString(kOneKiloByte));
response.end();
};
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
process.nextTick(() => {
// Trigger a garbage collection.
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
finishResponse!();
});
await collectStreamBody(response);
});
it('should collect unreferenced, ended requests without crash', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const urlRequest = net.request(serverUrl);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
const response = await getResponse(urlRequest);
await collectStreamBody(response);
});
it('should finish sending data when urlRequest is unreferenced', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
expect(received.length).to.equal(kOneMegaByte);
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.write(randomBuffer(kOneMegaByte));
const response = await getResponse(urlRequest);
await collectStreamBody(response);
});
it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
const response = await getResponse(urlRequest);
await collectStreamBody(response);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
await collectStreamBody(await getResponse(urlRequest));
});
it('should finish sending data when urlRequest is unreferenced', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.write(randomBuffer(kOneMegaByte));
await collectStreamBody(await getResponse(urlRequest));
});
it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
await collectStreamBody(await getResponse(urlRequest));
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
typings/internal-ambient.d.ts
|
/* eslint-disable no-var */
declare var internalBinding: any;
declare var binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function };
declare var isolatedApi: {
guestViewInternal: any;
allowGuestViewElementDefinition: NodeJS.InternalWebFrame['allowGuestViewElementDefinition'];
setIsWebView: (iframe: HTMLIFrameElement) => void;
}
declare const BUILDFLAG: (flag: boolean) => boolean;
declare const ENABLE_DESKTOP_CAPTURER: boolean;
declare const ENABLE_VIEWS_API: boolean;
declare namespace NodeJS {
interface FeaturesBinding {
isBuiltinSpellCheckerEnabled(): boolean;
isDesktopCapturerEnabled(): boolean;
isOffscreenRenderingEnabled(): boolean;
isPDFViewerEnabled(): boolean;
isRunAsNodeEnabled(): boolean;
isFakeLocationProviderEnabled(): boolean;
isViewApiEnabled(): boolean;
isTtsEnabled(): boolean;
isPrintingEnabled(): boolean;
isPictureInPictureEnabled(): boolean;
isExtensionsEnabled(): boolean;
isComponentBuild(): boolean;
}
interface IpcRendererBinding {
send(internal: boolean, channel: string, args: any[]): void;
sendSync(internal: boolean, channel: string, args: any[]): any;
sendToHost(channel: string, args: any[]): void;
sendTo(webContentsId: number, channel: string, args: any[]): void;
invoke<T>(internal: boolean, channel: string, args: any[]): Promise<{ error: string, result: T }>;
postMessage(channel: string, message: any, transferables: MessagePort[]): void;
}
interface V8UtilBinding {
getHiddenValue<T>(obj: any, key: string): T;
setHiddenValue<T>(obj: any, key: string, value: T): void;
deleteHiddenValue(obj: any, key: string): void;
requestGarbageCollectionForTesting(): void;
runUntilIdle(): void;
triggerFatalErrorForTesting(): void;
}
interface EnvironmentBinding {
getVar(name: string): string | null;
hasVar(name: string): boolean;
setVar(name: string, value: string): boolean;
unSetVar(name: string): boolean;
}
type AsarFileInfo = {
size: number;
unpacked: boolean;
offset: number;
integrity?: {
algorithm: 'SHA256';
hash: string;
}
};
type AsarFileStat = {
size: number;
offset: number;
isFile: boolean;
isDirectory: boolean;
isLink: boolean;
}
interface AsarArchive {
getFileInfo(path: string): AsarFileInfo | false;
stat(path: string): AsarFileStat | false;
readdir(path: string): string[] | false;
realpath(path: string): string | false;
copyFileOut(path: string): string | false;
getFdAndValidateIntegrityLater(): number | -1;
}
interface AsarBinding {
Archive: { new(path: string): AsarArchive };
splitPath(path: string): {
isAsar: false;
} | {
isAsar: true;
asarPath: string;
filePath: string;
};
initAsarSupport(require: NodeJS.Require): void;
}
interface PowerMonitorBinding extends Electron.PowerMonitor {
createPowerMonitor(): PowerMonitorBinding;
setListeningForShutdown(listening: boolean): void;
}
interface WebViewManagerBinding {
addGuest(guestInstanceId: number, embedder: Electron.WebContents, guest: Electron.WebContents, webPreferences: Electron.WebPreferences): void;
removeGuest(embedder: Electron.WebContents, guestInstanceId: number): void;
}
interface InternalWebPreferences {
isWebView: boolean;
hiddenPage: boolean;
nodeIntegration: boolean;
webviewTag: boolean;
}
interface InternalWebFrame extends Electron.WebFrame {
getWebPreference<K extends keyof InternalWebPreferences>(name: K): InternalWebPreferences[K];
getWebFrameId(window: Window): number;
allowGuestViewElementDefinition(context: object, callback: Function): void;
}
interface WebFrameBinding {
mainFrame: InternalWebFrame;
}
type DataPipe = {
write: (buf: Uint8Array) => Promise<void>;
done: () => void;
};
type BodyFunc = (pipe: DataPipe) => void;
type CreateURLLoaderOptions = {
method: string;
url: string;
extraHeaders?: Record<string, string>;
useSessionCookies?: boolean;
credentials?: 'include' | 'omit';
body: Uint8Array | BodyFunc;
session?: Electron.Session;
partition?: string;
referrer?: string;
origin?: string;
hasUserActivation?: boolean;
mode?: string;
destination?: string;
};
type ResponseHead = {
statusCode: number;
statusMessage: string;
httpVersion: { major: number, minor: number };
rawHeaders: { key: string, value: string }[];
};
type RedirectInfo = {
statusCode: number;
newMethod: string;
newUrl: string;
newSiteForCookies: string;
newReferrer: string;
insecureSchemeWasUpgraded: boolean;
isSignedExchangeFallbackRedirect: boolean;
}
interface URLLoader extends EventEmitter {
cancel(): void;
on(eventName: 'data', listener: (event: any, data: ArrayBuffer, resume: () => void) => void): this;
on(eventName: 'response-started', listener: (event: any, finalUrl: string, responseHead: ResponseHead) => void): this;
on(eventName: 'complete', listener: (event: any) => void): this;
on(eventName: 'error', listener: (event: any, netErrorString: string) => void): this;
on(eventName: 'login', listener: (event: any, authInfo: Electron.AuthInfo, callback: (username?: string, password?: string) => void) => void): this;
on(eventName: 'redirect', listener: (event: any, redirectInfo: RedirectInfo, headers: Record<string, string>) => void): this;
on(eventName: 'upload-progress', listener: (event: any, position: number, total: number) => void): this;
on(eventName: 'download-progress', listener: (event: any, current: number) => void): this;
}
interface Process {
internalBinding?(name: string): any;
_linkedBinding(name: string): any;
_linkedBinding(name: 'electron_common_asar'): AsarBinding;
_linkedBinding(name: 'electron_common_clipboard'): Electron.Clipboard;
_linkedBinding(name: 'electron_common_command_line'): Electron.CommandLine;
_linkedBinding(name: 'electron_common_environment'): EnvironmentBinding;
_linkedBinding(name: 'electron_common_features'): FeaturesBinding;
_linkedBinding(name: 'electron_common_native_image'): { nativeImage: typeof Electron.NativeImage };
_linkedBinding(name: 'electron_common_shell'): Electron.Shell;
_linkedBinding(name: 'electron_common_v8_util'): V8UtilBinding;
_linkedBinding(name: 'electron_browser_app'): { app: Electron.App, App: Function };
_linkedBinding(name: 'electron_browser_auto_updater'): { autoUpdater: Electron.AutoUpdater };
_linkedBinding(name: 'electron_browser_browser_view'): { BrowserView: typeof Electron.BrowserView };
_linkedBinding(name: 'electron_browser_crash_reporter'): Omit<Electron.CrashReporter, 'start'> & {
start(submitUrl: string,
uploadToServer: boolean,
ignoreSystemCrashHandler: boolean,
rateLimit: boolean,
compress: boolean,
globalExtra: Record<string, string>,
extra: Record<string, string>,
isNodeProcess: boolean): void;
};
_linkedBinding(name: 'electron_browser_desktop_capturer'): {
createDesktopCapturer(): ElectronInternal.DesktopCapturer;
};
_linkedBinding(name: 'electron_browser_event'): {
createWithSender(sender: Electron.WebContents): Electron.Event;
createEmpty(): Electron.Event;
};
_linkedBinding(name: 'electron_browser_event_emitter'): {
setEventEmitterPrototype(prototype: Object): void;
};
_linkedBinding(name: 'electron_browser_global_shortcut'): { globalShortcut: Electron.GlobalShortcut };
_linkedBinding(name: 'electron_browser_image_view'): { ImageView: any };
_linkedBinding(name: 'electron_browser_in_app_purchase'): { inAppPurchase: Electron.InAppPurchase };
_linkedBinding(name: 'electron_browser_message_port'): {
createPair(): { port1: Electron.MessagePortMain, port2: Electron.MessagePortMain };
};
_linkedBinding(name: 'electron_browser_native_theme'): { nativeTheme: Electron.NativeTheme };
_linkedBinding(name: 'electron_browser_net'): {
isOnline(): boolean;
isValidHeaderName: (headerName: string) => boolean;
isValidHeaderValue: (headerValue: string) => boolean;
fileURLToFilePath: (url: string) => string;
Net: any;
net: any;
createURLLoader(options: CreateURLLoaderOptions): URLLoader;
};
_linkedBinding(name: 'electron_browser_notification'): {
isSupported(): boolean;
Notification: typeof Electron.Notification;
}
_linkedBinding(name: 'electron_browser_power_monitor'): PowerMonitorBinding;
_linkedBinding(name: 'electron_browser_power_save_blocker'): { powerSaveBlocker: Electron.PowerSaveBlocker };
_linkedBinding(name: 'electron_browser_push_notifications'): { pushNotifications: Electron.PushNotifications };
_linkedBinding(name: 'electron_browser_safe_storage'): { safeStorage: Electron.SafeStorage };
_linkedBinding(name: 'electron_browser_session'): typeof Electron.Session;
_linkedBinding(name: 'electron_browser_screen'): { createScreen(): Electron.Screen };
_linkedBinding(name: 'electron_browser_system_preferences'): { systemPreferences: Electron.SystemPreferences };
_linkedBinding(name: 'electron_browser_tray'): { Tray: Electron.Tray };
_linkedBinding(name: 'electron_browser_view'): { View: Electron.View };
_linkedBinding(name: 'electron_browser_web_contents_view'): { WebContentsView: typeof Electron.WebContentsView };
_linkedBinding(name: 'electron_browser_web_view_manager'): WebViewManagerBinding;
_linkedBinding(name: 'electron_browser_web_frame_main'): {
WebFrameMain: typeof Electron.WebFrameMain;
fromId(processId: number, routingId: number): Electron.WebFrameMain;
fromIdOrNull(processId: number, routingId: number): Electron.WebFrameMain | null;
}
_linkedBinding(name: 'electron_renderer_crash_reporter'): Electron.CrashReporter;
_linkedBinding(name: 'electron_renderer_ipc'): { ipc: IpcRendererBinding };
_linkedBinding(name: 'electron_renderer_web_frame'): WebFrameBinding;
log: NodeJS.WriteStream['write'];
activateUvLoop(): void;
// Additional events
once(event: 'document-start', listener: () => any): this;
once(event: 'document-end', listener: () => any): this;
// Additional properties
_firstFileName?: string;
_serviceStartupScript: string;
helperExecPath: string;
mainModule?: NodeJS.Module | undefined;
}
}
declare module NodeJS {
interface Global {
require: NodeRequire;
module: NodeModule;
__filename: string;
__dirname: string;
}
}
interface ContextMenuItem {
id: number;
label: string;
type: 'normal' | 'separator' | 'subMenu' | 'checkbox';
checked: boolean;
enabled: boolean;
subItems: ContextMenuItem[];
}
declare interface Window {
ELECTRON_DISABLE_SECURITY_WARNINGS?: boolean;
ELECTRON_ENABLE_SECURITY_WARNINGS?: boolean;
InspectorFrontendHost?: {
showContextMenuAtPoint: (x: number, y: number, items: ContextMenuItem[]) => void
};
DevToolsAPI?: {
contextMenuItemSelected: (id: number) => void;
contextMenuCleared: () => void
};
UI?: {
createFileSelectorElement: (callback: () => void) => HTMLSpanElement
};
Persistence?: {
FileSystemWorkspaceBinding: {
completeURL: (project: string, path: string) => string;
}
};
WebView: typeof ElectronInternal.WebViewElement;
trustedTypes: TrustedTypePolicyFactory;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#trusted-types
type TrustedHTML = string;
type TrustedScript = string;
type TrustedScriptURL = string;
type TrustedType = TrustedHTML | TrustedScript | TrustedScriptURL;
type StringContext = 'TrustedHTML' | 'TrustedScript' | 'TrustedScriptURL';
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicy
interface TrustedTypePolicy {
createHTML(input: string, ...arguments: any[]): TrustedHTML;
createScript(input: string, ...arguments: any[]): TrustedScript;
createScriptURL(input: string, ...arguments: any[]): TrustedScriptURL;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyoptions
interface TrustedTypePolicyOptions {
createHTML?: (input: string, ...arguments: any[]) => TrustedHTML;
createScript?: (input: string, ...arguments: any[]) => TrustedScript;
createScriptURL?: (input: string, ...arguments: any[]) => TrustedScriptURL;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyfactory
interface TrustedTypePolicyFactory {
createPolicy(policyName: string, policyOptions: TrustedTypePolicyOptions): TrustedTypePolicy
isHTML(value: any): boolean;
isScript(value: any): boolean;
isScriptURL(value: any): boolean;
readonly emptyHTML: TrustedHTML;
readonly emptyScript: TrustedScript;
getAttributeType(tagName: string, attribute: string, elementNs?: string, attrNs?: string): StringContext | null;
getPropertyType(tagName: string, property: string, elementNs?: string): StringContext | null;
readonly defaultPolicy: TrustedTypePolicy | null;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
lib/browser/api/net.ts
|
import * as url from 'url';
import { Readable, Writable } from 'stream';
import { app } from 'electron/main';
import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
const {
isOnline,
isValidHeaderName,
isValidHeaderValue,
createURLLoader
} = process._linkedBinding('electron_browser_net');
const kSupportedProtocols = new Set(['http:', 'https:']);
// set of headers that Node.js discards duplicates for
// see https://nodejs.org/api/http.html#http_message_headers
const discardableDuplicateHeaders = new Set([
'content-type',
'content-length',
'user-agent',
'referer',
'host',
'authorization',
'proxy-authorization',
'if-modified-since',
'if-unmodified-since',
'from',
'location',
'max-forwards',
'retry-after',
'etag',
'last-modified',
'server',
'age',
'expires'
]);
class IncomingMessage extends Readable {
_shouldPush: boolean = false;
_data: (Buffer | null)[] = [];
_responseHead: NodeJS.ResponseHead;
_resume: (() => void) | null = null;
constructor (responseHead: NodeJS.ResponseHead) {
super();
this._responseHead = responseHead;
}
get statusCode () {
return this._responseHead.statusCode;
}
get statusMessage () {
return this._responseHead.statusMessage;
}
get headers () {
const filteredHeaders: Record<string, string | string[]> = {};
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
const keyLowerCase = header.key.toLowerCase();
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase) &&
discardableDuplicateHeaders.has(keyLowerCase)) {
// do nothing with discardable duplicate headers
} else {
if (keyLowerCase === 'set-cookie') {
// keep set-cookie as an array per Node.js rules
// see https://nodejs.org/api/http.html#http_message_headers
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) {
(filteredHeaders[keyLowerCase] as string[]).push(header.value);
} else {
filteredHeaders[keyLowerCase] = [header.value];
}
} else {
// for non-cookie headers, the values are joined together with ', '
if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) {
filteredHeaders[keyLowerCase] += `, ${header.value}`;
} else {
filteredHeaders[keyLowerCase] = header.value;
}
}
}
});
return filteredHeaders;
}
get rawHeaders () {
const rawHeadersArr: string[] = [];
const { rawHeaders } = this._responseHead;
rawHeaders.forEach(header => {
rawHeadersArr.push(header.key, header.value);
});
return rawHeadersArr;
}
get httpVersion () {
return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
}
get httpVersionMajor () {
return this._responseHead.httpVersion.major;
}
get httpVersionMinor () {
return this._responseHead.httpVersion.minor;
}
get rawTrailers () {
throw new Error('HTTP trailers are not supported');
}
get trailers () {
throw new Error('HTTP trailers are not supported');
}
_storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
// save the network callback for use in _pushInternalData
this._resume = resume;
this._data.push(chunk);
this._pushInternalData();
}
_pushInternalData () {
while (this._shouldPush && this._data.length > 0) {
const chunk = this._data.shift();
this._shouldPush = this.push(chunk);
}
if (this._shouldPush && this._resume) {
// Reset the callback, so that a new one is used for each
// batch of throttled data. Do this before calling resume to avoid a
// potential race-condition
const resume = this._resume;
this._resume = null;
resume();
}
}
_read () {
this._shouldPush = true;
this._pushInternalData();
}
}
/** Writable stream that buffers up everything written to it. */
class SlurpStream extends Writable {
_data: Buffer;
constructor () {
super();
this._data = Buffer.alloc(0);
}
_write (chunk: Buffer, encoding: string, callback: () => void) {
this._data = Buffer.concat([this._data, chunk]);
callback();
}
data () { return this._data; }
}
class ChunkedBodyStream extends Writable {
_pendingChunk: Buffer | undefined;
_downstream?: NodeJS.DataPipe;
_pendingCallback?: (error?: Error) => void;
_clientRequest: ClientRequest;
constructor (clientRequest: ClientRequest) {
super();
this._clientRequest = clientRequest;
}
_write (chunk: Buffer, encoding: string, callback: () => void) {
if (this._downstream) {
this._downstream.write(chunk).then(callback, callback);
} else {
// the contract of _write is that we won't be called again until we call
// the callback, so we're good to just save a single chunk.
this._pendingChunk = chunk;
this._pendingCallback = callback;
// The first write to a chunked body stream begins the request.
this._clientRequest._startRequest();
}
}
_final (callback: () => void) {
this._downstream!.done();
callback();
}
startReading (pipe: NodeJS.DataPipe) {
if (this._downstream) {
throw new Error('two startReading calls???');
}
this._downstream = pipe;
if (this._pendingChunk) {
const doneWriting = (maybeError: Error | void) => {
// If the underlying request has been aborted, we honestly don't care about the error
// all work should cease as soon as we abort anyway, this error is probably a
// "mojo pipe disconnected" error (code=9)
if (this._clientRequest._aborted) return;
const cb = this._pendingCallback!;
delete this._pendingCallback;
delete this._pendingChunk;
cb(maybeError || undefined);
};
this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
}
}
}
type RedirectPolicy = 'manual' | 'follow' | 'error';
function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } {
const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
let urlStr: string = options.url;
if (!urlStr) {
const urlObj: url.UrlObject = {};
const protocol = options.protocol || 'http:';
if (!kSupportedProtocols.has(protocol)) {
throw new Error('Protocol "' + protocol + '" not supported');
}
urlObj.protocol = protocol;
if (options.host) {
urlObj.host = options.host;
} else {
if (options.hostname) {
urlObj.hostname = options.hostname;
} else {
urlObj.hostname = 'localhost';
}
if (options.port) {
urlObj.port = options.port;
}
}
if (options.path && / /.test(options.path)) {
// The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
// with an additional rule for ignoring percentage-escaped characters
// but that's a) hard to capture in a regular expression that performs
// well, and b) possibly too restrictive for real-world usage. That's
// why it only scans for spaces because those are guaranteed to create
// an invalid request.
throw new TypeError('Request path contains unescaped characters');
}
const pathObj = url.parse(options.path || '/');
urlObj.pathname = pathObj.pathname;
urlObj.search = pathObj.search;
urlObj.hash = pathObj.hash;
urlStr = url.format(urlObj);
}
const redirectPolicy = options.redirect || 'follow';
if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
throw new Error('redirect mode should be one of follow, error or manual');
}
if (options.headers != null && typeof options.headers !== 'object') {
throw new TypeError('headers must be an object');
}
const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }> } = {
method: (options.method || 'GET').toUpperCase(),
url: urlStr,
redirectPolicy,
headers: {},
body: null as any,
useSessionCookies: options.useSessionCookies,
credentials: options.credentials,
origin: options.origin
};
const headers: Record<string, string | string[]> = options.headers || {};
for (const [name, value] of Object.entries(headers)) {
if (!isValidHeaderName(name)) {
throw new Error(`Invalid header name: '${name}'`);
}
if (!isValidHeaderValue(value.toString())) {
throw new Error(`Invalid value for header '${name}': '${value}'`);
}
const key = name.toLowerCase();
urlLoaderOptions.headers[key] = { name, value };
}
if (options.session) {
// Weak check, but it should be enough to catch 99% of accidental misuses.
if (options.session.constructor && options.session.constructor.name === 'Session') {
urlLoaderOptions.session = options.session;
} else {
throw new TypeError('`session` should be an instance of the Session class');
}
} else if (options.partition) {
if (typeof options.partition === 'string') {
urlLoaderOptions.partition = options.partition;
} else {
throw new TypeError('`partition` should be a string');
}
}
return urlLoaderOptions;
}
export class ClientRequest extends Writable implements Electron.ClientRequest {
_started: boolean = false;
_firstWrite: boolean = false;
_aborted: boolean = false;
_chunkedEncoding: boolean | undefined;
_body: Writable | undefined;
_urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
_redirectPolicy: RedirectPolicy;
_followRedirectCb?: () => void;
_uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
_urlLoader?: NodeJS.URLLoader;
_response?: IncomingMessage;
constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
super({ autoDestroy: true });
if (!app.isReady()) {
throw new Error('net module can only be used after app is ready');
}
if (callback) {
this.once('response', callback);
}
const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
this._urlLoaderOptions = urlLoaderOptions;
this._redirectPolicy = redirectPolicy;
}
get chunkedEncoding () {
return this._chunkedEncoding || false;
}
set chunkedEncoding (value: boolean) {
if (this._started) {
throw new Error('chunkedEncoding can only be set before the request is started');
}
if (typeof this._chunkedEncoding !== 'undefined') {
throw new Error('chunkedEncoding can only be set once');
}
this._chunkedEncoding = !!value;
if (this._chunkedEncoding) {
this._body = new ChunkedBodyStream(this);
this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
(this._body! as ChunkedBodyStream).startReading(pipe);
};
}
}
setHeader (name: string, value: string) {
if (typeof name !== 'string') {
throw new TypeError('`name` should be a string in setHeader(name, value)');
}
if (value == null) {
throw new Error('`value` required in setHeader("' + name + '", value)');
}
if (this._started || this._firstWrite) {
throw new Error('Can\'t set headers after they are sent');
}
if (!isValidHeaderName(name)) {
throw new Error(`Invalid header name: '${name}'`);
}
if (!isValidHeaderValue(value.toString())) {
throw new Error(`Invalid value for header '${name}': '${value}'`);
}
const key = name.toLowerCase();
this._urlLoaderOptions.headers[key] = { name, value };
}
getHeader (name: string) {
if (name == null) {
throw new Error('`name` is required for getHeader(name)');
}
const key = name.toLowerCase();
const header = this._urlLoaderOptions.headers[key];
return header && header.value as any;
}
removeHeader (name: string) {
if (name == null) {
throw new Error('`name` is required for removeHeader(name)');
}
if (this._started || this._firstWrite) {
throw new Error('Can\'t remove headers after they are sent');
}
const key = name.toLowerCase();
delete this._urlLoaderOptions.headers[key];
}
_write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
this._firstWrite = true;
if (!this._body) {
this._body = new SlurpStream();
this._body.on('finish', () => {
this._urlLoaderOptions.body = (this._body as SlurpStream).data();
this._startRequest();
});
}
// TODO: is this the right way to forward to another stream?
this._body.write(chunk, encoding, callback);
}
_final (callback: () => void) {
if (this._body) {
// TODO: is this the right way to forward to another stream?
this._body.end(callback);
} else {
// end() called without a body, go ahead and start the request
this._startRequest();
callback();
}
}
_startRequest () {
this._started = true;
const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
const ret: Record<string, string> = {};
for (const k of Object.keys(obj)) {
const kv = obj[k];
ret[kv.name] = kv.value.toString();
}
return ret;
};
this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
this._urlLoader = createURLLoader(opts);
this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
const response = this._response = new IncomingMessage(responseHead);
this.emit('response', response);
});
this._urlLoader.on('data', (event, data, resume) => {
this._response!._storeInternalData(Buffer.from(data), resume);
});
this._urlLoader.on('complete', () => {
if (this._response) { this._response._storeInternalData(null, null); }
});
this._urlLoader.on('error', (event, netErrorString) => {
const error = new Error(netErrorString);
if (this._response) this._response.destroy(error);
this._die(error);
});
this._urlLoader.on('login', (event, authInfo, callback) => {
const handled = this.emit('login', authInfo, callback);
if (!handled) {
// If there were no listeners, cancel the authentication request.
callback();
}
});
this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
const { statusCode, newMethod, newUrl } = redirectInfo;
if (this._redirectPolicy === 'error') {
this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
} else if (this._redirectPolicy === 'manual') {
let _followRedirect = false;
this._followRedirectCb = () => { _followRedirect = true; };
try {
this.emit('redirect', statusCode, newMethod, newUrl, headers);
} finally {
this._followRedirectCb = undefined;
if (!_followRedirect && !this._aborted) {
this._die(new Error('Redirect was cancelled'));
}
}
} else if (this._redirectPolicy === 'follow') {
// Calling followRedirect() when the redirect policy is 'follow' is
// allowed but does nothing. (Perhaps it should throw an error
// though...? Since the redirect will happen regardless.)
try {
this._followRedirectCb = () => {};
this.emit('redirect', statusCode, newMethod, newUrl, headers);
} finally {
this._followRedirectCb = undefined;
}
} else {
this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
}
});
this._urlLoader.on('upload-progress', (event, position, total) => {
this._uploadProgress = { active: true, started: true, current: position, total };
this.emit('upload-progress', position, total); // Undocumented, for now
});
this._urlLoader.on('download-progress', (event, current) => {
if (this._response) {
this._response.emit('download-progress', current); // Undocumented, for now
}
});
}
followRedirect () {
if (this._followRedirectCb) {
this._followRedirectCb();
} else {
throw new Error('followRedirect() called, but was not waiting for a redirect');
}
}
abort () {
if (!this._aborted) {
process.nextTick(() => { this.emit('abort'); });
}
this._aborted = true;
this._die();
}
_die (err?: Error) {
// Node.js assumes that any stream which is ended is no longer capable of emitted events
// which is a faulty assumption for the case of an object that is acting like a stream
// (our urlRequest). If we don't emit here, this causes errors since we *do* expect
// that error events can be emitted after urlRequest.end().
if ((this as any)._writableState.destroyed && err) {
this.emit('error', err);
}
this.destroy(err);
if (this._urlLoader) {
this._urlLoader.cancel();
if (this._response) this._response.destroy(err);
}
}
getUploadProgress (): UploadProgress {
return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
}
}
export function request (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
return new ClientRequest(options, callback);
}
exports.isOnline = isOnline;
Object.defineProperty(exports, 'online', {
get: () => isOnline()
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
shell/browser/api/electron_api_url_loader.cc
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_url_loader.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/no_destructor.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "net/base/load_flags.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h"
#include "services/network/public/mojom/http_raw_headers.mojom.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
namespace gin {
template <>
struct Converter<network::mojom::HttpRawHeaderPairPtr> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const network::mojom::HttpRawHeaderPairPtr& pair) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("key", pair->key);
dict.Set("value", pair->value);
return dict.GetHandle();
}
};
template <>
struct Converter<network::mojom::CredentialsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::CredentialsMode* out) {
std::string mode;
if (!ConvertFromV8(isolate, val, &mode))
return false;
if (mode == "omit")
*out = network::mojom::CredentialsMode::kOmit;
else if (mode == "include")
*out = network::mojom::CredentialsMode::kInclude;
else
// "same-origin" is technically a member of this enum as well, but it
// doesn't make sense in the context of `net.request()`, so don't convert
// it.
return false;
return true;
}
};
} // namespace gin
namespace electron::api {
namespace {
class BufferDataSource : public mojo::DataPipeProducer::DataSource {
public:
explicit BufferDataSource(base::span<char> buffer) {
buffer_.resize(buffer.size());
memcpy(buffer_.data(), buffer.data(), buffer_.size());
}
~BufferDataSource() override = default;
private:
// mojo::DataPipeProducer::DataSource:
uint64_t GetLength() const override { return buffer_.size(); }
ReadResult Read(uint64_t offset, base::span<char> buffer) override {
ReadResult result;
if (offset <= buffer_.size()) {
size_t readable_size = buffer_.size() - offset;
size_t writable_size = buffer.size();
size_t copyable_size = std::min(readable_size, writable_size);
if (copyable_size > 0) {
memcpy(buffer.data(), &buffer_[offset], copyable_size);
}
result.bytes_read = copyable_size;
} else {
NOTREACHED();
result.result = MOJO_RESULT_OUT_OF_RANGE;
}
return result;
}
std::vector<char> buffer_;
};
class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
public network::mojom::ChunkedDataPipeGetter {
public:
static gin::Handle<JSChunkedDataPipeGetter> Create(
v8::Isolate* isolate,
v8::Local<v8::Function> body_func,
mojo::PendingReceiver<network::mojom::ChunkedDataPipeGetter>
chunked_data_pipe_getter) {
return gin::CreateHandle(
isolate, new JSChunkedDataPipeGetter(
isolate, body_func, std::move(chunked_data_pipe_getter)));
}
// gin::Wrappable
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<JSChunkedDataPipeGetter>::GetObjectTemplateBuilder(
isolate)
.SetMethod("write", &JSChunkedDataPipeGetter::WriteChunk)
.SetMethod("done", &JSChunkedDataPipeGetter::Done);
}
static gin::WrapperInfo kWrapperInfo;
~JSChunkedDataPipeGetter() override = default;
private:
JSChunkedDataPipeGetter(
v8::Isolate* isolate,
v8::Local<v8::Function> body_func,
mojo::PendingReceiver<network::mojom::ChunkedDataPipeGetter>
chunked_data_pipe_getter)
: isolate_(isolate), body_func_(isolate, body_func) {
receiver_.Bind(std::move(chunked_data_pipe_getter));
}
// network::mojom::ChunkedDataPipeGetter:
void GetSize(GetSizeCallback callback) override {
size_callback_ = std::move(callback);
}
void StartReading(mojo::ScopedDataPipeProducerHandle pipe) override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (body_func_.IsEmpty()) {
LOG(ERROR) << "Tried to read twice from a JSChunkedDataPipeGetter";
// Drop the handle on the floor.
return;
}
data_producer_ = std::make_unique<mojo::DataPipeProducer>(std::move(pipe));
v8::HandleScope handle_scope(isolate_);
auto maybe_wrapper = GetWrapper(isolate_);
v8::Local<v8::Value> wrapper;
if (!maybe_wrapper.ToLocal(&wrapper)) {
return;
}
v8::Local<v8::Value> argv[] = {wrapper};
node::Environment* env = node::Environment::GetCurrent(isolate_);
auto global = env->context()->Global();
node::MakeCallback(isolate_, global, body_func_.Get(isolate_),
node::arraysize(argv), argv, {0, 0});
}
v8::Local<v8::Promise> WriteChunk(v8::Local<v8::Value> buffer_val) {
gin_helper::Promise<void> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!buffer_val->IsArrayBufferView()) {
promise.RejectWithErrorMessage("Expected an ArrayBufferView");
return handle;
}
if (is_writing_) {
promise.RejectWithErrorMessage("Only one write can be pending at a time");
return handle;
}
if (!size_callback_) {
promise.RejectWithErrorMessage("Can't write after calling done()");
return handle;
}
auto buffer = buffer_val.As<v8::ArrayBufferView>();
is_writing_ = true;
bytes_written_ += buffer->ByteLength();
auto backing_store = buffer->Buffer()->GetBackingStore();
auto buffer_span = base::make_span(
static_cast<char*>(backing_store->Data()) + buffer->ByteOffset(),
buffer->ByteLength());
auto buffer_source = std::make_unique<BufferDataSource>(buffer_span);
data_producer_->Write(
std::move(buffer_source),
base::BindOnce(&JSChunkedDataPipeGetter::OnWriteChunkComplete,
// We're OK to use Unretained here because we own
// |data_producer_|.
base::Unretained(this), std::move(promise)));
return handle;
}
void OnWriteChunkComplete(gin_helper::Promise<void> promise,
MojoResult result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
is_writing_ = false;
if (result == MOJO_RESULT_OK) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("mojo result not ok: " +
std::to_string(result));
Finished();
}
}
// TODO(nornagon): accept a net error here to allow the data provider to
// cancel the request with an error.
void Done() {
if (size_callback_) {
std::move(size_callback_).Run(net::OK, bytes_written_);
Finished();
}
}
void Finished() {
body_func_.Reset();
data_producer_.reset();
receiver_.reset();
size_callback_.Reset();
}
GetSizeCallback size_callback_;
mojo::Receiver<network::mojom::ChunkedDataPipeGetter> receiver_{this};
std::unique_ptr<mojo::DataPipeProducer> data_producer_;
bool is_writing_ = false;
uint64_t bytes_written_ = 0;
v8::Isolate* isolate_;
v8::Global<v8::Function> body_func_;
};
gin::WrapperInfo JSChunkedDataPipeGetter::kWrapperInfo = {
gin::kEmbedderNativeGin};
const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("electron_net_module", R"(
semantics {
sender: "Electron Net module"
description:
"Issue HTTP/HTTPS requests using Chromium's native networking "
"library."
trigger: "Using the Net module"
data: "Anything the user wants to send."
destination: OTHER
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting: "This feature cannot be disabled."
})");
} // namespace
gin::WrapperInfo SimpleURLLoaderWrapper::kWrapperInfo = {
gin::kEmbedderNativeGin};
SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
std::unique_ptr<network::ResourceRequest> request,
network::mojom::URLLoaderFactory* url_loader_factory,
int options) {
if (!request->trusted_params)
request->trusted_params = network::ResourceRequest::TrustedParams();
mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
url_loader_network_observer_remote;
url_loader_network_observer_receivers_.Add(
this,
url_loader_network_observer_remote.InitWithNewPipeAndPassReceiver());
request->trusted_params->url_loader_network_observer =
std::move(url_loader_network_observer_remote);
// Chromium filters headers using browser rules, while for net module we have
// every header passed. The following setting will allow us to capture the
// raw headers in the URLLoader.
request->report_raw_headers = true;
// SimpleURLLoader wants to control the request body itself. We have other
// ideas.
auto request_body = std::move(request->request_body);
auto* request_ref = request.get();
loader_ =
network::SimpleURLLoader::Create(std::move(request), kTrafficAnnotation);
if (request_body) {
request_ref->request_body = std::move(request_body);
}
loader_->SetAllowHttpErrorResults(true);
loader_->SetURLLoaderFactoryOptions(options);
loader_->SetOnResponseStartedCallback(base::BindOnce(
&SimpleURLLoaderWrapper::OnResponseStarted, base::Unretained(this)));
loader_->SetOnRedirectCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnRedirect, base::Unretained(this)));
loader_->SetOnUploadProgressCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnUploadProgress, base::Unretained(this)));
loader_->SetOnDownloadProgressCallback(base::BindRepeating(
&SimpleURLLoaderWrapper::OnDownloadProgress, base::Unretained(this)));
loader_->DownloadAsStream(url_loader_factory, this);
}
void SimpleURLLoaderWrapper::Pin() {
// Prevent ourselves from being GC'd until the request is complete. Must be
// called after gin::CreateHandle, otherwise the wrapper isn't initialized.
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
pinned_wrapper_.Reset(isolate, GetWrapper(isolate).ToLocalChecked());
}
void SimpleURLLoaderWrapper::PinBodyGetter(v8::Local<v8::Value> body_getter) {
pinned_chunk_pipe_getter_.Reset(JavascriptEnvironment::GetIsolate(),
body_getter);
}
SimpleURLLoaderWrapper::~SimpleURLLoaderWrapper() = default;
void SimpleURLLoaderWrapper::OnAuthRequired(
const absl::optional<base::UnguessableToken>& window_id,
uint32_t request_id,
const GURL& url,
bool first_auth_attempt,
const net::AuthChallengeInfo& auth_info,
const scoped_refptr<net::HttpResponseHeaders>& head_headers,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
mojo::Remote<network::mojom::AuthChallengeResponder> auth_responder(
std::move(auth_challenge_responder));
// WeakPtr because if we're Cancel()ed while waiting for auth, and the
// network service also decides to cancel at the same time and kill this
// pipe, we might end up trying to call Cancel again on dead memory.
auth_responder.set_disconnect_handler(base::BindOnce(
&SimpleURLLoaderWrapper::Cancel, weak_factory_.GetWeakPtr()));
auto cb = base::BindOnce(
[](mojo::Remote<network::mojom::AuthChallengeResponder> auth_responder,
gin::Arguments* args) {
std::u16string username_str, password_str;
if (!args->GetNext(&username_str) || !args->GetNext(&password_str)) {
auth_responder->OnAuthCredentials(absl::nullopt);
return;
}
auth_responder->OnAuthCredentials(
net::AuthCredentials(username_str, password_str));
},
std::move(auth_responder));
Emit("login", auth_info, base::AdaptCallbackForRepeating(std::move(cb)));
}
void SimpleURLLoaderWrapper::OnSSLCertificateError(
const GURL& url,
int net_error,
const net::SSLInfo& ssl_info,
bool fatal,
OnSSLCertificateErrorCallback response) {
std::move(response).Run(net_error);
}
void SimpleURLLoaderWrapper::OnClearSiteData(
const GURL& url,
const std::string& header_value,
int32_t load_flags,
const absl::optional<net::CookiePartitionKey>& cookie_partition_key,
OnClearSiteDataCallback callback) {
std::move(callback).Run();
}
void SimpleURLLoaderWrapper::OnLoadingStateUpdate(
network::mojom::LoadInfoPtr info,
OnLoadingStateUpdateCallback callback) {
std::move(callback).Run();
}
void SimpleURLLoaderWrapper::Clone(
mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver>
observer) {
url_loader_network_observer_receivers_.Add(this, std::move(observer));
}
void SimpleURLLoaderWrapper::Cancel() {
loader_.reset();
pinned_wrapper_.Reset();
pinned_chunk_pipe_getter_.Reset();
// This ensures that no further callbacks will be called, so there's no need
// for additional guards.
}
// static
gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
gin::Arguments* args) {
gin_helper::Dictionary opts;
if (!args->GetNext(&opts)) {
args->ThrowTypeError("Expected a dictionary");
return gin::Handle<SimpleURLLoaderWrapper>();
}
auto request = std::make_unique<network::ResourceRequest>();
opts.Get("method", &request->method);
opts.Get("url", &request->url);
request->site_for_cookies = net::SiteForCookies::FromUrl(request->url);
opts.Get("referrer", &request->referrer);
std::string origin;
opts.Get("origin", &origin);
if (!origin.empty()) {
request->request_initiator = url::Origin::Create(GURL(origin));
}
bool has_user_activation;
if (opts.Get("hasUserActivation", &has_user_activation)) {
request->trusted_params = network::ResourceRequest::TrustedParams();
request->trusted_params->has_user_activation = has_user_activation;
}
std::string mode;
if (opts.Get("mode", &mode) && !mode.empty()) {
if (mode == "navigate") {
request->mode = network::mojom::RequestMode::kNavigate;
} else if (mode == "cors") {
request->mode = network::mojom::RequestMode::kCors;
} else if (mode == "no-cors") {
request->mode = network::mojom::RequestMode::kNoCors;
} else if (mode == "same-origin") {
request->mode = network::mojom::RequestMode::kSameOrigin;
}
}
std::string destination;
if (opts.Get("destination", &destination) && !destination.empty()) {
if (destination == "empty") {
request->destination = network::mojom::RequestDestination::kEmpty;
} else if (destination == "audio") {
request->destination = network::mojom::RequestDestination::kAudio;
} else if (destination == "audioworklet") {
request->destination = network::mojom::RequestDestination::kAudioWorklet;
} else if (destination == "document") {
request->destination = network::mojom::RequestDestination::kDocument;
} else if (destination == "embed") {
request->destination = network::mojom::RequestDestination::kEmbed;
} else if (destination == "font") {
request->destination = network::mojom::RequestDestination::kFont;
} else if (destination == "frame") {
request->destination = network::mojom::RequestDestination::kFrame;
} else if (destination == "iframe") {
request->destination = network::mojom::RequestDestination::kIframe;
} else if (destination == "image") {
request->destination = network::mojom::RequestDestination::kImage;
} else if (destination == "manifest") {
request->destination = network::mojom::RequestDestination::kManifest;
} else if (destination == "object") {
request->destination = network::mojom::RequestDestination::kObject;
} else if (destination == "paintworklet") {
request->destination = network::mojom::RequestDestination::kPaintWorklet;
} else if (destination == "report") {
request->destination = network::mojom::RequestDestination::kReport;
} else if (destination == "script") {
request->destination = network::mojom::RequestDestination::kScript;
} else if (destination == "serviceworker") {
request->destination = network::mojom::RequestDestination::kServiceWorker;
} else if (destination == "style") {
request->destination = network::mojom::RequestDestination::kStyle;
} else if (destination == "track") {
request->destination = network::mojom::RequestDestination::kTrack;
} else if (destination == "video") {
request->destination = network::mojom::RequestDestination::kVideo;
} else if (destination == "worker") {
request->destination = network::mojom::RequestDestination::kWorker;
} else if (destination == "xslt") {
request->destination = network::mojom::RequestDestination::kXslt;
}
}
bool credentials_specified =
opts.Get("credentials", &request->credentials_mode);
std::vector<std::pair<std::string, std::string>> extra_headers;
if (opts.Get("extraHeaders", &extra_headers)) {
for (const auto& it : extra_headers) {
if (!net::HttpUtil::IsValidHeaderName(it.first) ||
!net::HttpUtil::IsValidHeaderValue(it.second)) {
args->ThrowTypeError("Invalid header name or value");
return gin::Handle<SimpleURLLoaderWrapper>();
}
request->headers.SetHeader(it.first, it.second);
}
}
bool use_session_cookies = false;
opts.Get("useSessionCookies", &use_session_cookies);
int options = 0;
if (!credentials_specified && !use_session_cookies) {
// This is the default case, as well as the case when credentials is not
// specified and useSessionCookies is false. credentials_mode will be
// kInclude, but cookies will be blocked.
request->credentials_mode = network::mojom::CredentialsMode::kInclude;
options |= network::mojom::kURLLoadOptionBlockAllCookies;
}
v8::Local<v8::Value> body;
v8::Local<v8::Value> chunk_pipe_getter;
if (opts.Get("body", &body)) {
if (body->IsArrayBufferView()) {
auto buffer_body = body.As<v8::ArrayBufferView>();
auto backing_store = buffer_body->Buffer()->GetBackingStore();
request->request_body = network::ResourceRequestBody::CreateFromBytes(
static_cast<char*>(backing_store->Data()) + buffer_body->ByteOffset(),
buffer_body->ByteLength());
} else if (body->IsFunction()) {
auto body_func = body.As<v8::Function>();
mojo::PendingRemote<network::mojom::ChunkedDataPipeGetter>
data_pipe_getter;
chunk_pipe_getter = JSChunkedDataPipeGetter::Create(
args->isolate(), body_func,
data_pipe_getter.InitWithNewPipeAndPassReceiver())
.ToV8();
request->request_body =
base::MakeRefCounted<network::ResourceRequestBody>();
request->request_body->SetToChunkedDataPipe(
std::move(data_pipe_getter),
network::ResourceRequestBody::ReadOnlyOnce(false));
}
}
std::string partition;
gin::Handle<Session> session;
if (!opts.Get("session", &session)) {
if (opts.Get("partition", &partition))
session = Session::FromPartition(args->isolate(), partition);
else // default session
session = Session::FromPartition(args->isolate(), "");
}
auto url_loader_factory = session->browser_context()->GetURLLoaderFactory();
auto ret = gin::CreateHandle(
args->isolate(),
new SimpleURLLoaderWrapper(std::move(request), url_loader_factory.get(),
options));
ret->Pin();
if (!chunk_pipe_getter.IsEmpty()) {
ret->PinBodyGetter(chunk_pipe_getter);
}
return ret;
}
void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece,
base::OnceClosure resume) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto array_buffer = v8::ArrayBuffer::New(isolate, string_piece.size());
auto backing_store = array_buffer->GetBackingStore();
memcpy(backing_store->Data(), string_piece.data(), string_piece.size());
Emit("data", array_buffer,
base::AdaptCallbackForRepeating(std::move(resume)));
}
void SimpleURLLoaderWrapper::OnComplete(bool success) {
if (success) {
Emit("complete");
} else {
Emit("error", net::ErrorToString(loader_->NetError()));
}
loader_.reset();
pinned_wrapper_.Reset();
pinned_chunk_pipe_getter_.Reset();
}
void SimpleURLLoaderWrapper::OnRetry(base::OnceClosure start_retry) {}
void SimpleURLLoaderWrapper::OnResponseStarted(
const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
gin::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("statusCode", response_head.headers->response_code());
dict.Set("statusMessage", response_head.headers->GetStatusText());
dict.Set("httpVersion", response_head.headers->GetHttpVersion());
// Note that |response_head.headers| are filtered by Chromium and should not
// be used here.
DCHECK(!response_head.raw_response_headers.empty());
dict.Set("rawHeaders", response_head.raw_response_headers);
Emit("response-started", final_url, dict);
}
void SimpleURLLoaderWrapper::OnRedirect(
const net::RedirectInfo& redirect_info,
const network::mojom::URLResponseHead& response_head,
std::vector<std::string>* removed_headers) {
Emit("redirect", redirect_info, response_head.headers.get());
}
void SimpleURLLoaderWrapper::OnUploadProgress(uint64_t position,
uint64_t total) {
Emit("upload-progress", position, total);
}
void SimpleURLLoaderWrapper::OnDownloadProgress(uint64_t current) {
Emit("download-progress", current);
}
// static
gin::ObjectTemplateBuilder SimpleURLLoaderWrapper::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin_helper::EventEmitterMixin<
SimpleURLLoaderWrapper>::GetObjectTemplateBuilder(isolate)
.SetMethod("cancel", &SimpleURLLoaderWrapper::Cancel);
}
const char* SimpleURLLoaderWrapper::GetTypeName() {
return "SimpleURLLoaderWrapper";
}
} // namespace electron::api
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
spec/api-net-spec.ts
|
import { expect } from 'chai';
import * as dns from 'dns';
import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions } from 'electron/main';
import * as http from 'http';
import * as url from 'url';
import { AddressInfo, Socket } from 'net';
import { emittedOnce } from './events-helpers';
import { defer, delay } from './spec-helpers';
// See https://github.com/nodejs/node/issues/40702.
dns.setDefaultResultOrder('ipv4first');
const kOneKiloByte = 1024;
const kOneMegaByte = kOneKiloByte * kOneKiloByte;
function randomBuffer (size: number, start: number = 0, end: number = 255) {
const range = 1 + end - start;
const buffer = Buffer.allocUnsafe(size);
for (let i = 0; i < size; ++i) {
buffer[i] = start + Math.floor(Math.random() * range);
}
return buffer;
}
function randomString (length: number) {
const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
return buffer.toString();
}
async function getResponse (urlRequest: Electron.ClientRequest) {
return new Promise<Electron.IncomingMessage>((resolve, reject) => {
urlRequest.on('error', reject);
urlRequest.on('abort', reject);
urlRequest.on('response', (response) => resolve(response));
urlRequest.end();
});
}
async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
return (await collectStreamBodyBuffer(response)).toString();
}
function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
return new Promise<Buffer>((resolve, reject) => {
response.on('error', reject);
(response as NodeJS.EventEmitter).on('aborted', reject);
const data: Buffer[] = [];
response.on('data', (chunk) => data.push(chunk));
response.on('end', (chunk?: Buffer) => {
if (chunk) data.push(chunk);
resolve(Buffer.concat(data));
});
});
}
function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
return new Promise((resolve) => {
const server = http.createServer((request, response) => {
fn(request, response);
// don't close if a redirect was returned
if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
n--;
server.close();
}
});
server.listen(0, '127.0.0.1', () => {
resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
});
const sockets: Socket[] = [];
server.on('connection', s => sockets.push(s));
defer(() => {
server.close();
sockets.forEach(s => s.destroy());
});
});
}
function respondOnce (fn: http.RequestListener) {
return respondNTimes(fn, 1);
}
let routeFailure = false;
respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
return respondNTimes((request, response) => {
if (Object.prototype.hasOwnProperty.call(routes, request.url || '')) {
(async () => {
await Promise.resolve(routes[request.url || ''](request, response));
})().catch((err) => {
routeFailure = true;
console.error('Route handler failed, this is probably why your test failed', err);
response.statusCode = 500;
response.end();
});
} else {
response.statusCode = 500;
response.end();
expect.fail(`Unexpected URL: ${request.url}`);
}
}, n);
};
respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
return respondNTimes.toRoutes({ [url]: fn }, n);
};
respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
const requestUrl = '/requestUrl';
return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
};
respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
describe('net module', () => {
beforeEach(() => {
routeFailure = false;
});
afterEach(async function () {
await session.defaultSession.clearCache();
if (routeFailure && this.test) {
if (!this.test.isFailed()) {
throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
}
}
});
describe('HTTP basics', () => {
it('should be able to issue a basic GET request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to issue a basic POST request', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('POST');
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should fetch correct data in a GET request', async () => {
const expectedBodyData = 'Hello World!';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.method).to.equal('GET');
response.end(expectedBodyData);
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
const body = await collectStreamBody(response);
expect(body).to.equal(expectedBodyData);
});
it('should post the correct data in a POST request', async () => {
const bodyData = 'Hello World!';
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const postedBodyData = await collectStreamBody(request);
expect(postedBodyData).to.equal(bodyData);
response.end();
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
urlRequest.write(bodyData);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should support chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.chunkedEncoding = true;
expect(request.method).to.equal('POST');
expect(request.headers['transfer-encoding']).to.equal('chunked');
expect(request.headers['content-length']).to.equal(undefined);
request.on('data', (chunk: Buffer) => {
response.write(chunk);
});
request.on('end', (chunk: Buffer) => {
response.end(chunk);
});
});
const urlRequest = net.request({
method: 'POST',
url: serverUrl
});
let chunkIndex = 0;
const chunkCount = 100;
let sent = Buffer.alloc(0);
urlRequest.chunkedEncoding = true;
while (chunkIndex < chunkCount) {
chunkIndex += 1;
const chunk = randomBuffer(kOneKiloByte);
sent = Buffer.concat([sent, chunk]);
urlRequest.write(chunk);
}
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
const received = await collectStreamBodyBuffer(response);
expect(sent.equals(received)).to.be.true();
expect(chunkIndex).to.be.equal(chunkCount);
});
for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
it('should emit the login event when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
let loginAuthInfo: Electron.AuthInfo;
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
loginAuthInfo = authInfo;
cb(user, pass);
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(200);
expect(loginAuthInfo!.realm).to.equal('Foo');
expect(loginAuthInfo!.scheme).to.equal('basic');
});
it('should receive 401 response when cancelling authentication', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
response.end('unauthenticated');
} else {
response.writeHead(200).end('ok');
}
});
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(401);
expect(body).to.equal('unauthenticated');
});
it('should share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
await collectStreamBody(response);
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
let logInCount = 0;
request.on('login', () => {
logInCount++;
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
});
it('should upload body when 401', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200);
request.on('data', (chunk) => response.write(chunk));
request.on('end', () => response.end());
});
const requestData = randomString(kOneKiloByte);
const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
request.on('login', (authInfo, cb) => {
cb(user, pass);
});
request.write(requestData);
const response = await getResponse(request);
const responseData = await collectStreamBody(response);
expect(responseData).to.equal(requestData);
});
});
}
describe('authentication when {"credentials":"omit"}', () => {
it('should not emit the login event when 401', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
response.writeHead(200).end('ok');
});
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail('unexpected login event');
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should not share credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const bw = new BrowserWindow({ show: false });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL(serverUrl);
bw.close();
const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
expect(response.statusCode).to.equal(401);
expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
it('should share proxy credentials with WebContents', async () => {
const [user, pass] = ['user', 'pass'];
const proxyUrl = await respondNTimes((request, response) => {
if (!request.headers['proxy-authorization']) {
return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
}
return response.writeHead(200).end('ok');
}, 2);
const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
bw.webContents.on('login', (event, details, authInfo, cb) => {
event.preventDefault();
cb(user, pass);
});
await bw.loadURL('http://127.0.0.1:9999');
bw.close();
const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
request.on('login', () => {
expect.fail();
});
const response = await getResponse(request);
const body = await collectStreamBody(response);
expect(response.statusCode).to.equal(200);
expect(body).to.equal('ok');
});
});
});
describe('ClientRequest API', () => {
it('request/response objects should emit expected events', async () => {
const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end(bodyData);
});
const urlRequest = net.request(serverUrl);
// request close event
const closePromise = emittedOnce(urlRequest, 'close');
// request finish event
const finishPromise = emittedOnce(urlRequest, 'close');
// request "response" event
const response = await getResponse(urlRequest);
response.on('error', (error: Error) => {
expect(error).to.be.an('Error');
});
const statusCode = response.statusCode;
expect(statusCode).to.equal(200);
// response data event
// respond end event
const body = await collectStreamBody(response);
expect(body).to.equal(bodyData);
urlRequest.on('error', (error) => {
expect(error).to.be.an('Error');
});
await Promise.all([closePromise, finishPromise]);
});
it('should be able to set a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set a non-string object as a header value', async () => {
const customHeaderName = 'Some-Integer-Value';
const customHeaderValue = 900;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue as any);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
urlRequest.write('');
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not change the case of header name', async () => {
const customHeaderName = 'X-Header-Name';
const customHeaderValue = 'value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to set a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.write('');
expect(() => {
urlRequest.setHeader(customHeaderName, customHeaderValue);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to remove a custom HTTP request header before first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.removeHeader(customHeaderName);
expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
urlRequest.write('');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should not be able to remove a custom HTTP request header after first write', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
urlRequest.write('');
expect(() => {
urlRequest.removeHeader(customHeaderName);
}).to.throw();
expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should keep the order of headers', async () => {
const customHeaderNameA = 'X-Header-100';
const customHeaderNameB = 'X-Header-200';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
const headerNames = Array.from(Object.keys(request.headers));
const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
expect(headerBIndex).to.be.below(headerAIndex);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderNameB, 'b');
urlRequest.setHeader(customHeaderNameA, 'a');
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to set cookie header line', async () => {
const cookieHeaderName = 'Cookie';
const cookieHeaderValue = 'test=12345';
const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
await customSession.cookies.set({
url: `${serverUrl}`,
name: 'test',
value: '11111',
expirationDate: 0
});
const urlRequest = net.request({
method: 'GET',
url: serverUrl,
session: customSession
});
urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should be able to receive cookies', async () => {
const cookie = ['cookie1', 'cookie2'];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', cookie);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.headers['set-cookie']).to.have.same.members(cookie);
});
it('should not use the sessions cookie store by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', `${request.headers.cookie!}`);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
});
for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
describe(`when ${JSON.stringify(extraOptions)}`, () => {
it('should be able to use the sessions cookie store', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('x-cookie', request.headers.cookie!);
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookieVal = `${Date.now()}`;
await sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
value: cookieVal
});
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
});
it('should be able to use the sessions cookie store with set-cookie', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', 'foo=bar');
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
await collectStreamBody(await getResponse(urlRequest));
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'foo',
value: 'bar',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: 'unspecified'
});
});
['Lax', 'Strict'].forEach((mode) => {
it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
const serverUrl = await respondNTimes.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
response.setHeader('x-cookie', `${request.headers.cookie}`);
response.end();
}, 2);
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
let cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(0);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response = await getResponse(urlRequest);
expect(response.headers['x-cookie']).to.equal('undefined');
await collectStreamBody(response);
cookies = await sess.cookies.get({});
expect(cookies).to.have.lengthOf(1);
expect(cookies[0]).to.deep.equal({
name: 'same',
value: 'site',
domain: '127.0.0.1',
hostOnly: true,
path: '/',
secure: false,
httpOnly: false,
session: true,
sameSite: mode.toLowerCase()
});
const urlRequest2 = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
const response2 = await getResponse(urlRequest2);
expect(response2.headers['x-cookie']).to.equal('same=site');
});
});
it('should be able to use the sessions cookie store safely across redirects', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
response.statusCode = 302;
response.statusMessage = 'Moved';
const newUrl = await respondOnce.toSingleURL((req, res) => {
res.statusCode = 200;
res.statusMessage = 'OK';
res.setHeader('x-cookie', req.headers.cookie!);
res.end();
});
response.setHeader('x-cookie', request.headers.cookie!);
response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
response.end();
});
const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
const cookie127Val = `${Date.now()}-127`;
const cookieLocalVal = `${Date.now()}-local`;
const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
expect(localhostUrl).to.not.equal(serverUrl);
// cookies with lax or strict same-site settings will not
// persist after redirects. no_restriction must be used
await Promise.all([
sess.cookies.set({
url: serverUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookie127Val
}), sess.cookies.set({
url: localhostUrl,
name: 'wild_cookie',
sameSite: 'no_restriction',
value: cookieLocalVal
})
]);
const urlRequest = net.request({
url: serverUrl,
session: sess,
...extraOptions
});
urlRequest.on('redirect', (status, method, url, headers) => {
// The initial redirect response should have received the 127 value here
expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
urlRequest.followRedirect();
});
const response = await getResponse(urlRequest);
// We expect the server to have received the localhost value here
// The original request was to a 127.0.0.1 URL
// That request would have the cookie127Val cookie attached
// The request is then redirect to a localhost URL (different site)
// Because we are using the session cookie store it should do the safe / secure thing
// and attach the cookies for the new target domain
expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
});
});
}
describe('when {"credentials":"omit"}', () => {
it('should not send cookies');
it('should not store cookies');
});
it('should set sec-fetch-site to same-origin for request from same origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.setHeader('Origin', serverUrl);
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-site to cross-site for request from other origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-site']).to.equal('cross-site');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: 'https://not-exists.com'
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should not send sec-fetch-user header by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers).not.to.have.property('sec-fetch-user');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-user to ?1 if requested', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-user']).to.equal('?1');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.setHeader('sec-fetch-user', '?1');
await collectStreamBody(await getResponse(urlRequest));
});
it('should set sec-fetch-mode to no-cors by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => {
it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-mode']).to.equal(mode);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
urlRequest.setHeader('sec-fetch-mode', mode);
await collectStreamBody(await getResponse(urlRequest));
});
});
it('should set sec-fetch-dest to empty by default', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal('empty');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
await collectStreamBody(await getResponse(urlRequest));
});
[
'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
'report', 'script', 'serviceworker', 'style', 'track', 'video',
'worker', 'xslt'
].forEach((dest) => {
it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers['sec-fetch-dest']).to.equal(dest);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
origin: serverUrl
});
urlRequest.setHeader('sec-fetch-dest', dest);
await collectStreamBody(await getResponse(urlRequest));
});
});
it('should be able to abort an HTTP request before first write', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
expect.fail('Unexpected request event');
});
const urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('unexpected response event');
});
const aborted = emittedOnce(urlRequest, 'abort');
urlRequest.abort();
urlRequest.write('');
urlRequest.end();
await aborted;
});
it('it should be able to abort an HTTP request before request end', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL(() => {
requestReceivedByServer = true;
urlRequest!.abort();
});
let requestAbortEventEmitted = false;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
expect.fail('Unexpected finish event');
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.on('abort', () => {
requestAbortEventEmitted = true;
});
await emittedOnce(urlRequest, 'close', () => {
urlRequest!.chunkedEncoding = true;
urlRequest!.write(randomString(kOneKiloByte));
});
expect(requestReceivedByServer).to.equal(true);
expect(requestAbortEventEmitted).to.equal(true);
});
it('it should be able to abort an HTTP request after request end and before response', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
requestReceivedByServer = true;
urlRequest!.abort();
process.nextTick(() => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
});
let requestFinishEventEmitted = false;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.equal(true);
expect(requestReceivedByServer).to.equal(true);
});
it('it should be able to abort an HTTP request after response start', async () => {
let requestReceivedByServer = false;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
requestReceivedByServer = true;
response.statusCode = 200;
response.statusMessage = 'OK';
response.write(randomString(kOneKiloByte));
});
let requestFinishEventEmitted = false;
let requestResponseEventEmitted = false;
let responseCloseEventEmitted = false;
const urlRequest = net.request(serverUrl);
urlRequest.on('response', (response) => {
requestResponseEventEmitted = true;
const statusCode = response.statusCode;
expect(statusCode).to.equal(200);
response.on('data', () => {});
response.on('end', () => {
expect.fail('Unexpected end event');
});
response.on('error', () => {
expect.fail('Unexpected error event');
});
response.on('close' as any, () => {
responseCloseEventEmitted = true;
});
urlRequest.abort();
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
expect(requestReceivedByServer).to.be.true('request should be received by the server');
expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
});
it('abort event should be emitted at most once', async () => {
let requestReceivedByServer = false;
let urlRequest: ClientRequest | null = null;
const serverUrl = await respondOnce.toSingleURL(() => {
requestReceivedByServer = true;
urlRequest!.abort();
urlRequest!.abort();
});
let requestFinishEventEmitted = false;
let abortsEmitted = 0;
urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {
expect.fail('Unexpected response event');
});
urlRequest.on('finish', () => {
requestFinishEventEmitted = true;
});
urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
urlRequest.on('abort', () => {
abortsEmitted++;
});
urlRequest.end(randomString(kOneKiloByte));
await emittedOnce(urlRequest, 'abort');
expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
expect(requestReceivedByServer).to.be.true('request should be received by server');
expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
});
it('should allow to read response body from non-2xx response', async () => {
const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 404;
response.end(bodyData);
});
const urlRequest = net.request(serverUrl);
const bodyCheckPromise = getResponse(urlRequest).then(r => {
expect(r.statusCode).to.equal(404);
return r;
}).then(collectStreamBody).then(receivedBodyData => {
expect(receivedBodyData.toString()).to.equal(bodyData);
});
const eventHandlers = Promise.all([
bodyCheckPromise,
emittedOnce(urlRequest, 'close')
]);
urlRequest.end();
await eventHandlers;
});
describe('webRequest', () => {
afterEach(() => {
session.defaultSession.webRequest.onBeforeRequest(null);
});
it('Should throw when invalid filters are passed', () => {
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
});
it('Should not throw when valid filters are passed', () => {
expect(() => {
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['*://www.googleapis.com/'] },
(details, callback) => { callback({ cancel: false }); }
);
}).to.not.throw();
});
it('Requests should be intercepted by webRequest module', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
let requestIsIntercepted = false;
session.defaultSession.webRequest.onBeforeRequest(
(details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request(`${serverUrl}${requestUrl}`);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
it('should to able to create and intercept a request using a custom session object', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
const customPartitionName = `custom-partition-${Math.random()}`;
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
session.defaultSession.webRequest.onBeforeRequest(() => {
expect.fail('Request should not be intercepted by the default session');
});
const customSession = session.fromPartition(customPartitionName, { cache: false });
let requestIsIntercepted = false;
customSession.webRequest.onBeforeRequest((details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`,
session: customSession
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
it('should to able to create and intercept a request using a custom partition name', async () => {
const requestUrl = '/requestUrl';
const redirectUrl = '/redirectUrl';
const customPartitionName = `custom-partition-${Math.random()}`;
let requestIsRedirected = false;
const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
requestIsRedirected = true;
response.end();
});
session.defaultSession.webRequest.onBeforeRequest(() => {
expect.fail('Request should not be intercepted by the default session');
});
const customSession = session.fromPartition(customPartitionName, { cache: false });
let requestIsIntercepted = false;
customSession.webRequest.onBeforeRequest((details, callback) => {
if (details.url === `${serverUrl}${requestUrl}`) {
requestIsIntercepted = true;
// Disabled due to false positive in StandardJS
// eslint-disable-next-line standard/no-callback-literal
callback({
redirectURL: `${serverUrl}${redirectUrl}`
});
} else {
callback({
cancel: false
});
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`,
partition: customPartitionName
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
});
it('should throw when calling getHeader without a name', () => {
expect(() => {
(net.request({ url: 'https://test' }).getHeader as any)();
}).to.throw(/`name` is required for getHeader\(name\)/);
expect(() => {
net.request({ url: 'https://test' }).getHeader(null as any);
}).to.throw(/`name` is required for getHeader\(name\)/);
});
it('should throw when calling removeHeader without a name', () => {
expect(() => {
(net.request({ url: 'https://test' }).removeHeader as any)();
}).to.throw(/`name` is required for removeHeader\(name\)/);
expect(() => {
net.request({ url: 'https://test' }).removeHeader(null as any);
}).to.throw(/`name` is required for removeHeader\(name\)/);
});
it('should follow redirect when no redirect handler is provided', async () => {
const requestUrl = '/302';
const serverUrl = await respondOnce.toRoutes({
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({
url: `${serverUrl}${requestUrl}`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should follow redirect chain when no redirect handler is provided', async () => {
const serverUrl = await respondOnce.toRoutes({
'/redirectChain': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/302');
response.end();
},
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({
url: `${serverUrl}/redirectChain`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
});
it('should not follow redirect when request is canceled in redirect handler', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
});
const urlRequest = net.request({
url: serverUrl
});
urlRequest.end();
urlRequest.on('redirect', () => { urlRequest.abort(); });
urlRequest.on('error', () => {});
await emittedOnce(urlRequest, 'abort');
});
it('should not follow redirect when mode is error', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
});
const urlRequest = net.request({
url: serverUrl,
redirect: 'error'
});
urlRequest.end();
await emittedOnce(urlRequest, 'error');
});
it('should follow redirect when handler calls callback', async () => {
const serverUrl = await respondOnce.toRoutes({
'/redirectChain': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/302');
response.end();
},
'/302': (request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
},
'/200': (request, response) => {
response.statusCode = 200;
response.end();
}
});
const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
const redirects: string[] = [];
urlRequest.on('redirect', (status, method, url) => {
redirects.push(url);
urlRequest.followRedirect();
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(redirects).to.deep.equal([
`${serverUrl}/302`,
`${serverUrl}/200`
]);
});
it('should throw if given an invalid session option', () => {
expect(() => {
net.request({
url: 'https://foo',
session: 1 as any
});
}).to.throw('`session` should be an instance of the Session class');
});
it('should throw if given an invalid partition option', () => {
expect(() => {
net.request({
url: 'https://foo',
partition: 1 as any
});
}).to.throw('`partition` should be a string');
});
it('should be able to create a request with options', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
expect(request.method).to.equal('GET');
expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const serverUrl = url.parse(serverUrlUnparsed);
const options = {
port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
hostname: '127.0.0.1',
headers: { [customHeaderName]: customHeaderValue }
};
const urlRequest = net.request(options);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.be.equal(200);
await collectStreamBody(response);
});
it('should be able to pipe a readable stream into a net request', async () => {
const bodyData = randomString(kOneMegaByte);
let netRequestReceived = false;
let netRequestEnded = false;
const [nodeServerUrl, netServerUrl] = await Promise.all([
respondOnce.toSingleURL((request, response) => response.end(bodyData)),
respondOnce.toSingleURL((request, response) => {
netRequestReceived = true;
let receivedBodyData = '';
request.on('data', (chunk) => {
receivedBodyData += chunk.toString();
});
request.on('end', (chunk: Buffer | undefined) => {
netRequestEnded = true;
if (chunk) {
receivedBodyData += chunk.toString();
}
expect(receivedBodyData).to.be.equal(bodyData);
response.end();
});
})
]);
const nodeRequest = http.request(nodeServerUrl);
const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
const netRequest = net.request(netServerUrl);
const responsePromise = emittedOnce(netRequest, 'response');
// TODO(@MarshallOfSound) - FIXME with #22730
nodeResponse.pipe(netRequest as any);
const [netResponse] = await responsePromise;
expect(netResponse.statusCode).to.equal(200);
await collectStreamBody(netResponse);
expect(netRequestReceived).to.be.true('net request received');
expect(netRequestEnded).to.be.true('net request ended');
});
it('should report upload progress', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const netRequest = net.request({ url: serverUrl, method: 'POST' });
expect(netRequest.getUploadProgress()).to.have.property('active', false);
netRequest.end(Buffer.from('hello'));
const [position, total] = await emittedOnce(netRequest, 'upload-progress');
expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
});
it('should emit error event on server socket destroy', async () => {
const serverUrl = await respondOnce.toSingleURL((request) => {
request.socket.destroy();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
const [error] = await emittedOnce(urlRequest, 'error');
expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
});
it('should emit error event on server request destroy', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
request.destroy();
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end(randomBuffer(kOneMegaByte));
const [error] = await emittedOnce(urlRequest, 'error');
expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
});
it('should not emit any event after close', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
await emittedOnce(urlRequest, 'close');
await new Promise((resolve, reject) => {
['finish', 'abort', 'close', 'error'].forEach(evName => {
urlRequest.on(evName as any, () => {
reject(new Error(`Unexpected ${evName} event`));
});
});
setTimeout(resolve, 50);
});
});
it('should remove the referer header when no referrer url specified', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers.referer).to.equal(undefined);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.end();
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
it('should set the referer header when a referrer url specified', async () => {
const referrerURL = 'https://www.electronjs.org/';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
expect(request.headers.referer).to.equal(referrerURL);
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.setHeader('referer', referrerURL);
urlRequest.end();
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
await collectStreamBody(response);
});
});
describe('IncomingMessage API', () => {
it('response object should implement the IncomingMessage API', async () => {
const customHeaderName = 'Some-Custom-Header-Name';
const customHeaderValue = 'Some-Customer-Header-Value';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader(customHeaderName, customHeaderValue);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
const headerValue = headers[customHeaderName.toLowerCase()];
expect(headerValue).to.equal(customHeaderValue);
const rawHeaders = response.rawHeaders;
expect(rawHeaders).to.be.an('array');
expect(rawHeaders[0]).to.equal(customHeaderName);
expect(rawHeaders[1]).to.equal(customHeaderValue);
const httpVersion = response.httpVersion;
expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
const httpVersionMajor = response.httpVersionMajor;
expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
const httpVersionMinor = response.httpVersionMinor;
expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
await collectStreamBody(response);
});
it('should discard duplicate headers', async () => {
const includedHeader = 'max-forwards';
const discardableHeader = 'Max-Forwards';
const includedHeaderValue = 'max-fwds-val';
const discardableHeaderValue = 'max-fwds-val-two';
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader(discardableHeader, discardableHeaderValue);
response.setHeader(includedHeader, includedHeaderValue);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property(includedHeader);
expect(headers).to.not.have.property(discardableHeader);
expect(headers[includedHeader]).to.equal(includedHeaderValue);
await collectStreamBody(response);
});
it('should join repeated non-discardable header values with ,', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('referrer-policy', ['first-text', 'second-text']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('referrer-policy');
expect(headers['referrer-policy']).to.equal('first-text, second-text');
await collectStreamBody(response);
});
it('should not join repeated discardable header values with ,', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('last-modified', ['yesterday', 'today']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('last-modified');
expect(headers['last-modified']).to.equal('yesterday');
await collectStreamBody(response);
});
it('should make set-cookie header an array even if single value', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', 'chocolate-chip');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('set-cookie');
expect(headers['set-cookie']).to.be.an('array');
expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
await collectStreamBody(response);
});
it('should keep set-cookie header an array when an array', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('set-cookie');
expect(headers['set-cookie']).to.be.an('array');
expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
expect(headers['set-cookie'][1]).to.equal('oatmeal');
await collectStreamBody(response);
});
it('should lowercase header keys', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
response.setHeader('HEADER-KEY', ['header-value']);
response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
response.setHeader('LAST-modified', 'yesterday');
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const headers = response.headers;
expect(headers).to.be.an('object');
expect(headers).to.have.property('header-key');
expect(headers).to.have.property('set-cookie');
expect(headers).to.have.property('referrer-policy');
expect(headers).to.have.property('last-modified');
await collectStreamBody(response);
});
it('should return correct raw headers', async () => {
const customHeaders: [string, string|string[]][] = [
['HEADER-KEY-ONE', 'header-value-one'],
['set-cookie', 'chocolate-chip'],
['header-key-two', 'header-value-two'],
['referrer-policy', ['first-text', 'second-text']],
['HEADER-KEY-THREE', 'header-value-three'],
['last-modified', ['first-text', 'second-text']],
['header-key-four', 'header-value-four']
];
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 200;
response.statusMessage = 'OK';
customHeaders.forEach((headerTuple) => {
response.setHeader(headerTuple[0], headerTuple[1]);
});
response.end();
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
expect(response.statusMessage).to.equal('OK');
const rawHeaders = response.rawHeaders;
expect(rawHeaders).to.be.an('array');
let rawHeadersIdx = 0;
customHeaders.forEach((headerTuple) => {
const headerKey = headerTuple[0];
const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
headerValues.forEach((headerValue) => {
expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
rawHeadersIdx += 2;
});
});
await collectStreamBody(response);
});
it('should be able to pipe a net response into a writable stream', async () => {
const bodyData = randomString(kOneKiloByte);
let nodeRequestProcessed = false;
const [netServerUrl, nodeServerUrl] = await Promise.all([
respondOnce.toSingleURL((request, response) => response.end(bodyData)),
respondOnce.toSingleURL(async (request, response) => {
const receivedBodyData = await collectStreamBody(request);
expect(receivedBodyData).to.be.equal(bodyData);
nodeRequestProcessed = true;
response.end();
})
]);
const netRequest = net.request(netServerUrl);
const netResponse = await getResponse(netRequest);
const serverUrl = url.parse(nodeServerUrl);
const nodeOptions = {
method: 'POST',
path: serverUrl.path,
port: serverUrl.port
};
const nodeRequest = http.request(nodeOptions);
const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
// TODO(@MarshallOfSound) - FIXME with #22730
(netResponse as any).pipe(nodeRequest);
const [nodeResponse] = await nodeResponsePromise;
netRequest.end();
await collectStreamBody(nodeResponse);
expect(nodeRequestProcessed).to.equal(true);
});
it('should correctly throttle an incoming stream', async () => {
let numChunksSent = 0;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
const data = randomString(kOneMegaByte);
const write = () => {
let ok = true;
do {
numChunksSent++;
if (numChunksSent > 30) return;
ok = response.write(data);
} while (ok);
response.once('drain', write);
};
write();
});
const urlRequest = net.request(serverUrl);
urlRequest.on('response', () => {});
urlRequest.end();
await delay(2000);
// TODO(nornagon): I think this ought to max out at 20, but in practice
// it seems to exceed that sometimes. This is at 25 to avoid test flakes,
// but we should investigate if there's actually something broken here and
// if so fix it and reset this to max at 20, and if not then delete this
// comment.
expect(numChunksSent).to.be.at.most(25);
});
});
describe('net.isOnline', () => {
it('getter returns boolean', () => {
expect(net.isOnline()).to.be.a('boolean');
});
it('property returns boolean', () => {
expect(net.online).to.be.a('boolean');
});
});
describe('Stability and performance', () => {
it('should free unreferenced, never-started request objects without crash', (done) => {
net.request('https://test');
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
done();
});
});
it('should collect on-going requests without crash', async () => {
let finishResponse: (() => void) | null = null;
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.write(randomString(kOneKiloByte));
finishResponse = () => {
response.write(randomString(kOneKiloByte));
response.end();
};
});
const urlRequest = net.request(serverUrl);
const response = await getResponse(urlRequest);
process.nextTick(() => {
// Trigger a garbage collection.
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
finishResponse!();
});
await collectStreamBody(response);
});
it('should collect unreferenced, ended requests without crash', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.end();
});
const urlRequest = net.request(serverUrl);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
const response = await getResponse(urlRequest);
await collectStreamBody(response);
});
it('should finish sending data when urlRequest is unreferenced', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
expect(received.length).to.equal(kOneMegaByte);
response.end();
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.write(randomBuffer(kOneMegaByte));
const response = await getResponse(urlRequest);
await collectStreamBody(response);
});
it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
const response = await getResponse(urlRequest);
await collectStreamBody(response);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
await collectStreamBody(await getResponse(urlRequest));
});
it('should finish sending data when urlRequest is unreferenced', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.write(randomBuffer(kOneMegaByte));
await collectStreamBody(await getResponse(urlRequest));
});
it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
const received = await collectStreamBodyBuffer(request);
response.end();
expect(received.length).to.equal(kOneMegaByte);
});
const urlRequest = net.request(serverUrl);
urlRequest.on('close', () => {
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
urlRequest.chunkedEncoding = true;
urlRequest.write(randomBuffer(kOneMegaByte));
await collectStreamBody(await getResponse(urlRequest));
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 27,895 |
net.request response is missing content-type header in 304 responses
|
### Preflight Checklist
* [x ] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [ x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [ x] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
10.1.7
* **Operating System:**
Windows 10 Enterprise 1909
When making a request with `net.request`, I can see that my response has a `content-type` header of `application/json; charset=utf-8` inside of my `webRequest.onHeadersReceived` handler:
```
electron.session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
// details.responseHeaders['content-type'] === 'application/json; charset=utf-8'
});
```
But by the time the `net.request` `request.on('response')` handler receives the headers, the content-type is gone.
```
request.on('response', (response) => {
/*
response.headers === {
// no content-type
};
*/
});
```
I haven't tested if this is an issue in all types of responses, but I can tell you this is occurring without fail for the case when the `response.statusCode === 200`, but the `response.headers.status === 304`.
### Expected Behavior
For `net.request` response handler to receive the content-type that clearly should exist on the response (proved by `webRequest.onHeadersReceived`).
### Actual Behavior
`net.request` response handler is receiving what seems to be a cached set of headers (or something?), which do not match what is seen in `webRequest.onHeadersReceived`.
|
https://github.com/electron/electron/issues/27895
|
https://github.com/electron/electron/pull/36666
|
8c837fda4f2d68d8568889cd68da801f833c862c
|
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
| 2021-02-24T16:57:50Z |
c++
| 2022-12-21T22:53:29Z |
typings/internal-ambient.d.ts
|
/* eslint-disable no-var */
declare var internalBinding: any;
declare var binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function };
declare var isolatedApi: {
guestViewInternal: any;
allowGuestViewElementDefinition: NodeJS.InternalWebFrame['allowGuestViewElementDefinition'];
setIsWebView: (iframe: HTMLIFrameElement) => void;
}
declare const BUILDFLAG: (flag: boolean) => boolean;
declare const ENABLE_DESKTOP_CAPTURER: boolean;
declare const ENABLE_VIEWS_API: boolean;
declare namespace NodeJS {
interface FeaturesBinding {
isBuiltinSpellCheckerEnabled(): boolean;
isDesktopCapturerEnabled(): boolean;
isOffscreenRenderingEnabled(): boolean;
isPDFViewerEnabled(): boolean;
isRunAsNodeEnabled(): boolean;
isFakeLocationProviderEnabled(): boolean;
isViewApiEnabled(): boolean;
isTtsEnabled(): boolean;
isPrintingEnabled(): boolean;
isPictureInPictureEnabled(): boolean;
isExtensionsEnabled(): boolean;
isComponentBuild(): boolean;
}
interface IpcRendererBinding {
send(internal: boolean, channel: string, args: any[]): void;
sendSync(internal: boolean, channel: string, args: any[]): any;
sendToHost(channel: string, args: any[]): void;
sendTo(webContentsId: number, channel: string, args: any[]): void;
invoke<T>(internal: boolean, channel: string, args: any[]): Promise<{ error: string, result: T }>;
postMessage(channel: string, message: any, transferables: MessagePort[]): void;
}
interface V8UtilBinding {
getHiddenValue<T>(obj: any, key: string): T;
setHiddenValue<T>(obj: any, key: string, value: T): void;
deleteHiddenValue(obj: any, key: string): void;
requestGarbageCollectionForTesting(): void;
runUntilIdle(): void;
triggerFatalErrorForTesting(): void;
}
interface EnvironmentBinding {
getVar(name: string): string | null;
hasVar(name: string): boolean;
setVar(name: string, value: string): boolean;
unSetVar(name: string): boolean;
}
type AsarFileInfo = {
size: number;
unpacked: boolean;
offset: number;
integrity?: {
algorithm: 'SHA256';
hash: string;
}
};
type AsarFileStat = {
size: number;
offset: number;
isFile: boolean;
isDirectory: boolean;
isLink: boolean;
}
interface AsarArchive {
getFileInfo(path: string): AsarFileInfo | false;
stat(path: string): AsarFileStat | false;
readdir(path: string): string[] | false;
realpath(path: string): string | false;
copyFileOut(path: string): string | false;
getFdAndValidateIntegrityLater(): number | -1;
}
interface AsarBinding {
Archive: { new(path: string): AsarArchive };
splitPath(path: string): {
isAsar: false;
} | {
isAsar: true;
asarPath: string;
filePath: string;
};
initAsarSupport(require: NodeJS.Require): void;
}
interface PowerMonitorBinding extends Electron.PowerMonitor {
createPowerMonitor(): PowerMonitorBinding;
setListeningForShutdown(listening: boolean): void;
}
interface WebViewManagerBinding {
addGuest(guestInstanceId: number, embedder: Electron.WebContents, guest: Electron.WebContents, webPreferences: Electron.WebPreferences): void;
removeGuest(embedder: Electron.WebContents, guestInstanceId: number): void;
}
interface InternalWebPreferences {
isWebView: boolean;
hiddenPage: boolean;
nodeIntegration: boolean;
webviewTag: boolean;
}
interface InternalWebFrame extends Electron.WebFrame {
getWebPreference<K extends keyof InternalWebPreferences>(name: K): InternalWebPreferences[K];
getWebFrameId(window: Window): number;
allowGuestViewElementDefinition(context: object, callback: Function): void;
}
interface WebFrameBinding {
mainFrame: InternalWebFrame;
}
type DataPipe = {
write: (buf: Uint8Array) => Promise<void>;
done: () => void;
};
type BodyFunc = (pipe: DataPipe) => void;
type CreateURLLoaderOptions = {
method: string;
url: string;
extraHeaders?: Record<string, string>;
useSessionCookies?: boolean;
credentials?: 'include' | 'omit';
body: Uint8Array | BodyFunc;
session?: Electron.Session;
partition?: string;
referrer?: string;
origin?: string;
hasUserActivation?: boolean;
mode?: string;
destination?: string;
};
type ResponseHead = {
statusCode: number;
statusMessage: string;
httpVersion: { major: number, minor: number };
rawHeaders: { key: string, value: string }[];
};
type RedirectInfo = {
statusCode: number;
newMethod: string;
newUrl: string;
newSiteForCookies: string;
newReferrer: string;
insecureSchemeWasUpgraded: boolean;
isSignedExchangeFallbackRedirect: boolean;
}
interface URLLoader extends EventEmitter {
cancel(): void;
on(eventName: 'data', listener: (event: any, data: ArrayBuffer, resume: () => void) => void): this;
on(eventName: 'response-started', listener: (event: any, finalUrl: string, responseHead: ResponseHead) => void): this;
on(eventName: 'complete', listener: (event: any) => void): this;
on(eventName: 'error', listener: (event: any, netErrorString: string) => void): this;
on(eventName: 'login', listener: (event: any, authInfo: Electron.AuthInfo, callback: (username?: string, password?: string) => void) => void): this;
on(eventName: 'redirect', listener: (event: any, redirectInfo: RedirectInfo, headers: Record<string, string>) => void): this;
on(eventName: 'upload-progress', listener: (event: any, position: number, total: number) => void): this;
on(eventName: 'download-progress', listener: (event: any, current: number) => void): this;
}
interface Process {
internalBinding?(name: string): any;
_linkedBinding(name: string): any;
_linkedBinding(name: 'electron_common_asar'): AsarBinding;
_linkedBinding(name: 'electron_common_clipboard'): Electron.Clipboard;
_linkedBinding(name: 'electron_common_command_line'): Electron.CommandLine;
_linkedBinding(name: 'electron_common_environment'): EnvironmentBinding;
_linkedBinding(name: 'electron_common_features'): FeaturesBinding;
_linkedBinding(name: 'electron_common_native_image'): { nativeImage: typeof Electron.NativeImage };
_linkedBinding(name: 'electron_common_shell'): Electron.Shell;
_linkedBinding(name: 'electron_common_v8_util'): V8UtilBinding;
_linkedBinding(name: 'electron_browser_app'): { app: Electron.App, App: Function };
_linkedBinding(name: 'electron_browser_auto_updater'): { autoUpdater: Electron.AutoUpdater };
_linkedBinding(name: 'electron_browser_browser_view'): { BrowserView: typeof Electron.BrowserView };
_linkedBinding(name: 'electron_browser_crash_reporter'): Omit<Electron.CrashReporter, 'start'> & {
start(submitUrl: string,
uploadToServer: boolean,
ignoreSystemCrashHandler: boolean,
rateLimit: boolean,
compress: boolean,
globalExtra: Record<string, string>,
extra: Record<string, string>,
isNodeProcess: boolean): void;
};
_linkedBinding(name: 'electron_browser_desktop_capturer'): {
createDesktopCapturer(): ElectronInternal.DesktopCapturer;
};
_linkedBinding(name: 'electron_browser_event'): {
createWithSender(sender: Electron.WebContents): Electron.Event;
createEmpty(): Electron.Event;
};
_linkedBinding(name: 'electron_browser_event_emitter'): {
setEventEmitterPrototype(prototype: Object): void;
};
_linkedBinding(name: 'electron_browser_global_shortcut'): { globalShortcut: Electron.GlobalShortcut };
_linkedBinding(name: 'electron_browser_image_view'): { ImageView: any };
_linkedBinding(name: 'electron_browser_in_app_purchase'): { inAppPurchase: Electron.InAppPurchase };
_linkedBinding(name: 'electron_browser_message_port'): {
createPair(): { port1: Electron.MessagePortMain, port2: Electron.MessagePortMain };
};
_linkedBinding(name: 'electron_browser_native_theme'): { nativeTheme: Electron.NativeTheme };
_linkedBinding(name: 'electron_browser_net'): {
isOnline(): boolean;
isValidHeaderName: (headerName: string) => boolean;
isValidHeaderValue: (headerValue: string) => boolean;
fileURLToFilePath: (url: string) => string;
Net: any;
net: any;
createURLLoader(options: CreateURLLoaderOptions): URLLoader;
};
_linkedBinding(name: 'electron_browser_notification'): {
isSupported(): boolean;
Notification: typeof Electron.Notification;
}
_linkedBinding(name: 'electron_browser_power_monitor'): PowerMonitorBinding;
_linkedBinding(name: 'electron_browser_power_save_blocker'): { powerSaveBlocker: Electron.PowerSaveBlocker };
_linkedBinding(name: 'electron_browser_push_notifications'): { pushNotifications: Electron.PushNotifications };
_linkedBinding(name: 'electron_browser_safe_storage'): { safeStorage: Electron.SafeStorage };
_linkedBinding(name: 'electron_browser_session'): typeof Electron.Session;
_linkedBinding(name: 'electron_browser_screen'): { createScreen(): Electron.Screen };
_linkedBinding(name: 'electron_browser_system_preferences'): { systemPreferences: Electron.SystemPreferences };
_linkedBinding(name: 'electron_browser_tray'): { Tray: Electron.Tray };
_linkedBinding(name: 'electron_browser_view'): { View: Electron.View };
_linkedBinding(name: 'electron_browser_web_contents_view'): { WebContentsView: typeof Electron.WebContentsView };
_linkedBinding(name: 'electron_browser_web_view_manager'): WebViewManagerBinding;
_linkedBinding(name: 'electron_browser_web_frame_main'): {
WebFrameMain: typeof Electron.WebFrameMain;
fromId(processId: number, routingId: number): Electron.WebFrameMain;
fromIdOrNull(processId: number, routingId: number): Electron.WebFrameMain | null;
}
_linkedBinding(name: 'electron_renderer_crash_reporter'): Electron.CrashReporter;
_linkedBinding(name: 'electron_renderer_ipc'): { ipc: IpcRendererBinding };
_linkedBinding(name: 'electron_renderer_web_frame'): WebFrameBinding;
log: NodeJS.WriteStream['write'];
activateUvLoop(): void;
// Additional events
once(event: 'document-start', listener: () => any): this;
once(event: 'document-end', listener: () => any): this;
// Additional properties
_firstFileName?: string;
_serviceStartupScript: string;
helperExecPath: string;
mainModule?: NodeJS.Module | undefined;
}
}
declare module NodeJS {
interface Global {
require: NodeRequire;
module: NodeModule;
__filename: string;
__dirname: string;
}
}
interface ContextMenuItem {
id: number;
label: string;
type: 'normal' | 'separator' | 'subMenu' | 'checkbox';
checked: boolean;
enabled: boolean;
subItems: ContextMenuItem[];
}
declare interface Window {
ELECTRON_DISABLE_SECURITY_WARNINGS?: boolean;
ELECTRON_ENABLE_SECURITY_WARNINGS?: boolean;
InspectorFrontendHost?: {
showContextMenuAtPoint: (x: number, y: number, items: ContextMenuItem[]) => void
};
DevToolsAPI?: {
contextMenuItemSelected: (id: number) => void;
contextMenuCleared: () => void
};
UI?: {
createFileSelectorElement: (callback: () => void) => HTMLSpanElement
};
Persistence?: {
FileSystemWorkspaceBinding: {
completeURL: (project: string, path: string) => string;
}
};
WebView: typeof ElectronInternal.WebViewElement;
trustedTypes: TrustedTypePolicyFactory;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#trusted-types
type TrustedHTML = string;
type TrustedScript = string;
type TrustedScriptURL = string;
type TrustedType = TrustedHTML | TrustedScript | TrustedScriptURL;
type StringContext = 'TrustedHTML' | 'TrustedScript' | 'TrustedScriptURL';
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicy
interface TrustedTypePolicy {
createHTML(input: string, ...arguments: any[]): TrustedHTML;
createScript(input: string, ...arguments: any[]): TrustedScript;
createScriptURL(input: string, ...arguments: any[]): TrustedScriptURL;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyoptions
interface TrustedTypePolicyOptions {
createHTML?: (input: string, ...arguments: any[]) => TrustedHTML;
createScript?: (input: string, ...arguments: any[]) => TrustedScript;
createScriptURL?: (input: string, ...arguments: any[]) => TrustedScriptURL;
}
// https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyfactory
interface TrustedTypePolicyFactory {
createPolicy(policyName: string, policyOptions: TrustedTypePolicyOptions): TrustedTypePolicy
isHTML(value: any): boolean;
isScript(value: any): boolean;
isScriptURL(value: any): boolean;
readonly emptyHTML: TrustedHTML;
readonly emptyScript: TrustedScript;
getAttributeType(tagName: string, attribute: string, elementNs?: string, attrNs?: string): StringContext | null;
getPropertyType(tagName: string, property: string, elementNs?: string): StringContext | null;
readonly defaultPolicy: TrustedTypePolicy | null;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/angle/.patches
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/angle/fix_rename_webswapcgllayer_to_webswapcgllayerchromium.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/config.json
|
{
"src/electron/patches/chromium": "src",
"src/electron/patches/boringssl": "src/third_party/boringssl/src",
"src/electron/patches/devtools_frontend": "src/third_party/devtools-frontend/src",
"src/electron/patches/ffmpeg": "src/third_party/ffmpeg",
"src/electron/patches/v8": "src/v8",
"src/electron/patches/node": "src/third_party/electron_node",
"src/electron/patches/nan": "src/third_party/nan",
"src/electron/patches/perfetto": "src/third_party/perfetto",
"src/electron/patches/squirrel.mac": "src/third_party/squirrel.mac",
"src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle",
"src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC"
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/angle/.patches
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/angle/fix_rename_webswapcgllayer_to_webswapcgllayerchromium.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,685 |
[Bug]: Warning: Class WebSwapCGLLayer is implemented in both system library and electron distribution
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
18.0.0
### What operating system are you using?
macOS
### Operating System Version
12.3.1
### What arch are you using?
x64
### Last Known Working Electron version
17.3.1
### Expected Behavior
Starting electron using the npm script `"app": "electron ."` starts the app with no warnings.
### Actual Behavior
Electron starts normally, but with the following warning:
```
Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffa5a006318) and /{path/to/app}/node_modules/electron/dist/Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libGLESv2.dylib (0x10f8a89c8). One of the two will be used. Which one is undefined.
```
(`{path/to/app}` has been substituted for the actual path to the app on my system.)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33685
|
https://github.com/electron/electron/pull/35961
|
700f43c90c714fbf0b91458288b88bc18eed7cb0
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
| 2022-04-08T20:19:04Z |
c++
| 2023-01-05T06:49:08Z |
patches/config.json
|
{
"src/electron/patches/chromium": "src",
"src/electron/patches/boringssl": "src/third_party/boringssl/src",
"src/electron/patches/devtools_frontend": "src/third_party/devtools-frontend/src",
"src/electron/patches/ffmpeg": "src/third_party/ffmpeg",
"src/electron/patches/v8": "src/v8",
"src/electron/patches/node": "src/third_party/electron_node",
"src/electron/patches/nan": "src/third_party/nan",
"src/electron/patches/perfetto": "src/third_party/perfetto",
"src/electron/patches/squirrel.mac": "src/third_party/squirrel.mac",
"src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle",
"src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC"
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,721 |
[Bug]: macOS confirmation dialog does not show blue border around focused button when it is default
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22
### What operating system are you using?
macOS
### Operating System Version
12.6.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
_No response_
### Expected Behavior
A focused button shows a blue border even when default button:

### Actual Behavior
A focused button does not show the blue border:

### Testcase Gist URL
https://gist.github.com/d9bd650ffc1efcf61016cbc81ea35652
### Additional Information
This only seems to happen when using non-standard labels for the buttons. It requires this macOS setting:

|
https://github.com/electron/electron/issues/36721
|
https://github.com/electron/electron/pull/36772
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
|
32288ac9c588fe8c3b814338aaf5df7fddbce276
| 2022-12-21T06:31:39Z |
c++
| 2023-01-05T08:56:38Z |
shell/browser/ui/message_box_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/message_box.h"
#include <map>
#include <string>
#include <utility>
#include <vector>
#import <Cocoa/Cocoa.h>
#include "base/callback.h"
#include "base/containers/contains.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/native_window.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/image/image_skia.h"
namespace electron {
MessageBoxSettings::MessageBoxSettings() = default;
MessageBoxSettings::MessageBoxSettings(const MessageBoxSettings&) = default;
MessageBoxSettings::~MessageBoxSettings() = default;
namespace {
// <ID, messageBox> map
std::map<int, NSAlert*>& GetDialogsMap() {
static base::NoDestructor<std::map<int, NSAlert*>> dialogs;
return *dialogs;
}
NSAlert* CreateNSAlert(const MessageBoxSettings& settings) {
// Ignore the title; it's the window title on other platforms and ignorable.
NSAlert* alert = [[NSAlert alloc] init];
[alert setMessageText:base::SysUTF8ToNSString(settings.message)];
[alert setInformativeText:base::SysUTF8ToNSString(settings.detail)];
switch (settings.type) {
case MessageBoxType::kInformation:
alert.alertStyle = NSAlertStyleInformational;
break;
case MessageBoxType::kWarning:
case MessageBoxType::kError:
// NSWarningAlertStyle shows the app icon while NSAlertStyleCritical
// shows a warning icon with an app icon badge. Since there is no
// error variant, lets just use NSAlertStyleCritical.
alert.alertStyle = NSAlertStyleCritical;
break;
default:
break;
}
for (size_t i = 0; i < settings.buttons.size(); ++i) {
NSString* title = base::SysUTF8ToNSString(settings.buttons[i]);
// An empty title causes crash on macOS.
if (settings.buttons[i].empty())
title = @"(empty)";
NSButton* button = [alert addButtonWithTitle:title];
[button setTag:i];
}
NSArray* ns_buttons = [alert buttons];
int button_count = static_cast<int>([ns_buttons count]);
if (settings.default_id >= 0 && settings.default_id < button_count) {
// Highlight the button at default_id
[[ns_buttons objectAtIndex:settings.default_id] highlight:YES];
// The first button added gets set as the default selected, so remove
// that and set the button @ default_id to be default.
[[ns_buttons objectAtIndex:0] setKeyEquivalent:@""];
[[ns_buttons objectAtIndex:settings.default_id] setKeyEquivalent:@"\r"];
}
// Bind cancel id button to escape key if there is more than one button
if (button_count > 1 && settings.cancel_id >= 0 &&
settings.cancel_id < button_count) {
[[ns_buttons objectAtIndex:settings.cancel_id] setKeyEquivalent:@"\e"];
}
if (!settings.checkbox_label.empty()) {
alert.showsSuppressionButton = YES;
alert.suppressionButton.title =
base::SysUTF8ToNSString(settings.checkbox_label);
alert.suppressionButton.state =
settings.checkbox_checked ? NSOnState : NSOffState;
}
if (!settings.icon.isNull()) {
NSImage* image = skia::SkBitmapToNSImageWithColorSpace(
*settings.icon.bitmap(), base::mac::GetGenericRGBColorSpace());
[alert setIcon:image];
}
if (settings.text_width > 0) {
NSRect rect = NSMakeRect(0, 0, settings.text_width, 0);
NSView* accessoryView = [[NSView alloc] initWithFrame:rect];
[alert setAccessoryView:[accessoryView autorelease]];
}
return alert;
}
} // namespace
int ShowMessageBoxSync(const MessageBoxSettings& settings) {
base::scoped_nsobject<NSAlert> alert(CreateNSAlert(settings));
// Use runModal for synchronous alert without parent, since we don't have a
// window to wait for. Also use it when window is provided but it is not
// shown as it would be impossible to dismiss the alert if it is connected
// to invisible window (see #22671).
if (!settings.parent_window || !settings.parent_window->IsVisible())
return [alert runModal];
__block int ret_code = -1;
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[alert beginSheetModalForWindow:window
completionHandler:^(NSModalResponse response) {
ret_code = response;
[NSApp stopModal];
}];
[NSApp runModalForWindow:window];
return ret_code;
}
void ShowMessageBox(const MessageBoxSettings& settings,
MessageBoxCallback callback) {
NSAlert* alert = CreateNSAlert(settings);
// Use runModal for synchronous alert without parent, since we don't have a
// window to wait for.
if (!settings.parent_window) {
int ret = [[alert autorelease] runModal];
std::move(callback).Run(ret, alert.suppressionButton.state == NSOnState);
} else {
if (settings.id) {
if (base::Contains(GetDialogsMap(), *settings.id))
CloseMessageBox(*settings.id);
GetDialogsMap()[*settings.id] = alert;
}
NSWindow* window =
settings.parent_window
? settings.parent_window->GetNativeWindow().GetNativeNSWindow()
: nil;
// Duplicate the callback object here since c is a reference and gcd would
// only store the pointer, by duplication we can force gcd to store a copy.
__block MessageBoxCallback callback_ = std::move(callback);
__block absl::optional<int> id = std::move(settings.id);
__block int cancel_id = settings.cancel_id;
auto handler = ^(NSModalResponse response) {
if (id)
GetDialogsMap().erase(*id);
// When the alert is cancelled programmatically, the response would be
// something like -1000. This currently only happens when users call
// CloseMessageBox API, and we should return cancelId as result.
if (response < 0)
response = cancel_id;
bool suppressed = alert.suppressionButton.state == NSOnState;
[alert release];
// The completionHandler runs inside a transaction commit, and we should
// not do any runModal inside it. However since we can not control what
// users will run in the callback, we have to delay running the callback
// until next tick, otherwise crash like this may happen:
// https://github.com/electron/electron/issues/26884
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback_), response, suppressed));
};
[alert beginSheetModalForWindow:window completionHandler:handler];
}
}
void CloseMessageBox(int id) {
auto it = GetDialogsMap().find(id);
if (it == GetDialogsMap().end()) {
LOG(ERROR) << "CloseMessageBox called with nonexistent ID";
return;
}
[NSApp endSheet:it->second.window];
}
void ShowErrorBox(const std::u16string& title, const std::u16string& content) {
NSAlert* alert = [[NSAlert alloc] init];
[alert setMessageText:base::SysUTF16ToNSString(title)];
[alert setInformativeText:base::SysUTF16ToNSString(content)];
[alert setAlertStyle:NSAlertStyleCritical];
[alert runModal];
[alert release];
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,721 |
[Bug]: macOS confirmation dialog does not show blue border around focused button when it is default
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22
### What operating system are you using?
macOS
### Operating System Version
12.6.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
_No response_
### Expected Behavior
A focused button shows a blue border even when default button:

### Actual Behavior
A focused button does not show the blue border:

### Testcase Gist URL
https://gist.github.com/d9bd650ffc1efcf61016cbc81ea35652
### Additional Information
This only seems to happen when using non-standard labels for the buttons. It requires this macOS setting:

|
https://github.com/electron/electron/issues/36721
|
https://github.com/electron/electron/pull/36772
|
42cda4a893e5c502ffe4bd1eb0f086709b586bd3
|
32288ac9c588fe8c3b814338aaf5df7fddbce276
| 2022-12-21T06:31:39Z |
c++
| 2023-01-05T08:56:38Z |
shell/browser/ui/message_box_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/message_box.h"
#include <map>
#include <string>
#include <utility>
#include <vector>
#import <Cocoa/Cocoa.h>
#include "base/callback.h"
#include "base/containers/contains.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/native_window.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/image/image_skia.h"
namespace electron {
MessageBoxSettings::MessageBoxSettings() = default;
MessageBoxSettings::MessageBoxSettings(const MessageBoxSettings&) = default;
MessageBoxSettings::~MessageBoxSettings() = default;
namespace {
// <ID, messageBox> map
std::map<int, NSAlert*>& GetDialogsMap() {
static base::NoDestructor<std::map<int, NSAlert*>> dialogs;
return *dialogs;
}
NSAlert* CreateNSAlert(const MessageBoxSettings& settings) {
// Ignore the title; it's the window title on other platforms and ignorable.
NSAlert* alert = [[NSAlert alloc] init];
[alert setMessageText:base::SysUTF8ToNSString(settings.message)];
[alert setInformativeText:base::SysUTF8ToNSString(settings.detail)];
switch (settings.type) {
case MessageBoxType::kInformation:
alert.alertStyle = NSAlertStyleInformational;
break;
case MessageBoxType::kWarning:
case MessageBoxType::kError:
// NSWarningAlertStyle shows the app icon while NSAlertStyleCritical
// shows a warning icon with an app icon badge. Since there is no
// error variant, lets just use NSAlertStyleCritical.
alert.alertStyle = NSAlertStyleCritical;
break;
default:
break;
}
for (size_t i = 0; i < settings.buttons.size(); ++i) {
NSString* title = base::SysUTF8ToNSString(settings.buttons[i]);
// An empty title causes crash on macOS.
if (settings.buttons[i].empty())
title = @"(empty)";
NSButton* button = [alert addButtonWithTitle:title];
[button setTag:i];
}
NSArray* ns_buttons = [alert buttons];
int button_count = static_cast<int>([ns_buttons count]);
if (settings.default_id >= 0 && settings.default_id < button_count) {
// Highlight the button at default_id
[[ns_buttons objectAtIndex:settings.default_id] highlight:YES];
// The first button added gets set as the default selected, so remove
// that and set the button @ default_id to be default.
[[ns_buttons objectAtIndex:0] setKeyEquivalent:@""];
[[ns_buttons objectAtIndex:settings.default_id] setKeyEquivalent:@"\r"];
}
// Bind cancel id button to escape key if there is more than one button
if (button_count > 1 && settings.cancel_id >= 0 &&
settings.cancel_id < button_count) {
[[ns_buttons objectAtIndex:settings.cancel_id] setKeyEquivalent:@"\e"];
}
if (!settings.checkbox_label.empty()) {
alert.showsSuppressionButton = YES;
alert.suppressionButton.title =
base::SysUTF8ToNSString(settings.checkbox_label);
alert.suppressionButton.state =
settings.checkbox_checked ? NSOnState : NSOffState;
}
if (!settings.icon.isNull()) {
NSImage* image = skia::SkBitmapToNSImageWithColorSpace(
*settings.icon.bitmap(), base::mac::GetGenericRGBColorSpace());
[alert setIcon:image];
}
if (settings.text_width > 0) {
NSRect rect = NSMakeRect(0, 0, settings.text_width, 0);
NSView* accessoryView = [[NSView alloc] initWithFrame:rect];
[alert setAccessoryView:[accessoryView autorelease]];
}
return alert;
}
} // namespace
int ShowMessageBoxSync(const MessageBoxSettings& settings) {
base::scoped_nsobject<NSAlert> alert(CreateNSAlert(settings));
// Use runModal for synchronous alert without parent, since we don't have a
// window to wait for. Also use it when window is provided but it is not
// shown as it would be impossible to dismiss the alert if it is connected
// to invisible window (see #22671).
if (!settings.parent_window || !settings.parent_window->IsVisible())
return [alert runModal];
__block int ret_code = -1;
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[alert beginSheetModalForWindow:window
completionHandler:^(NSModalResponse response) {
ret_code = response;
[NSApp stopModal];
}];
[NSApp runModalForWindow:window];
return ret_code;
}
void ShowMessageBox(const MessageBoxSettings& settings,
MessageBoxCallback callback) {
NSAlert* alert = CreateNSAlert(settings);
// Use runModal for synchronous alert without parent, since we don't have a
// window to wait for.
if (!settings.parent_window) {
int ret = [[alert autorelease] runModal];
std::move(callback).Run(ret, alert.suppressionButton.state == NSOnState);
} else {
if (settings.id) {
if (base::Contains(GetDialogsMap(), *settings.id))
CloseMessageBox(*settings.id);
GetDialogsMap()[*settings.id] = alert;
}
NSWindow* window =
settings.parent_window
? settings.parent_window->GetNativeWindow().GetNativeNSWindow()
: nil;
// Duplicate the callback object here since c is a reference and gcd would
// only store the pointer, by duplication we can force gcd to store a copy.
__block MessageBoxCallback callback_ = std::move(callback);
__block absl::optional<int> id = std::move(settings.id);
__block int cancel_id = settings.cancel_id;
auto handler = ^(NSModalResponse response) {
if (id)
GetDialogsMap().erase(*id);
// When the alert is cancelled programmatically, the response would be
// something like -1000. This currently only happens when users call
// CloseMessageBox API, and we should return cancelId as result.
if (response < 0)
response = cancel_id;
bool suppressed = alert.suppressionButton.state == NSOnState;
[alert release];
// The completionHandler runs inside a transaction commit, and we should
// not do any runModal inside it. However since we can not control what
// users will run in the callback, we have to delay running the callback
// until next tick, otherwise crash like this may happen:
// https://github.com/electron/electron/issues/26884
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback_), response, suppressed));
};
[alert beginSheetModalForWindow:window completionHandler:handler];
}
}
void CloseMessageBox(int id) {
auto it = GetDialogsMap().find(id);
if (it == GetDialogsMap().end()) {
LOG(ERROR) << "CloseMessageBox called with nonexistent ID";
return;
}
[NSApp endSheet:it->second.window];
}
void ShowErrorBox(const std::u16string& title, const std::u16string& content) {
NSAlert* alert = [[NSAlert alloc] init];
[alert setMessageText:base::SysUTF16ToNSString(title)];
[alert setInformativeText:base::SysUTF16ToNSString(content)];
[alert setAlertStyle:NSAlertStyleCritical];
[alert runModal];
[alert release];
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,842 |
[Bug]: Close Stale Issues has not been working since December 5th 2022
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS 13.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
_No response_
### Expected Behavior
Close Stale issues runs and checks out the issues and the number of days before the stale issue is closed.
### Actual Behavior
The Close Stale Issues workflow is failing every day with the error: "[Invalid workflow file: .github/workflows/stale.yml#L27](https://github.com/electron/electron/actions/runs/3870067541/workflow)
The workflow is not valid. .github/workflows/stale.yml (Line: 27, Col: 5): Required property is missing: runs-on"
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36842
|
https://github.com/electron/electron/pull/36843
|
1a9c338c92a50ad2891953a7fd2cecc2e7414bc0
|
f56a26c4f70dca6e9468ba15a82007d4a9ad53d6
| 2023-01-09T14:28:22Z |
c++
| 2023-01-09T18:16:58Z |
.github/workflows/stale.yml
|
name: 'Close stale issues'
on:
schedule:
# 1:30am every day
- cron: '30 1 * * *'
permissions:
issues: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
days-before-stale: 90
days-before-close: 30
stale-issue-label: stale
operations-per-run: 1750
stale-issue-message: >
This issue has been automatically marked as stale. **If this issue is still affecting you, please leave any comment** (for example, "bump"), and we'll keep it open. If you have any new additional information—in particular, if this is still reproducible in the [latest version of Electron](https://www.electronjs.org/releases/stable) or in the [beta](https://www.electronjs.org/releases/beta)—please include it with your comment!
close-issue-message: >
This issue has been closed due to inactivity, and will not be monitored. If this is a bug and you can reproduce this issue on a [supported version of Electron](https://www.electronjs.org/docs/latest/tutorial/electron-timelines#timeline) please open a new issue and include instructions for reproducing the issue.
exempt-issue-labels: "discussion,security \U0001F512,enhancement :sparkles:"
only-pr-labels: not-a-real-label
pending-repro:
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
days-before-stale: -1
days-before-close: 10
stale-issue-label: blocked/need-repro
stale-pr-label: not-a-real-label
operations-per-run: 1750
close-issue-message: >
Unfortunately, without a way to reproduce this issue, we're unable to continue investigation. This issue has been closed and will not be monitored further. If you're able to provide a minimal test case that reproduces this issue on a [supported version of Electron](https://www.electronjs.org/docs/latest/tutorial/electron-timelines#timeline) please open a new issue and include instructions for reproducing the issue.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,842 |
[Bug]: Close Stale Issues has not been working since December 5th 2022
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
17.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS 13.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
_No response_
### Expected Behavior
Close Stale issues runs and checks out the issues and the number of days before the stale issue is closed.
### Actual Behavior
The Close Stale Issues workflow is failing every day with the error: "[Invalid workflow file: .github/workflows/stale.yml#L27](https://github.com/electron/electron/actions/runs/3870067541/workflow)
The workflow is not valid. .github/workflows/stale.yml (Line: 27, Col: 5): Required property is missing: runs-on"
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36842
|
https://github.com/electron/electron/pull/36843
|
1a9c338c92a50ad2891953a7fd2cecc2e7414bc0
|
f56a26c4f70dca6e9468ba15a82007d4a9ad53d6
| 2023-01-09T14:28:22Z |
c++
| 2023-01-09T18:16:58Z |
.github/workflows/stale.yml
|
name: 'Close stale issues'
on:
schedule:
# 1:30am every day
- cron: '30 1 * * *'
permissions:
issues: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
days-before-stale: 90
days-before-close: 30
stale-issue-label: stale
operations-per-run: 1750
stale-issue-message: >
This issue has been automatically marked as stale. **If this issue is still affecting you, please leave any comment** (for example, "bump"), and we'll keep it open. If you have any new additional information—in particular, if this is still reproducible in the [latest version of Electron](https://www.electronjs.org/releases/stable) or in the [beta](https://www.electronjs.org/releases/beta)—please include it with your comment!
close-issue-message: >
This issue has been closed due to inactivity, and will not be monitored. If this is a bug and you can reproduce this issue on a [supported version of Electron](https://www.electronjs.org/docs/latest/tutorial/electron-timelines#timeline) please open a new issue and include instructions for reproducing the issue.
exempt-issue-labels: "discussion,security \U0001F512,enhancement :sparkles:"
only-pr-labels: not-a-real-label
pending-repro:
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
days-before-stale: -1
days-before-close: 10
stale-issue-label: blocked/need-repro
stale-pr-label: not-a-real-label
operations-per-run: 1750
close-issue-message: >
Unfortunately, without a way to reproduce this issue, we're unable to continue investigation. This issue has been closed and will not be monitored further. If you're able to provide a minimal test case that reproduces this issue on a [supported version of Electron](https://www.electronjs.org/docs/latest/tutorial/electron-timelines#timeline) please open a new issue and include instructions for reproducing the issue.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/browser.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/secure_password_input.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Tell the application that application did become active
void DidBecomeActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
#endif
base::Value about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/browser_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::ScopedCFTypeRef<CFErrorRef> out_err;
base::ScopedCFTypeRef<CFURLRef> openingApp(LSCopyDefaultApplicationURLForURL(
(CFURLRef)ns_url, kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::mac::CFToNSCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::mac::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::mac::NSToCFCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code = LSSetDefaultHandlerForURLScheme(
base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
base::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)));
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::mac::CFToNSCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::mac::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::mac::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
// This is needed when this fn is called before the browser
// process is ready, since supported scales are normally set
// by ui::ResourceBundle::InitSharedInstance
// during browser process startup.
if (!is_ready())
gfx::ImageSkia::SetSupportedScales({1.0f});
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options =
DictionaryValueToNSDictionary(about_panel_options_.GetDict());
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
base::scoped_nsobject<NSMutableDictionary> mutable_options(
[options mutableCopy]);
base::scoped_nsobject<NSAttributedString> creditString(
[[NSAttributedString alloc]
initWithString:credits
attributes:@{
NSForegroundColorAttributeName : [NSColor textColor]
}]);
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.GetDict().clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.GetDict().Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/electron_browser_main_parts.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_browser_main_parts.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/ui/color/chrome_color_mixers.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/key_storage_config_linux.h"
#include "components/os_crypt/os_crypt.h"
#include "content/browser/browser_main_loop.h" // nogncheck
#include "content/public/browser/browser_child_process_host_delegate.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
#include "media/base/localized_strings.h"
#include "services/network/public/cpp/features.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "shell/app/electron_main_delegate.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_web_ui_controller_factory.h"
#include "shell/browser/feature_list.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
#include "shell/browser/ui/devtools_manager_delegate.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/logging.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/idle/idle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#include "electron/electron_gtk_stubs.h"
#include "ui/base/cursor/cursor_factory.h"
#include "ui/base/ime/linux/linux_input_method_context_factory.h"
#include "ui/gfx/color_utils.h"
#include "ui/gtk/gtk_compat.h" // nogncheck
#include "ui/gtk/gtk_util.h" // nogncheck
#include "ui/linux/linux_ui.h"
#include "ui/linux/linux_ui_factory.h"
#include "ui/linux/linux_ui_getter.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/display/win/dpi.h"
#include "ui/gfx/system_fonts_win.h"
#include "ui/strings/grit/app_locale_settings.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "components/os_crypt/keychain_password_mac.h"
#include "services/device/public/cpp/geolocation/geolocation_manager.h"
#include "shell/browser/ui/cocoa/views_delegate_mac.h"
#else
#include "shell/browser/ui/views/electron_views_delegate.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/browser_context_keyed_service_factories.h"
#include "extensions/common/extension_api.h"
#include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h"
#include "shell/browser/extensions/electron_extensions_browser_client.h"
#include "shell/common/extensions/electron_extensions_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#include "shell/common/plugin_info.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
namespace electron {
namespace {
#if BUILDFLAG(IS_LINUX)
class LinuxUiGetterImpl : public ui::LinuxUiGetter {
public:
LinuxUiGetterImpl() = default;
~LinuxUiGetterImpl() override = default;
ui::LinuxUiTheme* GetForWindow(aura::Window* window) override {
return GetForProfile(nullptr);
}
ui::LinuxUiTheme* GetForProfile(Profile* profile) override {
return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk);
}
};
#endif
template <typename T>
void Erase(T* container, typename T::iterator iter) {
container->erase(iter);
}
#if BUILDFLAG(IS_WIN)
// gfx::Font callbacks
void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) {
l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override,
&font_adjustment->font_scale);
font_adjustment->font_scale *= display::win::GetAccessibilityFontScale();
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
#endif
std::u16string MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return u"Default";
#if BUILDFLAG(IS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return u"Communications";
#endif
default:
return std::u16string();
}
}
#if BUILDFLAG(IS_LINUX)
// GTK does not provide a way to check if current theme is dark, so we compare
// the text and background luminosity to get a result.
// This trick comes from FireFox.
void UpdateDarkThemeSetting() {
float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel"));
float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel"));
bool is_dark = fg > bg;
// Pass it to NativeUi theme, which is used by the nativeTheme module and most
// places in Electron.
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark);
// Pass it to Web Theme, to make "prefers-color-scheme" media query work.
ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark);
}
#endif
} // namespace
#if BUILDFLAG(IS_LINUX)
class DarkThemeObserver : public ui::NativeThemeObserver {
public:
DarkThemeObserver() = default;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override {
UpdateDarkThemeSetting();
}
};
#endif
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr;
ElectronBrowserMainParts::ElectronBrowserMainParts()
: fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
browser_(std::make_unique<Browser>()),
node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)),
electron_bindings_(
std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {
DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
self_ = this;
}
ElectronBrowserMainParts::~ElectronBrowserMainParts() = default;
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::Get() {
DCHECK(self_);
return self_;
}
bool ElectronBrowserMainParts::SetExitCode(int code) {
if (!exit_code_)
return false;
content::BrowserMainLoop::GetInstance()->SetResultCode(code);
*exit_code_ = code;
return true;
}
int ElectronBrowserMainParts::GetExitCode() const {
return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT);
}
int ElectronBrowserMainParts::PreEarlyInitialization() {
field_trial_list_ = std::make_unique<base::FieldTrialList>();
#if BUILDFLAG(IS_POSIX)
HandleSIGCHLD();
#endif
#if BUILDFLAG(IS_LINUX)
DetectOzonePlatform();
ui::OzonePlatform::PreEarlyInitialization();
#endif
#if BUILDFLAG(IS_MAC)
screen_ = std::make_unique<display::ScopedNativeScreen>();
#endif
ui::ColorProviderManager::Get().AppendColorProviderInitializer(
base::BindRepeating(AddChromeColorMixers));
return GetExitCode();
}
void ElectronBrowserMainParts::PostEarlyInitialization() {
// A workaround was previously needed because there was no ThreadTaskRunner
// set. If this check is failing we may need to re-add that workaround
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
// The ProxyResolverV8 has setup a complete V8 environment, in order to
// avoid conflicts we only initialize our V8 environment after that.
js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
v8::HandleScope scope(js_env_->isolate());
node_bindings_->Initialize();
// Create the global environment.
node::Environment* env = node_bindings_->CreateEnvironment(
js_env_->context(), js_env_->platform());
node_env_ = std::make_unique<NodeEnvironment>(env);
env->set_trace_sync_io(env->options()->trace_sync_io);
// We do not want to crash the main process on unhandled rejections.
env->options()->unhandled_rejections = "warn";
// Add Electron extended APIs.
electron_bindings_->BindTo(js_env_->isolate(), env->process_object());
// Create explicit microtasks runner.
js_env_->CreateMicrotasksRunner();
// Wrap the uv loop with global env.
node_bindings_->set_uv_env(env);
// Load everything.
node_bindings_->LoadEnvironment(env);
// We already initialized the feature list in PreEarlyInitialization(), but
// the user JS script would not have had a chance to alter the command-line
// switches at that point. Lets reinitialize it here to pick up the
// command-line changes.
base::FeatureList::ClearInstanceForTesting();
InitializeFeatureList();
// Initialize field trials.
InitializeFieldTrials();
// Reinitialize logging now that the app has had a chance to set the app name
// and/or user data directory.
logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
/* is_preinit = */ false);
// Initialize after user script environment creation.
fake_browser_process_->PostEarlyInitialization();
}
int ElectronBrowserMainParts::PreCreateThreads() {
if (!views::LayoutProvider::Get()) {
layout_provider_ = std::make_unique<views::LayoutProvider>();
}
// Fetch the system locale for Electron.
#if BUILDFLAG(IS_MAC)
fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale());
#else
fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale());
#endif
auto* command_line = base::CommandLine::ForCurrentProcess();
std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
#if BUILDFLAG(IS_MAC)
// The browser process only wants to support the language Cocoa will use,
// so force the app locale to be overridden with that value. This must
// happen before the ResourceBundle is loaded
if (locale.empty())
l10n_util::OverrideLocaleWithCocoaLocale();
#elif BUILDFLAG(IS_LINUX)
// l10n_util::GetApplicationLocaleInternal uses g_get_language_names(),
// which keys off of getenv("LC_ALL").
// We must set this env first to make ui::ResourceBundle accept the custom
// locale.
auto env = base::Environment::Create();
absl::optional<std::string> lc_all;
if (!locale.empty()) {
std::string str;
if (env->GetVar("LC_ALL", &str))
lc_all.emplace(std::move(str));
env->SetVar("LC_ALL", locale.c_str());
}
#endif
// Load resources bundle according to locale.
std::string loaded_locale = LoadResourceBundle(locale);
#if defined(USE_AURA)
// NB: must be called _after_ locale resource bundle is loaded,
// because ui lib makes use of it in X11
if (!display::Screen::GetScreen()) {
screen_ = views::CreateDesktopScreen();
}
#endif
// Initialize the app locale for Electron and Chromium.
std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale);
ElectronBrowserClient::SetApplicationLocale(app_locale);
fake_browser_process_->SetApplicationLocale(app_locale);
#if BUILDFLAG(IS_LINUX)
// Reset to the original LC_ALL since we should not be changing it.
if (!locale.empty()) {
if (lc_all)
env->SetVar("LC_ALL", *lc_all);
else
env->UnSetVar("LC_ALL");
}
#endif
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
#if BUILDFLAG(IS_MAC)
ui::InitIdleMonitor();
#endif
fake_browser_process_->PreCreateThreads();
// Notify observers.
Browser::Get()->PreCreateThreads();
return 0;
}
void ElectronBrowserMainParts::PostCreateThreads() {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
#if BUILDFLAG(ENABLE_PLUGINS)
// PluginService can only be used on the UI thread
// and ContentClient::AddPlugins gets called for both browser and render
// process where the latter will not have UI thread which leads to DCHECK.
// Separate the WebPluginInfo registration for these processes.
std::vector<content::WebPluginInfo> plugins;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->RefreshPlugins();
GetInternalPlugins(&plugins);
for (const auto& plugin : plugins)
plugin_service->RegisterInternalPlugin(plugin, true);
#endif
}
void ElectronBrowserMainParts::PostDestroyThreads() {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_browser_client_.reset();
extensions::ExtensionsBrowserClient::Set(nullptr);
#endif
#if BUILDFLAG(IS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
fake_browser_process_->PostDestroyThreads();
}
void ElectronBrowserMainParts::ToolkitInitialized() {
#if BUILDFLAG(IS_LINUX)
auto* linux_ui = ui::GetDefaultLinuxUi();
CHECK(linux_ui);
linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>();
// Try loading gtk symbols used by Electron.
electron::InitializeElectron_gtk(gtk::GetLibGtk());
if (!electron::IsElectron_gtkInitialized()) {
electron::UninitializeElectron_gtk();
}
electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf());
CHECK(electron::IsElectron_gdk_pixbufInitialized())
<< "Failed to initialize libgdk_pixbuf-2.0.so.0";
// Chromium does not respect GTK dark theme setting, but they may change
// in future and this code might be no longer needed. Check the Chromium
// issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=998903
UpdateDarkThemeSetting();
// Update the native theme when GTK theme changes. The GetNativeTheme
// here returns a NativeThemeGtk, which monitors GTK settings.
dark_theme_observer_ = std::make_unique<DarkThemeObserver>();
auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr);
CHECK(linux_ui_theme);
linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get());
ui::LinuxUi::SetInstance(linux_ui);
// Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager
// implementation). Start observing them once it's initialized.
ui::CursorFactory::GetInstance()->ObserveThemeChanges();
#endif
#if defined(USE_AURA)
wm_state_ = std::make_unique<wm::WMState>();
#endif
#if BUILDFLAG(IS_WIN)
gfx::win::SetAdjustFontCallback(&AdjustUIFont);
gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
#endif
#if BUILDFLAG(IS_MAC)
views_delegate_ = std::make_unique<ViewsDelegateMac>();
#else
views_delegate_ = std::make_unique<ViewsDelegate>();
#endif
}
int ElectronBrowserMainParts::PreMainMessageLoopRun() {
// Run user's main script before most things get initialized, so we can have
// a chance to setup everything.
node_bindings_->PrepareEmbedThread();
node_bindings_->StartPolling();
// url::Add*Scheme are not threadsafe, this helps prevent data races.
url::LockSchemeRegistries();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_client_ = std::make_unique<ElectronExtensionsClient>();
extensions::ExtensionsClient::Set(extensions_client_.get());
// BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient.
extensions_browser_client_ =
std::make_unique<ElectronExtensionsBrowserClient>();
extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt();
extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt();
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckServiceFactory::GetInstance();
#endif
content::WebUIControllerFactory::RegisterFactory(
ElectronWebUIControllerFactory::GetInstance());
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) {
// --remote-debugging-pipe
auto on_disconnect = base::BindOnce([]() {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); }));
});
content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
std::move(on_disconnect));
} else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
// --remote-debugging-port
DevToolsManagerDelegate::StartHttpHandler();
}
#if !BUILDFLAG(IS_MAC)
// The corresponding call in macOS is in ElectronApplicationDelegate.
Browser::Get()->WillFinishLaunching();
Browser::Get()->DidFinishLaunching(base::Value::Dict());
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
return GetExitCode();
}
void ElectronBrowserMainParts::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
exit_code_ = content::RESULT_CODE_NORMAL_EXIT;
Browser::Get()->SetMainMessageLoopQuitClosure(
run_loop->QuitWhenIdleClosure());
}
void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
std::string app_name = electron::Browser::Get()->GetName();
#endif
#if BUILDFLAG(IS_LINUX)
auto shutdown_cb =
base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop(
std::move(shutdown_cb),
content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput}));
bluez::DBusBluezManagerWrapperLinux::Initialize();
// Set up crypt config. This needs to be done before anything starts the
// network service, as the raw encryption key needs to be shared with the
// network service for encrypted cookie storage.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::unique_ptr<os_crypt::Config> config =
std::make_unique<os_crypt::Config>();
// Forward to os_crypt the flag to use a specific password store.
config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore);
config->product_name = app_name;
config->application_name = app_name;
config->main_thread_runner = base::ThreadTaskRunnerHandle::Get();
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
config->should_use_preference =
command_line.HasSwitch(::switches::kEnableEncryptionSelection);
base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
OSCrypt::SetConfig(std::move(config));
#endif
#if BUILDFLAG(IS_MAC)
KeychainPassword::GetServiceName() = app_name + " Safe Storage";
KeychainPassword::GetAccountName() = app_name;
#endif
#if BUILDFLAG(IS_POSIX)
// Exit in response to SIGINT, SIGTERM, etc.
InstallShutdownSignalHandlers(
base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())),
content::GetUIThreadTaskRunner({}));
#endif
}
void ElectronBrowserMainParts::PostMainMessageLoopRun() {
#if BUILDFLAG(IS_MAC)
FreeAppDelegate();
#endif
// Shutdown the DownloadManager before destroying Node to prevent
// DownloadItem callbacks from crashing.
for (auto& iter : ElectronBrowserContext::browser_context_map()) {
auto* download_manager = iter.second.get()->GetDownloadManager();
if (download_manager) {
download_manager->Shutdown();
}
}
// Shutdown utility process created with Electron API before
// stopping Node.js so that exit events can be emitted. We don't let
// content layer perform this action since it destroys
// child process only after this step (PostMainMessageLoopRun) via
// BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our
// use case.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108
//
// The following logic is based on
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159
//
// Although content::BrowserChildProcessHostIterator is only to be called from
// IO thread, it is safe to call from PostMainMessageLoopRun because thread
// restrictions have been lifted.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078
for (content::BrowserChildProcessHostIterator it(
content::PROCESS_TYPE_UTILITY);
!it.Done(); ++it) {
if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) {
auto& process = it.GetData().GetProcess();
if (!process.IsValid())
continue;
auto utility_process_wrapper =
api::UtilityProcessWrapper::FromProcessId(process.Pid());
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(0 /* exit_code */);
}
}
// Destroy node platform after all destructors_ are executed, as they may
// invoke Node/V8 APIs inside them.
node_env_->env()->set_trace_sync_io(false);
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_->env());
node_env_.reset();
auto default_context_key = ElectronBrowserContext::PartitionKey("", false);
std::unique_ptr<ElectronBrowserContext> default_context = std::move(
ElectronBrowserContext::browser_context_map()[default_context_key]);
ElectronBrowserContext::browser_context_map().clear();
default_context.reset();
fake_browser_process_->PostMainMessageLoopRun();
content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler();
#if BUILDFLAG(IS_LINUX)
ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun();
#endif
}
#if !BUILDFLAG(IS_MAC)
void ElectronBrowserMainParts::PreCreateMainMessageLoop() {
PreCreateMainMessageLoopCommon();
}
#endif
void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() {
#if BUILDFLAG(IS_MAC)
InitializeMainNib();
RegisterURLHandler();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
#if BUILDFLAG(IS_WIN)
auto* local_state = g_browser_process->local_state();
DCHECK(local_state);
bool os_crypt_init = OSCrypt::Init(local_state);
DCHECK(os_crypt_init);
#endif
}
device::mojom::GeolocationControl*
ElectronBrowserMainParts::GetGeolocationControl() {
if (!geolocation_control_) {
content::GetDeviceService().BindGeolocationControl(
geolocation_control_.BindNewPipeAndPassReceiver());
}
return geolocation_control_.get();
}
#if BUILDFLAG(IS_MAC)
device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() {
return geolocation_manager_.get();
}
#endif
IconManager* ElectronBrowserMainParts::GetIconManager() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!icon_manager_.get())
icon_manager_ = std::make_unique<IconManager>();
return icon_manager_.get();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/browser.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/secure_password_input.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Tell the application that application did become active
void DidBecomeActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
#endif
base::Value about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/browser_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::ScopedCFTypeRef<CFErrorRef> out_err;
base::ScopedCFTypeRef<CFURLRef> openingApp(LSCopyDefaultApplicationURLForURL(
(CFURLRef)ns_url, kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::mac::CFToNSCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::mac::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::mac::NSToCFCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code = LSSetDefaultHandlerForURLScheme(
base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::mac::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
base::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)));
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::mac::CFToNSCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::mac::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::mac::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
// This is needed when this fn is called before the browser
// process is ready, since supported scales are normally set
// by ui::ResourceBundle::InitSharedInstance
// during browser process startup.
if (!is_ready())
gfx::ImageSkia::SetSupportedScales({1.0f});
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options =
DictionaryValueToNSDictionary(about_panel_options_.GetDict());
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
base::scoped_nsobject<NSMutableDictionary> mutable_options(
[options mutableCopy]);
base::scoped_nsobject<NSAttributedString> creditString(
[[NSAttributedString alloc]
initWithString:credits
attributes:@{
NSForegroundColorAttributeName : [NSColor textColor]
}]);
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.GetDict().clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.GetDict().Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,539 |
[Bug]: settrafficLightPosition on macOS calculates incorrectly for RTL system languages
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS ventura 13.0.1
### What arch are you using?
x64
### Last Known Working Electron version
N/A
### Expected Behavior
<img width="807" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٣٣ ص" src="https://user-images.githubusercontent.com/964386/205172660-1e95a7ac-cb60-4873-8a27-e93586547cb0.png">
### Actual Behavior
<img width="804" alt="لقطة الشاشة ٢٠٢٢-١٢-٠٢ في ٧ ٢٨ ٥٧ ص" src="https://user-images.githubusercontent.com/964386/205172682-87a89c5c-a178-4e25-b2a8-923d50f079c5.png">
### Testcase Gist URL
https://gist.github.com/deepak1556/3025154b48cb156126cfdcc74338ec8e
### Additional Information
Set the system preferred language to any RTL language value and restart the OS. When system preferred language is in RTL and application language is set to `en`, the traffic light positions are calculated from outside the window frame positions.
|
https://github.com/electron/electron/issues/36539
|
https://github.com/electron/electron/pull/36839
|
168726a0521dd53f160b216f7b84832b1368fff5
|
414791232a79c783d3d758fe11a864344d513660
| 2022-12-01T22:33:43Z |
c++
| 2023-01-10T11:19:00Z |
shell/browser/electron_browser_main_parts.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_browser_main_parts.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/ui/color/chrome_color_mixers.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/key_storage_config_linux.h"
#include "components/os_crypt/os_crypt.h"
#include "content/browser/browser_main_loop.h" // nogncheck
#include "content/public/browser/browser_child_process_host_delegate.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
#include "media/base/localized_strings.h"
#include "services/network/public/cpp/features.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "shell/app/electron_main_delegate.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_web_ui_controller_factory.h"
#include "shell/browser/feature_list.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
#include "shell/browser/ui/devtools_manager_delegate.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/logging.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/idle/idle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#include "electron/electron_gtk_stubs.h"
#include "ui/base/cursor/cursor_factory.h"
#include "ui/base/ime/linux/linux_input_method_context_factory.h"
#include "ui/gfx/color_utils.h"
#include "ui/gtk/gtk_compat.h" // nogncheck
#include "ui/gtk/gtk_util.h" // nogncheck
#include "ui/linux/linux_ui.h"
#include "ui/linux/linux_ui_factory.h"
#include "ui/linux/linux_ui_getter.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/display/win/dpi.h"
#include "ui/gfx/system_fonts_win.h"
#include "ui/strings/grit/app_locale_settings.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "components/os_crypt/keychain_password_mac.h"
#include "services/device/public/cpp/geolocation/geolocation_manager.h"
#include "shell/browser/ui/cocoa/views_delegate_mac.h"
#else
#include "shell/browser/ui/views/electron_views_delegate.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/browser_context_keyed_service_factories.h"
#include "extensions/common/extension_api.h"
#include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h"
#include "shell/browser/extensions/electron_extensions_browser_client.h"
#include "shell/common/extensions/electron_extensions_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#include "shell/common/plugin_info.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
namespace electron {
namespace {
#if BUILDFLAG(IS_LINUX)
class LinuxUiGetterImpl : public ui::LinuxUiGetter {
public:
LinuxUiGetterImpl() = default;
~LinuxUiGetterImpl() override = default;
ui::LinuxUiTheme* GetForWindow(aura::Window* window) override {
return GetForProfile(nullptr);
}
ui::LinuxUiTheme* GetForProfile(Profile* profile) override {
return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk);
}
};
#endif
template <typename T>
void Erase(T* container, typename T::iterator iter) {
container->erase(iter);
}
#if BUILDFLAG(IS_WIN)
// gfx::Font callbacks
void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) {
l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override,
&font_adjustment->font_scale);
font_adjustment->font_scale *= display::win::GetAccessibilityFontScale();
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
#endif
std::u16string MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return u"Default";
#if BUILDFLAG(IS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return u"Communications";
#endif
default:
return std::u16string();
}
}
#if BUILDFLAG(IS_LINUX)
// GTK does not provide a way to check if current theme is dark, so we compare
// the text and background luminosity to get a result.
// This trick comes from FireFox.
void UpdateDarkThemeSetting() {
float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel"));
float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel"));
bool is_dark = fg > bg;
// Pass it to NativeUi theme, which is used by the nativeTheme module and most
// places in Electron.
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark);
// Pass it to Web Theme, to make "prefers-color-scheme" media query work.
ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark);
}
#endif
} // namespace
#if BUILDFLAG(IS_LINUX)
class DarkThemeObserver : public ui::NativeThemeObserver {
public:
DarkThemeObserver() = default;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override {
UpdateDarkThemeSetting();
}
};
#endif
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr;
ElectronBrowserMainParts::ElectronBrowserMainParts()
: fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
browser_(std::make_unique<Browser>()),
node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)),
electron_bindings_(
std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {
DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
self_ = this;
}
ElectronBrowserMainParts::~ElectronBrowserMainParts() = default;
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::Get() {
DCHECK(self_);
return self_;
}
bool ElectronBrowserMainParts::SetExitCode(int code) {
if (!exit_code_)
return false;
content::BrowserMainLoop::GetInstance()->SetResultCode(code);
*exit_code_ = code;
return true;
}
int ElectronBrowserMainParts::GetExitCode() const {
return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT);
}
int ElectronBrowserMainParts::PreEarlyInitialization() {
field_trial_list_ = std::make_unique<base::FieldTrialList>();
#if BUILDFLAG(IS_POSIX)
HandleSIGCHLD();
#endif
#if BUILDFLAG(IS_LINUX)
DetectOzonePlatform();
ui::OzonePlatform::PreEarlyInitialization();
#endif
#if BUILDFLAG(IS_MAC)
screen_ = std::make_unique<display::ScopedNativeScreen>();
#endif
ui::ColorProviderManager::Get().AppendColorProviderInitializer(
base::BindRepeating(AddChromeColorMixers));
return GetExitCode();
}
void ElectronBrowserMainParts::PostEarlyInitialization() {
// A workaround was previously needed because there was no ThreadTaskRunner
// set. If this check is failing we may need to re-add that workaround
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
// The ProxyResolverV8 has setup a complete V8 environment, in order to
// avoid conflicts we only initialize our V8 environment after that.
js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
v8::HandleScope scope(js_env_->isolate());
node_bindings_->Initialize();
// Create the global environment.
node::Environment* env = node_bindings_->CreateEnvironment(
js_env_->context(), js_env_->platform());
node_env_ = std::make_unique<NodeEnvironment>(env);
env->set_trace_sync_io(env->options()->trace_sync_io);
// We do not want to crash the main process on unhandled rejections.
env->options()->unhandled_rejections = "warn";
// Add Electron extended APIs.
electron_bindings_->BindTo(js_env_->isolate(), env->process_object());
// Create explicit microtasks runner.
js_env_->CreateMicrotasksRunner();
// Wrap the uv loop with global env.
node_bindings_->set_uv_env(env);
// Load everything.
node_bindings_->LoadEnvironment(env);
// We already initialized the feature list in PreEarlyInitialization(), but
// the user JS script would not have had a chance to alter the command-line
// switches at that point. Lets reinitialize it here to pick up the
// command-line changes.
base::FeatureList::ClearInstanceForTesting();
InitializeFeatureList();
// Initialize field trials.
InitializeFieldTrials();
// Reinitialize logging now that the app has had a chance to set the app name
// and/or user data directory.
logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
/* is_preinit = */ false);
// Initialize after user script environment creation.
fake_browser_process_->PostEarlyInitialization();
}
int ElectronBrowserMainParts::PreCreateThreads() {
if (!views::LayoutProvider::Get()) {
layout_provider_ = std::make_unique<views::LayoutProvider>();
}
// Fetch the system locale for Electron.
#if BUILDFLAG(IS_MAC)
fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale());
#else
fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale());
#endif
auto* command_line = base::CommandLine::ForCurrentProcess();
std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
#if BUILDFLAG(IS_MAC)
// The browser process only wants to support the language Cocoa will use,
// so force the app locale to be overridden with that value. This must
// happen before the ResourceBundle is loaded
if (locale.empty())
l10n_util::OverrideLocaleWithCocoaLocale();
#elif BUILDFLAG(IS_LINUX)
// l10n_util::GetApplicationLocaleInternal uses g_get_language_names(),
// which keys off of getenv("LC_ALL").
// We must set this env first to make ui::ResourceBundle accept the custom
// locale.
auto env = base::Environment::Create();
absl::optional<std::string> lc_all;
if (!locale.empty()) {
std::string str;
if (env->GetVar("LC_ALL", &str))
lc_all.emplace(std::move(str));
env->SetVar("LC_ALL", locale.c_str());
}
#endif
// Load resources bundle according to locale.
std::string loaded_locale = LoadResourceBundle(locale);
#if defined(USE_AURA)
// NB: must be called _after_ locale resource bundle is loaded,
// because ui lib makes use of it in X11
if (!display::Screen::GetScreen()) {
screen_ = views::CreateDesktopScreen();
}
#endif
// Initialize the app locale for Electron and Chromium.
std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale);
ElectronBrowserClient::SetApplicationLocale(app_locale);
fake_browser_process_->SetApplicationLocale(app_locale);
#if BUILDFLAG(IS_LINUX)
// Reset to the original LC_ALL since we should not be changing it.
if (!locale.empty()) {
if (lc_all)
env->SetVar("LC_ALL", *lc_all);
else
env->UnSetVar("LC_ALL");
}
#endif
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
#if BUILDFLAG(IS_MAC)
ui::InitIdleMonitor();
#endif
fake_browser_process_->PreCreateThreads();
// Notify observers.
Browser::Get()->PreCreateThreads();
return 0;
}
void ElectronBrowserMainParts::PostCreateThreads() {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
#if BUILDFLAG(ENABLE_PLUGINS)
// PluginService can only be used on the UI thread
// and ContentClient::AddPlugins gets called for both browser and render
// process where the latter will not have UI thread which leads to DCHECK.
// Separate the WebPluginInfo registration for these processes.
std::vector<content::WebPluginInfo> plugins;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->RefreshPlugins();
GetInternalPlugins(&plugins);
for (const auto& plugin : plugins)
plugin_service->RegisterInternalPlugin(plugin, true);
#endif
}
void ElectronBrowserMainParts::PostDestroyThreads() {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_browser_client_.reset();
extensions::ExtensionsBrowserClient::Set(nullptr);
#endif
#if BUILDFLAG(IS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
fake_browser_process_->PostDestroyThreads();
}
void ElectronBrowserMainParts::ToolkitInitialized() {
#if BUILDFLAG(IS_LINUX)
auto* linux_ui = ui::GetDefaultLinuxUi();
CHECK(linux_ui);
linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>();
// Try loading gtk symbols used by Electron.
electron::InitializeElectron_gtk(gtk::GetLibGtk());
if (!electron::IsElectron_gtkInitialized()) {
electron::UninitializeElectron_gtk();
}
electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf());
CHECK(electron::IsElectron_gdk_pixbufInitialized())
<< "Failed to initialize libgdk_pixbuf-2.0.so.0";
// Chromium does not respect GTK dark theme setting, but they may change
// in future and this code might be no longer needed. Check the Chromium
// issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=998903
UpdateDarkThemeSetting();
// Update the native theme when GTK theme changes. The GetNativeTheme
// here returns a NativeThemeGtk, which monitors GTK settings.
dark_theme_observer_ = std::make_unique<DarkThemeObserver>();
auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr);
CHECK(linux_ui_theme);
linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get());
ui::LinuxUi::SetInstance(linux_ui);
// Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager
// implementation). Start observing them once it's initialized.
ui::CursorFactory::GetInstance()->ObserveThemeChanges();
#endif
#if defined(USE_AURA)
wm_state_ = std::make_unique<wm::WMState>();
#endif
#if BUILDFLAG(IS_WIN)
gfx::win::SetAdjustFontCallback(&AdjustUIFont);
gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
#endif
#if BUILDFLAG(IS_MAC)
views_delegate_ = std::make_unique<ViewsDelegateMac>();
#else
views_delegate_ = std::make_unique<ViewsDelegate>();
#endif
}
int ElectronBrowserMainParts::PreMainMessageLoopRun() {
// Run user's main script before most things get initialized, so we can have
// a chance to setup everything.
node_bindings_->PrepareEmbedThread();
node_bindings_->StartPolling();
// url::Add*Scheme are not threadsafe, this helps prevent data races.
url::LockSchemeRegistries();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_client_ = std::make_unique<ElectronExtensionsClient>();
extensions::ExtensionsClient::Set(extensions_client_.get());
// BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient.
extensions_browser_client_ =
std::make_unique<ElectronExtensionsBrowserClient>();
extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt();
extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt();
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckServiceFactory::GetInstance();
#endif
content::WebUIControllerFactory::RegisterFactory(
ElectronWebUIControllerFactory::GetInstance());
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) {
// --remote-debugging-pipe
auto on_disconnect = base::BindOnce([]() {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); }));
});
content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
std::move(on_disconnect));
} else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
// --remote-debugging-port
DevToolsManagerDelegate::StartHttpHandler();
}
#if !BUILDFLAG(IS_MAC)
// The corresponding call in macOS is in ElectronApplicationDelegate.
Browser::Get()->WillFinishLaunching();
Browser::Get()->DidFinishLaunching(base::Value::Dict());
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
return GetExitCode();
}
void ElectronBrowserMainParts::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
exit_code_ = content::RESULT_CODE_NORMAL_EXIT;
Browser::Get()->SetMainMessageLoopQuitClosure(
run_loop->QuitWhenIdleClosure());
}
void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
std::string app_name = electron::Browser::Get()->GetName();
#endif
#if BUILDFLAG(IS_LINUX)
auto shutdown_cb =
base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop(
std::move(shutdown_cb),
content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput}));
bluez::DBusBluezManagerWrapperLinux::Initialize();
// Set up crypt config. This needs to be done before anything starts the
// network service, as the raw encryption key needs to be shared with the
// network service for encrypted cookie storage.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::unique_ptr<os_crypt::Config> config =
std::make_unique<os_crypt::Config>();
// Forward to os_crypt the flag to use a specific password store.
config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore);
config->product_name = app_name;
config->application_name = app_name;
config->main_thread_runner = base::ThreadTaskRunnerHandle::Get();
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
config->should_use_preference =
command_line.HasSwitch(::switches::kEnableEncryptionSelection);
base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
OSCrypt::SetConfig(std::move(config));
#endif
#if BUILDFLAG(IS_MAC)
KeychainPassword::GetServiceName() = app_name + " Safe Storage";
KeychainPassword::GetAccountName() = app_name;
#endif
#if BUILDFLAG(IS_POSIX)
// Exit in response to SIGINT, SIGTERM, etc.
InstallShutdownSignalHandlers(
base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())),
content::GetUIThreadTaskRunner({}));
#endif
}
void ElectronBrowserMainParts::PostMainMessageLoopRun() {
#if BUILDFLAG(IS_MAC)
FreeAppDelegate();
#endif
// Shutdown the DownloadManager before destroying Node to prevent
// DownloadItem callbacks from crashing.
for (auto& iter : ElectronBrowserContext::browser_context_map()) {
auto* download_manager = iter.second.get()->GetDownloadManager();
if (download_manager) {
download_manager->Shutdown();
}
}
// Shutdown utility process created with Electron API before
// stopping Node.js so that exit events can be emitted. We don't let
// content layer perform this action since it destroys
// child process only after this step (PostMainMessageLoopRun) via
// BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our
// use case.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108
//
// The following logic is based on
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159
//
// Although content::BrowserChildProcessHostIterator is only to be called from
// IO thread, it is safe to call from PostMainMessageLoopRun because thread
// restrictions have been lifted.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078
for (content::BrowserChildProcessHostIterator it(
content::PROCESS_TYPE_UTILITY);
!it.Done(); ++it) {
if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) {
auto& process = it.GetData().GetProcess();
if (!process.IsValid())
continue;
auto utility_process_wrapper =
api::UtilityProcessWrapper::FromProcessId(process.Pid());
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(0 /* exit_code */);
}
}
// Destroy node platform after all destructors_ are executed, as they may
// invoke Node/V8 APIs inside them.
node_env_->env()->set_trace_sync_io(false);
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_->env());
node_env_.reset();
auto default_context_key = ElectronBrowserContext::PartitionKey("", false);
std::unique_ptr<ElectronBrowserContext> default_context = std::move(
ElectronBrowserContext::browser_context_map()[default_context_key]);
ElectronBrowserContext::browser_context_map().clear();
default_context.reset();
fake_browser_process_->PostMainMessageLoopRun();
content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler();
#if BUILDFLAG(IS_LINUX)
ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun();
#endif
}
#if !BUILDFLAG(IS_MAC)
void ElectronBrowserMainParts::PreCreateMainMessageLoop() {
PreCreateMainMessageLoopCommon();
}
#endif
void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() {
#if BUILDFLAG(IS_MAC)
InitializeMainNib();
RegisterURLHandler();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
#if BUILDFLAG(IS_WIN)
auto* local_state = g_browser_process->local_state();
DCHECK(local_state);
bool os_crypt_init = OSCrypt::Init(local_state);
DCHECK(os_crypt_init);
#endif
}
device::mojom::GeolocationControl*
ElectronBrowserMainParts::GetGeolocationControl() {
if (!geolocation_control_) {
content::GetDeviceService().BindGeolocationControl(
geolocation_control_.BindNewPipeAndPassReceiver());
}
return geolocation_control_.get();
}
#if BUILDFLAG(IS_MAC)
device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() {
return geolocation_manager_.get();
}
#endif
IconManager* ElectronBrowserMainParts::GetIconManager() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!icon_manager_.get())
icon_manager_ = std::make_unique<IconManager>();
return icon_manager_.get();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jeremy Rose <[email protected]>
Date: Tue, 12 Jul 2022 16:51:43 -0700
Subject: short-circuit permissions checks in MediaStreamDevicesController
The //components/permissions architecture is complicated and not that
widely used in Chromium, and mostly oriented around showing permissions
UI and/or remembering per-site permissions, which we're not interested
in.
Since we do a permissions check prior to invoking the
MediaStreamDevicesController, and don't (yet) provide the ability to set
granular permissions (e.g. allow video but not audio), just
short-circuit all the permissions checks in MSDC for now to allow us to
unduplicate this code.
diff --git a/components/webrtc/media_stream_devices_controller.cc b/components/webrtc/media_stream_devices_controller.cc
index 7dbbcc13901dcd8b7a9ca9c9bdce4f924c1c6a55..5de44c5c20c92a1793060492f925519d6b8befe5 100644
--- a/components/webrtc/media_stream_devices_controller.cc
+++ b/components/webrtc/media_stream_devices_controller.cc
@@ -92,10 +92,13 @@ void MediaStreamDevicesController::RequestPermissions(
std::vector<blink::PermissionType> permission_types;
+#if 0
content::PermissionController* permission_controller =
web_contents->GetBrowserContext()->GetPermissionController();
+#endif
if (controller->ShouldRequestAudio()) {
+#if 0
content::PermissionResult permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::AUDIO_CAPTURE, rfh);
@@ -110,10 +113,12 @@ void MediaStreamDevicesController::RequestPermissions(
content::PermissionStatusSource::FENCED_FRAME);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::AUDIO_CAPTURE);
}
if (controller->ShouldRequestVideo()) {
+#if 0
content::PermissionResult permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::VIDEO_CAPTURE, rfh);
@@ -128,6 +133,7 @@ void MediaStreamDevicesController::RequestPermissions(
content::PermissionStatusSource::FENCED_FRAME);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::VIDEO_CAPTURE);
@@ -139,6 +145,7 @@ void MediaStreamDevicesController::RequestPermissions(
// pan-tilt-zoom permission and there are suitable PTZ capable devices
// available.
if (request.request_pan_tilt_zoom_permission && has_pan_tilt_zoom_camera) {
+#if 0
permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::CAMERA_PAN_TILT_ZOOM, rfh);
@@ -148,6 +155,7 @@ void MediaStreamDevicesController::RequestPermissions(
controller->RunCallback(/*blocked_by_permissions_policy=*/false);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::CAMERA_PAN_TILT_ZOOM);
}
@@ -434,6 +442,7 @@ bool MediaStreamDevicesController::PermissionIsBlockedForReason(
return false;
}
+#if 0
// TODO(raymes): This function wouldn't be needed if
// PermissionManager::RequestPermissions returned a denial reason.
content::PermissionResult result =
@@ -444,6 +453,7 @@ bool MediaStreamDevicesController::PermissionIsBlockedForReason(
DCHECK_EQ(blink::mojom::PermissionStatus::DENIED, result.status);
return true;
}
+#endif
return false;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
shell/browser/web_contents_permission_helper.cc
|
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/web_contents_permission_helper.h"
#include <memory>
#include <string>
#include <utility>
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/electron_permission_manager.h"
// #include "shell/browser/media/media_stream_devices_controller.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/webrtc/media_stream_devices_controller.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
namespace {
std::string MediaStreamTypeToString(blink::mojom::MediaStreamType type) {
switch (type) {
case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE:
return "audio";
case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE:
return "video";
default:
return "unknown";
}
}
} // namespace
namespace electron {
namespace {
// Handles requests for legacy-style `navigator.getUserMedia(...)` calls.
// This includes desktop capture through the chromeMediaSource /
// chromeMediaSourceId constraints.
void HandleUserMediaRequest(const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
blink::mojom::StreamDevicesSetPtr stream_devices_set =
blink::mojom::StreamDevicesSet::New();
stream_devices_set->stream_devices.emplace_back(
blink::mojom::StreamDevices::New());
blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0];
if (request.audio_type ==
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
devices.audio_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE, "", "");
}
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE) {
devices.video_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE, "", "");
}
if (request.audio_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE) {
devices.audio_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE, "loopback",
"System Audio");
}
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE) {
content::DesktopMediaID screen_id;
// If the device id wasn't specified then this is a screen capture request
// (i.e. chooseDesktopMedia() API wasn't used to generate device id).
if (request.requested_video_device_id.empty()) {
screen_id = content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN,
-1 /* kFullDesktopScreenId */);
} else {
screen_id =
content::DesktopMediaID::Parse(request.requested_video_device_id);
}
devices.video_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE,
screen_id.ToString(), "Screen");
}
bool empty =
!devices.audio_device.has_value() && !devices.video_device.has_value();
std::move(callback).Run(
*stream_devices_set,
empty ? blink::mojom::MediaStreamRequestResult::NO_HARDWARE
: blink::mojom::MediaStreamRequestResult::OK,
nullptr);
}
void OnMediaStreamRequestResponse(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result,
bool blocked_by_permissions_policy,
ContentSetting audio_setting,
ContentSetting video_setting) {
std::move(callback).Run(stream_devices_set, result, nullptr);
}
void MediaAccessAllowed(const content::MediaStreamRequest& request,
content::MediaResponseCallback callback,
bool allowed) {
if (allowed) {
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE ||
request.video_type ==
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
HandleUserMediaRequest(request, std::move(callback));
} else if (request.video_type ==
blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) {
webrtc::MediaStreamDevicesController::RequestPermissions(
request, MediaCaptureDevicesDispatcher::GetInstance(),
base::BindOnce(&OnMediaStreamRequestResponse, std::move(callback)));
} else if (request.video_type ==
blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE ||
request.video_type == blink::mojom::MediaStreamType::
DISPLAY_VIDEO_CAPTURE_THIS_TAB ||
request.video_type ==
blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE_SET ||
request.audio_type ==
blink::mojom::MediaStreamType::DISPLAY_AUDIO_CAPTURE) {
content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
request.render_process_id, request.render_frame_id);
if (!rfh)
return;
content::BrowserContext* browser_context = rfh->GetBrowserContext();
ElectronBrowserContext* electron_browser_context =
static_cast<ElectronBrowserContext*>(browser_context);
auto split_callback = base::SplitOnceCallback(std::move(callback));
if (electron_browser_context->ChooseDisplayMediaDevice(
request, std::move(split_callback.second)))
return;
std::move(split_callback.first)
.Run(blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr);
} else {
std::move(callback).Run(
blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr);
}
} else {
std::move(callback).Run(
blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED, nullptr);
}
}
void OnPermissionResponse(base::OnceCallback<void(bool)> callback,
blink::mojom::PermissionStatus status) {
if (status == blink::mojom::PermissionStatus::GRANTED)
std::move(callback).Run(true);
else
std::move(callback).Run(false);
}
} // namespace
WebContentsPermissionHelper::WebContentsPermissionHelper(
content::WebContents* web_contents)
: content::WebContentsUserData<WebContentsPermissionHelper>(*web_contents),
web_contents_(web_contents) {}
WebContentsPermissionHelper::~WebContentsPermissionHelper() = default;
void WebContentsPermissionHelper::RequestPermission(
content::RenderFrameHost* requesting_frame,
blink::PermissionType permission,
base::OnceCallback<void(bool)> callback,
bool user_gesture,
base::Value::Dict details) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
web_contents_->GetBrowserContext()->GetPermissionControllerDelegate());
auto origin = web_contents_->GetLastCommittedURL();
permission_manager->RequestPermissionWithDetails(
permission, requesting_frame, origin, false, std::move(details),
base::BindOnce(&OnPermissionResponse, std::move(callback)));
}
bool WebContentsPermissionHelper::CheckPermission(
blink::PermissionType permission,
base::Value::Dict details) const {
auto* rfh = web_contents_->GetPrimaryMainFrame();
auto* permission_manager = static_cast<ElectronPermissionManager*>(
web_contents_->GetBrowserContext()->GetPermissionControllerDelegate());
auto origin = web_contents_->GetLastCommittedURL();
return permission_manager->CheckPermissionWithDetails(permission, rfh, origin,
std::move(details));
}
void WebContentsPermissionHelper::RequestFullscreenPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback) {
RequestPermission(
requesting_frame,
static_cast<blink::PermissionType>(PermissionType::FULLSCREEN),
std::move(callback));
}
void WebContentsPermissionHelper::RequestMediaAccessPermission(
const content::MediaStreamRequest& request,
content::MediaResponseCallback response_callback) {
auto callback = base::BindOnce(&MediaAccessAllowed, request,
std::move(response_callback));
base::Value::Dict details;
base::Value::List media_types;
if (request.audio_type ==
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) {
media_types.Append("audio");
}
if (request.video_type ==
blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) {
media_types.Append("video");
}
details.Set("mediaTypes", std::move(media_types));
details.Set("securityOrigin", request.security_origin.spec());
// The permission type doesn't matter here, AUDIO_CAPTURE/VIDEO_CAPTURE
// are presented as same type in content_converter.h.
RequestPermission(content::RenderFrameHost::FromID(request.render_process_id,
request.render_frame_id),
blink::PermissionType::AUDIO_CAPTURE, std::move(callback),
false, std::move(details));
}
void WebContentsPermissionHelper::RequestWebNotificationPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback) {
RequestPermission(requesting_frame, blink::PermissionType::NOTIFICATIONS,
std::move(callback));
}
void WebContentsPermissionHelper::RequestPointerLockPermission(
bool user_gesture,
bool last_unlocked_by_target,
base::OnceCallback<void(content::WebContents*, bool, bool, bool)>
callback) {
RequestPermission(
web_contents_->GetPrimaryMainFrame(),
static_cast<blink::PermissionType>(PermissionType::POINTER_LOCK),
base::BindOnce(std::move(callback), web_contents_, user_gesture,
last_unlocked_by_target),
user_gesture);
}
void WebContentsPermissionHelper::RequestOpenExternalPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback,
bool user_gesture,
const GURL& url) {
base::Value::Dict details;
details.Set("externalURL", url.spec());
RequestPermission(
requesting_frame,
static_cast<blink::PermissionType>(PermissionType::OPEN_EXTERNAL),
std::move(callback), user_gesture, std::move(details));
}
bool WebContentsPermissionHelper::CheckMediaAccessPermission(
const GURL& security_origin,
blink::mojom::MediaStreamType type) const {
base::Value::Dict details;
details.Set("securityOrigin", security_origin.spec());
details.Set("mediaType", MediaStreamTypeToString(type));
// The permission type doesn't matter here, AUDIO_CAPTURE/VIDEO_CAPTURE
// are presented as same type in content_converter.h.
return CheckPermission(blink::PermissionType::AUDIO_CAPTURE,
std::move(details));
}
bool WebContentsPermissionHelper::CheckSerialAccessPermission(
const url::Origin& embedding_origin) const {
base::Value::Dict details;
details.Set("securityOrigin", embedding_origin.GetURL().spec());
return CheckPermission(
static_cast<blink::PermissionType>(PermissionType::SERIAL),
std::move(details));
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsPermissionHelper);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
spec/api-session-spec.ts
|
import { expect } from 'chai';
import * as http from 'http';
import * as https from 'https';
import * as path from 'path';
import * as fs from 'fs';
import * as ChildProcess from 'child_process';
import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
import * as send from 'send';
import * as auth from 'basic-auth';
import { closeAllWindows } from './window-helpers';
import { emittedOnce } from './events-helpers';
import { defer, delay } from './spec-helpers';
import { AddressInfo } from 'net';
/* The whole session API doesn't use standard callbacks */
/* eslint-disable standard/no-callback-literal */
describe('session module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const url = 'http://127.0.0.1';
describe('session.defaultSession', () => {
it('returns the default session', () => {
expect(session.defaultSession).to.equal(session.fromPartition(''));
});
});
describe('session.fromPartition(partition, options)', () => {
it('returns existing session with same partition', () => {
expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
});
});
describe('ses.cookies', () => {
const name = '0';
const value = '0';
afterEach(closeAllWindows);
// Clear cookie of defaultSession after each test.
afterEach(async () => {
const { cookies } = session.defaultSession;
const cs = await cookies.get({ url });
for (const c of cs) {
await cookies.remove(url, c.name);
}
});
it('should get cookies', async () => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`]);
res.end('finished');
server.close();
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
const w = new BrowserWindow({ show: false });
await w.loadURL(`${url}:${port}`);
const list = await w.webContents.session.cookies.get({ url });
const cookie = list.find(cookie => cookie.name === name);
expect(cookie).to.exist.and.to.have.property('value', value);
});
it('sets cookies', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(false);
});
it('sets session cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '1';
await cookies.set({ url, name, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(true);
});
it('sets cookies without name', async () => {
const { cookies } = session.defaultSession;
const value = '3';
await cookies.set({ url, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
});
for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
it(`sets cookies with samesite=${sameSite}`, async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await cookies.set({ url, value, sameSite });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
expect(c.sameSite).to.equal(sameSite);
});
}
it('fails to set cookies with samesite=garbage', async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value');
});
it('gets cookies without url', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const cs = await cookies.get({ domain: '127.0.0.1' });
expect(cs.some(c => c.name === name && c.value === value)).to.equal(true);
});
it('yields an error when setting a cookie with missing required fields', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: '', name, value })
).to.eventually.be.rejectedWith('Failed to get cookie domain');
});
it('yields an error when setting a cookie with an invalid URL', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: 'asdf', name, value })
).to.eventually.be.rejectedWith('Failed to get cookie domain');
});
it('should overwrite previous cookies', async () => {
const { cookies } = session.defaultSession;
const name = 'DidOverwrite';
for (const value of ['No', 'Yes']) {
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true);
}
});
it('should remove cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '2';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
await cookies.remove(url, name);
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false);
});
it.skip('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession;
const domain = 'fake-host';
const url = `${standardScheme}://${domain}`;
const name = 'custom';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list).to.have.lengthOf(1);
expect(list[0]).to.have.property('name', name);
expect(list[0]).to.have.property('value', value);
expect(list[0]).to.have.property('domain', domain);
});
it('emits a changed event when a cookie is added or removed', async () => {
const { cookies } = session.fromPartition('cookies-changed');
const name = 'foo';
const value = 'bar';
const a = emittedOnce(cookies, 'changed');
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const [, setEventCookie, setEventCause, setEventRemoved] = await a;
const b = emittedOnce(cookies, 'changed');
await cookies.remove(url, name);
const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
expect(setEventCookie.name).to.equal(name);
expect(setEventCookie.value).to.equal(value);
expect(setEventCause).to.equal('explicit');
expect(setEventRemoved).to.equal(false);
expect(removeEventCookie.name).to.equal(name);
expect(removeEventCookie.value).to.equal(value);
expect(removeEventCause).to.equal('explicit');
expect(removeEventRemoved).to.equal(true);
});
describe('ses.cookies.flushStore()', async () => {
it('flushes the cookies to disk', async () => {
const name = 'foo';
const value = 'bar';
const { cookies } = session.defaultSession;
await cookies.set({ url, name, value });
await cookies.flushStore();
});
});
it('should survive an app restart for persistent partition', async function () {
this.timeout(60000);
const appPath = path.join(fixtures, 'api', 'cookie-app');
const runAppWithPhase = (phase: string) => {
return new Promise((resolve) => {
let output = '';
const appProcess = ChildProcess.spawn(
process.execPath,
[appPath],
{ env: { PHASE: phase, ...process.env } }
);
appProcess.stdout.on('data', data => { output += data; });
appProcess.on('exit', () => {
resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
});
});
};
expect(await runAppWithPhase('one')).to.equal('011');
expect(await runAppWithPhase('two')).to.equal('110');
});
});
describe('ses.clearStorageData(options)', () => {
afterEach(closeAllWindows);
it('clears localstorage data', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
};
await w.webContents.session.clearStorageData(options);
while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
// The storage clear isn't instantly visible to the renderer, so keep
// trying until it is.
}
});
});
describe('will-download event', () => {
afterEach(closeAllWindows);
it('can cancel default download behavior', async () => {
const w = new BrowserWindow({ show: false });
const mockFile = Buffer.alloc(1024);
const contentDisposition = 'inline; filename="mockFile.txt"';
const downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockFile.length,
'Content-Type': 'application/plain',
'Content-Disposition': contentDisposition
});
res.end(mockFile);
downloadServer.close();
});
await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
const port = (downloadServer.address() as AddressInfo).port;
const url = `http://127.0.0.1:${port}/`;
const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
e.preventDefault();
resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
});
});
w.loadURL(url);
const { item, itemUrl, itemFilename } = await downloadPrevented;
expect(itemUrl).to.equal(url);
expect(itemFilename).to.equal('mockFile.txt');
// Delay till the next tick.
await new Promise<void>(resolve => setImmediate(() => resolve()));
expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
});
});
describe('ses.protocol', () => {
const partitionName = 'temp';
const protocolName = 'sp';
let customSession: Session;
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
};
beforeEach(async () => {
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
});
afterEach(async () => {
await customSession.protocol.unregisterProtocol(protocolName);
customSession = null as any;
});
afterEach(closeAllWindows);
it('does not affect defaultSession', () => {
const result1 = protocol.isProtocolRegistered(protocolName);
expect(result1).to.equal(false);
const result2 = customSession.protocol.isProtocolRegistered(protocolName);
expect(result2).to.equal(true);
});
it('handles requests from partition', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: partitionName,
nodeIntegration: true,
contextIsolation: false
}
});
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
w.loadURL(`${protocolName}://fake-host`);
await emittedOnce(ipcMain, 'hello');
});
});
describe('ses.setProxy(options)', () => {
let server: http.Server;
let customSession: Electron.Session;
let created = false;
beforeEach(async () => {
customSession = session.fromPartition('proxyconfig');
if (!created) {
// Work around for https://github.com/electron/electron/issues/26166 to
// reduce flake
await delay(100);
created = true;
}
});
afterEach(() => {
if (server) {
server.close();
}
customSession = null as any;
});
it('allows configuring proxy settings', async () => {
const config = { proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://localhost');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
{
const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
{
const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
});
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `direct`', async () => {
const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `auto_detect`', async () => {
const config = { mode: 'auto_detect' as any };
await customSession.setProxy(config);
});
it('allows configuring proxy settings with mode `pac_script`', async () => {
const config = { mode: 'pac_script' as any };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `fixed_servers`', async () => {
const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with mode `system`', async () => {
const config = { mode: 'system' as any };
await customSession.setProxy(config);
});
it('disallows configuring proxy settings with mode `invalid`', async () => {
const config = { mode: 'invalid' as any };
await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
});
it('reload proxy configuration', async () => {
let proxyPort = 8132;
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:${proxyPort}";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
{
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
{
proxyPort = 8133;
await customSession.forceReloadProxyConfig();
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
});
});
describe('ses.getBlobData()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const postData = JSON.stringify({
type: 'blob',
value: 'hello'
});
const content = `<html>
<script>
let fd = new FormData();
fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
expect(result.toString()).to.equal(postData);
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.getBlobData2()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const content = `<html>
<script>
let fd = new FormData();
fd.append("data", new Blob(new Array(65_537).fill('a')));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
const data = new Array(65_537).fill('a');
expect(result.toString()).to.equal(data.join(''));
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.setCertificateVerifyProc(callback)', () => {
let server: http.Server;
beforeEach((done) => {
const certPath = path.join(fixtures, 'certificates');
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
rejectUnauthorized: false
};
server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('<title>hello</title>');
});
server.listen(0, '127.0.0.1', done);
});
afterEach((done) => {
server.close(done);
});
afterEach(closeAllWindows);
it('accepts the request when the callback is called with 0', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(errorCode).to.be.oneOf([-202, -200]);
};
callback(0);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`);
expect(w.webContents.getTitle()).to.equal('hello');
expect(validate!).not.to.be.undefined();
validate!();
});
it('rejects the request when the callback is called with -2', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(certificate.issuerName).to.equal('Intermediate CA');
expect(certificate.subjectName).to.equal('localhost');
expect(certificate.issuer.commonName).to.equal('Intermediate CA');
expect(certificate.subject.commonName).to.equal('localhost');
expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(isIssuedByKnownRoot).to.be.false();
};
callback(-2);
});
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(w.webContents.getTitle()).to.equal(url);
expect(validate!).not.to.be.undefined();
validate!();
});
it('saves cached results', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let numVerificationRequests = 0;
ses.setCertificateVerifyProc((e, callback) => {
if (e.hostname !== '127.0.0.1') return callback(-3);
numVerificationRequests++;
callback(-2);
});
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
await emittedOnce(w.webContents, 'did-stop-loading');
await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(w.webContents.getTitle()).to.equal(url + '/test');
expect(numVerificationRequests).to.equal(1);
});
it('does not cancel requests in other sessions', async () => {
const ses1 = session.fromPartition(`${Math.random()}`);
ses1.setCertificateVerifyProc((opts, cb) => cb(0));
const ses2 = session.fromPartition(`${Math.random()}`);
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const req = net.request({ url, session: ses1, credentials: 'include' });
req.end();
setTimeout(() => {
ses2.setCertificateVerifyProc((opts, callback) => callback(0));
});
await expect(new Promise<void>((resolve, reject) => {
req.on('error', (err) => {
reject(err);
});
req.on('response', () => {
resolve();
});
})).to.eventually.be.fulfilled();
});
});
describe('ses.clearAuthCache()', () => {
it('can clear http auth info from cache', async () => {
const ses = session.fromPartition('auth-cache');
const server = http.createServer((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
res.end();
} else {
res.end('authenticated');
}
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as AddressInfo).port;
const fetch = (url: string) => new Promise((resolve, reject) => {
const request = net.request({ url, session: ses });
request.on('response', (response) => {
let data: string | null = null;
response.on('data', (chunk) => {
if (!data) {
data = '';
}
data += chunk;
});
response.on('end', () => {
if (!data) {
reject(new Error('Empty response'));
} else {
resolve(data);
}
});
response.on('error', (error: any) => { reject(new Error(error)); });
});
request.on('error', (error: any) => { reject(new Error(error)); });
request.end();
});
// the first time should throw due to unauthenticated
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
// passing the password should let us in
expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
// subsequently, the credentials are cached
expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
await ses.clearAuthCache();
// once the cache is cleared, we should get an error again
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
});
});
describe('DownloadItem', () => {
const mockPDF = Buffer.alloc(1024 * 1024 * 5);
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const protocolName = 'custom-dl';
const contentDisposition = 'inline; filename="mock.pdf"';
let address: AddressInfo;
let downloadServer: http.Server;
before(async () => {
downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockPDF.length,
'Content-Type': 'application/pdf',
'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
});
res.end(mockPDF);
});
await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
address = downloadServer.address() as AddressInfo;
});
after(async () => {
await new Promise(resolve => downloadServer.close(resolve));
});
afterEach(closeAllWindows);
const isPathEqual = (path1: string, path2: string) => {
return path.relative(path1, path2) === '';
};
const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
expect(state).to.equal('completed');
expect(item.getFilename()).to.equal('mock.pdf');
expect(path.isAbsolute(item.savePath)).to.equal(true);
expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
if (isCustom) {
expect(item.getURL()).to.equal(`${protocolName}://item`);
} else {
expect(item.getURL()).to.be.equal(`${url}:${address.port}/`);
}
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(mockPDF.length);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
fs.unlinkSync(downloadFilePath);
};
it('can download using session.downloadURL', (done) => {
const port = address.port;
session.defaultSession.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
session.defaultSession.downloadURL(`${url}:${port}`);
});
it('can download using WebContents.downloadURL', (done) => {
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${url}:${port}`);
});
it('can download from custom protocols using WebContents.downloadURL', (done) => {
const protocol = session.defaultSession.protocol;
const port = address.port;
const handler = (ignoredError: any, callback: Function) => {
callback({ url: `${url}:${port}` });
};
protocol.registerHttpProtocol(protocolName, handler);
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item, true);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${protocolName}://item`);
});
it('can download using WebView.downloadURL', async () => {
const port = address.port;
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
await w.loadURL('about:blank');
function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
const webview = new (window as any).WebView();
webview.addEventListener('did-finish-load', () => {
webview.downloadURL(`${url}:${port}/`);
});
webview.src = `file://${fixtures}/api/blank.html`;
document.body.appendChild(webview);
}
const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
resolve([state, item]);
});
});
});
await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
const [state, item] = await done;
assertDownload(state, item);
});
it('can cancel download', (done) => {
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
expect(state).to.equal('cancelled');
expect(item.getFilename()).to.equal('mock.pdf');
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(0);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/`);
});
it('can generate a default filename', function (done) {
if (process.env.APPVEYOR === 'True') {
// FIXME(alexeykuzmin): Skip the test.
// this.skip()
return done();
}
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function () {
try {
expect(item.getFilename()).to.equal('download.pdf');
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/?testFilename`);
});
it('can set options for the save dialog', (done) => {
const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
const port = address.port;
const options = {
window: null,
title: 'title',
message: 'message',
buttonLabel: 'buttonLabel',
nameFieldLabel: 'nameFieldLabel',
defaultPath: '/',
filters: [{
name: '1', extensions: ['.1', '.2']
}, {
name: '2', extensions: ['.3', '.4', '.5']
}],
showsTagField: true,
securityScopedBookmarks: true
};
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(filePath);
item.setSaveDialogOptions(options);
item.on('done', function () {
try {
expect(item.getSaveDialogOptions()).to.deep.equal(options);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}`);
});
describe('when a save path is specified and the URL is unavailable', () => {
it('does not display a save dialog and reports the done state as interrupted', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
if (item.getState() === 'interrupted') {
item.resume();
}
item.on('done', function (e, state) {
try {
expect(state).to.equal('interrupted');
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
});
});
});
describe('ses.createInterruptedDownload(options)', () => {
afterEach(closeAllWindows);
it('can create an interrupted download item', async () => {
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const options = {
path: downloadFilePath,
urlChain: ['http://127.0.0.1/'],
mimeType: 'application/pdf',
offset: 0,
length: 5242880
};
const w = new BrowserWindow({ show: false });
const p = emittedOnce(w.webContents.session, 'will-download');
w.webContents.session.createInterruptedDownload(options);
const [, item] = await p;
expect(item.getState()).to.equal('interrupted');
item.cancel();
expect(item.getURLChain()).to.deep.equal(options.urlChain);
expect(item.getMimeType()).to.equal(options.mimeType);
expect(item.getReceivedBytes()).to.equal(options.offset);
expect(item.getTotalBytes()).to.equal(options.length);
expect(item.savePath).to.equal(downloadFilePath);
});
it('can be resumed', async () => {
const downloadFilePath = path.join(fixtures, 'logo.png');
const rangeServer = http.createServer((req, res) => {
const options = { root: fixtures };
send(req, req.url!, options)
.on('error', (error: any) => { throw error; }).pipe(res);
});
try {
await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve));
const port = (rangeServer.address() as AddressInfo).port;
const w = new BrowserWindow({ show: false });
const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(downloadFilePath);
item.on('done', function () {
resolve(item);
});
item.cancel();
});
});
const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`;
w.webContents.downloadURL(downloadUrl);
const item = await downloadCancelled;
expect(item.getState()).to.equal('cancelled');
const options = {
path: item.savePath,
urlChain: item.getURLChain(),
mimeType: item.getMimeType(),
offset: item.getReceivedBytes(),
length: item.getTotalBytes(),
lastModified: item.getLastModifiedTime(),
eTag: item.getETag()
};
const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
expect(item.getState()).to.equal('interrupted');
item.setSavePath(downloadFilePath);
item.resume();
item.on('done', function () {
resolve(item);
});
});
});
w.webContents.session.createInterruptedDownload(options);
const completedItem = await downloadResumed;
expect(completedItem.getState()).to.equal('completed');
expect(completedItem.getFilename()).to.equal('logo.png');
expect(completedItem.savePath).to.equal(downloadFilePath);
expect(completedItem.getURL()).to.equal(downloadUrl);
expect(completedItem.getMimeType()).to.equal('image/png');
expect(completedItem.getReceivedBytes()).to.equal(14022);
expect(completedItem.getTotalBytes()).to.equal(14022);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
} finally {
rangeServer.close();
}
});
});
describe('ses.setPermissionRequestHandler(handler)', () => {
afterEach(closeAllWindows);
it('cancels any pending requests when cleared', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler',
nodeIntegration: true,
contextIsolation: false
}
});
const ses = w.webContents.session;
ses.setPermissionRequestHandler(() => {
ses.setPermissionRequestHandler(null);
});
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb(`<html><script>(${remote})()</script></html>`);
});
const result = emittedOnce(require('electron').ipcMain, 'message');
function remote () {
(navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
require('electron').ipcRenderer.send('message', err.name);
});
}
await w.loadURL('https://myfakesite');
const [, name] = await result;
expect(name).to.deep.equal('SecurityError');
});
});
describe('ses.setPermissionCheckHandler(handler)', () => {
afterEach(closeAllWindows);
it('details provides requestingURL for mainFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = () => {
return w.webContents.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadURL(loadUrl);
const state = await readClipboardPermission();
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
});
it('details provides requestingURL for cross origin subFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = (frame: WebFrameMain) => {
return frame.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe');
iframe.src = '${loadUrl}';
document.body.appendChild(iframe);
null;
`);
const [,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-finish-load');
const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
expect(handlerDetails!.isMainFrame).to.be.false();
expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
});
});
describe('ses.isPersistent()', () => {
afterEach(closeAllWindows);
it('returns default session as persistent', () => {
const w = new BrowserWindow({
show: false
});
const ses = w.webContents.session;
expect(ses.isPersistent()).to.be.true();
});
it('returns persist: session as persistent', () => {
const ses = session.fromPartition(`persist:${Math.random()}`);
expect(ses.isPersistent()).to.be.true();
});
it('returns temporary session as not persistent', () => {
const ses = session.fromPartition(`${Math.random()}`);
expect(ses.isPersistent()).to.be.false();
});
});
describe('ses.setUserAgent()', () => {
afterEach(closeAllWindows);
it('can be retrieved with getUserAgent()', () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent);
expect(ses.getUserAgent()).to.equal(userAgent);
});
it('sets the User-Agent header for web requests made from renderers', async () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent, 'en-US,fr,de');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
let headers: http.IncomingHttpHeaders | null = null;
const server = http.createServer((req, res) => {
headers = req.headers;
res.end();
server.close();
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
expect(headers!['user-agent']).to.equal(userAgent);
expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
});
});
describe('session-created event', () => {
it('is emitted when a session is created', async () => {
const sessionCreated = emittedOnce(app, 'session-created');
const session1 = session.fromPartition('' + Math.random());
const [session2] = await sessionCreated;
expect(session1).to.equal(session2);
});
});
describe('session.storagePage', () => {
it('returns a string', () => {
expect(session.defaultSession.storagePath).to.be.a('string');
});
it('returns null for in memory sessions', () => {
expect(session.fromPartition('in-memory').storagePath).to.equal(null);
});
it('returns different paths for partitions and the default session', () => {
expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
it('returns different paths for different partitions', () => {
expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
});
describe('session.setCodeCachePath()', () => {
it('throws when relative or empty path is provided', () => {
expect(() => {
session.defaultSession.setCodeCachePath('../fixtures');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath('');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
}).to.not.throw();
});
});
describe('ses.setSSLConfig()', () => {
it('can disable cipher suites', async () => {
const ses = session.fromPartition('' + Math.random());
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
const server = https.createServer({
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.2',
ciphers: 'AES128-GCM-SHA256'
}, (req, res) => {
res.end('hi');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
defer(() => server.close());
const { port } = server.address() as AddressInfo;
function request () {
return new Promise((resolve, reject) => {
const r = net.request({
url: `https://127.0.0.1:${port}`,
session: ses
});
r.on('response', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk.toString('utf8');
});
res.on('end', () => {
resolve(data);
});
});
r.on('error', (err) => {
reject(err);
});
r.end();
});
}
await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
ses.setSSLConfig({
disabledCipherSuites: [0x009C]
});
await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Jeremy Rose <[email protected]>
Date: Tue, 12 Jul 2022 16:51:43 -0700
Subject: short-circuit permissions checks in MediaStreamDevicesController
The //components/permissions architecture is complicated and not that
widely used in Chromium, and mostly oriented around showing permissions
UI and/or remembering per-site permissions, which we're not interested
in.
Since we do a permissions check prior to invoking the
MediaStreamDevicesController, and don't (yet) provide the ability to set
granular permissions (e.g. allow video but not audio), just
short-circuit all the permissions checks in MSDC for now to allow us to
unduplicate this code.
diff --git a/components/webrtc/media_stream_devices_controller.cc b/components/webrtc/media_stream_devices_controller.cc
index 7dbbcc13901dcd8b7a9ca9c9bdce4f924c1c6a55..5de44c5c20c92a1793060492f925519d6b8befe5 100644
--- a/components/webrtc/media_stream_devices_controller.cc
+++ b/components/webrtc/media_stream_devices_controller.cc
@@ -92,10 +92,13 @@ void MediaStreamDevicesController::RequestPermissions(
std::vector<blink::PermissionType> permission_types;
+#if 0
content::PermissionController* permission_controller =
web_contents->GetBrowserContext()->GetPermissionController();
+#endif
if (controller->ShouldRequestAudio()) {
+#if 0
content::PermissionResult permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::AUDIO_CAPTURE, rfh);
@@ -110,10 +113,12 @@ void MediaStreamDevicesController::RequestPermissions(
content::PermissionStatusSource::FENCED_FRAME);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::AUDIO_CAPTURE);
}
if (controller->ShouldRequestVideo()) {
+#if 0
content::PermissionResult permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::VIDEO_CAPTURE, rfh);
@@ -128,6 +133,7 @@ void MediaStreamDevicesController::RequestPermissions(
content::PermissionStatusSource::FENCED_FRAME);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::VIDEO_CAPTURE);
@@ -139,6 +145,7 @@ void MediaStreamDevicesController::RequestPermissions(
// pan-tilt-zoom permission and there are suitable PTZ capable devices
// available.
if (request.request_pan_tilt_zoom_permission && has_pan_tilt_zoom_camera) {
+#if 0
permission_status =
permission_controller->GetPermissionResultForCurrentDocument(
blink::PermissionType::CAMERA_PAN_TILT_ZOOM, rfh);
@@ -148,6 +155,7 @@ void MediaStreamDevicesController::RequestPermissions(
controller->RunCallback(/*blocked_by_permissions_policy=*/false);
return;
}
+#endif
permission_types.push_back(blink::PermissionType::CAMERA_PAN_TILT_ZOOM);
}
@@ -434,6 +442,7 @@ bool MediaStreamDevicesController::PermissionIsBlockedForReason(
return false;
}
+#if 0
// TODO(raymes): This function wouldn't be needed if
// PermissionManager::RequestPermissions returned a denial reason.
content::PermissionResult result =
@@ -444,6 +453,7 @@ bool MediaStreamDevicesController::PermissionIsBlockedForReason(
DCHECK_EQ(blink::mojom::PermissionStatus::DENIED, result.status);
return true;
}
+#endif
return false;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
shell/browser/web_contents_permission_helper.cc
|
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/web_contents_permission_helper.h"
#include <memory>
#include <string>
#include <utility>
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/electron_permission_manager.h"
// #include "shell/browser/media/media_stream_devices_controller.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/webrtc/media_stream_devices_controller.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
namespace {
std::string MediaStreamTypeToString(blink::mojom::MediaStreamType type) {
switch (type) {
case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE:
return "audio";
case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE:
return "video";
default:
return "unknown";
}
}
} // namespace
namespace electron {
namespace {
// Handles requests for legacy-style `navigator.getUserMedia(...)` calls.
// This includes desktop capture through the chromeMediaSource /
// chromeMediaSourceId constraints.
void HandleUserMediaRequest(const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
blink::mojom::StreamDevicesSetPtr stream_devices_set =
blink::mojom::StreamDevicesSet::New();
stream_devices_set->stream_devices.emplace_back(
blink::mojom::StreamDevices::New());
blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0];
if (request.audio_type ==
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
devices.audio_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE, "", "");
}
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE) {
devices.video_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE, "", "");
}
if (request.audio_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE) {
devices.audio_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE, "loopback",
"System Audio");
}
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE) {
content::DesktopMediaID screen_id;
// If the device id wasn't specified then this is a screen capture request
// (i.e. chooseDesktopMedia() API wasn't used to generate device id).
if (request.requested_video_device_id.empty()) {
screen_id = content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN,
-1 /* kFullDesktopScreenId */);
} else {
screen_id =
content::DesktopMediaID::Parse(request.requested_video_device_id);
}
devices.video_device = blink::MediaStreamDevice(
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE,
screen_id.ToString(), "Screen");
}
bool empty =
!devices.audio_device.has_value() && !devices.video_device.has_value();
std::move(callback).Run(
*stream_devices_set,
empty ? blink::mojom::MediaStreamRequestResult::NO_HARDWARE
: blink::mojom::MediaStreamRequestResult::OK,
nullptr);
}
void OnMediaStreamRequestResponse(
content::MediaResponseCallback callback,
const blink::mojom::StreamDevicesSet& stream_devices_set,
blink::mojom::MediaStreamRequestResult result,
bool blocked_by_permissions_policy,
ContentSetting audio_setting,
ContentSetting video_setting) {
std::move(callback).Run(stream_devices_set, result, nullptr);
}
void MediaAccessAllowed(const content::MediaStreamRequest& request,
content::MediaResponseCallback callback,
bool allowed) {
if (allowed) {
if (request.video_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::GUM_DESKTOP_AUDIO_CAPTURE ||
request.video_type ==
blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::GUM_TAB_AUDIO_CAPTURE) {
HandleUserMediaRequest(request, std::move(callback));
} else if (request.video_type ==
blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE ||
request.audio_type ==
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) {
webrtc::MediaStreamDevicesController::RequestPermissions(
request, MediaCaptureDevicesDispatcher::GetInstance(),
base::BindOnce(&OnMediaStreamRequestResponse, std::move(callback)));
} else if (request.video_type ==
blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE ||
request.video_type == blink::mojom::MediaStreamType::
DISPLAY_VIDEO_CAPTURE_THIS_TAB ||
request.video_type ==
blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE_SET ||
request.audio_type ==
blink::mojom::MediaStreamType::DISPLAY_AUDIO_CAPTURE) {
content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(
request.render_process_id, request.render_frame_id);
if (!rfh)
return;
content::BrowserContext* browser_context = rfh->GetBrowserContext();
ElectronBrowserContext* electron_browser_context =
static_cast<ElectronBrowserContext*>(browser_context);
auto split_callback = base::SplitOnceCallback(std::move(callback));
if (electron_browser_context->ChooseDisplayMediaDevice(
request, std::move(split_callback.second)))
return;
std::move(split_callback.first)
.Run(blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr);
} else {
std::move(callback).Run(
blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr);
}
} else {
std::move(callback).Run(
blink::mojom::StreamDevicesSet(),
blink::mojom::MediaStreamRequestResult::PERMISSION_DENIED, nullptr);
}
}
void OnPermissionResponse(base::OnceCallback<void(bool)> callback,
blink::mojom::PermissionStatus status) {
if (status == blink::mojom::PermissionStatus::GRANTED)
std::move(callback).Run(true);
else
std::move(callback).Run(false);
}
} // namespace
WebContentsPermissionHelper::WebContentsPermissionHelper(
content::WebContents* web_contents)
: content::WebContentsUserData<WebContentsPermissionHelper>(*web_contents),
web_contents_(web_contents) {}
WebContentsPermissionHelper::~WebContentsPermissionHelper() = default;
void WebContentsPermissionHelper::RequestPermission(
content::RenderFrameHost* requesting_frame,
blink::PermissionType permission,
base::OnceCallback<void(bool)> callback,
bool user_gesture,
base::Value::Dict details) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
web_contents_->GetBrowserContext()->GetPermissionControllerDelegate());
auto origin = web_contents_->GetLastCommittedURL();
permission_manager->RequestPermissionWithDetails(
permission, requesting_frame, origin, false, std::move(details),
base::BindOnce(&OnPermissionResponse, std::move(callback)));
}
bool WebContentsPermissionHelper::CheckPermission(
blink::PermissionType permission,
base::Value::Dict details) const {
auto* rfh = web_contents_->GetPrimaryMainFrame();
auto* permission_manager = static_cast<ElectronPermissionManager*>(
web_contents_->GetBrowserContext()->GetPermissionControllerDelegate());
auto origin = web_contents_->GetLastCommittedURL();
return permission_manager->CheckPermissionWithDetails(permission, rfh, origin,
std::move(details));
}
void WebContentsPermissionHelper::RequestFullscreenPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback) {
RequestPermission(
requesting_frame,
static_cast<blink::PermissionType>(PermissionType::FULLSCREEN),
std::move(callback));
}
void WebContentsPermissionHelper::RequestMediaAccessPermission(
const content::MediaStreamRequest& request,
content::MediaResponseCallback response_callback) {
auto callback = base::BindOnce(&MediaAccessAllowed, request,
std::move(response_callback));
base::Value::Dict details;
base::Value::List media_types;
if (request.audio_type ==
blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) {
media_types.Append("audio");
}
if (request.video_type ==
blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) {
media_types.Append("video");
}
details.Set("mediaTypes", std::move(media_types));
details.Set("securityOrigin", request.security_origin.spec());
// The permission type doesn't matter here, AUDIO_CAPTURE/VIDEO_CAPTURE
// are presented as same type in content_converter.h.
RequestPermission(content::RenderFrameHost::FromID(request.render_process_id,
request.render_frame_id),
blink::PermissionType::AUDIO_CAPTURE, std::move(callback),
false, std::move(details));
}
void WebContentsPermissionHelper::RequestWebNotificationPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback) {
RequestPermission(requesting_frame, blink::PermissionType::NOTIFICATIONS,
std::move(callback));
}
void WebContentsPermissionHelper::RequestPointerLockPermission(
bool user_gesture,
bool last_unlocked_by_target,
base::OnceCallback<void(content::WebContents*, bool, bool, bool)>
callback) {
RequestPermission(
web_contents_->GetPrimaryMainFrame(),
static_cast<blink::PermissionType>(PermissionType::POINTER_LOCK),
base::BindOnce(std::move(callback), web_contents_, user_gesture,
last_unlocked_by_target),
user_gesture);
}
void WebContentsPermissionHelper::RequestOpenExternalPermission(
content::RenderFrameHost* requesting_frame,
base::OnceCallback<void(bool)> callback,
bool user_gesture,
const GURL& url) {
base::Value::Dict details;
details.Set("externalURL", url.spec());
RequestPermission(
requesting_frame,
static_cast<blink::PermissionType>(PermissionType::OPEN_EXTERNAL),
std::move(callback), user_gesture, std::move(details));
}
bool WebContentsPermissionHelper::CheckMediaAccessPermission(
const GURL& security_origin,
blink::mojom::MediaStreamType type) const {
base::Value::Dict details;
details.Set("securityOrigin", security_origin.spec());
details.Set("mediaType", MediaStreamTypeToString(type));
// The permission type doesn't matter here, AUDIO_CAPTURE/VIDEO_CAPTURE
// are presented as same type in content_converter.h.
return CheckPermission(blink::PermissionType::AUDIO_CAPTURE,
std::move(details));
}
bool WebContentsPermissionHelper::CheckSerialAccessPermission(
const url::Origin& embedding_origin) const {
base::Value::Dict details;
details.Set("securityOrigin", embedding_origin.GetURL().spec());
return CheckPermission(
static_cast<blink::PermissionType>(PermissionType::SERIAL),
std::move(details));
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsPermissionHelper);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,629 |
[Bug]: `getUserMedia` triggers extra call to `setPermissionRequestHandler` handler with missing metadata
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
macOS
### Operating System Version
12.6
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
20.3.8
### Expected Behavior
In Electron 20.3.8, registering a handler with `setPermissionRequestHandler` and calling `navigator.getUserMedia({ audio: true }, ...)` in the browser produces one call to the handler, which includes a `securityOrigin` property in its `details`.
### Actual Behavior
Starting in Electron 21.0.0, the handler is also called a second time, with a `details` param that doesn't include a `securityOrigin` or `mediaTypes` property. Returning `false` for this call will cause the `getUserMedia` call to fail. Example log output from Fiddle:
<img width="832" alt="image" src="https://user-images.githubusercontent.com/114442851/206822049-094ec08e-3ed4-4968-b491-419a4790329b.png">
### Testcase Gist URL
https://gist.github.com/rf-figma/35de0678214fe97a8e736b64e1a26ead
|
https://github.com/electron/electron/issues/36629
|
https://github.com/electron/electron/pull/36787
|
1d9a4ab02cb198de27de8636d0893bcc27c671cf
|
f31826f4a0c44756305087f11cf0de794e68c447
| 2022-12-10T01:39:19Z |
c++
| 2023-01-11T10:55:31Z |
spec/api-session-spec.ts
|
import { expect } from 'chai';
import * as http from 'http';
import * as https from 'https';
import * as path from 'path';
import * as fs from 'fs';
import * as ChildProcess from 'child_process';
import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
import * as send from 'send';
import * as auth from 'basic-auth';
import { closeAllWindows } from './window-helpers';
import { emittedOnce } from './events-helpers';
import { defer, delay } from './spec-helpers';
import { AddressInfo } from 'net';
/* The whole session API doesn't use standard callbacks */
/* eslint-disable standard/no-callback-literal */
describe('session module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const url = 'http://127.0.0.1';
describe('session.defaultSession', () => {
it('returns the default session', () => {
expect(session.defaultSession).to.equal(session.fromPartition(''));
});
});
describe('session.fromPartition(partition, options)', () => {
it('returns existing session with same partition', () => {
expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
});
});
describe('ses.cookies', () => {
const name = '0';
const value = '0';
afterEach(closeAllWindows);
// Clear cookie of defaultSession after each test.
afterEach(async () => {
const { cookies } = session.defaultSession;
const cs = await cookies.get({ url });
for (const c of cs) {
await cookies.remove(url, c.name);
}
});
it('should get cookies', async () => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`]);
res.end('finished');
server.close();
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
const w = new BrowserWindow({ show: false });
await w.loadURL(`${url}:${port}`);
const list = await w.webContents.session.cookies.get({ url });
const cookie = list.find(cookie => cookie.name === name);
expect(cookie).to.exist.and.to.have.property('value', value);
});
it('sets cookies', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(false);
});
it('sets session cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '1';
await cookies.set({ url, name, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(true);
});
it('sets cookies without name', async () => {
const { cookies } = session.defaultSession;
const value = '3';
await cookies.set({ url, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
});
for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
it(`sets cookies with samesite=${sameSite}`, async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await cookies.set({ url, value, sameSite });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
expect(c.sameSite).to.equal(sameSite);
});
}
it('fails to set cookies with samesite=garbage', async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value');
});
it('gets cookies without url', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const cs = await cookies.get({ domain: '127.0.0.1' });
expect(cs.some(c => c.name === name && c.value === value)).to.equal(true);
});
it('yields an error when setting a cookie with missing required fields', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: '', name, value })
).to.eventually.be.rejectedWith('Failed to get cookie domain');
});
it('yields an error when setting a cookie with an invalid URL', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: 'asdf', name, value })
).to.eventually.be.rejectedWith('Failed to get cookie domain');
});
it('should overwrite previous cookies', async () => {
const { cookies } = session.defaultSession;
const name = 'DidOverwrite';
for (const value of ['No', 'Yes']) {
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true);
}
});
it('should remove cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '2';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
await cookies.remove(url, name);
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false);
});
it.skip('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession;
const domain = 'fake-host';
const url = `${standardScheme}://${domain}`;
const name = 'custom';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list).to.have.lengthOf(1);
expect(list[0]).to.have.property('name', name);
expect(list[0]).to.have.property('value', value);
expect(list[0]).to.have.property('domain', domain);
});
it('emits a changed event when a cookie is added or removed', async () => {
const { cookies } = session.fromPartition('cookies-changed');
const name = 'foo';
const value = 'bar';
const a = emittedOnce(cookies, 'changed');
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const [, setEventCookie, setEventCause, setEventRemoved] = await a;
const b = emittedOnce(cookies, 'changed');
await cookies.remove(url, name);
const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
expect(setEventCookie.name).to.equal(name);
expect(setEventCookie.value).to.equal(value);
expect(setEventCause).to.equal('explicit');
expect(setEventRemoved).to.equal(false);
expect(removeEventCookie.name).to.equal(name);
expect(removeEventCookie.value).to.equal(value);
expect(removeEventCause).to.equal('explicit');
expect(removeEventRemoved).to.equal(true);
});
describe('ses.cookies.flushStore()', async () => {
it('flushes the cookies to disk', async () => {
const name = 'foo';
const value = 'bar';
const { cookies } = session.defaultSession;
await cookies.set({ url, name, value });
await cookies.flushStore();
});
});
it('should survive an app restart for persistent partition', async function () {
this.timeout(60000);
const appPath = path.join(fixtures, 'api', 'cookie-app');
const runAppWithPhase = (phase: string) => {
return new Promise((resolve) => {
let output = '';
const appProcess = ChildProcess.spawn(
process.execPath,
[appPath],
{ env: { PHASE: phase, ...process.env } }
);
appProcess.stdout.on('data', data => { output += data; });
appProcess.on('exit', () => {
resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
});
});
};
expect(await runAppWithPhase('one')).to.equal('011');
expect(await runAppWithPhase('two')).to.equal('110');
});
});
describe('ses.clearStorageData(options)', () => {
afterEach(closeAllWindows);
it('clears localstorage data', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
};
await w.webContents.session.clearStorageData(options);
while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
// The storage clear isn't instantly visible to the renderer, so keep
// trying until it is.
}
});
});
describe('will-download event', () => {
afterEach(closeAllWindows);
it('can cancel default download behavior', async () => {
const w = new BrowserWindow({ show: false });
const mockFile = Buffer.alloc(1024);
const contentDisposition = 'inline; filename="mockFile.txt"';
const downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockFile.length,
'Content-Type': 'application/plain',
'Content-Disposition': contentDisposition
});
res.end(mockFile);
downloadServer.close();
});
await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
const port = (downloadServer.address() as AddressInfo).port;
const url = `http://127.0.0.1:${port}/`;
const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
e.preventDefault();
resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
});
});
w.loadURL(url);
const { item, itemUrl, itemFilename } = await downloadPrevented;
expect(itemUrl).to.equal(url);
expect(itemFilename).to.equal('mockFile.txt');
// Delay till the next tick.
await new Promise<void>(resolve => setImmediate(() => resolve()));
expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
});
});
describe('ses.protocol', () => {
const partitionName = 'temp';
const protocolName = 'sp';
let customSession: Session;
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
};
beforeEach(async () => {
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
});
afterEach(async () => {
await customSession.protocol.unregisterProtocol(protocolName);
customSession = null as any;
});
afterEach(closeAllWindows);
it('does not affect defaultSession', () => {
const result1 = protocol.isProtocolRegistered(protocolName);
expect(result1).to.equal(false);
const result2 = customSession.protocol.isProtocolRegistered(protocolName);
expect(result2).to.equal(true);
});
it('handles requests from partition', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: partitionName,
nodeIntegration: true,
contextIsolation: false
}
});
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
w.loadURL(`${protocolName}://fake-host`);
await emittedOnce(ipcMain, 'hello');
});
});
describe('ses.setProxy(options)', () => {
let server: http.Server;
let customSession: Electron.Session;
let created = false;
beforeEach(async () => {
customSession = session.fromPartition('proxyconfig');
if (!created) {
// Work around for https://github.com/electron/electron/issues/26166 to
// reduce flake
await delay(100);
created = true;
}
});
afterEach(() => {
if (server) {
server.close();
}
customSession = null as any;
});
it('allows configuring proxy settings', async () => {
const config = { proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://localhost');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
{
const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
{
const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
});
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `direct`', async () => {
const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `auto_detect`', async () => {
const config = { mode: 'auto_detect' as any };
await customSession.setProxy(config);
});
it('allows configuring proxy settings with mode `pac_script`', async () => {
const config = { mode: 'pac_script' as any };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `fixed_servers`', async () => {
const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with mode `system`', async () => {
const config = { mode: 'system' as any };
await customSession.setProxy(config);
});
it('disallows configuring proxy settings with mode `invalid`', async () => {
const config = { mode: 'invalid' as any };
await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
});
it('reload proxy configuration', async () => {
let proxyPort = 8132;
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:${proxyPort}";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` };
await customSession.setProxy(config);
{
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
{
proxyPort = 8133;
await customSession.forceReloadProxyConfig();
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
});
});
describe('ses.getBlobData()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const postData = JSON.stringify({
type: 'blob',
value: 'hello'
});
const content = `<html>
<script>
let fd = new FormData();
fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
expect(result.toString()).to.equal(postData);
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.getBlobData2()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const content = `<html>
<script>
let fd = new FormData();
fd.append("data", new Blob(new Array(65_537).fill('a')));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
const data = new Array(65_537).fill('a');
expect(result.toString()).to.equal(data.join(''));
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.setCertificateVerifyProc(callback)', () => {
let server: http.Server;
beforeEach((done) => {
const certPath = path.join(fixtures, 'certificates');
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
rejectUnauthorized: false
};
server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('<title>hello</title>');
});
server.listen(0, '127.0.0.1', done);
});
afterEach((done) => {
server.close(done);
});
afterEach(closeAllWindows);
it('accepts the request when the callback is called with 0', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(errorCode).to.be.oneOf([-202, -200]);
};
callback(0);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`);
expect(w.webContents.getTitle()).to.equal('hello');
expect(validate!).not.to.be.undefined();
validate!();
});
it('rejects the request when the callback is called with -2', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(certificate.issuerName).to.equal('Intermediate CA');
expect(certificate.subjectName).to.equal('localhost');
expect(certificate.issuer.commonName).to.equal('Intermediate CA');
expect(certificate.subject.commonName).to.equal('localhost');
expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(isIssuedByKnownRoot).to.be.false();
};
callback(-2);
});
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(w.webContents.getTitle()).to.equal(url);
expect(validate!).not.to.be.undefined();
validate!();
});
it('saves cached results', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let numVerificationRequests = 0;
ses.setCertificateVerifyProc((e, callback) => {
if (e.hostname !== '127.0.0.1') return callback(-3);
numVerificationRequests++;
callback(-2);
});
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
await emittedOnce(w.webContents, 'did-stop-loading');
await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(w.webContents.getTitle()).to.equal(url + '/test');
expect(numVerificationRequests).to.equal(1);
});
it('does not cancel requests in other sessions', async () => {
const ses1 = session.fromPartition(`${Math.random()}`);
ses1.setCertificateVerifyProc((opts, cb) => cb(0));
const ses2 = session.fromPartition(`${Math.random()}`);
const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`;
const req = net.request({ url, session: ses1, credentials: 'include' });
req.end();
setTimeout(() => {
ses2.setCertificateVerifyProc((opts, callback) => callback(0));
});
await expect(new Promise<void>((resolve, reject) => {
req.on('error', (err) => {
reject(err);
});
req.on('response', () => {
resolve();
});
})).to.eventually.be.fulfilled();
});
});
describe('ses.clearAuthCache()', () => {
it('can clear http auth info from cache', async () => {
const ses = session.fromPartition('auth-cache');
const server = http.createServer((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
res.end();
} else {
res.end('authenticated');
}
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const port = (server.address() as AddressInfo).port;
const fetch = (url: string) => new Promise((resolve, reject) => {
const request = net.request({ url, session: ses });
request.on('response', (response) => {
let data: string | null = null;
response.on('data', (chunk) => {
if (!data) {
data = '';
}
data += chunk;
});
response.on('end', () => {
if (!data) {
reject(new Error('Empty response'));
} else {
resolve(data);
}
});
response.on('error', (error: any) => { reject(new Error(error)); });
});
request.on('error', (error: any) => { reject(new Error(error)); });
request.end();
});
// the first time should throw due to unauthenticated
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
// passing the password should let us in
expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
// subsequently, the credentials are cached
expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
await ses.clearAuthCache();
// once the cache is cleared, we should get an error again
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
});
});
describe('DownloadItem', () => {
const mockPDF = Buffer.alloc(1024 * 1024 * 5);
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const protocolName = 'custom-dl';
const contentDisposition = 'inline; filename="mock.pdf"';
let address: AddressInfo;
let downloadServer: http.Server;
before(async () => {
downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockPDF.length,
'Content-Type': 'application/pdf',
'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
});
res.end(mockPDF);
});
await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve));
address = downloadServer.address() as AddressInfo;
});
after(async () => {
await new Promise(resolve => downloadServer.close(resolve));
});
afterEach(closeAllWindows);
const isPathEqual = (path1: string, path2: string) => {
return path.relative(path1, path2) === '';
};
const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
expect(state).to.equal('completed');
expect(item.getFilename()).to.equal('mock.pdf');
expect(path.isAbsolute(item.savePath)).to.equal(true);
expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
if (isCustom) {
expect(item.getURL()).to.equal(`${protocolName}://item`);
} else {
expect(item.getURL()).to.be.equal(`${url}:${address.port}/`);
}
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(mockPDF.length);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
fs.unlinkSync(downloadFilePath);
};
it('can download using session.downloadURL', (done) => {
const port = address.port;
session.defaultSession.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
session.defaultSession.downloadURL(`${url}:${port}`);
});
it('can download using WebContents.downloadURL', (done) => {
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${url}:${port}`);
});
it('can download from custom protocols using WebContents.downloadURL', (done) => {
const protocol = session.defaultSession.protocol;
const port = address.port;
const handler = (ignoredError: any, callback: Function) => {
callback({ url: `${url}:${port}` });
};
protocol.registerHttpProtocol(protocolName, handler);
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item, true);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${protocolName}://item`);
});
it('can download using WebView.downloadURL', async () => {
const port = address.port;
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
await w.loadURL('about:blank');
function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
const webview = new (window as any).WebView();
webview.addEventListener('did-finish-load', () => {
webview.downloadURL(`${url}:${port}/`);
});
webview.src = `file://${fixtures}/api/blank.html`;
document.body.appendChild(webview);
}
const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
resolve([state, item]);
});
});
});
await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
const [state, item] = await done;
assertDownload(state, item);
});
it('can cancel download', (done) => {
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
expect(state).to.equal('cancelled');
expect(item.getFilename()).to.equal('mock.pdf');
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(0);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/`);
});
it('can generate a default filename', function (done) {
if (process.env.APPVEYOR === 'True') {
// FIXME(alexeykuzmin): Skip the test.
// this.skip()
return done();
}
const port = address.port;
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function () {
try {
expect(item.getFilename()).to.equal('download.pdf');
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/?testFilename`);
});
it('can set options for the save dialog', (done) => {
const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
const port = address.port;
const options = {
window: null,
title: 'title',
message: 'message',
buttonLabel: 'buttonLabel',
nameFieldLabel: 'nameFieldLabel',
defaultPath: '/',
filters: [{
name: '1', extensions: ['.1', '.2']
}, {
name: '2', extensions: ['.3', '.4', '.5']
}],
showsTagField: true,
securityScopedBookmarks: true
};
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(filePath);
item.setSaveDialogOptions(options);
item.on('done', function () {
try {
expect(item.getSaveDialogOptions()).to.deep.equal(options);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}`);
});
describe('when a save path is specified and the URL is unavailable', () => {
it('does not display a save dialog and reports the done state as interrupted', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
if (item.getState() === 'interrupted') {
item.resume();
}
item.on('done', function (e, state) {
try {
expect(state).to.equal('interrupted');
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
});
});
});
describe('ses.createInterruptedDownload(options)', () => {
afterEach(closeAllWindows);
it('can create an interrupted download item', async () => {
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const options = {
path: downloadFilePath,
urlChain: ['http://127.0.0.1/'],
mimeType: 'application/pdf',
offset: 0,
length: 5242880
};
const w = new BrowserWindow({ show: false });
const p = emittedOnce(w.webContents.session, 'will-download');
w.webContents.session.createInterruptedDownload(options);
const [, item] = await p;
expect(item.getState()).to.equal('interrupted');
item.cancel();
expect(item.getURLChain()).to.deep.equal(options.urlChain);
expect(item.getMimeType()).to.equal(options.mimeType);
expect(item.getReceivedBytes()).to.equal(options.offset);
expect(item.getTotalBytes()).to.equal(options.length);
expect(item.savePath).to.equal(downloadFilePath);
});
it('can be resumed', async () => {
const downloadFilePath = path.join(fixtures, 'logo.png');
const rangeServer = http.createServer((req, res) => {
const options = { root: fixtures };
send(req, req.url!, options)
.on('error', (error: any) => { throw error; }).pipe(res);
});
try {
await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve));
const port = (rangeServer.address() as AddressInfo).port;
const w = new BrowserWindow({ show: false });
const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(downloadFilePath);
item.on('done', function () {
resolve(item);
});
item.cancel();
});
});
const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`;
w.webContents.downloadURL(downloadUrl);
const item = await downloadCancelled;
expect(item.getState()).to.equal('cancelled');
const options = {
path: item.savePath,
urlChain: item.getURLChain(),
mimeType: item.getMimeType(),
offset: item.getReceivedBytes(),
length: item.getTotalBytes(),
lastModified: item.getLastModifiedTime(),
eTag: item.getETag()
};
const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
expect(item.getState()).to.equal('interrupted');
item.setSavePath(downloadFilePath);
item.resume();
item.on('done', function () {
resolve(item);
});
});
});
w.webContents.session.createInterruptedDownload(options);
const completedItem = await downloadResumed;
expect(completedItem.getState()).to.equal('completed');
expect(completedItem.getFilename()).to.equal('logo.png');
expect(completedItem.savePath).to.equal(downloadFilePath);
expect(completedItem.getURL()).to.equal(downloadUrl);
expect(completedItem.getMimeType()).to.equal('image/png');
expect(completedItem.getReceivedBytes()).to.equal(14022);
expect(completedItem.getTotalBytes()).to.equal(14022);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
} finally {
rangeServer.close();
}
});
});
describe('ses.setPermissionRequestHandler(handler)', () => {
afterEach(closeAllWindows);
it('cancels any pending requests when cleared', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler',
nodeIntegration: true,
contextIsolation: false
}
});
const ses = w.webContents.session;
ses.setPermissionRequestHandler(() => {
ses.setPermissionRequestHandler(null);
});
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb(`<html><script>(${remote})()</script></html>`);
});
const result = emittedOnce(require('electron').ipcMain, 'message');
function remote () {
(navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
require('electron').ipcRenderer.send('message', err.name);
});
}
await w.loadURL('https://myfakesite');
const [, name] = await result;
expect(name).to.deep.equal('SecurityError');
});
});
describe('ses.setPermissionCheckHandler(handler)', () => {
afterEach(closeAllWindows);
it('details provides requestingURL for mainFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = () => {
return w.webContents.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadURL(loadUrl);
const state = await readClipboardPermission();
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
});
it('details provides requestingURL for cross origin subFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = (frame: WebFrameMain) => {
return frame.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe');
iframe.src = '${loadUrl}';
document.body.appendChild(iframe);
null;
`);
const [,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-finish-load');
const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
expect(handlerDetails!.isMainFrame).to.be.false();
expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
});
});
describe('ses.isPersistent()', () => {
afterEach(closeAllWindows);
it('returns default session as persistent', () => {
const w = new BrowserWindow({
show: false
});
const ses = w.webContents.session;
expect(ses.isPersistent()).to.be.true();
});
it('returns persist: session as persistent', () => {
const ses = session.fromPartition(`persist:${Math.random()}`);
expect(ses.isPersistent()).to.be.true();
});
it('returns temporary session as not persistent', () => {
const ses = session.fromPartition(`${Math.random()}`);
expect(ses.isPersistent()).to.be.false();
});
});
describe('ses.setUserAgent()', () => {
afterEach(closeAllWindows);
it('can be retrieved with getUserAgent()', () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent);
expect(ses.getUserAgent()).to.equal(userAgent);
});
it('sets the User-Agent header for web requests made from renderers', async () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent, 'en-US,fr,de');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
let headers: http.IncomingHttpHeaders | null = null;
const server = http.createServer((req, res) => {
headers = req.headers;
res.end();
server.close();
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
expect(headers!['user-agent']).to.equal(userAgent);
expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
});
});
describe('session-created event', () => {
it('is emitted when a session is created', async () => {
const sessionCreated = emittedOnce(app, 'session-created');
const session1 = session.fromPartition('' + Math.random());
const [session2] = await sessionCreated;
expect(session1).to.equal(session2);
});
});
describe('session.storagePage', () => {
it('returns a string', () => {
expect(session.defaultSession.storagePath).to.be.a('string');
});
it('returns null for in memory sessions', () => {
expect(session.fromPartition('in-memory').storagePath).to.equal(null);
});
it('returns different paths for partitions and the default session', () => {
expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
it('returns different paths for different partitions', () => {
expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
});
describe('session.setCodeCachePath()', () => {
it('throws when relative or empty path is provided', () => {
expect(() => {
session.defaultSession.setCodeCachePath('../fixtures');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath('');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
}).to.not.throw();
});
});
describe('ses.setSSLConfig()', () => {
it('can disable cipher suites', async () => {
const ses = session.fromPartition('' + Math.random());
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
const server = https.createServer({
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.2',
ciphers: 'AES128-GCM-SHA256'
}, (req, res) => {
res.end('hi');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
defer(() => server.close());
const { port } = server.address() as AddressInfo;
function request () {
return new Promise((resolve, reject) => {
const r = net.request({
url: `https://127.0.0.1:${port}`,
session: ses
});
r.on('response', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk.toString('utf8');
});
res.on('end', () => {
resolve(data);
});
});
r.on('error', (err) => {
reject(err);
});
r.end();
});
}
await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
ses.setSSLConfig({
disabledCipherSuites: [0x009C]
});
await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,503 |
CMD + Tab not working on Mac after exiting kiosk (full screen) mode
|
Electron Version: 17.1.2
Last know working version 12.0.5
OS Version: Mac OS Big Sur 11.6.4
Prerequisite: electron app that can transition to/from kiosk mode without exiting.
Expected Behavior: After exiting kiosk mode CMD + Tab, CMD + ` etc. should work.
Actual Behavior: CMD + Tab and any similar key combinations are non-functional as if still in kiosk mode. After exiting or blurring the app, CMD + Tab are functional. This bug was introduced in the 12.0.6 release.
Update: Menu bar is also hidden and remains hidden until electron app is blurred or exited.
|
https://github.com/electron/electron/issues/33503
|
https://github.com/electron/electron/pull/36854
|
ad1a09bb10870a73de95232d97886ae273226242
|
a9e7bb0027d6fc29a864d41fcd76cadd61a01e72
| 2022-03-29T13:42:18Z |
c++
| 2023-01-16T09:06:43Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// The NSWindowStyleMaskFullSizeContentView style removes rounded corners
// for frameless window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
// Hide all children of the current window before hiding the window.
// components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
// expects this when window visibility changes.
if ([window_ childWindows]) {
for (NSWindow* child in [window_ childWindows]) {
[child orderOut:nil];
}
}
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
// For a window to be visible, it must be visible to the user in the
// foreground of the app, which means that it should not be minimized or
// occluded
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::ENTERING
: FullScreenTransitionState::EXITING;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::NONE;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
[NSApp setPresentationOptions:kiosk_options_];
is_kiosk_ = false;
SetFullScreen(false);
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::InvalidateShadow() {
[window_ invalidateShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = base::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to functionally
// mimic app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
ProcessSerialNumber psn = {0, kCurrentProcess};
if (visibleOnFullScreen) {
[window_ setCanHide:NO];
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
} else {
[window_ setCanHide:YES];
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetTrafficLightPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
[[window_ parentWindow] removeChildWindow:window_];
// Set new parent window.
// Note that this method will force the window to become visible.
if (parent && attach) {
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[parent->GetNativeWindow().GetNativeNSWindow()
addChildWindow:window_
ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,503 |
CMD + Tab not working on Mac after exiting kiosk (full screen) mode
|
Electron Version: 17.1.2
Last know working version 12.0.5
OS Version: Mac OS Big Sur 11.6.4
Prerequisite: electron app that can transition to/from kiosk mode without exiting.
Expected Behavior: After exiting kiosk mode CMD + Tab, CMD + ` etc. should work.
Actual Behavior: CMD + Tab and any similar key combinations are non-functional as if still in kiosk mode. After exiting or blurring the app, CMD + Tab are functional. This bug was introduced in the 12.0.6 release.
Update: Menu bar is also hidden and remains hidden until electron app is blurred or exited.
|
https://github.com/electron/electron/issues/33503
|
https://github.com/electron/electron/pull/36854
|
ad1a09bb10870a73de95232d97886ae273226242
|
a9e7bb0027d6fc29a864d41fcd76cadd61a01e72
| 2022-03-29T13:42:18Z |
c++
| 2023-01-16T09:06:43Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// The NSWindowStyleMaskFullSizeContentView style removes rounded corners
// for frameless window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
// Hide all children of the current window before hiding the window.
// components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
// expects this when window visibility changes.
if ([window_ childWindows]) {
for (NSWindow* child in [window_ childWindows]) {
[child orderOut:nil];
}
}
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
// For a window to be visible, it must be visible to the user in the
// foreground of the app, which means that it should not be minimized or
// occluded
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::NONE) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::ENTERING
: FullScreenTransitionState::EXITING;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::NONE;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
[NSApp setPresentationOptions:kiosk_options_];
is_kiosk_ = false;
SetFullScreen(false);
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::InvalidateShadow() {
[window_ invalidateShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = base::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to functionally
// mimic app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
ProcessSerialNumber psn = {0, kCurrentProcess};
if (visibleOnFullScreen) {
[window_ setCanHide:NO];
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
} else {
[window_ setCanHide:YES];
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetTrafficLightPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
[[window_ parentWindow] removeChildWindow:window_];
// Set new parent window.
// Note that this method will force the window to become visible.
if (parent && attach) {
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[parent->GetNativeWindow().GetNativeNSWindow()
addChildWindow:window_
ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
docs/api/structures/display.md
|
# Display Object
* `id` number - Unique identifier associated with the display.
* `rotation` number - Can be 0, 90, 180, 270, represents screen rotation in
clock-wise degrees.
* `scaleFactor` number - Output device's pixel scale factor.
* `touchSupport` string - Can be `available`, `unavailable`, `unknown`.
* `monochrome` boolean - Whether or not the display is a monochrome display.
* `accelerometerSupport` string - Can be `available`, `unavailable`, `unknown`.
* `colorSpace` string - represent a color space (three-dimensional object which contains all realizable color combinations) for the purpose of color conversions
* `colorDepth` number - The number of bits per pixel.
* `depthPerComponent` number - The number of bits per color component.
* `displayFrequency` number - The display refresh rate.
* `bounds` [Rectangle](rectangle.md) - the bounds of the display in DIP points.
* `size` [Size](size.md)
* `workArea` [Rectangle](rectangle.md) - the work area of the display in DIP points.
* `workAreaSize` [Size](size.md)
* `internal` boolean - `true` for an internal display and `false` for an external display
The `Display` object represents a physical display connected to the system. A
fake `Display` may exist on a headless system, or a `Display` may correspond to
a remote, virtual display.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
shell/common/gin_converters/gfx_converter.cc
|
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/gfx/geometry/size.h"
namespace gin {
v8::Local<v8::Value> Converter<gfx::Point>::ToV8(v8::Isolate* isolate,
const gfx::Point& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::Point>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Point* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
double x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::Point(static_cast<int>(std::round(x)),
static_cast<int>(std::round(y)));
return true;
}
v8::Local<v8::Value> Converter<gfx::PointF>::ToV8(v8::Isolate* isolate,
const gfx::PointF& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::PointF>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::PointF* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
float x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::PointF(x, y);
return true;
}
v8::Local<v8::Value> Converter<gfx::Size>::ToV8(v8::Isolate* isolate,
const gfx::Size& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Size>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Size* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int width, height;
if (!dict.Get("width", &width) || !dict.Get("height", &height))
return false;
*out = gfx::Size(width, height);
return true;
}
v8::Local<v8::Value> Converter<gfx::Rect>::ToV8(v8::Isolate* isolate,
const gfx::Rect& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Rect>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Rect* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int x, y, width, height;
if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) ||
!dict.Get("height", &height))
return false;
*out = gfx::Rect(x, y, width, height);
return true;
}
template <>
struct Converter<display::Display::AccelerometerSupport> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const display::Display::AccelerometerSupport& val) {
switch (val) {
case display::Display::AccelerometerSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::AccelerometerSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
template <>
struct Converter<display::Display::TouchSupport> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const display::Display::TouchSupport& val) {
switch (val) {
case display::Display::TouchSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::TouchSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
v8::Local<v8::Value> Converter<display::Display>::ToV8(
v8::Isolate* isolate,
const display::Display& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("id", val.id());
dict.Set("bounds", val.bounds());
dict.Set("workArea", val.work_area());
dict.Set("accelerometerSupport", val.accelerometer_support());
dict.Set("monochrome", val.is_monochrome());
dict.Set("colorDepth", val.color_depth());
dict.Set("colorSpace", val.color_spaces().GetRasterColorSpace().ToString());
dict.Set("depthPerComponent", val.depth_per_component());
dict.Set("size", val.size());
dict.Set("displayFrequency", val.display_frequency());
dict.Set("workAreaSize", val.work_area_size());
dict.Set("scaleFactor", val.device_scale_factor());
dict.Set("rotation", val.RotationAsDegree());
dict.Set("internal", val.IsInternal());
dict.Set("touchSupport", val.touch_support());
return dict.GetHandle();
}
v8::Local<v8::Value> Converter<gfx::ResizeEdge>::ToV8(
v8::Isolate* isolate,
const gfx::ResizeEdge& val) {
switch (val) {
case gfx::ResizeEdge::kRight:
return StringToV8(isolate, "right");
case gfx::ResizeEdge::kBottom:
return StringToV8(isolate, "bottom");
case gfx::ResizeEdge::kTop:
return StringToV8(isolate, "top");
case gfx::ResizeEdge::kLeft:
return StringToV8(isolate, "left");
case gfx::ResizeEdge::kTopLeft:
return StringToV8(isolate, "top-left");
case gfx::ResizeEdge::kTopRight:
return StringToV8(isolate, "top-right");
case gfx::ResizeEdge::kBottomLeft:
return StringToV8(isolate, "bottom-left");
case gfx::ResizeEdge::kBottomRight:
return StringToV8(isolate, "bottom-right");
default:
return StringToV8(isolate, "unknown");
}
}
} // namespace gin
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
spec/api-screen-spec.ts
|
import { expect } from 'chai';
import { screen } from 'electron/main';
describe('screen module', () => {
describe('methods reassignment', () => {
it('works for a selected method', () => {
const originalFunction = screen.getPrimaryDisplay;
try {
(screen as any).getPrimaryDisplay = () => null;
expect(screen.getPrimaryDisplay()).to.be.null();
} finally {
screen.getPrimaryDisplay = originalFunction;
}
});
});
describe('screen.getCursorScreenPoint()', () => {
it('returns a point object', () => {
const point = screen.getCursorScreenPoint();
expect(point.x).to.be.a('number');
expect(point.y).to.be.a('number');
});
});
describe('screen.getPrimaryDisplay()', () => {
it('returns a display object', () => {
const display = screen.getPrimaryDisplay();
expect(display).to.be.an('object');
});
it('has the correct non-object properties', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('scaleFactor').that.is.a('number');
expect(display).to.have.property('id').that.is.a('number');
expect(display).to.have.property('rotation').that.is.a('number');
expect(display).to.have.property('touchSupport').that.is.a('string');
expect(display).to.have.property('accelerometerSupport').that.is.a('string');
expect(display).to.have.property('internal').that.is.a('boolean');
expect(display).to.have.property('monochrome').that.is.a('boolean');
expect(display).to.have.property('depthPerComponent').that.is.a('number');
expect(display).to.have.property('colorDepth').that.is.a('number');
expect(display).to.have.property('colorSpace').that.is.a('string');
expect(display).to.have.property('displayFrequency').that.is.a('number');
});
it('has a size object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('size').that.is.an('object');
const size = display.size;
expect(size).to.have.property('width').that.is.greaterThan(0);
expect(size).to.have.property('height').that.is.greaterThan(0);
});
it('has a workAreaSize object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('workAreaSize').that.is.an('object');
const workAreaSize = display.workAreaSize;
expect(workAreaSize).to.have.property('width').that.is.greaterThan(0);
expect(workAreaSize).to.have.property('height').that.is.greaterThan(0);
});
it('has a bounds object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('bounds').that.is.an('object');
const bounds = display.bounds;
expect(bounds).to.have.property('x').that.is.a('number');
expect(bounds).to.have.property('y').that.is.a('number');
expect(bounds).to.have.property('width').that.is.greaterThan(0);
expect(bounds).to.have.property('height').that.is.greaterThan(0);
});
it('has a workArea object property', function () {
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('workArea').that.is.an('object');
const workArea = display.workArea;
expect(workArea).to.have.property('x').that.is.a('number');
expect(workArea).to.have.property('y').that.is.a('number');
expect(workArea).to.have.property('width').that.is.greaterThan(0);
expect(workArea).to.have.property('height').that.is.greaterThan(0);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
docs/api/structures/display.md
|
# Display Object
* `id` number - Unique identifier associated with the display.
* `rotation` number - Can be 0, 90, 180, 270, represents screen rotation in
clock-wise degrees.
* `scaleFactor` number - Output device's pixel scale factor.
* `touchSupport` string - Can be `available`, `unavailable`, `unknown`.
* `monochrome` boolean - Whether or not the display is a monochrome display.
* `accelerometerSupport` string - Can be `available`, `unavailable`, `unknown`.
* `colorSpace` string - represent a color space (three-dimensional object which contains all realizable color combinations) for the purpose of color conversions
* `colorDepth` number - The number of bits per pixel.
* `depthPerComponent` number - The number of bits per color component.
* `displayFrequency` number - The display refresh rate.
* `bounds` [Rectangle](rectangle.md) - the bounds of the display in DIP points.
* `size` [Size](size.md)
* `workArea` [Rectangle](rectangle.md) - the work area of the display in DIP points.
* `workAreaSize` [Size](size.md)
* `internal` boolean - `true` for an internal display and `false` for an external display
The `Display` object represents a physical display connected to the system. A
fake `Display` may exist on a headless system, or a `Display` may correspond to
a remote, virtual display.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
shell/common/gin_converters/gfx_converter.cc
|
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/gfx/geometry/size.h"
namespace gin {
v8::Local<v8::Value> Converter<gfx::Point>::ToV8(v8::Isolate* isolate,
const gfx::Point& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::Point>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Point* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
double x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::Point(static_cast<int>(std::round(x)),
static_cast<int>(std::round(y)));
return true;
}
v8::Local<v8::Value> Converter<gfx::PointF>::ToV8(v8::Isolate* isolate,
const gfx::PointF& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
return dict.GetHandle();
}
bool Converter<gfx::PointF>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::PointF* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
float x, y;
if (!dict.Get("x", &x) || !dict.Get("y", &y))
return false;
*out = gfx::PointF(x, y);
return true;
}
v8::Local<v8::Value> Converter<gfx::Size>::ToV8(v8::Isolate* isolate,
const gfx::Size& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Size>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Size* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int width, height;
if (!dict.Get("width", &width) || !dict.Get("height", &height))
return false;
*out = gfx::Size(width, height);
return true;
}
v8::Local<v8::Value> Converter<gfx::Rect>::ToV8(v8::Isolate* isolate,
const gfx::Rect& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("x", val.x());
dict.Set("y", val.y());
dict.Set("width", val.width());
dict.Set("height", val.height());
return dict.GetHandle();
}
bool Converter<gfx::Rect>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
gfx::Rect* out) {
gin::Dictionary dict(isolate);
if (!gin::ConvertFromV8(isolate, val, &dict))
return false;
int x, y, width, height;
if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) ||
!dict.Get("height", &height))
return false;
*out = gfx::Rect(x, y, width, height);
return true;
}
template <>
struct Converter<display::Display::AccelerometerSupport> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const display::Display::AccelerometerSupport& val) {
switch (val) {
case display::Display::AccelerometerSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::AccelerometerSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
template <>
struct Converter<display::Display::TouchSupport> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const display::Display::TouchSupport& val) {
switch (val) {
case display::Display::TouchSupport::AVAILABLE:
return StringToV8(isolate, "available");
case display::Display::TouchSupport::UNAVAILABLE:
return StringToV8(isolate, "unavailable");
default:
return StringToV8(isolate, "unknown");
}
}
};
v8::Local<v8::Value> Converter<display::Display>::ToV8(
v8::Isolate* isolate,
const display::Display& val) {
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
dict.SetHidden("simple", true);
dict.Set("id", val.id());
dict.Set("bounds", val.bounds());
dict.Set("workArea", val.work_area());
dict.Set("accelerometerSupport", val.accelerometer_support());
dict.Set("monochrome", val.is_monochrome());
dict.Set("colorDepth", val.color_depth());
dict.Set("colorSpace", val.color_spaces().GetRasterColorSpace().ToString());
dict.Set("depthPerComponent", val.depth_per_component());
dict.Set("size", val.size());
dict.Set("displayFrequency", val.display_frequency());
dict.Set("workAreaSize", val.work_area_size());
dict.Set("scaleFactor", val.device_scale_factor());
dict.Set("rotation", val.RotationAsDegree());
dict.Set("internal", val.IsInternal());
dict.Set("touchSupport", val.touch_support());
return dict.GetHandle();
}
v8::Local<v8::Value> Converter<gfx::ResizeEdge>::ToV8(
v8::Isolate* isolate,
const gfx::ResizeEdge& val) {
switch (val) {
case gfx::ResizeEdge::kRight:
return StringToV8(isolate, "right");
case gfx::ResizeEdge::kBottom:
return StringToV8(isolate, "bottom");
case gfx::ResizeEdge::kTop:
return StringToV8(isolate, "top");
case gfx::ResizeEdge::kLeft:
return StringToV8(isolate, "left");
case gfx::ResizeEdge::kTopLeft:
return StringToV8(isolate, "top-left");
case gfx::ResizeEdge::kTopRight:
return StringToV8(isolate, "top-right");
case gfx::ResizeEdge::kBottomLeft:
return StringToV8(isolate, "bottom-left");
case gfx::ResizeEdge::kBottomRight:
return StringToV8(isolate, "bottom-right");
default:
return StringToV8(isolate, "unknown");
}
}
} // namespace gin
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,826 |
[Feature Request]: Expose Display label property
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
In line with #6899 and #25252 I would like request support for getting the display label. It looks like chromium provides a "User-friendly label, determined by the platform." that isn't currently used by electron.
https://chromium.googlesource.com/chromium/src/+/master/ui/display/display.h
### Proposed Solution
Based off of similar previous accepted changes I think these are the edits necessary:
In gfx_converter.cc line 147:
`dict.Set("label", val.label());`
In api-screen-spec.ts line 37:
`expect(display).to.have.property('label').that.is.a('string');`
And finally in the docs display.md line 4:
`* `label` string - User-friendly label, determined by the platform.`
### Alternatives Considered
No alternatives necessary.
### Additional Information
I would be happy to contribute the changes myself, but I am a little confused by the contribution workflow and unfortunately I couldn't get a successful build using the build-tools.
|
https://github.com/electron/electron/issues/36826
|
https://github.com/electron/electron/pull/36855
|
a7bc57922010062784b2be877ba778323499e0f9
|
2c56a06ad36c624d680c499725d5d9ec3e4d88b0
| 2023-01-07T20:57:54Z |
c++
| 2023-01-18T06:44:40Z |
spec/api-screen-spec.ts
|
import { expect } from 'chai';
import { screen } from 'electron/main';
describe('screen module', () => {
describe('methods reassignment', () => {
it('works for a selected method', () => {
const originalFunction = screen.getPrimaryDisplay;
try {
(screen as any).getPrimaryDisplay = () => null;
expect(screen.getPrimaryDisplay()).to.be.null();
} finally {
screen.getPrimaryDisplay = originalFunction;
}
});
});
describe('screen.getCursorScreenPoint()', () => {
it('returns a point object', () => {
const point = screen.getCursorScreenPoint();
expect(point.x).to.be.a('number');
expect(point.y).to.be.a('number');
});
});
describe('screen.getPrimaryDisplay()', () => {
it('returns a display object', () => {
const display = screen.getPrimaryDisplay();
expect(display).to.be.an('object');
});
it('has the correct non-object properties', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('scaleFactor').that.is.a('number');
expect(display).to.have.property('id').that.is.a('number');
expect(display).to.have.property('rotation').that.is.a('number');
expect(display).to.have.property('touchSupport').that.is.a('string');
expect(display).to.have.property('accelerometerSupport').that.is.a('string');
expect(display).to.have.property('internal').that.is.a('boolean');
expect(display).to.have.property('monochrome').that.is.a('boolean');
expect(display).to.have.property('depthPerComponent').that.is.a('number');
expect(display).to.have.property('colorDepth').that.is.a('number');
expect(display).to.have.property('colorSpace').that.is.a('string');
expect(display).to.have.property('displayFrequency').that.is.a('number');
});
it('has a size object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('size').that.is.an('object');
const size = display.size;
expect(size).to.have.property('width').that.is.greaterThan(0);
expect(size).to.have.property('height').that.is.greaterThan(0);
});
it('has a workAreaSize object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('workAreaSize').that.is.an('object');
const workAreaSize = display.workAreaSize;
expect(workAreaSize).to.have.property('width').that.is.greaterThan(0);
expect(workAreaSize).to.have.property('height').that.is.greaterThan(0);
});
it('has a bounds object property', function () {
if (process.platform === 'linux') this.skip();
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('bounds').that.is.an('object');
const bounds = display.bounds;
expect(bounds).to.have.property('x').that.is.a('number');
expect(bounds).to.have.property('y').that.is.a('number');
expect(bounds).to.have.property('width').that.is.greaterThan(0);
expect(bounds).to.have.property('height').that.is.greaterThan(0);
});
it('has a workArea object property', function () {
const display = screen.getPrimaryDisplay();
expect(display).to.have.property('workArea').that.is.an('object');
const workArea = display.workArea;
expect(workArea).to.have.property('x').that.is.a('number');
expect(workArea).to.have.property('y').that.is.a('number');
expect(workArea).to.have.property('width').that.is.greaterThan(0);
expect(workArea).to.have.property('height').that.is.greaterThan(0);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,417 |
[Bug]: webview tag background color do not follow browser window when reload webview
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
21.2.0
### What operating system are you using?
macOS
### Operating System Version
macOS Big Sur 11.4
### What arch are you using?
x64
### Last Known Working Electron version
11.4.5
### Expected Behavior
Recently, we upgraded our electron version from 11.4.5 to 21.2.0 and met a problem.
The final problem I located is that webview's background color do not follow browser window when reload webview. So it caused from white -> red instead of browser windows' bg color -> red in my demo.

### Actual Behavior

### Testcase Gist URL
https://gist.github.com/PerfectPan/100900b7758293b8f72b23d0babdb1cc
### Additional Information
In our situation, we use webview to load chrome devtools frontend. This app styles background color asynchronous, so we met this problem. A hack way maybe we modify the inspect.html to hardcode our background color in it. But we want to know if there are any other way to solve this.
|
https://github.com/electron/electron/issues/36417
|
https://github.com/electron/electron/pull/36920
|
1d98b27a6643d6b6cbc4d9d426d6d5acc4b45e2a
|
b1548c2dbefdcd8f823c18175715fc5d34b09781
| 2022-11-21T13:15:40Z |
c++
| 2023-01-18T13:46:47Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.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"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
std::string type;
if (ConvertFromV8(isolate, val, &type)) {
if (type == "default") {
*out = printing::mojom::MarginType::kDefaultMargins;
return true;
}
if (type == "none") {
*out = printing::mojom::MarginType::kNoMargins;
return true;
}
if (type == "printableArea") {
*out = printing::mojom::MarginType::kPrintableAreaMargins;
return true;
}
if (type == "custom") {
*out = printing::mojom::MarginType::kCustomMargins;
return true;
}
}
return false;
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "simplex") {
*out = printing::mojom::DuplexMode::kSimplex;
return true;
}
if (mode == "longEdge") {
*out = printing::mojom::DuplexMode::kLongEdge;
return true;
}
if (mode == "shortEdge") {
*out = printing::mojom::DuplexMode::kShortEdge;
return true;
}
}
return false;
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
std::string save_type;
if (!ConvertFromV8(isolate, val, &save_type))
return false;
save_type = base::ToLowerASCII(save_type);
if (save_type == "htmlonly") {
*out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
} else if (save_type == "htmlcomplete") {
*out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
} else if (save_type == "mhtml") {
*out = content::SAVE_PAGE_TYPE_AS_MHTML;
} else {
return false;
}
return true;
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Type = electron::api::WebContents::Type;
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "backgroundPage") {
*out = Type::kBackgroundPage;
} else if (type == "browserView") {
*out = Type::kBrowserView;
} else if (type == "webview") {
*out = Type::kWebView;
#if BUILDFLAG(ENABLE_OSR)
} else if (type == "offscreen") {
*out = Type::kOffScreen;
#endif
} else {
return false;
}
return true;
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
#if BUILDFLAG(ENABLE_OSR)
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
#endif
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
#if BUILDFLAG(ENABLE_OSR)
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
#endif
web_contents = content::WebContents::Create(params);
#if BUILDFLAG(ENABLE_OSR)
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
#endif
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_->HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
return owner_window_ && owner_window_->IsFullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window_)
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::HTML);
exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window_)
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_->keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
Emit("-audio-state-changed", audible);
}
void WebContents::BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor();
web_contents()->SetPageBaseBackgroundColor(maybe_color);
bool guest = IsGuest() || type_ == Type::kBrowserView;
SkColor color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
SetBackgroundColor(rwhv, color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame =
WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId());
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if (old_host)
old_host->GetWidget()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
return Emit(event, url, is_same_document, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments) {
TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
auto* target_web_contents = FromID(web_contents_id);
if (target_web_contents) {
content::RenderFrameHost* frame = target_web_contents->MainFrame();
DCHECK(frame);
v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
gin::Handle<WebFrameMain> web_frame_main =
WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
if (!web_frame_main->CheckRenderFrame())
return;
int32_t sender_id = ID();
web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
std::move(arguments), sender_id);
}
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
#if BUILDFLAG(ENABLE_OSR)
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
#endif
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, "", content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICTIONARY);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
#endif
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
#endif
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
// TODO(codebytere): remove in Electron v23.
void WebContents::IncrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.incrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
gfx::Size size;
bool stay_hidden = false;
bool stay_awake = false;
// get size arguments if they exist
args->GetNext(&size);
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
std::ignore = web_contents()
->IncrementCapturerCount(size, stay_hidden, stay_awake)
.Release();
}
// TODO(codebytere): remove in Electron v23.
void WebContents::DecrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.decrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
bool stay_hidden = false;
bool stay_awake = false;
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
web_contents()->DecrementCapturerCount(stay_hidden, stay_awake);
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const content::WebCursor& webcursor) {
const ui::Cursor& cursor = webcursor.cursor();
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
#if BUILDFLAG(ENABLE_OSR)
return type_ == Type::kOffScreen;
#else
return false;
#endif
}
#if BUILDFLAG(ENABLE_OSR)
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
#endif
void WebContents::Invalidate() {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
#endif
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return html_fullscreen_;
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::NONE;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::HTML;
return html_fullscreen_ || (in_transition && is_html_transition);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
#else
return content::PictureInPictureResult::kNotSupported;
#endif
}
void WebContents::ExitPictureInPicture() {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
#endif
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
std::unique_ptr<base::Value> parsed_excluded_folders =
base::JSONReader::ReadDeprecated(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window_->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
return gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
#if BUILDFLAG(ENABLE_OSR)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
#endif
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount)
.SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,417 |
[Bug]: webview tag background color do not follow browser window when reload webview
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
21.2.0
### What operating system are you using?
macOS
### Operating System Version
macOS Big Sur 11.4
### What arch are you using?
x64
### Last Known Working Electron version
11.4.5
### Expected Behavior
Recently, we upgraded our electron version from 11.4.5 to 21.2.0 and met a problem.
The final problem I located is that webview's background color do not follow browser window when reload webview. So it caused from white -> red instead of browser windows' bg color -> red in my demo.

### Actual Behavior

### Testcase Gist URL
https://gist.github.com/PerfectPan/100900b7758293b8f72b23d0babdb1cc
### Additional Information
In our situation, we use webview to load chrome devtools frontend. This app styles background color asynchronous, so we met this problem. A hack way maybe we modify the inspect.html to hardcode our background color in it. But we want to know if there are any other way to solve this.
|
https://github.com/electron/electron/issues/36417
|
https://github.com/electron/electron/pull/36920
|
1d98b27a6643d6b6cbc4d9d426d6d5acc4b45e2a
|
b1548c2dbefdcd8f823c18175715fc5d34b09781
| 2022-11-21T13:15:40Z |
c++
| 2023-01-18T13:46:47Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.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"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
std::string type;
if (ConvertFromV8(isolate, val, &type)) {
if (type == "default") {
*out = printing::mojom::MarginType::kDefaultMargins;
return true;
}
if (type == "none") {
*out = printing::mojom::MarginType::kNoMargins;
return true;
}
if (type == "printableArea") {
*out = printing::mojom::MarginType::kPrintableAreaMargins;
return true;
}
if (type == "custom") {
*out = printing::mojom::MarginType::kCustomMargins;
return true;
}
}
return false;
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "simplex") {
*out = printing::mojom::DuplexMode::kSimplex;
return true;
}
if (mode == "longEdge") {
*out = printing::mojom::DuplexMode::kLongEdge;
return true;
}
if (mode == "shortEdge") {
*out = printing::mojom::DuplexMode::kShortEdge;
return true;
}
}
return false;
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
std::string save_type;
if (!ConvertFromV8(isolate, val, &save_type))
return false;
save_type = base::ToLowerASCII(save_type);
if (save_type == "htmlonly") {
*out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
} else if (save_type == "htmlcomplete") {
*out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
} else if (save_type == "mhtml") {
*out = content::SAVE_PAGE_TYPE_AS_MHTML;
} else {
return false;
}
return true;
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Type = electron::api::WebContents::Type;
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "backgroundPage") {
*out = Type::kBackgroundPage;
} else if (type == "browserView") {
*out = Type::kBrowserView;
} else if (type == "webview") {
*out = Type::kWebView;
#if BUILDFLAG(ENABLE_OSR)
} else if (type == "offscreen") {
*out = Type::kOffScreen;
#endif
} else {
return false;
}
return true;
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
#if BUILDFLAG(ENABLE_OSR)
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
#endif
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
#if BUILDFLAG(ENABLE_OSR)
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
#endif
web_contents = content::WebContents::Create(params);
#if BUILDFLAG(ENABLE_OSR)
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
#endif
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_->HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
return owner_window_ && owner_window_->IsFullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window_)
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::HTML);
exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window_)
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_->keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
Emit("-audio-state-changed", audible);
}
void WebContents::BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor();
web_contents()->SetPageBaseBackgroundColor(maybe_color);
bool guest = IsGuest() || type_ == Type::kBrowserView;
SkColor color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
SetBackgroundColor(rwhv, color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame =
WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId());
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if (old_host)
old_host->GetWidget()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
return Emit(event, url, is_same_document, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments) {
TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
auto* target_web_contents = FromID(web_contents_id);
if (target_web_contents) {
content::RenderFrameHost* frame = target_web_contents->MainFrame();
DCHECK(frame);
v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
gin::Handle<WebFrameMain> web_frame_main =
WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
if (!web_frame_main->CheckRenderFrame())
return;
int32_t sender_id = ID();
web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
std::move(arguments), sender_id);
}
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
#if BUILDFLAG(ENABLE_OSR)
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
#endif
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, "", content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICTIONARY);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
#endif
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
#endif
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
// TODO(codebytere): remove in Electron v23.
void WebContents::IncrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.incrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
gfx::Size size;
bool stay_hidden = false;
bool stay_awake = false;
// get size arguments if they exist
args->GetNext(&size);
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
std::ignore = web_contents()
->IncrementCapturerCount(size, stay_hidden, stay_awake)
.Release();
}
// TODO(codebytere): remove in Electron v23.
void WebContents::DecrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.decrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
bool stay_hidden = false;
bool stay_awake = false;
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
web_contents()->DecrementCapturerCount(stay_hidden, stay_awake);
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const content::WebCursor& webcursor) {
const ui::Cursor& cursor = webcursor.cursor();
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
#if BUILDFLAG(ENABLE_OSR)
return type_ == Type::kOffScreen;
#else
return false;
#endif
}
#if BUILDFLAG(ENABLE_OSR)
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
#endif
void WebContents::Invalidate() {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
#endif
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return html_fullscreen_;
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::NONE;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::HTML;
return html_fullscreen_ || (in_transition && is_html_transition);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
#else
return content::PictureInPictureResult::kNotSupported;
#endif
}
void WebContents::ExitPictureInPicture() {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
#endif
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
std::unique_ptr<base::Value> parsed_excluded_folders =
base::JSONReader::ReadDeprecated(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window_->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
return gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
#if BUILDFLAG(ENABLE_OSR)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
#endif
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount)
.SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,906 |
[Bug]: Datalist positioning is broken in Electron v22.x.y
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.x.y
### What operating system are you using?
Windows
### Operating System Version
Windows 10 build 19045.2486
### What arch are you using?
x64
### Last Known Working Electron version
21.3.4
### Expected Behavior
I expect that a datalist when displayed, should be positioned horizontally in line with it's bound input box; either above or below depending on space available.
See Image below from Electron fiddle using Electron v21.3.4

__
### Actual Behavior
In Electron v22.0..0+ The datalist is positioned offset to the left of its bound input box by quite a distance. In some instance it can appear as if the datalist is clamped to the left margin.
See Image below from Electron fiddle using Electron v22.0.0 although the same can be reproduced using any of the currently available v22.0.y -> 22.0.1, 22.0.2 And a quick test with v23.0.0-beta2 also exhibity the same behaviour.

### Testcase Gist URL
https://gist.github.com/e50cb256d567ed25b7bbf12b9cbe5417
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36906
|
https://github.com/electron/electron/pull/36934
|
9630e26e6dec503bc82ca4b9f87ebf0344311ca5
|
55c818d0a84400621c0817c8a2e4cc17d9eb24c8
| 2023-01-13T11:34:12Z |
c++
| 2023-01-19T18:44:23Z |
shell/browser/ui/autofill_popup.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <memory>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "components/autofill/core/common/autofill_features.h"
#include "electron/buildflags/buildflags.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/autofill_popup.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/text_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_view_proxy.h"
#endif
namespace electron {
void CalculatePopupXAndWidthHorizontallyCentered(
int popup_preferred_width,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
gfx::Rect* bubble_bounds) {
// The preferred horizontal starting point for the pop-up is at the horizontal
// center of the field.
int preferred_starting_point =
base::clamp(element_bounds.x() + (element_bounds.size().width() / 2),
content_area_bounds.x(), content_area_bounds.right());
// The space available to the left and to the right.
int space_to_right = content_area_bounds.right() - preferred_starting_point;
int space_to_left = preferred_starting_point - content_area_bounds.x();
// Calculate the pop-up width. This is either the preferred pop-up width, or
// alternatively the maximum space available if there is not sufficient space
// for the preferred width.
int popup_width =
std::min(popup_preferred_width, space_to_left + space_to_right);
// Calculates the space that is available to grow into the preferred
// direction. In RTL, this is the space to the right side of the content
// area, in LTR this is the space to the left side of the content area.
int space_to_grow_in_preferred_direction =
is_rtl ? space_to_left : space_to_right;
// Calculate how much the pop-up needs to grow into the non-preferred
// direction.
int amount_to_grow_in_unpreferred_direction =
std::max(0, popup_width - space_to_grow_in_preferred_direction);
bubble_bounds->set_width(popup_width);
if (is_rtl) {
// Note, in RTL the |pop_up_width| must be subtracted to achieve
// right-alignment of the pop-up with the element.
bubble_bounds->set_x(preferred_starting_point - popup_width +
amount_to_grow_in_unpreferred_direction);
} else {
bubble_bounds->set_x(preferred_starting_point -
amount_to_grow_in_unpreferred_direction);
}
}
void CalculatePopupXAndWidth(int popup_preferred_width,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
gfx::Rect* bubble_bounds) {
int right_growth_start = base::clamp(
element_bounds.x(), content_area_bounds.x(), content_area_bounds.right());
int left_growth_end =
base::clamp(element_bounds.right(), content_area_bounds.x(),
content_area_bounds.right());
int right_available = content_area_bounds.right() - right_growth_start;
int left_available = left_growth_end - content_area_bounds.x();
int popup_width = std::min(popup_preferred_width,
std::max(left_available, right_available));
// Prefer to grow towards the end (right for LTR, left for RTL). But if there
// is not enough space available in the desired direction and more space in
// the other direction, reverse it.
bool grow_left = false;
if (is_rtl) {
grow_left =
left_available >= popup_width || left_available >= right_available;
} else {
grow_left =
right_available < popup_width && right_available < left_available;
}
bubble_bounds->set_width(popup_width);
bubble_bounds->set_x(grow_left ? left_growth_end - popup_width
: right_growth_start);
}
void CalculatePopupYAndHeight(int popup_preferred_height,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
gfx::Rect* bubble_bounds) {
int top_growth_end = base::clamp(element_bounds.y(), content_area_bounds.y(),
content_area_bounds.bottom());
int bottom_growth_start =
base::clamp(element_bounds.bottom(), content_area_bounds.y(),
content_area_bounds.bottom());
int top_available = top_growth_end - content_area_bounds.y();
int bottom_available = content_area_bounds.bottom() - bottom_growth_start;
bubble_bounds->set_height(popup_preferred_height);
bubble_bounds->set_y(top_growth_end);
if (bottom_available >= popup_preferred_height ||
bottom_available >= top_available) {
bubble_bounds->AdjustToFit(
gfx::Rect(bubble_bounds->x(), element_bounds.bottom(),
bubble_bounds->width(), bottom_available));
} else {
bubble_bounds->AdjustToFit(
gfx::Rect(bubble_bounds->x(), content_area_bounds.y(),
bubble_bounds->width(), top_available));
}
}
gfx::Rect CalculatePopupBounds(const gfx::Size& desired_size,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
bool horizontally_centered) {
gfx::Rect bubble_bounds;
if (horizontally_centered) {
CalculatePopupXAndWidthHorizontallyCentered(
desired_size.width(), content_area_bounds, element_bounds, is_rtl,
&bubble_bounds);
} else {
CalculatePopupXAndWidth(desired_size.width(), content_area_bounds,
element_bounds, is_rtl, &bubble_bounds);
}
CalculatePopupYAndHeight(desired_size.height(), content_area_bounds,
element_bounds, &bubble_bounds);
return bubble_bounds;
}
AutofillPopup::AutofillPopup() {
bold_font_list_ = gfx::FontList().DeriveWithWeight(gfx::Font::Weight::BOLD);
smaller_font_list_ =
gfx::FontList().DeriveWithSizeDelta(kSmallerFontSizeDelta);
}
AutofillPopup::~AutofillPopup() {
Hide();
}
void AutofillPopup::CreateView(content::RenderFrameHost* frame_host,
content::RenderFrameHost* embedder_frame_host,
bool offscreen,
views::View* parent,
const gfx::RectF& r) {
Hide();
frame_host_ = frame_host;
element_bounds_ = gfx::ToEnclosedRect(r);
gfx::Vector2d height_offset(0, element_bounds_.height());
gfx::Point menu_position(element_bounds_.origin() + height_offset);
views::View::ConvertPointToScreen(parent, &menu_position);
popup_bounds_ = gfx::Rect(menu_position, element_bounds_.size());
parent_ = parent;
parent_->AddObserver(this);
view_ = new AutofillPopupView(this, parent->GetWidget());
#if BUILDFLAG(ENABLE_OSR)
if (offscreen) {
auto* rwhv = frame_host->GetView();
if (embedder_frame_host != nullptr) {
rwhv = embedder_frame_host->GetView();
}
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(rwhv);
view_->view_proxy_ = std::make_unique<OffscreenViewProxy>(view_);
osr_rwhv->AddViewProxy(view_->view_proxy_.get());
}
#endif
// Do this after OSR setup, we check for view_proxy_ when showing
view_->Show();
}
void AutofillPopup::Hide() {
if (parent_) {
parent_->RemoveObserver(this);
parent_ = nullptr;
}
if (view_) {
view_->Hide();
view_ = nullptr;
}
}
void AutofillPopup::SetItems(const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) {
DCHECK(view_);
values_ = values;
labels_ = labels;
UpdatePopupBounds();
view_->OnSuggestionsChanged();
if (view_) // could be hidden after the change
view_->DoUpdateBoundsAndRedrawPopup();
}
void AutofillPopup::AcceptSuggestion(int index) {
mojo::AssociatedRemote<mojom::ElectronAutofillAgent> autofill_agent;
frame_host_->GetRemoteAssociatedInterfaces()->GetInterface(&autofill_agent);
autofill_agent->AcceptDataListSuggestion(GetValueAt(index));
}
void AutofillPopup::UpdatePopupBounds() {
DCHECK(parent_);
gfx::Point origin(element_bounds_.origin());
views::View::ConvertPointToScreen(parent_, &origin);
gfx::Rect bounds(origin, element_bounds_.size());
gfx::Rect window_bounds = parent_->GetBoundsInScreen();
gfx::Size preferred_size =
gfx::Size(GetDesiredPopupWidth(), GetDesiredPopupHeight());
popup_bounds_ = CalculatePopupBounds(preferred_size, window_bounds, bounds,
base::i18n::IsRTL(), true);
CalculatePopupXAndWidthHorizontallyCentered(
preferred_size.width(), window_bounds, element_bounds_,
base::i18n::IsRTL(), &popup_bounds_);
}
gfx::Rect AutofillPopup::popup_bounds_in_view() {
gfx::Point origin(popup_bounds_.origin());
views::View::ConvertPointFromScreen(parent_, &origin);
return gfx::Rect(origin, popup_bounds_.size());
}
void AutofillPopup::OnViewBoundsChanged(views::View* view) {
UpdatePopupBounds();
view_->DoUpdateBoundsAndRedrawPopup();
}
void AutofillPopup::OnViewIsDeleting(views::View* view) {
Hide();
}
int AutofillPopup::GetDesiredPopupHeight() {
return 2 * kPopupBorderThickness + values_.size() * kRowHeight;
}
int AutofillPopup::GetDesiredPopupWidth() {
int popup_width = element_bounds_.width();
for (size_t i = 0; i < values_.size(); ++i) {
int row_size =
kEndPadding + 2 * kPopupBorderThickness +
gfx::GetStringWidth(GetValueAt(i), GetValueFontListForRow(i)) +
gfx::GetStringWidth(GetLabelAt(i), GetLabelFontListForRow(i));
if (!GetLabelAt(i).empty())
row_size += kNamePadding + kEndPadding;
popup_width = std::max(popup_width, row_size);
}
return popup_width;
}
gfx::Rect AutofillPopup::GetRowBounds(int index) {
int top = kPopupBorderThickness + index * kRowHeight;
return gfx::Rect(kPopupBorderThickness, top,
popup_bounds_.width() - 2 * kPopupBorderThickness,
kRowHeight);
}
const gfx::FontList& AutofillPopup::GetValueFontListForRow(int index) const {
return bold_font_list_;
}
const gfx::FontList& AutofillPopup::GetLabelFontListForRow(int index) const {
return smaller_font_list_;
}
ui::ColorId AutofillPopup::GetBackgroundColorIDForRow(int index) const {
return (view_ && index == view_->GetSelectedLine())
? ui::kColorResultsTableHoveredBackground
: ui::kColorResultsTableNormalBackground;
}
int AutofillPopup::GetLineCount() {
return values_.size();
}
std::u16string AutofillPopup::GetValueAt(int i) {
return values_.at(i);
}
std::u16string AutofillPopup::GetLabelAt(int i) {
return labels_.at(i);
}
int AutofillPopup::LineFromY(int y) const {
int current_height = kPopupBorderThickness;
for (size_t i = 0; i < values_.size(); ++i) {
current_height += kRowHeight;
if (y <= current_height)
return i;
}
return values_.size() - 1;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,906 |
[Bug]: Datalist positioning is broken in Electron v22.x.y
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.x.y
### What operating system are you using?
Windows
### Operating System Version
Windows 10 build 19045.2486
### What arch are you using?
x64
### Last Known Working Electron version
21.3.4
### Expected Behavior
I expect that a datalist when displayed, should be positioned horizontally in line with it's bound input box; either above or below depending on space available.
See Image below from Electron fiddle using Electron v21.3.4

__
### Actual Behavior
In Electron v22.0..0+ The datalist is positioned offset to the left of its bound input box by quite a distance. In some instance it can appear as if the datalist is clamped to the left margin.
See Image below from Electron fiddle using Electron v22.0.0 although the same can be reproduced using any of the currently available v22.0.y -> 22.0.1, 22.0.2 And a quick test with v23.0.0-beta2 also exhibity the same behaviour.

### Testcase Gist URL
https://gist.github.com/e50cb256d567ed25b7bbf12b9cbe5417
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36906
|
https://github.com/electron/electron/pull/36934
|
9630e26e6dec503bc82ca4b9f87ebf0344311ca5
|
55c818d0a84400621c0817c8a2e4cc17d9eb24c8
| 2023-01-13T11:34:12Z |
c++
| 2023-01-19T18:44:23Z |
shell/browser/ui/autofill_popup.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <memory>
#include <vector>
#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "components/autofill/core/common/autofill_features.h"
#include "electron/buildflags/buildflags.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/autofill_popup.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/text_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_view_proxy.h"
#endif
namespace electron {
void CalculatePopupXAndWidthHorizontallyCentered(
int popup_preferred_width,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
gfx::Rect* bubble_bounds) {
// The preferred horizontal starting point for the pop-up is at the horizontal
// center of the field.
int preferred_starting_point =
base::clamp(element_bounds.x() + (element_bounds.size().width() / 2),
content_area_bounds.x(), content_area_bounds.right());
// The space available to the left and to the right.
int space_to_right = content_area_bounds.right() - preferred_starting_point;
int space_to_left = preferred_starting_point - content_area_bounds.x();
// Calculate the pop-up width. This is either the preferred pop-up width, or
// alternatively the maximum space available if there is not sufficient space
// for the preferred width.
int popup_width =
std::min(popup_preferred_width, space_to_left + space_to_right);
// Calculates the space that is available to grow into the preferred
// direction. In RTL, this is the space to the right side of the content
// area, in LTR this is the space to the left side of the content area.
int space_to_grow_in_preferred_direction =
is_rtl ? space_to_left : space_to_right;
// Calculate how much the pop-up needs to grow into the non-preferred
// direction.
int amount_to_grow_in_unpreferred_direction =
std::max(0, popup_width - space_to_grow_in_preferred_direction);
bubble_bounds->set_width(popup_width);
if (is_rtl) {
// Note, in RTL the |pop_up_width| must be subtracted to achieve
// right-alignment of the pop-up with the element.
bubble_bounds->set_x(preferred_starting_point - popup_width +
amount_to_grow_in_unpreferred_direction);
} else {
bubble_bounds->set_x(preferred_starting_point -
amount_to_grow_in_unpreferred_direction);
}
}
void CalculatePopupXAndWidth(int popup_preferred_width,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
gfx::Rect* bubble_bounds) {
int right_growth_start = base::clamp(
element_bounds.x(), content_area_bounds.x(), content_area_bounds.right());
int left_growth_end =
base::clamp(element_bounds.right(), content_area_bounds.x(),
content_area_bounds.right());
int right_available = content_area_bounds.right() - right_growth_start;
int left_available = left_growth_end - content_area_bounds.x();
int popup_width = std::min(popup_preferred_width,
std::max(left_available, right_available));
// Prefer to grow towards the end (right for LTR, left for RTL). But if there
// is not enough space available in the desired direction and more space in
// the other direction, reverse it.
bool grow_left = false;
if (is_rtl) {
grow_left =
left_available >= popup_width || left_available >= right_available;
} else {
grow_left =
right_available < popup_width && right_available < left_available;
}
bubble_bounds->set_width(popup_width);
bubble_bounds->set_x(grow_left ? left_growth_end - popup_width
: right_growth_start);
}
void CalculatePopupYAndHeight(int popup_preferred_height,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
gfx::Rect* bubble_bounds) {
int top_growth_end = base::clamp(element_bounds.y(), content_area_bounds.y(),
content_area_bounds.bottom());
int bottom_growth_start =
base::clamp(element_bounds.bottom(), content_area_bounds.y(),
content_area_bounds.bottom());
int top_available = top_growth_end - content_area_bounds.y();
int bottom_available = content_area_bounds.bottom() - bottom_growth_start;
bubble_bounds->set_height(popup_preferred_height);
bubble_bounds->set_y(top_growth_end);
if (bottom_available >= popup_preferred_height ||
bottom_available >= top_available) {
bubble_bounds->AdjustToFit(
gfx::Rect(bubble_bounds->x(), element_bounds.bottom(),
bubble_bounds->width(), bottom_available));
} else {
bubble_bounds->AdjustToFit(
gfx::Rect(bubble_bounds->x(), content_area_bounds.y(),
bubble_bounds->width(), top_available));
}
}
gfx::Rect CalculatePopupBounds(const gfx::Size& desired_size,
const gfx::Rect& content_area_bounds,
const gfx::Rect& element_bounds,
bool is_rtl,
bool horizontally_centered) {
gfx::Rect bubble_bounds;
if (horizontally_centered) {
CalculatePopupXAndWidthHorizontallyCentered(
desired_size.width(), content_area_bounds, element_bounds, is_rtl,
&bubble_bounds);
} else {
CalculatePopupXAndWidth(desired_size.width(), content_area_bounds,
element_bounds, is_rtl, &bubble_bounds);
}
CalculatePopupYAndHeight(desired_size.height(), content_area_bounds,
element_bounds, &bubble_bounds);
return bubble_bounds;
}
AutofillPopup::AutofillPopup() {
bold_font_list_ = gfx::FontList().DeriveWithWeight(gfx::Font::Weight::BOLD);
smaller_font_list_ =
gfx::FontList().DeriveWithSizeDelta(kSmallerFontSizeDelta);
}
AutofillPopup::~AutofillPopup() {
Hide();
}
void AutofillPopup::CreateView(content::RenderFrameHost* frame_host,
content::RenderFrameHost* embedder_frame_host,
bool offscreen,
views::View* parent,
const gfx::RectF& r) {
Hide();
frame_host_ = frame_host;
element_bounds_ = gfx::ToEnclosedRect(r);
gfx::Vector2d height_offset(0, element_bounds_.height());
gfx::Point menu_position(element_bounds_.origin() + height_offset);
views::View::ConvertPointToScreen(parent, &menu_position);
popup_bounds_ = gfx::Rect(menu_position, element_bounds_.size());
parent_ = parent;
parent_->AddObserver(this);
view_ = new AutofillPopupView(this, parent->GetWidget());
#if BUILDFLAG(ENABLE_OSR)
if (offscreen) {
auto* rwhv = frame_host->GetView();
if (embedder_frame_host != nullptr) {
rwhv = embedder_frame_host->GetView();
}
auto* osr_rwhv = static_cast<OffScreenRenderWidgetHostView*>(rwhv);
view_->view_proxy_ = std::make_unique<OffscreenViewProxy>(view_);
osr_rwhv->AddViewProxy(view_->view_proxy_.get());
}
#endif
// Do this after OSR setup, we check for view_proxy_ when showing
view_->Show();
}
void AutofillPopup::Hide() {
if (parent_) {
parent_->RemoveObserver(this);
parent_ = nullptr;
}
if (view_) {
view_->Hide();
view_ = nullptr;
}
}
void AutofillPopup::SetItems(const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) {
DCHECK(view_);
values_ = values;
labels_ = labels;
UpdatePopupBounds();
view_->OnSuggestionsChanged();
if (view_) // could be hidden after the change
view_->DoUpdateBoundsAndRedrawPopup();
}
void AutofillPopup::AcceptSuggestion(int index) {
mojo::AssociatedRemote<mojom::ElectronAutofillAgent> autofill_agent;
frame_host_->GetRemoteAssociatedInterfaces()->GetInterface(&autofill_agent);
autofill_agent->AcceptDataListSuggestion(GetValueAt(index));
}
void AutofillPopup::UpdatePopupBounds() {
DCHECK(parent_);
gfx::Point origin(element_bounds_.origin());
views::View::ConvertPointToScreen(parent_, &origin);
gfx::Rect bounds(origin, element_bounds_.size());
gfx::Rect window_bounds = parent_->GetBoundsInScreen();
gfx::Size preferred_size =
gfx::Size(GetDesiredPopupWidth(), GetDesiredPopupHeight());
popup_bounds_ = CalculatePopupBounds(preferred_size, window_bounds, bounds,
base::i18n::IsRTL(), true);
CalculatePopupXAndWidthHorizontallyCentered(
preferred_size.width(), window_bounds, element_bounds_,
base::i18n::IsRTL(), &popup_bounds_);
}
gfx::Rect AutofillPopup::popup_bounds_in_view() {
gfx::Point origin(popup_bounds_.origin());
views::View::ConvertPointFromScreen(parent_, &origin);
return gfx::Rect(origin, popup_bounds_.size());
}
void AutofillPopup::OnViewBoundsChanged(views::View* view) {
UpdatePopupBounds();
view_->DoUpdateBoundsAndRedrawPopup();
}
void AutofillPopup::OnViewIsDeleting(views::View* view) {
Hide();
}
int AutofillPopup::GetDesiredPopupHeight() {
return 2 * kPopupBorderThickness + values_.size() * kRowHeight;
}
int AutofillPopup::GetDesiredPopupWidth() {
int popup_width = element_bounds_.width();
for (size_t i = 0; i < values_.size(); ++i) {
int row_size =
kEndPadding + 2 * kPopupBorderThickness +
gfx::GetStringWidth(GetValueAt(i), GetValueFontListForRow(i)) +
gfx::GetStringWidth(GetLabelAt(i), GetLabelFontListForRow(i));
if (!GetLabelAt(i).empty())
row_size += kNamePadding + kEndPadding;
popup_width = std::max(popup_width, row_size);
}
return popup_width;
}
gfx::Rect AutofillPopup::GetRowBounds(int index) {
int top = kPopupBorderThickness + index * kRowHeight;
return gfx::Rect(kPopupBorderThickness, top,
popup_bounds_.width() - 2 * kPopupBorderThickness,
kRowHeight);
}
const gfx::FontList& AutofillPopup::GetValueFontListForRow(int index) const {
return bold_font_list_;
}
const gfx::FontList& AutofillPopup::GetLabelFontListForRow(int index) const {
return smaller_font_list_;
}
ui::ColorId AutofillPopup::GetBackgroundColorIDForRow(int index) const {
return (view_ && index == view_->GetSelectedLine())
? ui::kColorResultsTableHoveredBackground
: ui::kColorResultsTableNormalBackground;
}
int AutofillPopup::GetLineCount() {
return values_.size();
}
std::u16string AutofillPopup::GetValueAt(int i) {
return values_.at(i);
}
std::u16string AutofillPopup::GetLabelAt(int i) {
return labels_.at(i);
}
int AutofillPopup::LineFromY(int y) const {
int current_height = kPopupBorderThickness;
for (size_t i = 0; i < values_.size(); ++i) {
current_height += kRowHeight;
if (y <= current_height)
return i;
}
return values_.size() - 1;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,970 |
[Bug]: Regression: #35930 broke CJS via ESM loading when exporting null/undefined with ELECTRON_RUN_AS_NODE
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.3
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 22.10
### What arch are you using?
x64
### Last Known Working Electron version
20.3.1 / 21.1.0
### Expected Behavior
1. `npm i [email protected] ava`
2. `ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron ./node_modules/.bin/ava`
3. Works (can't find any tests obviously)
I was successfully running my esm tests via `ELECTRON_RUN_AS_NODE` until now
### Actual Behavior
1. `npm i [email protected] ava`
2. `ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron ./node_modules/.bin/ava`
3. Crashes
```
node:internal/modules/esm/translators:178
if (!ObjectPrototypeHasOwnProperty(exports, exportName) ||
^
TypeError: Cannot convert undefined or null to object
at hasOwnProperty (<anonymous>)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:178:12)
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
```
### Testcase Gist URL
_No response_
### Additional Information
I was able to track this down and repro without ava as well (https://github.com/avajs/ava/discussions/3155). It appears you can no longer export `null` because it crashes the esm loader patch.
index.mjs
```js
import m from './module.cjs';
```
module.cjs
```js
module.exports = null;
```
`ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron index.mjs`
It broke between `20.3.1` and `20.3.2` because of #35930 . If you're curious, in ava this comes from this dep https://github.com/jamiebuilds/ci-parallel-vars/blob/994940e4882bdddf046a5c076b49d700449e4b38/index.js#L41-L56
> Weirdly, this is like the 4th time I've tried this.
@MarshallOfSound fifth time is the charm
|
https://github.com/electron/electron/issues/36970
|
https://github.com/electron/electron/pull/37009
|
4bc6b15f53a3e4f961c2ade3c96fa9229ec00367
|
58beec1da2cacd59a91a556b86f47ec0147b9c36
| 2023-01-20T09:12:15Z |
c++
| 2023-01-25T21:03:47Z |
patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Samuel Attard <[email protected]>
Date: Thu, 6 Oct 2022 04:09:16 -0700
Subject: fix: expose the built-in electron module via the ESM loader
This allows usage of `import { app } from 'electron'` and `import('electron')` natively in the browser + non-sandboxed renderer
diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js
index a7329d279bb07542d3f4027e0c8e2b035d493e5b..5cff70923b4ea7a4df918b2d3d1fbc7106159218 100644
--- a/lib/internal/modules/esm/get_format.js
+++ b/lib/internal/modules/esm/get_format.js
@@ -30,6 +30,7 @@ const protocolHandlers = {
'http:': getHttpProtocolModuleFormat,
'https:': getHttpProtocolModuleFormat,
'node:'() { return 'builtin'; },
+ 'electron:'() { return 'commonjs'; },
};
/**
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
index 7cec4e9a3e3675ba75d66a44ed4e142d13ca1821..0c7aad193442a7e5cab62638441969a7d4983ef9 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -824,6 +824,8 @@ function parsePackageName(specifier, base) {
return { packageName, packageSubpath, isScoped };
}
+const electronSpecifiers = new SafeSet(['electron', 'electron/main', 'electron/common', 'electron/renderer']);
+
/**
* @param {string} specifier
* @param {string | URL | undefined} base
@@ -836,6 +838,10 @@ function packageResolve(specifier, base, conditions) {
return new URL('node:' + specifier);
}
+ if (electronSpecifiers.has(specifier)) {
+ return new URL('electron:electron');
+ }
+
const { packageName, packageSubpath, isScoped } =
parsePackageName(specifier, base);
@@ -1034,7 +1040,7 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
function throwIfUnsupportedURLProtocol(url) {
if (url.protocol !== 'file:' && url.protocol !== 'data:' &&
- url.protocol !== 'node:') {
+ url.protocol !== 'node:' && url.protocol !== 'electron:') {
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url);
}
}
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..d1527b859bbea15fdf30622fc8f2700bde5b4591 100644
--- a/lib/internal/modules/esm/translators.js
+++ b/lib/internal/modules/esm/translators.js
@@ -154,7 +154,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
if (!cjsParse) await initCJSParse();
const { module, exportNames } = cjsPreparseModuleExports(filename);
- const namesWithDefault = exportNames.has('default') ?
+ const namesWithDefault = filename === 'electron' ? ['default', ...Object.keys(module.exports)] : exportNames.has('default') ?
[...exportNames] : ['default', ...exportNames];
return new ModuleWrap(url, undefined, namesWithDefault, function() {
@@ -173,7 +173,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
}
}
- for (const exportName of exportNames) {
+ for (const exportName of namesWithDefault) {
if (!ObjectPrototypeHasOwnProperty(exports, exportName) ||
exportName === 'default')
continue;
diff --git a/lib/internal/url.js b/lib/internal/url.js
index 40b25f6890b5db721923ba2e9cc351e514ca22bc..288f3253b4c686d1b061dfcdf18dc95794943d87 100644
--- a/lib/internal/url.js
+++ b/lib/internal/url.js
@@ -1488,6 +1488,8 @@ function fileURLToPath(path) {
path = new URL(path);
else if (!isURLInstance(path))
throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path);
+ if (path.protocol === 'electron:')
+ return 'electron';
if (path.protocol !== 'file:')
throw new ERR_INVALID_URL_SCHEME('file');
return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path);
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,970 |
[Bug]: Regression: #35930 broke CJS via ESM loading when exporting null/undefined with ELECTRON_RUN_AS_NODE
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.3
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 22.10
### What arch are you using?
x64
### Last Known Working Electron version
20.3.1 / 21.1.0
### Expected Behavior
1. `npm i [email protected] ava`
2. `ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron ./node_modules/.bin/ava`
3. Works (can't find any tests obviously)
I was successfully running my esm tests via `ELECTRON_RUN_AS_NODE` until now
### Actual Behavior
1. `npm i [email protected] ava`
2. `ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron ./node_modules/.bin/ava`
3. Crashes
```
node:internal/modules/esm/translators:178
if (!ObjectPrototypeHasOwnProperty(exports, exportName) ||
^
TypeError: Cannot convert undefined or null to object
at hasOwnProperty (<anonymous>)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:178:12)
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
```
### Testcase Gist URL
_No response_
### Additional Information
I was able to track this down and repro without ava as well (https://github.com/avajs/ava/discussions/3155). It appears you can no longer export `null` because it crashes the esm loader patch.
index.mjs
```js
import m from './module.cjs';
```
module.cjs
```js
module.exports = null;
```
`ELECTRON_RUN_AS_NODE=true ./node_modules/.bin/electron index.mjs`
It broke between `20.3.1` and `20.3.2` because of #35930 . If you're curious, in ava this comes from this dep https://github.com/jamiebuilds/ci-parallel-vars/blob/994940e4882bdddf046a5c076b49d700449e4b38/index.js#L41-L56
> Weirdly, this is like the 4th time I've tried this.
@MarshallOfSound fifth time is the charm
|
https://github.com/electron/electron/issues/36970
|
https://github.com/electron/electron/pull/37009
|
4bc6b15f53a3e4f961c2ade3c96fa9229ec00367
|
58beec1da2cacd59a91a556b86f47ec0147b9c36
| 2023-01-20T09:12:15Z |
c++
| 2023-01-25T21:03:47Z |
patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Samuel Attard <[email protected]>
Date: Thu, 6 Oct 2022 04:09:16 -0700
Subject: fix: expose the built-in electron module via the ESM loader
This allows usage of `import { app } from 'electron'` and `import('electron')` natively in the browser + non-sandboxed renderer
diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js
index a7329d279bb07542d3f4027e0c8e2b035d493e5b..5cff70923b4ea7a4df918b2d3d1fbc7106159218 100644
--- a/lib/internal/modules/esm/get_format.js
+++ b/lib/internal/modules/esm/get_format.js
@@ -30,6 +30,7 @@ const protocolHandlers = {
'http:': getHttpProtocolModuleFormat,
'https:': getHttpProtocolModuleFormat,
'node:'() { return 'builtin'; },
+ 'electron:'() { return 'commonjs'; },
};
/**
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
index 7cec4e9a3e3675ba75d66a44ed4e142d13ca1821..0c7aad193442a7e5cab62638441969a7d4983ef9 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -824,6 +824,8 @@ function parsePackageName(specifier, base) {
return { packageName, packageSubpath, isScoped };
}
+const electronSpecifiers = new SafeSet(['electron', 'electron/main', 'electron/common', 'electron/renderer']);
+
/**
* @param {string} specifier
* @param {string | URL | undefined} base
@@ -836,6 +838,10 @@ function packageResolve(specifier, base, conditions) {
return new URL('node:' + specifier);
}
+ if (electronSpecifiers.has(specifier)) {
+ return new URL('electron:electron');
+ }
+
const { packageName, packageSubpath, isScoped } =
parsePackageName(specifier, base);
@@ -1034,7 +1040,7 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
function throwIfUnsupportedURLProtocol(url) {
if (url.protocol !== 'file:' && url.protocol !== 'data:' &&
- url.protocol !== 'node:') {
+ url.protocol !== 'node:' && url.protocol !== 'electron:') {
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(url);
}
}
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..d1527b859bbea15fdf30622fc8f2700bde5b4591 100644
--- a/lib/internal/modules/esm/translators.js
+++ b/lib/internal/modules/esm/translators.js
@@ -154,7 +154,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
if (!cjsParse) await initCJSParse();
const { module, exportNames } = cjsPreparseModuleExports(filename);
- const namesWithDefault = exportNames.has('default') ?
+ const namesWithDefault = filename === 'electron' ? ['default', ...Object.keys(module.exports)] : exportNames.has('default') ?
[...exportNames] : ['default', ...exportNames];
return new ModuleWrap(url, undefined, namesWithDefault, function() {
@@ -173,7 +173,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
}
}
- for (const exportName of exportNames) {
+ for (const exportName of namesWithDefault) {
if (!ObjectPrototypeHasOwnProperty(exports, exportName) ||
exportName === 'default')
continue;
diff --git a/lib/internal/url.js b/lib/internal/url.js
index 40b25f6890b5db721923ba2e9cc351e514ca22bc..288f3253b4c686d1b061dfcdf18dc95794943d87 100644
--- a/lib/internal/url.js
+++ b/lib/internal/url.js
@@ -1488,6 +1488,8 @@ function fileURLToPath(path) {
path = new URL(path);
else if (!isURLInstance(path))
throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path);
+ if (path.protocol === 'electron:')
+ return 'electron';
if (path.protocol !== 'file:')
throw new ERR_INVALID_URL_SCHEME('file');
return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path);
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
docs/api/web-contents.md
|
# webContents
> Render and control web pages.
Process: [Main](../glossary.md#main-process)
`webContents` is an [EventEmitter][event-emitter].
It is responsible for rendering and controlling a web page and is a property of
the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('http://github.com')
const contents = win.webContents
console.log(contents)
```
## Methods
These methods can be accessed from the `webContents` module:
```javascript
const { webContents } = require('electron')
console.log(webContents)
```
### `webContents.getAllWebContents()`
Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents
for all windows, webviews, opened devtools, and devtools extension background pages.
### `webContents.getFocusedWebContents()`
Returns `WebContents` | null - The web contents that is focused in this application, otherwise
returns `null`.
### `webContents.fromId(id)`
* `id` Integer
Returns `WebContents` | undefined - A WebContents instance with the given ID, or
`undefined` if there is no WebContents associated with the given ID.
### `webContents.fromFrame(frame)`
* `frame` WebFrameMain
Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or
`undefined` if there is no WebContents associated with the given WebFrameMain.
### `webContents.fromDevToolsTargetId(targetId)`
* `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance.
Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or
`undefined` if there is no WebContents associated with the given TargetID.
When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/),
it can be useful to lookup a WebContents instance based on its assigned TargetID.
```js
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await webContents.fromDevToolsTargetId(targetId)
}
```
## Class: WebContents
> Render and control the contents of a BrowserWindow instance.
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
### Instance Events
#### Event: 'did-finish-load'
Emitted when the navigation is done, i.e. the spinner of the tab has stopped
spinning, and the `onload` event was dispatched.
#### Event: 'did-fail-load'
Returns:
* `event` Event
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
This event is like `did-finish-load` but emitted when the load failed.
The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
#### Event: 'did-fail-provisional-load'
Returns:
* `event` Event
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
This event is like `did-fail-load` but emitted when the load was cancelled
(e.g. `window.stop()` was invoked).
#### Event: 'did-frame-finish-load'
Returns:
* `event` Event
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when a frame has done navigation.
#### Event: 'did-start-loading'
Corresponds to the points in time when the spinner of the tab started spinning.
#### Event: 'did-stop-loading'
Corresponds to the points in time when the spinner of the tab stopped spinning.
#### Event: 'dom-ready'
Emitted when the document in the top-level frame is loaded.
#### Event: 'page-title-updated'
Returns:
* `event` Event
* `title` string
* `explicitSet` boolean
Fired when page title is set during navigation. `explicitSet` is false when
title is synthesized from file url.
#### Event: 'page-favicon-updated'
Returns:
* `event` Event
* `favicons` string[] - Array of URLs.
Emitted when page receives favicon urls.
#### Event: 'content-bounds-updated'
Returns:
* `event` Event
* `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds
Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs.
By default, this will move the window. To prevent that behavior, call
`event.preventDefault()`.
#### Event: 'did-create-window'
Returns:
* `window` BrowserWindow
* `details` Object
* `url` string - URL for the created window.
* `frameName` string - Name given to the created window in the
`window.open()` call.
* `options` BrowserWindowConstructorOptions - The options used to create the
BrowserWindow. They are merged in increasing precedence: parsed options
from the `features` string from `window.open()`, security-related
webPreferences inherited from the parent, and options given by
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
Unrecognized options are not filtered out.
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
passed to the new window. May or may not result in the `Referer` header
being sent, depending on the referrer policy.
* `postBody` [PostBody](structures/post-body.md) (optional) - The post data
that will be sent to the new window, along with the appropriate headers
that will be set. If no post data is to be sent, the value will be `null`.
Only defined when the window is being created by a form that set
`target=_blank`.
* `disposition` string - Can be `default`, `foreground-tab`,
`background-tab`, `new-window`, `save-to-disk` and `other`.
Emitted _after_ successful creation of a window via `window.open` in the renderer.
Not emitted if the creation of the window is canceled from
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`.
#### Event: 'will-navigate'
Returns:
* `event` Event
* `url` string
Emitted when a user or the page wants to start navigation. It can happen when
the `window.location` object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with
APIs like `webContents.loadURL` and `webContents.back`.
It is also not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
Calling `event.preventDefault()` will prevent the navigation.
#### Event: 'did-start-navigation'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame (including main) starts navigating. `isInPlace` will be
`true` for in-page navigations.
#### Event: 'will-redirect'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when a server side redirect occurs during navigation. For example a 302
redirect.
This event will be emitted after `did-start-navigation` and always before the
`did-redirect-navigation` event for the same navigation.
Calling `event.preventDefault()` will prevent the navigation (not just the
redirect).
#### Event: 'did-redirect-navigation'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted after a server side redirect occurs during navigation. For example a 302
redirect.
This event cannot be prevented, if you want to prevent redirects you should
checkout out the `will-redirect` event above.
#### Event: 'did-navigate'
Returns:
* `event` Event
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations
Emitted when a main frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
#### Event: 'did-frame-navigate'
Returns:
* `event` Event
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations,
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
#### Event: 'did-navigate-in-page'
Returns:
* `event` Event
* `url` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when an in-page navigation happened in any frame.
When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM `hashchange` event is triggered.
#### Event: 'will-prevent-unload'
Returns:
* `event` Event
Emitted when a `beforeunload` event handler is attempting to cancel a page unload.
Calling `event.preventDefault()` will ignore the `beforeunload` event handler
and allow the page to be unloaded.
```javascript
const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBoxSync(win, {
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
const leave = (choice === 0)
if (leave) {
event.preventDefault()
}
})
```
**Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
#### Event: 'crashed' _Deprecated_
Returns:
* `event` Event
* `killed` boolean
Emitted when the renderer process crashes or is killed.
**Deprecated:** This event is superceded by the `render-process-gone` event
which contains more information about why the render process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
#### Event: 'render-process-gone'
Returns:
* `event` Event
* `details` Object
* `reason` string - The reason the render process is gone. Possible values:
* `clean-exit` - Process exited with an exit code of zero
* `abnormal-exit` - Process exited with a non-zero exit code
* `killed` - Process was sent a SIGTERM or otherwise killed externally
* `crashed` - Process crashed
* `oom` - Process ran out of memory
* `launch-failed` - Process never successfully launched
* `integrity-failure` - Windows code integrity checks failed
* `exitCode` Integer - The exit code of the process, unless `reason` is
`launch-failed`, in which case `exitCode` will be a platform-specific
launch failure error code.
Emitted when the renderer process unexpectedly disappears. This is normally
because it was crashed or killed.
#### Event: 'unresponsive'
Emitted when the web page becomes unresponsive.
#### Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
#### Event: 'plugin-crashed'
Returns:
* `event` Event
* `name` string
* `version` string
Emitted when a plugin process has crashed.
#### Event: 'destroyed'
Emitted when `webContents` is destroyed.
#### Event: 'input-event'
Returns:
* `event` Event
* `inputEvent` [InputEvent](structures/input-event.md)
Emitted when an input event is sent to the WebContents. See
[InputEvent](structures/input-event.md) for details.
#### Event: 'before-input-event'
Returns:
* `event` Event
* `input` Object - Input properties.
* `type` string - Either `keyUp` or `keyDown`.
* `key` string - Equivalent to [KeyboardEvent.key][keyboardevent].
* `code` string - Equivalent to [KeyboardEvent.code][keyboardevent].
* `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent].
* `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent].
* `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent].
* `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent].
* `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent].
* `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent].
* `location` number - Equivalent to [KeyboardEvent.location][keyboardevent].
* `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md).
Emitted before dispatching the `keydown` and `keyup` events in the page.
Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events
and the menu shortcuts.
To only prevent the menu shortcuts, use
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore):
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when
// Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
```
#### Event: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
#### Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
#### Event: 'zoom-changed'
Returns:
* `event` Event
* `zoomDirection` string - Can be `in` or `out`.
Emitted when the user is requesting to change the zoom level using the mouse wheel.
#### Event: 'blur'
Emitted when the `WebContents` loses focus.
#### Event: 'focus'
Emitted when the `WebContents` gains focus.
Note that on macOS, having focus means the `WebContents` is the first responder
of window, so switching focus between windows would not trigger the `focus` and
`blur` events of `WebContents`, as the first responder of each window is not
changed.
The `focus` and `blur` events of `WebContents` should only be used to detect
focus change between different `WebContents` and `BrowserView` in the same
window.
#### Event: 'devtools-opened'
Emitted when DevTools is opened.
#### Event: 'devtools-closed'
Emitted when DevTools is closed.
#### Event: 'devtools-focused'
Emitted when DevTools is focused / opened.
#### Event: 'certificate-error'
Returns:
* `event` Event
* `url` string
* `error` string - The error code.
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` boolean - Indicates whether the certificate can be considered trusted.
* `isMainFrame` boolean
Emitted when failed to verify the `certificate` for `url`.
The usage is the same with [the `certificate-error` event of
`app`](app.md#event-certificate-error).
#### Event: 'select-client-certificate'
Returns:
* `event` Event
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list.
Emitted when a client certificate is requested.
The usage is the same with [the `select-client-certificate` event of
`app`](app.md#event-select-client-certificate).
#### Event: 'login'
Returns:
* `event` Event
* `authenticationResponseDetails` Object
* `url` URL
* `authInfo` Object
* `isProxy` boolean
* `scheme` string
* `host` string
* `port` Integer
* `realm` string
* `callback` Function
* `username` string (optional)
* `password` string (optional)
Emitted when `webContents` wants to do basic auth.
The usage is the same with [the `login` event of `app`](app.md#event-login).
#### Event: 'found-in-page'
Returns:
* `event` Event
* `result` Object
* `requestId` Integer
* `activeMatchOrdinal` Integer - Position of the active match.
* `matches` Integer - Number of Matches.
* `selectionArea` Rectangle - Coordinates of first match region.
* `finalUpdate` boolean
Emitted when a result is available for
[`webContents.findInPage`](#contentsfindinpagetext-options) request.
#### Event: 'media-started-playing'
Emitted when media starts playing.
#### Event: 'media-paused'
Emitted when media is paused or done playing.
#### Event: 'did-change-theme-color'
Returns:
* `event` Event
* `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set.
Emitted when a page's theme color changes. This is usually due to encountering
a meta tag:
```html
<meta name='theme-color' content='#ff0000'>
```
#### Event: 'update-target-url'
Returns:
* `event` Event
* `url` string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
#### Event: 'cursor-changed'
Returns:
* `event` Event
* `type` string
* `image` [NativeImage](native-image.md) (optional)
* `scale` Float (optional) - scaling factor for the custom cursor.
* `size` [Size](structures/size.md) (optional) - the size of the `image`.
* `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot.
Emitted when the cursor's type changes. The `type` parameter can be `default`,
`crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`,
`ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`,
`ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`,
`row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`,
`s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`,
`cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`,
`not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`.
If the `type` parameter is `custom`, the `image` parameter will hold the custom
cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold
additional information about the custom cursor.
#### Event: 'context-menu'
Returns:
* `event` Event
* `params` Object
* `x` Integer - x coordinate.
* `y` Integer - y coordinate.
* `frame` WebFrameMain - Frame from which the context menu was invoked.
* `linkURL` string - URL of the link that encloses the node the context menu
was invoked on.
* `linkText` string - Text associated with the link. May be an empty
string if the contents of the link are an image.
* `pageURL` string - URL of the top level page that the context menu was
invoked on.
* `frameURL` string - URL of the subframe that the context menu was invoked
on.
* `srcURL` string - Source URL for the element that the context menu
was invoked on. Elements with source URLs are images, audio and video.
* `mediaType` string - Type of the node the context menu was invoked on. Can
be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`.
* `hasImageContents` boolean - Whether the context menu was invoked on an image
which has non-empty contents.
* `isEditable` boolean - Whether the context is editable.
* `selectionText` string - Text of the selection that the context menu was
invoked on.
* `titleText` string - Title text of the selection that the context menu was
invoked on.
* `altText` string - Alt text of the selection that the context menu was
invoked on.
* `suggestedFilename` string - Suggested filename to be used when saving file through 'Save
Link As' option of context menu.
* `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection.
* `selectionStartOffset` number - Start position of the selection text.
* `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked.
* `misspelledWord` string - The misspelled word under the cursor, if any.
* `dictionarySuggestions` string[] - An array of suggested words to show the
user to replace the `misspelledWord`. Only available if there is a misspelled
word and spellchecker is enabled.
* `frameCharset` string - The character encoding of the frame on which the
menu was invoked.
* `inputFieldType` string - If the context menu was invoked on an input
field, the type of that field. Possible values are `none`, `plainText`,
`password`, `other`.
* `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled.
* `menuSourceType` string - Input source that invoked the context menu.
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
* `mediaFlags` Object - The flags for the media element the context menu was
invoked on.
* `inError` boolean - Whether the media element has crashed.
* `isPaused` boolean - Whether the media element is paused.
* `isMuted` boolean - Whether the media element is muted.
* `hasAudio` boolean - Whether the media element has audio.
* `isLooping` boolean - Whether the media element is looping.
* `isControlsVisible` boolean - Whether the media element's controls are
visible.
* `canToggleControls` boolean - Whether the media element's controls are
toggleable.
* `canPrint` boolean - Whether the media element can be printed.
* `canSave` boolean - Whether or not the media element can be downloaded.
* `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture.
* `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture.
* `canRotate` boolean - Whether the media element can be rotated.
* `canLoop` boolean - Whether the media element can be looped.
* `editFlags` Object - These flags indicate whether the renderer believes it
is able to perform the corresponding action.
* `canUndo` boolean - Whether the renderer believes it can undo.
* `canRedo` boolean - Whether the renderer believes it can redo.
* `canCut` boolean - Whether the renderer believes it can cut.
* `canCopy` boolean - Whether the renderer believes it can copy.
* `canPaste` boolean - Whether the renderer believes it can paste.
* `canDelete` boolean - Whether the renderer believes it can delete.
* `canSelectAll` boolean - Whether the renderer believes it can select all.
* `canEditRichly` boolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
#### Event: 'select-bluetooth-device'
Returns:
* `event` Event
* `devices` [BluetoothDevice[]](structures/bluetooth-device.md)
* `callback` Function
* `deviceId` string
Emitted when bluetooth device needs to be selected on call to
`navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api
`webBluetooth` should be enabled. If `event.preventDefault` is not called,
first available device will be selected. `callback` should be called with
`deviceId` to be selected, passing empty string to `callback` will
cancel the request.
If no event listener is added for this event, all bluetooth requests will be cancelled.
```javascript
const { app, BrowserWindow } = require('electron')
let win = null
app.commandLine.appendSwitch('enable-experimental-web-platform-features')
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
const result = deviceList.find((device) => {
return device.deviceName === 'test'
})
if (!result) {
callback('')
} else {
callback(result.deviceId)
}
})
})
```
#### Event: 'paint'
Returns:
* `event` Event
* `dirtyRect` [Rectangle](structures/rectangle.md)
* `image` [NativeImage](native-image.md) - The image data of the whole frame.
Emitted when a new frame is generated. Only the dirty area is passed in the
buffer.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('http://github.com')
```
#### Event: 'devtools-reload-page'
Emitted when the devtools window instructs the webContents to reload
#### Event: 'will-attach-webview'
Returns:
* `event` Event
* `webPreferences` WebPreferences - The web preferences that will be used by the guest
page. This object can be modified to adjust the preferences for the guest
page.
* `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL.
This object can be modified to adjust the parameters of the guest page.
Emitted when a `<webview>`'s web contents is being attached to this web
contents. Calling `event.preventDefault()` will destroy the guest page.
This event can be used to configure `webPreferences` for the `webContents`
of a `<webview>` before it's loaded, and provides the ability to set settings
that can't be set via `<webview>` attributes.
#### Event: 'did-attach-webview'
Returns:
* `event` Event
* `webContents` WebContents - The guest web contents that is used by the
`<webview>`.
Emitted when a `<webview>` has been attached to this web contents.
#### Event: 'console-message'
Returns:
* `event` Event
* `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
* `message` string - The actual console message
* `line` Integer - The line number of the source that triggered this console message
* `sourceId` string
Emitted when the associated window logs a console message.
#### Event: 'preload-error'
Returns:
* `event` Event
* `preloadPath` string
* `error` Error
Emitted when the preload script `preloadPath` throws an unhandled exception `error`.
#### Event: 'ipc-message'
Returns:
* `event` Event
* `channel` string
* `...args` any[]
Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`.
See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents.
#### Event: 'ipc-message-sync'
Returns:
* `event` Event
* `channel` string
* `...args` any[]
Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`.
See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents.
#### Event: 'preferred-size-changed'
Returns:
* `event` Event
* `preferredSize` [Size](structures/size.md) - The minimum size needed to
contain the layout of the document—without requiring scrolling.
Emitted when the `WebContents` preferred size has changed.
This event will only be emitted when `enablePreferredSizeMode` is set to `true`
in `webPreferences`.
#### Event: 'frame-created'
Returns:
* `event` Event
* `details` Object
* `frame` WebFrameMain
Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page.
### Instance Methods
#### `contents.loadURL(url[, options])`
* `url` string
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n".
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see
[`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the `url` in the window. The `url` must contain the protocol prefix,
e.g. the `http://` or `file://`. If the load should bypass http cache then
use the `pragma` header to achieve it.
```javascript
const { webContents } = require('electron')
const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options)
```
#### `contents.loadFile(filePath[, options])`
* `filePath` string
* `options` Object (optional)
* `query` Record<string, string> (optional) - Passed to `url.format()`.
* `search` string (optional) - Passed to `url.format()`.
* `hash` string (optional) - Passed to `url.format()`.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Loads the given file in the window, `filePath` should be a path to
an HTML file relative to the root of your application. For instance
an app structure like this:
```sh
| root
| - package.json
| - src
| - main.js
| - index.html
```
Would require code like this
```js
win.loadFile('src/index.html')
```
#### `contents.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url` without navigating. The
`will-download` event of `session` will be triggered.
#### `contents.getURL()`
Returns `string` - The URL of the current web page.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})
```
#### `contents.getTitle()`
Returns `string` - The title of the current web page.
#### `contents.isDestroyed()`
Returns `boolean` - Whether the web page is destroyed.
#### `contents.close([opts])`
* `opts` Object (optional)
* `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event
before closing the page. If the page prevents the unload, the WebContents
will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload)
will be fired if the page requests prevention of unload.
Closes the page, as if the web content had called `window.close()`.
If the page is successfully closed (i.e. the unload is not prevented by the
page, or `waitForBeforeUnload` is false or unspecified), the WebContents will
be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event
will be emitted.
#### `contents.focus()`
Focuses the web page.
#### `contents.isFocused()`
Returns `boolean` - Whether the web page is focused.
#### `contents.isLoading()`
Returns `boolean` - Whether web page is still loading resources.
#### `contents.isLoadingMainFrame()`
Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is
still loading.
#### `contents.isWaitingForResponse()`
Returns `boolean` - Whether the web page is waiting for a first-response from the main
resource of the page.
#### `contents.stop()`
Stops any pending navigation.
#### `contents.reload()`
Reloads the current web page.
#### `contents.reloadIgnoringCache()`
Reloads current page and ignores cache.
#### `contents.canGoBack()`
Returns `boolean` - Whether the browser can go back to previous web page.
#### `contents.canGoForward()`
Returns `boolean` - Whether the browser can go forward to next web page.
#### `contents.canGoToOffset(offset)`
* `offset` Integer
Returns `boolean` - Whether the web page can go to `offset`.
#### `contents.clearHistory()`
Clears the navigation history.
#### `contents.goBack()`
Makes the browser go back a web page.
#### `contents.goForward()`
Makes the browser go forward a web page.
#### `contents.goToIndex(index)`
* `index` Integer
Navigates browser to the specified absolute web page index.
#### `contents.goToOffset(offset)`
* `offset` Integer
Navigates to the specified offset from the "current entry".
#### `contents.isCrashed()`
Returns `boolean` - Whether the renderer process has crashed.
#### `contents.forcefullyCrashRenderer()`
Forcefully terminates the renderer process that is currently hosting this
`webContents`. This will cause the `render-process-gone` event to be emitted
with the `reason=killed || reason=crashed`. Please note that some webContents share renderer
processes and therefore calling this method may also crash the host process
for other webContents as well.
Calling `reload()` immediately after calling this
method will force the reload to occur in a new process. This should be used
when this process is unstable or unusable, for instance in order to recover
from the `unresponsive` event.
```js
contents.on('unresponsive', async () => {
const { response } = await dialog.showMessageBox({
message: 'App X has become unresponsive',
title: 'Do you want to try forcefully reloading the app?',
buttons: ['OK', 'Cancel'],
cancelId: 1
})
if (response === 0) {
contents.forcefullyCrashRenderer()
contents.reload()
}
})
```
#### `contents.setUserAgent(userAgent)`
* `userAgent` string
Overrides the user agent for this web page.
#### `contents.getUserAgent()`
Returns `string` - The user agent for this web page.
#### `contents.insertCSS(css[, options])`
* `css` string
* `options` Object (optional)
* `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'.
Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`.
Injects CSS into the current web page and returns a unique key for the inserted
stylesheet.
```js
contents.on('did-finish-load', () => {
contents.insertCSS('html, body { background-color: #f00; }')
})
```
#### `contents.removeInsertedCSS(key)`
* `key` string
Returns `Promise<void>` - Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from `contents.insertCSS(css)`.
```js
contents.on('did-finish-load', async () => {
const key = await contents.insertCSS('html, body { background-color: #f00; }')
contents.removeInsertedCSS(key)
})
```
#### `contents.executeJavaScript(code[, userGesture])`
* `code` string
* `userGesture` boolean (optional) - Default is `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page.
In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
Code execution will be suspended until web page stop loading.
```js
contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})
```
#### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])`
* `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here.
* `scripts` [WebSource[]](structures/web-source.md)
* `userGesture` boolean (optional) - Default is `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Works like `executeJavaScript` but evaluates `scripts` in an isolated context.
#### `contents.setIgnoreMenuShortcuts(ignore)`
* `ignore` boolean
Ignore application menu shortcuts while this web contents is focused.
#### `contents.setWindowOpenHandler(handler)`
* `handler` Function<{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}>
* `details` Object
* `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`.
* `frameName` string - Name of the window provided in `window.open()`
* `features` string - Comma separated list of window features provided to `window.open()`.
* `disposition` string - Can be `default`, `foreground-tab`, `background-tab`,
`new-window`, `save-to-disk` or `other`.
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
passed to the new window. May or may not result in the `Referer` header being
sent, depending on the referrer policy.
* `postBody` [PostBody](structures/post-body.md) (optional) - The post data that
will be sent to the new window, along with the appropriate headers that will
be set. If no post data is to be sent, the value will be `null`. Only defined
when the window is being created by a form that set `target=_blank`.
Returns `{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new
window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window.
By default, child windows are closed when their opener is closed. This can be
changed by specifying `outlivesOpener: true`, in which case the opened window
will not be closed when its opener is closed.
Returning an unrecognized value such as a null, undefined, or an object
without a recognized 'action' value will result in a console error and have
the same effect as returning `{action: 'deny'}`.
Called before creating a window a new window is requested by the renderer, e.g.
by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or
submitting a form with `<form target="_blank">`. See
[`window.open()`](window-open.md) for more details and how to use this in
conjunction with `did-create-window`.
#### `contents.setAudioMuted(muted)`
* `muted` boolean
Mute the audio on the current web page.
#### `contents.isAudioMuted()`
Returns `boolean` - Whether this page has been muted.
#### `contents.isCurrentlyAudible()`
Returns `boolean` - Whether audio is currently playing.
#### `contents.setZoomFactor(factor)`
* `factor` Double - Zoom factor; default is 1.0.
Changes the zoom factor to the specified factor. Zoom factor is
zoom percent divided by 100, so 300% = 3.0.
The factor must be greater than 0.0.
#### `contents.getZoomFactor()`
Returns `number` - the current zoom factor.
#### `contents.setZoomLevel(level)`
* `level` number - Zoom level.
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
`scale := 1.2 ^ level`.
> **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the
> zoom level for a specific domain propagates across all instances of windows with
> the same domain. Differentiating the window URLs will make zoom work per-window.
#### `contents.getZoomLevel()`
Returns `number` - the current zoom level.
#### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` number
* `maximumLevel` number
Returns `Promise<void>`
Sets the maximum and minimum pinch-to-zoom level.
> **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call:
>
> ```js
> contents.setVisualZoomLevelLimits(1, 3)
> ```
#### `contents.undo()`
Executes the editing command `undo` in web page.
#### `contents.redo()`
Executes the editing command `redo` in web page.
#### `contents.cut()`
Executes the editing command `cut` in web page.
#### `contents.copy()`
Executes the editing command `copy` in web page.
#### `contents.copyImageAt(x, y)`
* `x` Integer
* `y` Integer
Copy the image at the given position to the clipboard.
#### `contents.paste()`
Executes the editing command `paste` in web page.
#### `contents.pasteAndMatchStyle()`
Executes the editing command `pasteAndMatchStyle` in web page.
#### `contents.delete()`
Executes the editing command `delete` in web page.
#### `contents.selectAll()`
Executes the editing command `selectAll` in web page.
#### `contents.unselect()`
Executes the editing command `unselect` in web page.
#### `contents.replace(text)`
* `text` string
Executes the editing command `replace` in web page.
#### `contents.replaceMisspelling(text)`
* `text` string
Executes the editing command `replaceMisspelling` in web page.
#### `contents.insertText(text)`
* `text` string
Returns `Promise<void>`
Inserts `text` to the focused element.
#### `contents.findInPage(text[, options])`
* `text` string - Content to be searched, must not be empty.
* `options` Object (optional)
* `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`.
* `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
* `matchCase` boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
Returns `Integer` - The request id used for the request.
Starts a request to find all matches for the `text` in the web page. The result of the request
can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event.
#### `contents.stopFindInPage(action)`
* `action` string - Specifies the action to take place when ending
[`webContents.findInPage`](#contentsfindinpagetext-options) request.
* `clearSelection` - Clear the selection.
* `keepSelection` - Translate the selection into a normal selection.
* `activateSelection` - Focus and click the selection node.
Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript
const { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)
```
#### `contents.capturePage([rect, opts])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.
* `opts` Object (optional)
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page.
The page is considered visible when its browser window is hidden and the capturer count is non-zero.
If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
#### `contents.isBeingCaptured()`
Returns `boolean` - Whether this page is being captured. It returns true when the capturer count
is large then 0.
#### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` _Deprecated_
* `size` [Size](structures/size.md) (optional) - The preferred size for the capturer.
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
Increase the capturer count by one. The page is considered visible when its browser window is
hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
This also affects the Page Visibility API.
**Deprecated:** This API's functionality is now handled automatically within `contents.capturePage()`. See [breaking changes](../breaking-changes.md).
#### `contents.decrementCapturerCount([stayHidden, stayAwake])` _Deprecated_
* `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
Decrease the capturer count by one. The page will be set to hidden or occluded state when its
browser window is hidden or occluded and the capturer count reaches zero. If you want to
decrease the hidden capturer count instead you should set `stayHidden` to true.
**Deprecated:** This API's functionality is now handled automatically within `contents.capturePage()`.
See [breaking changes](../breaking-changes.md).
#### `contents.getPrinters()` _Deprecated_
Get the system printer list.
Returns [`PrinterInfo[]`](structures/printer-info.md)
**Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API.
#### `contents.getPrintersAsync()`
Get the system printer list.
Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md)
#### `contents.print([options], [callback])`
* `options` Object (optional)
* `silent` boolean (optional) - Don't ask user for print settings. Default is `false`.
* `printBackground` boolean (optional) - Prints the background color and image of
the web page. Default is `false`.
* `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.
* `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`.
* `margins` Object (optional)
* `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`.
* `top` number (optional) - The top margin of the printed web page, in pixels.
* `bottom` number (optional) - The bottom margin of the printed web page, in pixels.
* `left` number (optional) - The left margin of the printed web page, in pixels.
* `right` number (optional) - The right margin of the printed web page, in pixels.
* `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`.
* `scaleFactor` number (optional) - The scale factor of the web page.
* `pagesPerSheet` number (optional) - The number of pages to print per page sheet.
* `collate` boolean (optional) - Whether the web page should be collated.
* `copies` number (optional) - The number of copies of the web page to print.
* `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored.
* `from` number - Index of the first page to print (0-based).
* `to` number - Index of the last page to print (inclusive) (0-based).
* `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`.
* `dpi` Record<string, number> (optional)
* `horizontal` number (optional) - The horizontal dpi.
* `vertical` number (optional) - The vertical dpi.
* `header` string (optional) - string to be printed as page header.
* `footer` string (optional) - string to be printed as page footer.
* `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`.
* `callback` Function (optional)
* `success` boolean - Indicates success of the print call.
* `failureReason` string - Error description called back if the print fails.
When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems.
Prints window's web page. When `silent` is set to `true`, Electron will pick
the system's default printer if `deviceName` is empty and the default settings for printing.
Use `page-break-before: always;` CSS style to force to print to a new page.
Example usage:
```js
const options = {
silent: true,
deviceName: 'My-Printer',
pageRanges: [{
from: 0,
to: 1
}]
}
win.webContents.print(options, (success, errorType) => {
if (!success) console.log(errorType)
})
```
#### `contents.printToPDF(options)`
* `options` Object
* `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false.
* `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false.
* `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false.
* `scale` number(optional) - Scale of the webpage rendering. Defaults to 1.
* `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`,
`A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`.
* `margins` Object (optional)
* `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
* `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
* `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
* `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
* `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
* `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title.
* `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`.
* `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
Returns `Promise<Buffer>` - Resolves with the generated PDF data.
Prints the window's web page as PDF.
The `landscape` will be ignored if `@page` CSS at-rule is used in the web page.
An example of `webContents.printToPDF`:
```javascript
const { BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')
const win = new BrowserWindow()
win.loadURL('http://github.com')
win.webContents.on('did-finish-load', () => {
// Use default printing options
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
win.webContents.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
```
See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information.
#### `contents.addWorkSpace(path)`
* `path` string
Adds the specified path to DevTools workspace. Must be used after DevTools
creation:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
```
#### `contents.removeWorkSpace(path)`
* `path` string
Removes the specified path from DevTools workspace.
#### `contents.setDevToolsWebContents(devToolsWebContents)`
* `devToolsWebContents` WebContents
Uses the `devToolsWebContents` as the target `WebContents` to show devtools.
The `devToolsWebContents` must not have done any navigation, and it should not
be used for other purposes after the call.
By default Electron manages the devtools by creating an internal `WebContents`
with native view, which developers have very limited control of. With the
`setDevToolsWebContents` method, developers can use any `WebContents` to show
the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>`
tag.
Note that closing the devtools does not destroy the `devToolsWebContents`, it
is caller's responsibility to destroy `devToolsWebContents`.
An example of showing devtools in a `<webview>` tag:
```html
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools" src="about:blank"></webview>
<script>
const { ipcRenderer } = require('electron')
const emittedOnce = (element, eventName) => new Promise(resolve => {
element.addEventListener(eventName, event => resolve(event), { once: true })
})
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
const browserReady = emittedOnce(browserView, 'dom-ready')
const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(() => {
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
```
```js
// Main process
const { ipcMain, webContents } = require('electron')
ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})
```
An example of showing devtools in a `BrowserWindow`:
```js
const { app, BrowserWindow } = require('electron')
let win = null
let devtools = null
app.whenReady().then(() => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({ mode: 'detach' })
})
```
#### `contents.openDevTools([options])`
* `options` Object (optional)
* `mode` string - Opens the devtools with specified dock state, can be
`left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state.
In `undocked` mode it's possible to dock back. In `detach` mode it's not.
* `activate` boolean (optional) - Whether to bring the opened devtools window
to the foreground. The default is `true`.
Opens the devtools.
When `contents` is a `<webview>` tag, the `mode` would be `detach` by default,
explicitly passing an empty `mode` can force using last used dock state.
On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`.
#### `contents.closeDevTools()`
Closes the devtools.
#### `contents.isDevToolsOpened()`
Returns `boolean` - Whether the devtools is opened.
#### `contents.isDevToolsFocused()`
Returns `boolean` - Whether the devtools view is focused .
#### `contents.toggleDevTools()`
Toggles the developer tools.
#### `contents.inspectElement(x, y)`
* `x` Integer
* `y` Integer
Starts inspecting element at position (`x`, `y`).
#### `contents.inspectSharedWorker()`
Opens the developer tools for the shared worker context.
#### `contents.inspectSharedWorkerById(workerId)`
* `workerId` string
Inspects the shared worker based on its ID.
#### `contents.getAllSharedWorkers()`
Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers.
#### `contents.inspectServiceWorker()`
Opens the developer tools for the service worker context.
#### `contents.send(channel, ...args)`
* `channel` string
* `...args` any[]
Send an asynchronous message to the renderer process via `channel`, along with
arguments. Arguments will be serialized with the [Structured Clone
Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
throw an exception.
> **NOTE**: Sending non-standard JavaScript types such as DOM objects or
> special Electron objects will throw an exception.
The renderer process can handle the message by listening to `channel` with the
[`ipcRenderer`](ipc-renderer.md) module.
An example of sending messages from the main process to the renderer process:
```javascript
// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
```
```html
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>
```
#### `contents.sendToFrame(frameId, channel, ...args)`
* `frameId` Integer | \[number, number] - the ID of the frame to send to, or a
pair of `[processId, frameId]` if the frame is in a different process to the
main frame.
* `channel` string
* `...args` any[]
Send an asynchronous message to a specific frame in a renderer process via
`channel`, along with arguments. Arguments will be serialized with the
[Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype
chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or
WeakSets will throw an exception.
> **NOTE:** Sending non-standard JavaScript types such as DOM objects or
> special Electron objects will throw an exception.
The renderer process can handle the message by listening to `channel` with the
[`ipcRenderer`](ipc-renderer.md) module.
If you want to get the `frameId` of a given renderer context you should use
the `webFrame.routingId` value. E.g.
```js
// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)
```
You can also read `frameId` from all incoming IPC messages in the main process.
```js
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
```
#### `contents.postMessage(channel, message, [transfer])`
* `channel` string
* `message` any
* `transfer` MessagePortMain[] (optional)
Send a message to the renderer process, optionally transferring ownership of
zero or more [`MessagePortMain`][] objects.
The transferred `MessagePortMain` objects will be available in the renderer
process by accessing the `ports` property of the emitted event. When they
arrive in the renderer, they will be native DOM `MessagePort` objects.
For example:
```js
// Main process
const { port1, port2 } = new MessageChannelMain()
webContents.postMessage('port', { message: 'hello' }, [port1])
// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
```
#### `contents.enableDeviceEmulation(parameters)`
* `parameters` Object
* `screenPosition` string - Specify the screen type to emulate
(default: `desktop`):
* `desktop` - Desktop screen type.
* `mobile` - Mobile screen type.
* `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile).
* `viewPosition` [Point](structures/point.md) - Position the view on the screen
(screenPosition == mobile) (default: `{ x: 0, y: 0 }`).
* `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to
original device scale factor) (default: `0`).
* `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override)
* `scale` Float - Scale of emulated view inside available space (not in fit to
view mode) (default: `1`).
Enable device emulation with the given parameters.
#### `contents.disableDeviceEmulation()`
Disable device emulation enabled by `webContents.enableDeviceEmulation`.
#### `contents.sendInputEvent(inputEvent)`
* `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md)
Sends an input `event` to the page.
**Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for
`sendInputEvent()` to work.
#### `contents.beginFrameSubscription([onlyDirty ,]callback)`
* `onlyDirty` boolean (optional) - Defaults to `false`.
* `callback` Function
* `image` [NativeImage](native-image.md)
* `dirtyRect` [Rectangle](structures/rectangle.md)
Begin subscribing for presentation events and captured frames, the `callback`
will be called with `callback(image, dirtyRect)` when there is a presentation
event.
The `image` is an instance of [NativeImage](native-image.md) that stores the
captured frame.
The `dirtyRect` is an object with `x, y, width, height` properties that
describes which part of the page was repainted. If `onlyDirty` is set to
`true`, `image` will only contain the repainted area. `onlyDirty` defaults to
`false`.
#### `contents.endFrameSubscription()`
End subscribing for frame presentation events.
#### `contents.startDrag(item)`
* `item` Object
* `file` string - The path to the file being dragged.
* `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field)
* `icon` [NativeImage](native-image.md) | string - The image must be
non-empty on macOS.
Sets the `item` as dragging item for current drag-drop operation, `file` is the
absolute path of the file to be dragged, and `icon` is the image showing under
the cursor when dragging.
#### `contents.savePage(fullPath, saveType)`
* `fullPath` string - The absolute file path.
* `saveType` string - Specify the save type.
* `HTMLOnly` - Save only the HTML of the page.
* `HTMLComplete` - Save complete-html page.
* `MHTML` - Save complete-html page as MHTML.
Returns `Promise<void>` - resolves if the page is saved.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', async () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => {
console.log('Page was saved successfully.')
}).catch(err => {
console.log(err)
})
})
```
#### `contents.showDefinitionForSelection()` _macOS_
Shows pop-up dictionary that searches the selected word on the page.
#### `contents.isOffscreen()`
Returns `boolean` - Indicates whether *offscreen rendering* is enabled.
#### `contents.startPainting()`
If *offscreen rendering* is enabled and not painting, start painting.
#### `contents.stopPainting()`
If *offscreen rendering* is enabled and painting, stop painting.
#### `contents.isPainting()`
Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting.
#### `contents.setFrameRate(fps)`
* `fps` Integer
If *offscreen rendering* is enabled sets the frame rate to the specified number.
Only values between 1 and 240 are accepted.
#### `contents.getFrameRate()`
Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate.
#### `contents.invalidate()`
Schedules a full repaint of the window this web contents is in.
If *offscreen rendering* is enabled invalidates the frame and generates a new
one through the `'paint'` event.
#### `contents.getWebRTCIPHandlingPolicy()`
Returns `string` - Returns the WebRTC IP Handling Policy.
#### `contents.setWebRTCIPHandlingPolicy(policy)`
* `policy` string - Specify the WebRTC IP Handling Policy.
* `default` - Exposes user's public and local IPs. This is the default
behavior. When this policy is used, WebRTC has the right to enumerate all
interfaces and bind them to discover public interfaces.
* `default_public_interface_only` - Exposes user's public IP, but does not
expose user's local IP. When this policy is used, WebRTC should only use the
default route used by http. This doesn't expose any local addresses.
* `default_public_and_private_interfaces` - Exposes user's public and local
IPs. When this policy is used, WebRTC should only use the default route used
by http. This also exposes the associated default private address. Default
route is the route chosen by the OS on a multi-homed endpoint.
* `disable_non_proxied_udp` - Does not expose public or local IPs. When this
policy is used, WebRTC should only use TCP to contact peers or servers unless
the proxy server supports UDP.
Setting the WebRTC IP handling policy allows you to control which IPs are
exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for
more details.
#### `contents.getMediaSourceId(requestWebContents)`
* `requestWebContents` WebContents - Web contents that the id will be registered to.
Returns `string` - The identifier of a WebContents stream. This identifier can be used
with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`.
The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.
#### `contents.getOSProcessId()`
Returns `Integer` - The operating system `pid` of the associated renderer
process.
#### `contents.getProcessId()`
Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can
be compared to the `frameProcessId` passed by frame specific navigation events
(e.g. `did-frame-navigate`)
#### `contents.takeHeapSnapshot(filePath)`
* `filePath` string - Path to the output file.
Returns `Promise<void>` - Indicates whether the snapshot has been created successfully.
Takes a V8 heap snapshot and saves it to `filePath`.
#### `contents.getBackgroundThrottling()`
Returns `boolean` - whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.setBackgroundThrottling(allowed)`
* `allowed` boolean
Controls whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.getType()`
Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`.
#### `contents.setImageAnimationPolicy(policy)`
* `policy` string - Can be `animate`, `animateOnce` or `noAnimation`.
Sets the image animation policy for this webContents. The policy only affects
_new_ images, existing images that are currently being animated are unaffected.
This is a known limitation in Chromium, you can force image animation to be
recalculated with `img.src = img.src` which will result in no network traffic
but will update the animation policy.
This corresponds to the [animationPolicy][] accessibility feature in Chromium.
[animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy
### Instance Properties
#### `contents.ipc` _Readonly_
An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this
WebContents.
IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or
`ipcRenderer.postMessage` will be delivered in the following order:
1. `contents.on('ipc-message')`
2. `contents.mainFrame.on(channel)`
3. `contents.ipc.on(channel)`
4. `ipcMain.on(channel)`
Handlers registered with `invoke` will be checked in the following order. The
first one that is defined will be called, the rest will be ignored.
1. `contents.mainFrame.handle(channel)`
2. `contents.handle(channel)`
3. `ipcMain.handle(channel)`
A handler or event listener registered on the WebContents will receive IPC
messages sent from any frame, including child frames. In most cases, only the
main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames`
option is enabled, it is possible for child frames to send IPC messages also.
In that case, handlers should check the `senderFrame` property of the IPC event
to ensure that the message is coming from the expected frame. Alternatively,
register handlers on the appropriate frame directly using the
[`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface.
#### `contents.audioMuted`
A `boolean` property that determines whether this page is muted.
#### `contents.userAgent`
A `string` property that determines the user agent for this web page.
#### `contents.zoomLevel`
A `number` property that determines the zoom level for this web contents.
The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`.
#### `contents.zoomFactor`
A `number` property that determines the zoom factor for this web contents.
The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
#### `contents.frameRate`
An `Integer` property that sets the frame rate of the web contents to the specified number.
Only values between 1 and 240 are accepted.
Only applicable if *offscreen rendering* is enabled.
#### `contents.id` _Readonly_
A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application.
#### `contents.session` _Readonly_
A [`Session`](session.md) used by this webContents.
#### `contents.hostWebContents` _Readonly_
A [`WebContents`](web-contents.md) instance that might own this `WebContents`.
#### `contents.devToolsWebContents` _Readonly_
A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`.
**Note:** Users should never store this object because it may become `null`
when the DevTools has been closed.
#### `contents.debugger` _Readonly_
A [`Debugger`](debugger.md) instance for this webContents.
#### `contents.backgroundThrottling`
A `boolean` property that determines whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.mainFrame` _Readonly_
A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy.
#### `contents.opener` _Readonly_
A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either
with open(), or by navigating a link with a target attribute.
[keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
[SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
[`MessagePortMain`]: message-port-main.md
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
docs/api/webview-tag.md
|
# `<webview>` Tag
## Warning
Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which
is undergoing dramatic architectural changes. This impacts the stability of `webviews`,
including rendering, navigation, and event routing. We currently recommend to not
use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md),
or an architecture that avoids embedded content altogether.
## Enabling
By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by
setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For
more information see the [BrowserWindow constructor docs](browser-window.md).
## Overview
> Display external web content in an isolated frame and process.
Process: [Renderer](../glossary.md#renderer-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
Use the `webview` tag to embed 'guest' content (such as web pages) in your
Electron app. The guest content is contained within the `webview` container.
An embedded page within your app controls how the guest content is laid out and
rendered.
Unlike an `iframe`, the `webview` runs in a separate process than your
app. It doesn't have the same permissions as your web page and all interactions
between your app and embedded content will be asynchronous. This keeps your app
safe from the embedded content. **Note:** Most methods called on the
webview from the host page require a synchronous call to the main process.
## Example
To embed a web page in your app, add the `webview` tag to your app's embedder
page (this is the app page that will display the guest content). In its simplest
form, the `webview` tag includes the `src` of the web page and css styles that
control the appearance of the `webview` container:
```html
<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>
```
If you want to control the guest content in any way, you can write JavaScript
that listens for `webview` events and responds to those events using the
`webview` methods. Here's sample code with two event listeners: one that listens
for the web page to start loading, the other for the web page to stop loading,
and displays a "loading..." message during the load time:
```html
<script>
onload = () => {
const webview = document.querySelector('webview')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
```
## Internal implementation
Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes).
The `webview` tag is essentially a custom element using shadow DOM to wrap an
`iframe` element inside it.
So the behavior of `webview` is very similar to a cross-domain `iframe`, as
examples:
* When clicking into a `webview`, the page focus will move from the embedder
frame to `webview`.
* You can not add keyboard, mouse, and scroll event listeners to `webview`.
* All reactions between the embedder frame and `webview` are asynchronous.
## CSS Styling Notes
Please note that the `webview` tag's style uses `display:flex;` internally to
ensure the child `iframe` element fills the full height and width of its `webview`
container when used with traditional and flexbox layouts. Please do not
overwrite the default `display:flex;` CSS property, unless specifying
`display:inline-flex;` for inline layout.
## Tag Attributes
The `webview` tag has the following attributes:
### `src`
```html
<webview src="https://www.github.com/"></webview>
```
A `string` representing the visible URL. Writing to this attribute initiates top-level
navigation.
Assigning `src` its own value will reload the current page.
The `src` attribute can also accept data URLs, such as
`data:text/plain,Hello, world!`.
### `nodeintegration`
```html
<webview src="http://www.google.com/" nodeintegration></webview>
```
A `boolean`. When this attribute is present the guest page in `webview` will have node
integration and can use node APIs like `require` and `process` to access low
level system resources. Node integration is disabled by default in the guest
page.
### `nodeintegrationinsubframes`
```html
<webview src="http://www.google.com/" nodeintegrationinsubframes></webview>
```
A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes
inside the `webview`. All your preloads will load for every iframe, you can
use `process.isMainFrame` to determine if you are in the main frame or not.
This option is disabled by default in the guest page.
### `plugins`
```html
<webview src="https://www.github.com/" plugins></webview>
```
A `boolean`. When this attribute is present the guest page in `webview` will be able to use
browser plugins. Plugins are disabled by default.
### `preload`
```html
<!-- from a file -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- or if you want to load from an asar archive -->
<webview src="https://www.github.com/" preload="./app.asar/test.js"></webview>
```
A `string` that specifies a script that will be loaded before other scripts run in the guest
page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because
it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual
directories.
When the guest page doesn't have node integration this script will still have
access to all Node APIs, but global objects injected by Node will be deleted
after this script has finished executing.
### `httpreferrer`
```html
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
```
A `string` that sets the referrer URL for the guest page.
### `useragent`
```html
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
```
A `string` that sets the user agent for the guest page before the page is navigated to. Once the
page is loaded, use the `setUserAgent` method to change the user agent.
### `disablewebsecurity`
```html
<webview src="https://www.github.com/" disablewebsecurity></webview>
```
A `boolean`. When this attribute is present the guest page will have web security disabled.
Web security is enabled by default.
### `partition`
```html
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>
```
A `string` that sets the session used by the page. If `partition` starts with `persist:`, the
page will use a persistent session available to all pages in the app with the
same `partition`. if there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. If the `partition` is unset then default session of the app
will be used.
This value can only be modified before the first navigation, since the session
of an active renderer process cannot change. Subsequent attempts to modify the
value will fail with a DOM exception.
### `allowpopups`
```html
<webview src="https://www.github.com/" allowpopups></webview>
```
A `boolean`. When this attribute is present the guest page will be allowed to open new
windows. Popups are disabled by default.
### `webpreferences`
```html
<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>
```
A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview.
The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions).
The string follows the same format as the features string in `window.open`.
A name by itself is given a `true` boolean value.
A preference can be set to another value by including an `=`, followed by the value.
Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`.
### `enableblinkfeatures`
```html
<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
```
A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`.
The full list of supported feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
### `disableblinkfeatures`
```html
<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
```
A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`.
The full list of supported feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
## Methods
The `webview` tag has the following methods:
**Note:** The webview element must be loaded before using the methods.
**Example**
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
```
### `<webview>.loadURL(url[, options])`
* `url` URL
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n"
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files.
Returns `Promise<void>` - The promise will resolve when the page has finished loading
(see [`did-finish-load`](webview-tag.md#event-did-finish-load)), and rejects
if the page fails to load (see
[`did-fail-load`](webview-tag.md#event-did-fail-load)).
Loads the `url` in the webview, the `url` must contain the protocol prefix,
e.g. the `http://` or `file://`.
### `<webview>.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url` without navigating.
### `<webview>.getURL()`
Returns `string` - The URL of guest page.
### `<webview>.getTitle()`
Returns `string` - The title of guest page.
### `<webview>.isLoading()`
Returns `boolean` - Whether guest page is still loading resources.
### `<webview>.isLoadingMainFrame()`
Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is
still loading.
### `<webview>.isWaitingForResponse()`
Returns `boolean` - Whether the guest page is waiting for a first-response for the
main resource of the page.
### `<webview>.stop()`
Stops any pending navigation.
### `<webview>.reload()`
Reloads the guest page.
### `<webview>.reloadIgnoringCache()`
Reloads the guest page and ignores cache.
### `<webview>.canGoBack()`
Returns `boolean` - Whether the guest page can go back.
### `<webview>.canGoForward()`
Returns `boolean` - Whether the guest page can go forward.
### `<webview>.canGoToOffset(offset)`
* `offset` Integer
Returns `boolean` - Whether the guest page can go to `offset`.
### `<webview>.clearHistory()`
Clears the navigation history.
### `<webview>.goBack()`
Makes the guest page go back.
### `<webview>.goForward()`
Makes the guest page go forward.
### `<webview>.goToIndex(index)`
* `index` Integer
Navigates to the specified absolute index.
### `<webview>.goToOffset(offset)`
* `offset` Integer
Navigates to the specified offset from the "current entry".
### `<webview>.isCrashed()`
Returns `boolean` - Whether the renderer process has crashed.
### `<webview>.setUserAgent(userAgent)`
* `userAgent` string
Overrides the user agent for the guest page.
### `<webview>.getUserAgent()`
Returns `string` - The user agent for guest page.
### `<webview>.insertCSS(css)`
* `css` string
Returns `Promise<string>` - A promise that resolves with a key for the inserted
CSS that can later be used to remove the CSS via
`<webview>.removeInsertedCSS(key)`.
Injects CSS into the current web page and returns a unique key for the inserted
stylesheet.
### `<webview>.removeInsertedCSS(key)`
* `key` string
Returns `Promise<void>` - Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from `<webview>.insertCSS(css)`.
### `<webview>.executeJavaScript(code[, userGesture])`
* `code` string
* `userGesture` boolean (optional) - Default `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page. If `userGesture` is set, it will create the user
gesture context in the page. HTML APIs like `requestFullScreen`, which require
user action, can take advantage of this option for automation.
### `<webview>.openDevTools()`
Opens a DevTools window for guest page.
### `<webview>.closeDevTools()`
Closes the DevTools window of guest page.
### `<webview>.isDevToolsOpened()`
Returns `boolean` - Whether guest page has a DevTools window attached.
### `<webview>.isDevToolsFocused()`
Returns `boolean` - Whether DevTools window of guest page is focused.
### `<webview>.inspectElement(x, y)`
* `x` Integer
* `y` Integer
Starts inspecting element at position (`x`, `y`) of guest page.
### `<webview>.inspectSharedWorker()`
Opens the DevTools for the shared worker context present in the guest page.
### `<webview>.inspectServiceWorker()`
Opens the DevTools for the service worker context present in the guest page.
### `<webview>.setAudioMuted(muted)`
* `muted` boolean
Set guest page muted.
### `<webview>.isAudioMuted()`
Returns `boolean` - Whether guest page has been muted.
### `<webview>.isCurrentlyAudible()`
Returns `boolean` - Whether audio is currently playing.
### `<webview>.undo()`
Executes editing command `undo` in page.
### `<webview>.redo()`
Executes editing command `redo` in page.
### `<webview>.cut()`
Executes editing command `cut` in page.
### `<webview>.copy()`
Executes editing command `copy` in page.
### `<webview>.paste()`
Executes editing command `paste` in page.
### `<webview>.pasteAndMatchStyle()`
Executes editing command `pasteAndMatchStyle` in page.
### `<webview>.delete()`
Executes editing command `delete` in page.
### `<webview>.selectAll()`
Executes editing command `selectAll` in page.
### `<webview>.unselect()`
Executes editing command `unselect` in page.
### `<webview>.replace(text)`
* `text` string
Executes editing command `replace` in page.
### `<webview>.replaceMisspelling(text)`
* `text` string
Executes editing command `replaceMisspelling` in page.
### `<webview>.insertText(text)`
* `text` string
Returns `Promise<void>`
Inserts `text` to the focused element.
### `<webview>.findInPage(text[, options])`
* `text` string - Content to be searched, must not be empty.
* `options` Object (optional)
* `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`.
* `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
* `matchCase` boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
Returns `Integer` - The request id used for the request.
Starts a request to find all matches for the `text` in the web page. The result of the request
can be obtained by subscribing to [`found-in-page`](webview-tag.md#event-found-in-page) event.
### `<webview>.stopFindInPage(action)`
* `action` string - Specifies the action to take place when ending
[`<webview>.findInPage`](#webviewfindinpagetext-options) request.
* `clearSelection` - Clear the selection.
* `keepSelection` - Translate the selection into a normal selection.
* `activateSelection` - Focus and click the selection node.
Stops any `findInPage` request for the `webview` with the provided `action`.
### `<webview>.print([options])`
* `options` Object (optional)
* `silent` boolean (optional) - Don't ask user for print settings. Default is `false`.
* `printBackground` boolean (optional) - Prints the background color and image of
the web page. Default is `false`.
* `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.
* `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`.
* `margins` Object (optional)
* `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`.
* `top` number (optional) - The top margin of the printed web page, in pixels.
* `bottom` number (optional) - The bottom margin of the printed web page, in pixels.
* `left` number (optional) - The left margin of the printed web page, in pixels.
* `right` number (optional) - The right margin of the printed web page, in pixels.
* `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`.
* `scaleFactor` number (optional) - The scale factor of the web page.
* `pagesPerSheet` number (optional) - The number of pages to print per page sheet.
* `collate` boolean (optional) - Whether the web page should be collated.
* `copies` number (optional) - The number of copies of the web page to print.
* `pageRanges` Object[] (optional) - The page range to print.
* `from` number - Index of the first page to print (0-based).
* `to` number - Index of the last page to print (inclusive) (0-based).
* `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`.
* `dpi` Record<string, number> (optional)
* `horizontal` number (optional) - The horizontal dpi.
* `vertical` number (optional) - The vertical dpi.
* `header` string (optional) - string to be printed as page header.
* `footer` string (optional) - string to be printed as page footer.
* `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` in microns.
Returns `Promise<void>`
Prints `webview`'s web page. Same as `webContents.print([options])`.
### `<webview>.printToPDF(options)`
* `options` Object
* `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false.
* `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false.
* `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false.
* `scale` number(optional) - Scale of the webpage rendering. Defaults to 1.
* `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`,
`A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`.
* `margins` Object (optional)
* `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
* `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
* `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
* `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
* `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
* `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title.
* `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`.
* `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
Returns `Promise<Uint8Array>` - Resolves with the generated PDF data.
Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`.
### `<webview>.capturePage([rect])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page.
### `<webview>.send(channel, ...args)`
* `channel` string
* `...args` any[]
Returns `Promise<void>`
Send an asynchronous message to renderer process via `channel`, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module.
See [webContents.send](web-contents.md#contentssendchannel-args) for
examples.
### `<webview>.sendToFrame(frameId, channel, ...args)`
* `frameId` \[number, number] - `[processId, frameId]`
* `channel` string
* `...args` any[]
Returns `Promise<void>`
Send an asynchronous message to renderer process via `channel`, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module.
See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for
examples.
### `<webview>.sendInputEvent(event)`
* `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md)
Returns `Promise<void>`
Sends an input `event` to the page.
See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent)
for detailed description of `event` object.
### `<webview>.setZoomFactor(factor)`
* `factor` number - Zoom factor.
Changes the zoom factor to the specified factor. Zoom factor is
zoom percent divided by 100, so 300% = 3.0.
### `<webview>.setZoomLevel(level)`
* `level` number - Zoom level.
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
`scale := 1.2 ^ level`.
> **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the
> zoom level for a specific domain propagates across all instances of windows with
> the same domain. Differentiating the window URLs will make zoom work per-window.
### `<webview>.getZoomFactor()`
Returns `number` - the current zoom factor.
### `<webview>.getZoomLevel()`
Returns `number` - the current zoom level.
### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` number
* `maximumLevel` number
Returns `Promise<void>`
Sets the maximum and minimum pinch-to-zoom level.
### `<webview>.showDefinitionForSelection()` _macOS_
Shows pop-up dictionary that searches the selected word on the page.
### `<webview>.getWebContentsId()`
Returns `number` - The WebContents ID of this `webview`.
## DOM Events
The following DOM events are available to the `webview` tag:
### Event: 'load-commit'
Returns:
* `url` string
* `isMainFrame` boolean
Fired when a load has committed. This includes navigation within the current
document as well as subframe document-level loads, but does not include
asynchronous resource loads.
### Event: 'did-finish-load'
Fired when the navigation is done, i.e. the spinner of the tab will stop
spinning, and the `onload` event is dispatched.
### Event: 'did-fail-load'
Returns:
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
This event is like `did-finish-load`, but fired when the load failed or was
cancelled, e.g. `window.stop()` is invoked.
### Event: 'did-frame-finish-load'
Returns:
* `isMainFrame` boolean
Fired when a frame has done navigation.
### Event: 'did-start-loading'
Corresponds to the points in time when the spinner of the tab starts spinning.
### Event: 'did-stop-loading'
Corresponds to the points in time when the spinner of the tab stops spinning.
### Event: 'did-attach'
Fired when attached to the embedder web contents.
### Event: 'dom-ready'
Fired when document in the given frame is loaded.
### Event: 'page-title-updated'
Returns:
* `title` string
* `explicitSet` boolean
Fired when page title is set during navigation. `explicitSet` is false when
title is synthesized from file url.
### Event: 'page-favicon-updated'
Returns:
* `favicons` string[] - Array of URLs.
Fired when page receives favicon urls.
### Event: 'enter-html-full-screen'
Fired when page enters fullscreen triggered by HTML API.
### Event: 'leave-html-full-screen'
Fired when page leaves fullscreen triggered by HTML API.
### Event: 'console-message'
Returns:
* `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
* `message` string - The actual console message
* `line` Integer - The line number of the source that triggered this console message
* `sourceId` string
Fired when the guest window logs a console message.
The following example code forwards all log messages to the embedder's console
without regard for log level or other properties.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
})
```
### Event: 'found-in-page'
Returns:
* `result` Object
* `requestId` Integer
* `activeMatchOrdinal` Integer - Position of the active match.
* `matches` Integer - Number of Matches.
* `selectionArea` Rectangle - Coordinates of first match region.
* `finalUpdate` boolean
Fired when a result is available for
[`webview.findInPage`](#webviewfindinpagetext-options) request.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test')
console.log(requestId)
```
### Event: 'will-navigate'
Returns:
* `url` string
Emitted when a user or the page wants to start navigation. It can happen when
the `window.location` object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with
APIs like `<webview>.loadURL` and `<webview>.back`.
It is also not emitted during in-page navigation, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
Calling `event.preventDefault()` does __NOT__ have any effect.
### Event: 'did-start-navigation'
Returns:
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame (including main) starts navigating. `isInPlace` will be
`true` for in-page navigations.
### Event: 'did-redirect-navigation'
Returns:
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted after a server side redirect occurs during navigation. For example a 302
redirect.
### Event: 'did-navigate'
Returns:
* `url` string
Emitted when a navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
### Event: 'did-frame-navigate'
Returns:
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations,
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
### Event: 'did-navigate-in-page'
Returns:
* `isMainFrame` boolean
* `url` string
Emitted when an in-page navigation happened.
When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM `hashchange` event is triggered.
### Event: 'close'
Fired when the guest page attempts to close itself.
The following example code navigates the `webview` to `about:blank` when the
guest attempts to close itself.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})
```
### Event: 'ipc-message'
Returns:
* `frameId` \[number, number] - pair of `[processId, frameId]`.
* `channel` string
* `args` any[]
Fired when the guest page has sent an asynchronous message to embedder page.
With `sendToHost` method and `ipc-message` event you can communicate
between guest page and embedder page:
```javascript
// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
```
```javascript
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
```
### Event: 'crashed'
Fired when the renderer process is crashed.
### Event: 'plugin-crashed'
Returns:
* `name` string
* `version` string
Fired when a plugin process is crashed.
### Event: 'destroyed'
Fired when the WebContents is destroyed.
### Event: 'media-started-playing'
Emitted when media starts playing.
### Event: 'media-paused'
Emitted when media is paused or done playing.
### Event: 'did-change-theme-color'
Returns:
* `themeColor` string
Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
```html
<meta name='theme-color' content='#ff0000'>
```
### Event: 'update-target-url'
Returns:
* `url` string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
### Event: 'devtools-opened'
Emitted when DevTools is opened.
### Event: 'devtools-closed'
Emitted when DevTools is closed.
### Event: 'devtools-focused'
Emitted when DevTools is focused / opened.
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
[chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/
### Event: 'context-menu'
Returns:
* `params` Object
* `x` Integer - x coordinate.
* `y` Integer - y coordinate.
* `linkURL` string - URL of the link that encloses the node the context menu
was invoked on.
* `linkText` string - Text associated with the link. May be an empty
string if the contents of the link are an image.
* `pageURL` string - URL of the top level page that the context menu was
invoked on.
* `frameURL` string - URL of the subframe that the context menu was invoked
on.
* `srcURL` string - Source URL for the element that the context menu
was invoked on. Elements with source URLs are images, audio and video.
* `mediaType` string - Type of the node the context menu was invoked on. Can
be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`.
* `hasImageContents` boolean - Whether the context menu was invoked on an image
which has non-empty contents.
* `isEditable` boolean - Whether the context is editable.
* `selectionText` string - Text of the selection that the context menu was
invoked on.
* `titleText` string - Title text of the selection that the context menu was
invoked on.
* `altText` string - Alt text of the selection that the context menu was
invoked on.
* `suggestedFilename` string - Suggested filename to be used when saving file through 'Save
Link As' option of context menu.
* `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection.
* `selectionStartOffset` number - Start position of the selection text.
* `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked.
* `misspelledWord` string - The misspelled word under the cursor, if any.
* `dictionarySuggestions` string[] - An array of suggested words to show the
user to replace the `misspelledWord`. Only available if there is a misspelled
word and spellchecker is enabled.
* `frameCharset` string - The character encoding of the frame on which the
menu was invoked.
* `inputFieldType` string - If the context menu was invoked on an input
field, the type of that field. Possible values are `none`, `plainText`,
`password`, `other`.
* `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled.
* `menuSourceType` string - Input source that invoked the context menu.
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
* `mediaFlags` Object - The flags for the media element the context menu was
invoked on.
* `inError` boolean - Whether the media element has crashed.
* `isPaused` boolean - Whether the media element is paused.
* `isMuted` boolean - Whether the media element is muted.
* `hasAudio` boolean - Whether the media element has audio.
* `isLooping` boolean - Whether the media element is looping.
* `isControlsVisible` boolean - Whether the media element's controls are
visible.
* `canToggleControls` boolean - Whether the media element's controls are
toggleable.
* `canPrint` boolean - Whether the media element can be printed.
* `canSave` boolean - Whether or not the media element can be downloaded.
* `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture.
* `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture.
* `canRotate` boolean - Whether the media element can be rotated.
* `canLoop` boolean - Whether the media element can be looped.
* `editFlags` Object - These flags indicate whether the renderer believes it
is able to perform the corresponding action.
* `canUndo` boolean - Whether the renderer believes it can undo.
* `canRedo` boolean - Whether the renderer believes it can redo.
* `canCut` boolean - Whether the renderer believes it can cut.
* `canCopy` boolean - Whether the renderer believes it can copy.
* `canPaste` boolean - Whether the renderer believes it can paste.
* `canDelete` boolean - Whether the renderer believes it can delete.
* `canSelectAll` boolean - Whether the renderer believes it can select all.
* `canEditRichly` boolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
lib/browser/web-view-events.ts
|
export const webViewEvents: Record<string, readonly string[]> = {
'load-commit': ['url', 'isMainFrame'],
'did-attach': [],
'did-finish-load': [],
'did-fail-load': ['errorCode', 'errorDescription', 'validatedURL', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-frame-finish-load': ['isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-start-loading': [],
'did-stop-loading': [],
'dom-ready': [],
'console-message': ['level', 'message', 'line', 'sourceId'],
'context-menu': ['params'],
'devtools-opened': [],
'devtools-closed': [],
'devtools-focused': [],
'will-navigate': ['url'],
'did-start-navigation': ['url', 'isInPlace', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-redirect-navigation': ['url', 'isInPlace', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-navigate': ['url', 'httpResponseCode', 'httpStatusText'],
'did-frame-navigate': ['url', 'httpResponseCode', 'httpStatusText', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-navigate-in-page': ['url', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'-focus-change': ['focus'],
close: [],
crashed: [],
'render-process-gone': ['details'],
'plugin-crashed': ['name', 'version'],
destroyed: [],
'page-title-updated': ['title', 'explicitSet'],
'page-favicon-updated': ['favicons'],
'enter-html-full-screen': [],
'leave-html-full-screen': [],
'media-started-playing': [],
'media-paused': [],
'found-in-page': ['result'],
'did-change-theme-color': ['themeColor'],
'update-target-url': ['url']
} as const;
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.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"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
std::string type;
if (ConvertFromV8(isolate, val, &type)) {
if (type == "default") {
*out = printing::mojom::MarginType::kDefaultMargins;
return true;
}
if (type == "none") {
*out = printing::mojom::MarginType::kNoMargins;
return true;
}
if (type == "printableArea") {
*out = printing::mojom::MarginType::kPrintableAreaMargins;
return true;
}
if (type == "custom") {
*out = printing::mojom::MarginType::kCustomMargins;
return true;
}
}
return false;
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "simplex") {
*out = printing::mojom::DuplexMode::kSimplex;
return true;
}
if (mode == "longEdge") {
*out = printing::mojom::DuplexMode::kLongEdge;
return true;
}
if (mode == "shortEdge") {
*out = printing::mojom::DuplexMode::kShortEdge;
return true;
}
}
return false;
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
std::string save_type;
if (!ConvertFromV8(isolate, val, &save_type))
return false;
save_type = base::ToLowerASCII(save_type);
if (save_type == "htmlonly") {
*out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
} else if (save_type == "htmlcomplete") {
*out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
} else if (save_type == "mhtml") {
*out = content::SAVE_PAGE_TYPE_AS_MHTML;
} else {
return false;
}
return true;
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Type = electron::api::WebContents::Type;
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "backgroundPage") {
*out = Type::kBackgroundPage;
} else if (type == "browserView") {
*out = Type::kBrowserView;
} else if (type == "webview") {
*out = Type::kWebView;
#if BUILDFLAG(ENABLE_OSR)
} else if (type == "offscreen") {
*out = Type::kOffScreen;
#endif
} else {
return false;
}
return true;
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
#if BUILDFLAG(ENABLE_OSR)
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
#endif
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
#if BUILDFLAG(ENABLE_OSR)
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
#endif
web_contents = content::WebContents::Create(params);
#if BUILDFLAG(ENABLE_OSR)
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
#endif
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_->HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
return owner_window_ && owner_window_->IsFullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window_)
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::HTML);
exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window_)
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_->keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
Emit("-audio-state-changed", audible);
}
void WebContents::BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame =
WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId());
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if (old_host)
old_host->GetWidget()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
return Emit(event, url, is_same_document, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments) {
TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
auto* target_web_contents = FromID(web_contents_id);
if (target_web_contents) {
content::RenderFrameHost* frame = target_web_contents->MainFrame();
DCHECK(frame);
v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
gin::Handle<WebFrameMain> web_frame_main =
WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
if (!web_frame_main->CheckRenderFrame())
return;
int32_t sender_id = ID();
web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
std::move(arguments), sender_id);
}
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
#if BUILDFLAG(ENABLE_OSR)
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
#endif
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, "", content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICTIONARY);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
#endif
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
#endif
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
// TODO(codebytere): remove in Electron v23.
void WebContents::IncrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.incrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
gfx::Size size;
bool stay_hidden = false;
bool stay_awake = false;
// get size arguments if they exist
args->GetNext(&size);
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
std::ignore = web_contents()
->IncrementCapturerCount(size, stay_hidden, stay_awake)
.Release();
}
// TODO(codebytere): remove in Electron v23.
void WebContents::DecrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.decrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
bool stay_hidden = false;
bool stay_awake = false;
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
web_contents()->DecrementCapturerCount(stay_hidden, stay_awake);
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const content::WebCursor& webcursor) {
const ui::Cursor& cursor = webcursor.cursor();
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
#if BUILDFLAG(ENABLE_OSR)
return type_ == Type::kOffScreen;
#else
return false;
#endif
}
#if BUILDFLAG(ENABLE_OSR)
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
#endif
void WebContents::Invalidate() {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
#endif
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return html_fullscreen_;
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::NONE;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::HTML;
return html_fullscreen_ || (in_transition && is_html_transition);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
#else
return content::PictureInPictureResult::kNotSupported;
#endif
}
void WebContents::ExitPictureInPicture() {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
#endif
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
std::unique_ptr<base::Value> parsed_excluded_folders =
base::JSONReader::ReadDeprecated(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window_->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
return gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
#if BUILDFLAG(ENABLE_OSR)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
#endif
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount)
.SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/api/electron_api_web_contents.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "chrome/browser/devtools/devtools_eye_dropper.h"
#include "chrome/browser/devtools/devtools_file_system_indexer.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck
#include "content/common/cursors/webcursor.h"
#include "content/common/frame.mojom.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/frame_subscriber.h"
#include "shell/browser/api/save_page_handler.h"
#include "shell/browser/event_emitter_mixin.h"
#include "shell/browser/extended_web_contents_observer.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/pinnable.h"
#include "ui/base/models/image_model.h"
#include "ui/gfx/image/image.h"
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/common/mojom/view_type.mojom.h"
namespace extensions {
class ScriptExecutor;
}
#endif
namespace blink {
struct DeviceEmulationParams;
// enum class PermissionType;
} // namespace blink
namespace gin_helper {
class Dictionary;
}
namespace network {
class ResourceRequestBody;
}
namespace gin {
class Arguments;
}
class ExclusiveAccessManager;
class SkRegion;
namespace electron {
class ElectronBrowserContext;
class ElectronJavaScriptDialogManager;
class InspectableWebContents;
class WebContentsZoomController;
class WebViewGuestDelegate;
class FrameSubscriber;
class WebDialogHelper;
class NativeWindow;
#if BUILDFLAG(ENABLE_OSR)
class OffScreenRenderWidgetHostView;
class OffScreenWebContentsView;
#endif
namespace api {
// Wrapper around the content::WebContents.
class WebContents : public ExclusiveAccessContext,
public gin::Wrappable<WebContents>,
public gin_helper::EventEmitterMixin<WebContents>,
public gin_helper::Constructible<WebContents>,
public gin_helper::Pinnable<WebContents>,
public gin_helper::CleanedUpAtExit,
public content::WebContentsObserver,
public content::WebContentsDelegate,
public content::RenderWidgetHost::InputEventObserver,
public InspectableWebContentsDelegate,
public InspectableWebContentsViewDelegate {
public:
enum class Type {
kBackgroundPage, // An extension background page.
kBrowserWindow, // Used by BrowserWindow.
kBrowserView, // Used by BrowserView.
kRemote, // Thin wrap around an existing WebContents.
kWebView, // Used by <webview>.
kOffScreen, // Used for offscreen rendering
};
// Create a new WebContents and return the V8 wrapper of it.
static gin::Handle<WebContents> New(v8::Isolate* isolate,
const gin_helper::Dictionary& options);
// Create a new V8 wrapper for an existing |web_content|.
//
// The lifetime of |web_contents| will be managed by this class.
static gin::Handle<WebContents> CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Get the api::WebContents associated with |web_contents|. Returns nullptr
// if there is no associated wrapper.
static WebContents* From(content::WebContents* web_contents);
static WebContents* FromID(int32_t id);
// Get the V8 wrapper of the |web_contents|, or create one if not existed.
//
// The lifetime of |web_contents| is NOT managed by this class, and the type
// of this wrapper is always REMOTE.
static gin::Handle<WebContents> FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents);
static gin::Handle<WebContents> CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
static v8::Local<v8::ObjectTemplate> FillObjectTemplate(
v8::Isolate*,
v8::Local<v8::ObjectTemplate>);
const char* GetTypeName() override;
void Destroy();
void Close(absl::optional<gin_helper::Dictionary> options);
base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
bool GetBackgroundThrottling() const;
void SetBackgroundThrottling(bool allowed);
int GetProcessID() const;
base::ProcessId GetOSProcessID() const;
Type GetType() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const gin_helper::Dictionary& options);
void Reload();
void ReloadIgnoringCache();
void DownloadURL(const GURL& url);
GURL GetURL() const;
std::u16string GetTitle() const;
bool IsLoading() const;
bool IsLoadingMainFrame() const;
bool IsWaitingForResponse() const;
void Stop();
bool CanGoBack() const;
void GoBack();
bool CanGoForward() const;
void GoForward();
bool CanGoToOffset(int offset) const;
void GoToOffset(int offset);
bool CanGoToIndex(int index) const;
void GoToIndex(int index);
int GetActiveIndex() const;
void ClearHistory();
int GetHistoryLength() const;
const std::string GetWebRTCIPHandlingPolicy() const;
void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy);
std::string GetMediaSourceID(content::WebContents* request_web_contents);
bool IsCrashed() const;
void ForcefullyCrashRenderer();
void SetUserAgent(const std::string& user_agent);
std::string GetUserAgent();
void InsertCSS(const std::string& css);
v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path,
const content::SavePageType& save_type);
void OpenDevTools(gin::Arguments* args);
void CloseDevTools();
bool IsDevToolsOpened();
bool IsDevToolsFocused();
void ToggleDevTools();
void EnableDeviceEmulation(const blink::DeviceEmulationParams& params);
void DisableDeviceEmulation();
void InspectElement(int x, int y);
void InspectSharedWorker();
void InspectSharedWorkerById(const std::string& workerId);
std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers();
void InspectServiceWorker();
void SetIgnoreMenuShortcuts(bool ignore);
void SetAudioMuted(bool muted);
bool IsAudioMuted();
bool IsCurrentlyAudible();
void SetEmbedder(const WebContents* embedder);
void SetDevToolsWebContents(const WebContents* devtools);
v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const;
void IncrementCapturerCount(gin::Arguments* args);
void DecrementCapturerCount(gin::Arguments* args);
bool IsBeingCaptured();
void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host);
#if BUILDFLAG(ENABLE_PRINTING)
void OnGetDeviceNameToUse(base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info);
void Print(gin::Arguments* args);
// Print current page as PDF.
v8::Local<v8::Promise> PrintToPDF(const base::Value& settings);
void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data);
#endif
void SetNextChildWebPreferences(const gin_helper::Dictionary);
// DevTools workspace api.
void AddWorkSpace(gin::Arguments* args, const base::FilePath& path);
void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path);
// Editing commands.
void Undo();
void Redo();
void Cut();
void Copy();
void Paste();
void PasteAndMatchStyle();
void Delete();
void SelectAll();
void Unselect();
void Replace(const std::u16string& word);
void ReplaceMisspelling(const std::u16string& word);
uint32_t FindInPage(gin::Arguments* args);
void StopFindInPage(content::StopFindAction action);
void ShowDefinitionForSelection();
void CopyImageAt(int x, int y);
// Focus.
void Focus();
bool IsFocused() const;
// Send WebInputEvent to the page.
void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event);
// Subscribe to the frame updates.
void BeginFrameSubscription(gin::Arguments* args);
void EndFrameSubscription();
// Dragging native items.
void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args);
// Captures the page with |rect|, |callback| would be called when capturing is
// done.
v8::Local<v8::Promise> CapturePage(gin::Arguments* args);
// Methods for creating <webview>.
bool IsGuest() const;
void AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id);
void DetachFromOuterFrame();
// Methods for offscreen rendering
bool IsOffScreen() const;
#if BUILDFLAG(ENABLE_OSR)
void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap);
void StartPainting();
void StopPainting();
bool IsPainting() const;
void SetFrameRate(int frame_rate);
int GetFrameRate() const;
#endif
void Invalidate();
gfx::Size GetSizeForNewRenderView(content::WebContents*) override;
// Methods for zoom handling.
void SetZoomLevel(double level);
double GetZoomLevel() const;
void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor);
double GetZoomFactor() const;
// Callback triggered on permission response.
void OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed);
// Create window with the given disposition.
void OnCreateWindow(const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body);
// Returns the preload script path of current WebContents.
std::vector<base::FilePath> GetPreloadPaths() const;
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const;
// Returns the owner window.
v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const;
// Notifies the web page that there is user interaction.
void NotifyUserActivation();
v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate,
const base::FilePath& file_path);
v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate);
// Properties.
int32_t ID() const { return id_; }
v8::Local<v8::Value> Session(v8::Isolate* isolate);
content::WebContents* HostWebContents() const;
v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
content::RenderFrameHost* MainFrame();
content::RenderFrameHost* Opener();
WebContentsZoomController* GetZoomController() { return zoom_controller_; }
void AddObserver(ExtendedWebContentsObserver* obs) {
observers_.AddObserver(obs);
}
void RemoveObserver(ExtendedWebContentsObserver* obs) {
// Trying to remove from an empty collection leads to an access violation
if (!observers_.empty())
observers_.RemoveObserver(obs);
}
bool EmitNavigationEvent(const std::string& event,
content::NavigationHandle* navigation_handle);
// this.emit(name, new Event(sender, message), args...);
template <typename... Args>
bool EmitWithSender(base::StringPiece name,
content::RenderFrameHost* sender,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
Args&&... args) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return false;
v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent(
isolate, wrapper, sender, std::move(callback));
return EmitCustomEvent(name, event, std::forward<Args>(args)...);
}
WebContents* embedder() { return embedder_; }
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ScriptExecutor* script_executor() {
return script_executor_.get();
}
#endif
// Set the window as owner window.
void SetOwnerWindow(NativeWindow* owner_window);
void SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window);
// Returns the WebContents managed by this delegate.
content::WebContents* GetWebContents() const;
// Returns the WebContents of devtools.
content::WebContents* GetDevToolsWebContents() const;
InspectableWebContents* inspectable_web_contents() const {
return inspectable_web_contents_.get();
}
NativeWindow* owner_window() const { return owner_window_.get(); }
bool is_html_fullscreen() const { return html_fullscreen_; }
void set_fullscreen_frame(content::RenderFrameHost* rfh) {
fullscreen_frame_ = rfh;
}
// mojom::ElectronApiIPC
void Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host);
void Invoke(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host);
void ReceivePostMessage(const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host);
void MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host);
void MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments);
void MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host);
// mojom::ElectronWebContentsUtility
void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host);
void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions);
void SetTemporaryZoomLevel(double level);
void DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback);
void SetImageAnimationPolicy(const std::string& new_policy);
// content::RenderWidgetHost::InputEventObserver:
void OnInputEvent(const blink::WebInputEvent& event) override;
SkRegion* draggable_region() { return draggable_region_.get(); }
// disable copy
WebContents(const WebContents&) = delete;
WebContents& operator=(const WebContents&) = delete;
private:
// Does not manage lifetime of |web_contents|.
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
// Takes over ownership of |web_contents|.
WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Creates a new content::WebContents.
WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options);
~WebContents() override;
// Delete this if garbage collection has not started.
void DeleteThisIfAlive();
// Creates a InspectableWebContents object and takes ownership of
// |web_contents|.
void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest);
void InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
gin::Handle<class Session> session,
const gin_helper::Dictionary& options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type);
#endif
// content::WebContentsDelegate:
bool DidAddMessageToConsole(content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) override;
bool IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) override;
content::WebContents* CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) override;
void WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override;
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override;
void SetContentsBounds(content::WebContents* source,
const gfx::Rect& pos) override;
void CloseContents(content::WebContents* source) override;
void ActivateContents(content::WebContents* contents) override;
void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
bool HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
bool PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event);
content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
void ContentsZoomChange(bool zoom_in) override;
void EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
void RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) override;
void RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) override;
bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) override;
void RequestExclusivePointerAccess(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed);
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
void LostMouseLock() override;
void RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) override;
void CancelKeyboardLockRequest(content::WebContents* web_contents) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void OnAudioStateChanged(bool audible) override;
void UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) override;
// content::WebContentsObserver:
void BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) override;
void OnBackgroundColorChanged() override;
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override;
void FrameDeleted(int frame_tree_node_id) override;
void RenderViewDeleted(content::RenderViewHost*) override;
void PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) override;
void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override;
void DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) override;
void DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code) override;
void DidStartLoading() override;
void DidStopLoading() override;
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override;
void DidRedirectNavigation(
content::NavigationHandle* navigation_handle) override;
void ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
void WebContentsDestroyed() override;
void NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) override;
void TitleWasSet(content::NavigationEntry* entry) override;
void DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) override;
void PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) override;
void MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) override;
void MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) override;
void DidChangeThemeColor() override;
void OnCursorChanged(const content::WebCursor& cursor) override;
void DidAcquireFullscreen(content::RenderFrameHost* rfh) override;
void OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) override;
void OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) override;
void RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) override;
// InspectableWebContentsDelegate:
void DevToolsReloadPage() override;
// InspectableWebContentsViewDelegate:
void DevToolsFocused() override;
void DevToolsOpened() override;
void DevToolsClosed() override;
void DevToolsResized() override;
ElectronBrowserContext* GetBrowserContext() const;
void OnElectronBrowserConnectionError();
#if BUILDFLAG(ENABLE_OSR)
OffScreenWebContentsView* GetOffScreenWebContentsView() const;
OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
#endif
// Called when received a synchronous message from renderer to
// get the zoom level.
void OnGetZoomLevel(content::RenderFrameHost* frame_host,
IPC::Message* reply_msg);
void InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options);
// content::WebContentsDelegate:
bool CanOverscrollContent() override;
std::unique_ptr<content::EyeDropper> OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) override;
// ExclusiveAccessContext:
Profile* GetProfile() override;
bool IsFullscreen() const override;
void EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) override;
void ExitFullscreen() override;
void UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) override;
void OnExclusiveAccessUserInput() override;
content::WebContents* GetActiveWebContents() override;
bool CanUserExitFullscreen() const override;
bool IsExclusiveAccessBubbleDisplayed() const override;
bool IsFullscreenForTabOrPending(const content::WebContents* source) override;
bool TakeFocus(content::WebContents* source, bool reverse) override;
content::PictureInPictureResult EnterPictureInPicture(
content::WebContents* web_contents) override;
void ExitPictureInPicture() override;
// InspectableWebContentsDelegate:
void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) override;
void DevToolsAppendToFile(const std::string& url,
const std::string& content) override;
void DevToolsRequestFileSystems() override;
void DevToolsAddFileSystem(const std::string& type,
const base::FilePath& file_system_path) override;
void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) override;
void DevToolsIndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) override;
void DevToolsStopIndexing(int request_id) override;
void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) override;
void DevToolsSetEyeDropperActive(bool active) override;
// InspectableWebContentsViewDelegate:
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel GetDevToolsWindowIcon() override;
#endif
#if BUILDFLAG(IS_LINUX)
void GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) override;
#endif
void ColorPickedInEyeDropper(int r, int g, int b, int a);
// DevTools index event callbacks.
void OnDevToolsIndexingWorkCalculated(int request_id,
const std::string& file_system_path,
int total_work);
void OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked);
void OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path);
void OnDevToolsSearchCompleted(int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths);
// Set fullscreen mode triggered by html api.
void SetHtmlApiFullscreen(bool enter_fullscreen);
// Update the html fullscreen flag in both browser and renderer.
void UpdateHtmlApiFullscreen(bool fullscreen);
v8::Global<v8::Value> session_;
v8::Global<v8::Value> devtools_web_contents_;
v8::Global<v8::Value> debugger_;
std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_;
std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
std::unique_ptr<FrameSubscriber> frame_subscriber_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
std::unique_ptr<extensions::ScriptExecutor> script_executor_;
#endif
// The host webcontents that may contain this webcontents.
WebContents* embedder_ = nullptr;
// Whether the guest view has been attached.
bool attached_ = false;
// The zoom controller for this webContents.
WebContentsZoomController* zoom_controller_ = nullptr;
// The type of current WebContents.
Type type_ = Type::kBrowserWindow;
int32_t id_;
// Request id used for findInPage request.
uint32_t find_in_page_request_id_ = 0;
// Whether background throttling is disabled.
bool background_throttling_ = true;
// Whether to enable devtools.
bool enable_devtools_ = true;
// Observers of this WebContents.
base::ObserverList<ExtendedWebContentsObserver> observers_;
v8::Global<v8::Value> pending_child_web_preferences_;
// The window that this WebContents belongs to.
base::WeakPtr<NativeWindow> owner_window_;
bool offscreen_ = false;
// Whether window is fullscreened by HTML5 api.
bool html_fullscreen_ = false;
// Whether window is fullscreened by window api.
bool native_fullscreen_ = false;
scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_;
std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_;
std::unique_ptr<DevToolsEyeDropper> eye_dropper_;
ElectronBrowserContext* browser_context_;
// The stored InspectableWebContents object.
// Notice that inspectable_web_contents_ must be placed after
// dialog_manager_, so we can make sure inspectable_web_contents_ is
// destroyed before dialog_manager_, otherwise a crash would happen.
std::unique_ptr<InspectableWebContents> inspectable_web_contents_;
// Maps url to file path, used by the file requests sent from devtools.
typedef std::map<std::string, base::FilePath> PathsMap;
PathsMap saved_files_;
// Map id to index job, used for file system indexing requests from devtools.
typedef std::
map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>>
DevToolsIndexingJobsMap;
DevToolsIndexingJobsMap devtools_indexing_jobs_;
scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
#if BUILDFLAG(ENABLE_PRINTING)
scoped_refptr<base::TaskRunner> print_task_runner_;
#endif
// Stores the frame thats currently in fullscreen, nullptr if there is none.
content::RenderFrameHost* fullscreen_frame_ = nullptr;
std::unique_ptr<SkRegion> draggable_region_;
base::WeakPtrFactory<WebContents> weak_factory_{this};
};
} // namespace api
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/ui/inspectable_web_contents.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "shell/browser/ui/inspectable_web_contents.h"
#include <memory>
#include <utility>
#include "base/base64.h"
#include "base/guid.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/json/string_escape.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/user_agent.h"
#include "ipc/ipc_channel.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/net/asar/asar_url_loader_factory.h"
#include "shell/browser/protocol_registry.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "shell/common/platform_util.h"
#include "third_party/blink/public/common/logging/logging_utils.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#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/permissions/permissions_data.h"
#include "shell/browser/electron_browser_context.h"
#endif
namespace electron {
namespace {
const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9,
1.0, 1.1, 1.25, 1.5, 1.75, 2.0,
2.5, 3.0, 4.0, 5.0};
const char kChromeUIDevToolsURL[] =
"devtools://devtools/bundled/devtools_app.html?"
"remoteBase=%s&"
"can_dock=%s&"
"toolbarColor=rgba(223,223,223,1)&"
"textColor=rgba(0,0,0,1)&"
"experiments=true";
const char kChromeUIDevToolsRemoteFrontendBase[] =
"https://chrome-devtools-frontend.appspot.com/";
const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file";
const char kDevToolsBoundsPref[] = "electron.devtools.bounds";
const char kDevToolsZoomPref[] = "electron.devtools.zoom";
const char kDevToolsPreferences[] = "electron.devtools.preferences";
const char kFrontendHostId[] = "id";
const char kFrontendHostMethod[] = "method";
const char kFrontendHostParams[] = "params";
const char kTitleFormat[] = "Developer Tools - %s";
const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;
// Stores all instances of InspectableWebContents.
InspectableWebContents::List g_web_contents_instances_;
base::Value RectToDictionary(const gfx::Rect& bounds) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetKey("x", base::Value(bounds.x()));
dict.SetKey("y", base::Value(bounds.y()));
dict.SetKey("width", base::Value(bounds.width()));
dict.SetKey("height", base::Value(bounds.height()));
return dict;
}
gfx::Rect DictionaryToRect(const base::Value* dict) {
const base::Value* found = dict->FindKey("x");
int x = found ? found->GetInt() : 0;
found = dict->FindKey("y");
int y = found ? found->GetInt() : 0;
found = dict->FindKey("width");
int width = found ? found->GetInt() : 800;
found = dict->FindKey("height");
int height = found ? found->GetInt() : 600;
return gfx::Rect(x, y, width, height);
}
bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) {
return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) &&
point.y() > rect.y() && point.y() < (rect.height() + rect.y());
}
bool IsPointInScreen(const gfx::Point& point) {
for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) {
if (IsPointInRect(point, display.bounds()))
return true;
}
return false;
}
void SetZoomLevelForWebContents(content::WebContents* web_contents,
double level) {
content::HostZoomMap::SetZoomLevel(web_contents, level);
}
double GetNextZoomLevel(double level, bool out) {
double factor = blink::PageZoomLevelToZoomFactor(level);
size_t size = std::size(kPresetZoomFactors);
for (size_t i = 0; i < size; ++i) {
if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor))
continue;
if (out && i > 0)
return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]);
if (!out && i != size - 1)
return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]);
}
return level;
}
GURL GetRemoteBaseURL() {
return GURL(base::StringPrintf("%s%s/%s/",
kChromeUIDevToolsRemoteFrontendBase,
kChromeUIDevToolsRemoteFrontendPath,
content::GetChromiumGitRevision().c_str()));
}
GURL GetDevToolsURL(bool can_dock) {
auto url_string = base::StringPrintf(kChromeUIDevToolsURL,
GetRemoteBaseURL().spec().c_str(),
can_dock ? "true" : "");
return GURL(url_string);
}
void OnOpenItemComplete(const base::FilePath& path, const std::string& result) {
platform_util::ShowItemInFolder(path);
}
constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250);
constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10);
} // namespace
class InspectableWebContents::NetworkResourceLoader
: public network::SimpleURLLoaderStreamConsumer {
public:
class URLLoaderFactoryHolder {
public:
network::mojom::URLLoaderFactory* get() {
return ptr_.get() ? ptr_.get() : refptr_.get();
}
void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) {
ptr_ = std::move(ptr);
}
void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) {
refptr_ = std::move(refptr);
}
private:
std::unique_ptr<network::mojom::URLLoaderFactory> ptr_;
scoped_refptr<network::SharedURLLoaderFactory> refptr_;
};
static void Create(int stream_id,
InspectableWebContents* bindings,
const network::ResourceRequest& resource_request,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
URLLoaderFactoryHolder url_loader_factory,
DispatchCallback callback,
base::TimeDelta retry_delay = base::TimeDelta()) {
auto resource_loader =
std::make_unique<InspectableWebContents::NetworkResourceLoader>(
stream_id, bindings, resource_request, traffic_annotation,
std::move(url_loader_factory), std::move(callback), retry_delay);
bindings->loaders_.insert(std::move(resource_loader));
}
NetworkResourceLoader(
int stream_id,
InspectableWebContents* bindings,
const network::ResourceRequest& resource_request,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
URLLoaderFactoryHolder url_loader_factory,
DispatchCallback callback,
base::TimeDelta delay)
: stream_id_(stream_id),
bindings_(bindings),
resource_request_(resource_request),
traffic_annotation_(traffic_annotation),
loader_(network::SimpleURLLoader::Create(
std::make_unique<network::ResourceRequest>(resource_request),
traffic_annotation)),
url_loader_factory_(std::move(url_loader_factory)),
callback_(std::move(callback)),
retry_delay_(delay) {
loader_->SetOnResponseStartedCallback(base::BindOnce(
&NetworkResourceLoader::OnResponseStarted, base::Unretained(this)));
timer_.Start(FROM_HERE, delay,
base::BindRepeating(&NetworkResourceLoader::DownloadAsStream,
base::Unretained(this)));
}
NetworkResourceLoader(const NetworkResourceLoader&) = delete;
NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete;
private:
void DownloadAsStream() {
loader_->DownloadAsStream(url_loader_factory_.get(), this);
}
base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) {
if (delta.is_zero()) {
return kInitialBackoffDelay;
} else {
return delta * 1.3;
}
}
void OnResponseStarted(const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
response_headers_ = response_head.headers;
}
void OnDataReceived(base::StringPiece chunk,
base::OnceClosure resume) override {
base::Value chunkValue;
bool encoded = !base::IsStringUTF8(chunk);
if (encoded) {
std::string encoded_string;
base::Base64Encode(chunk, &encoded_string);
chunkValue = base::Value(std::move(encoded_string));
} else {
chunkValue = base::Value(chunk);
}
base::Value id(stream_id_);
base::Value encodedValue(encoded);
bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id),
std::move(chunkValue),
std::move(encodedValue));
std::move(resume).Run();
}
void OnComplete(bool success) override {
if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES &&
retry_delay_ < kMaxBackoffDelay) {
const base::TimeDelta delay =
GetNextExponentialBackoffDelay(retry_delay_);
LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = "
<< stream_id_
<< " failed with insufficient resources, retrying in "
<< delay << "." << std::endl;
NetworkResourceLoader::Create(
stream_id_, bindings_, resource_request_, traffic_annotation_,
std::move(url_loader_factory_), std::move(callback_), delay);
} else {
base::Value response(base::Value::Type::DICT);
response.GetDict().Set(
"statusCode", response_headers_ ? response_headers_->response_code()
: net::HTTP_OK);
base::Value::Dict headers;
size_t iterator = 0;
std::string name;
std::string value;
while (response_headers_ &&
response_headers_->EnumerateHeaderLines(&iterator, &name, &value))
headers.Set(name, value);
response.GetDict().Set("headers", std::move(headers));
std::move(callback_).Run(&response);
}
bindings_->loaders_.erase(bindings_->loaders_.find(this));
}
void OnRetry(base::OnceClosure start_retry) override {}
const int stream_id_;
InspectableWebContents* const bindings_;
const network::ResourceRequest resource_request_;
const net::NetworkTrafficAnnotationTag traffic_annotation_;
std::unique_ptr<network::SimpleURLLoader> loader_;
URLLoaderFactoryHolder url_loader_factory_;
DispatchCallback callback_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
base::OneShotTimer timer_;
base::TimeDelta retry_delay_;
};
// Implemented separately on each platform.
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents);
// static
const InspectableWebContents::List& InspectableWebContents::GetAll() {
return g_web_contents_instances_;
}
// static
void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(kDevToolsBoundsPref,
RectToDictionary(gfx::Rect(0, 0, 800, 600)));
registry->RegisterDoublePref(kDevToolsZoomPref, 0.);
registry->RegisterDictionaryPref(kDevToolsPreferences);
}
InspectableWebContents::InspectableWebContents(
std::unique_ptr<content::WebContents> web_contents,
PrefService* pref_service,
bool is_guest)
: pref_service_(pref_service),
web_contents_(std::move(web_contents)),
is_guest_(is_guest),
view_(CreateInspectableContentsView(this)) {
const base::Value* bounds_dict =
&pref_service_->GetValue(kDevToolsBoundsPref);
if (bounds_dict->is_dict()) {
devtools_bounds_ = DictionaryToRect(bounds_dict);
// Sometimes the devtools window is out of screen or has too small size.
if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) {
devtools_bounds_.set_height(600);
devtools_bounds_.set_width(800);
}
if (!IsPointInScreen(devtools_bounds_.origin())) {
gfx::Rect display;
if (!is_guest && web_contents_->GetNativeView()) {
display = display::Screen::GetScreen()
->GetDisplayNearestView(web_contents_->GetNativeView())
.bounds();
} else {
display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds();
}
devtools_bounds_.set_x(display.x() +
(display.width() - devtools_bounds_.width()) / 2);
devtools_bounds_.set_y(
display.y() + (display.height() - devtools_bounds_.height()) / 2);
}
}
g_web_contents_instances_.push_back(this);
}
InspectableWebContents::~InspectableWebContents() {
g_web_contents_instances_.remove(this);
// Unsubscribe from devtools and Clean up resources.
if (GetDevToolsWebContents())
WebContentsDestroyed();
// Let destructor destroy managed_devtools_web_contents_.
}
InspectableWebContentsView* InspectableWebContents::GetView() const {
return view_.get();
}
content::WebContents* InspectableWebContents::GetWebContents() const {
return web_contents_.get();
}
content::WebContents* InspectableWebContents::GetDevToolsWebContents() const {
if (external_devtools_web_contents_)
return external_devtools_web_contents_;
else
return managed_devtools_web_contents_.get();
}
void InspectableWebContents::InspectElement(int x, int y) {
if (agent_host_)
agent_host_->InspectElement(web_contents_->GetPrimaryMainFrame(), x, y);
}
void InspectableWebContents::SetDelegate(
InspectableWebContentsDelegate* delegate) {
delegate_ = delegate;
}
InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const {
return delegate_;
}
bool InspectableWebContents::IsGuest() const {
return is_guest_;
}
void InspectableWebContents::ReleaseWebContents() {
web_contents_.release();
WebContentsDestroyed();
view_.reset();
}
void InspectableWebContents::SetDockState(const std::string& state) {
if (state == "detach") {
can_dock_ = false;
} else {
can_dock_ = true;
dock_state_ = state;
}
}
void InspectableWebContents::SetDevToolsWebContents(
content::WebContents* devtools) {
if (!managed_devtools_web_contents_)
external_devtools_web_contents_ = devtools;
}
void InspectableWebContents::ShowDevTools(bool activate) {
if (embedder_message_dispatcher_) {
if (managed_devtools_web_contents_)
view_->ShowDevTools(activate);
return;
}
activate_ = activate;
// Show devtools only after it has done loading, this is to make sure the
// SetIsDocked is called *BEFORE* ShowDevTools.
embedder_message_dispatcher_ =
DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this);
if (!external_devtools_web_contents_) { // no external devtools
managed_devtools_web_contents_ = content::WebContents::Create(
content::WebContents::CreateParams(web_contents_->GetBrowserContext()));
managed_devtools_web_contents_->SetDelegate(this);
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
api::WebContents::FromOrCreate(isolate,
managed_devtools_web_contents_.get());
}
Observe(GetDevToolsWebContents());
AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get()));
GetDevToolsWebContents()->GetController().LoadURL(
GetDevToolsURL(can_dock_), content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string());
}
void InspectableWebContents::CloseDevTools() {
if (GetDevToolsWebContents()) {
frontend_loaded_ = false;
if (managed_devtools_web_contents_) {
view_->CloseDevTools();
managed_devtools_web_contents_.reset();
}
embedder_message_dispatcher_.reset();
if (!IsGuest())
web_contents_->Focus();
}
}
bool InspectableWebContents::IsDevToolsViewShowing() {
return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing();
}
void InspectableWebContents::AttachTo(
scoped_refptr<content::DevToolsAgentHost> host) {
Detach();
agent_host_ = std::move(host);
// We could use ForceAttachClient here if problem arises with
// devtools multiple session support.
agent_host_->AttachClient(this);
}
void InspectableWebContents::Detach() {
if (agent_host_)
agent_host_->DetachClient(this);
agent_host_ = nullptr;
}
void InspectableWebContents::Reattach(DispatchCallback callback) {
if (agent_host_) {
agent_host_->DetachClient(this);
agent_host_->AttachClient(this);
}
std::move(callback).Run(nullptr);
}
void InspectableWebContents::CallClientFunction(
const std::string& object_name,
const std::string& method_name,
base::Value arg1,
base::Value arg2,
base::Value arg3,
base::OnceCallback<void(base::Value)> cb) {
if (!GetDevToolsWebContents())
return;
base::Value::List arguments;
if (!arg1.is_none()) {
arguments.Append(std::move(arg1));
if (!arg2.is_none()) {
arguments.Append(std::move(arg2));
if (!arg3.is_none()) {
arguments.Append(std::move(arg3));
}
}
}
GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScriptMethod(
base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name),
std::move(arguments), std::move(cb));
}
gfx::Rect InspectableWebContents::GetDevToolsBounds() const {
return devtools_bounds_;
}
void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) {
pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds));
devtools_bounds_ = bounds;
}
double InspectableWebContents::GetDevToolsZoomLevel() const {
return pref_service_->GetDouble(kDevToolsZoomPref);
}
void InspectableWebContents::UpdateDevToolsZoomLevel(double level) {
pref_service_->SetDouble(kDevToolsZoomPref, level);
}
void InspectableWebContents::ActivateWindow() {
// Set the zoom level.
SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel());
}
void InspectableWebContents::CloseWindow() {
GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */);
}
void InspectableWebContents::LoadCompleted() {
frontend_loaded_ = true;
if (managed_devtools_web_contents_)
view_->ShowDevTools(activate_);
// If the devtools can dock, "SetIsDocked" will be called by devtools itself.
if (!can_dock_) {
SetIsDocked(DispatchCallback(), false);
} else {
if (dock_state_.empty()) {
const base::Value::Dict& prefs =
pref_service_->GetDict(kDevToolsPreferences);
const std::string* current_dock_state =
prefs.FindString("currentDockState");
base::RemoveChars(*current_dock_state, "\"", &dock_state_);
}
std::u16string javascript = base::UTF8ToUTF16(
"UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");");
GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScript(
javascript, base::NullCallback());
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
AddDevToolsExtensionsToClient();
#endif
if (view_->GetDelegate())
view_->GetDelegate()->DevToolsOpened();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void InspectableWebContents::AddDevToolsExtensionsToClient() {
// get main browser context
auto* browser_context = web_contents_->GetBrowserContext();
const extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(browser_context);
if (!registry)
return;
base::Value::List results;
for (auto& extension : registry->enabled_extensions()) {
auto devtools_page_url =
extensions::chrome_manifest_urls::GetDevToolsPage(extension.get());
if (devtools_page_url.is_empty())
continue;
// Each devtools extension will need to be able to run in the devtools
// process. Grant the devtools process the ability to request URLs from the
// extension.
content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin(
web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(),
url::Origin::Create(extension->url()));
base::Value::Dict extension_info;
extension_info.Set("startPage", devtools_page_url.spec());
extension_info.Set("name", extension->name());
extension_info.Set("exposeExperimentalAPIs",
extension->permissions_data()->HasAPIPermission(
extensions::mojom::APIPermissionID::kExperimental));
results.Append(base::Value(std::move(extension_info)));
}
CallClientFunction("DevToolsAPI", "addExtensions",
base::Value(std::move(results)));
}
#endif
void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) {
DevToolsContentsResizingStrategy strategy(rect);
if (contents_resizing_strategy_.Equals(strategy))
return;
contents_resizing_strategy_.CopyFrom(strategy);
if (managed_devtools_web_contents_)
view_->SetContentsResizingStrategy(contents_resizing_strategy_);
}
void InspectableWebContents::InspectElementCompleted() {}
void InspectableWebContents::InspectedURLChanged(const std::string& url) {
if (managed_devtools_web_contents_)
view_->SetTitle(
base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str())));
}
void InspectableWebContents::LoadNetworkResource(DispatchCallback callback,
const std::string& url,
const std::string& headers,
int stream_id) {
GURL gurl(url);
if (!gurl.is_valid()) {
base::Value response(base::Value::Type::DICT);
response.GetDict().Set("statusCode", net::HTTP_NOT_FOUND);
std::move(callback).Run(&response);
return;
}
// Create traffic annotation tag.
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"(
semantics {
sender: "Developer Tools"
description:
"When user opens Developer Tools, the browser may fetch additional "
"resources from the network to enrich the debugging experience "
"(e.g. source map resources)."
trigger: "User opens Developer Tools to debug a web page."
data: "Any resources requested by Developer Tools."
destination: WEBSITE
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting:
"It's not possible to disable this feature from settings."
})");
network::ResourceRequest resource_request;
resource_request.url = gurl;
resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl);
resource_request.headers.AddHeadersFromString(headers);
auto* protocol_registry = ProtocolRegistry::FromBrowserContext(
GetDevToolsWebContents()->GetBrowserContext());
NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory;
if (gurl.SchemeIsFile()) {
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
AsarURLLoaderFactory::Create();
url_loader_factory = network::SharedURLLoaderFactory::Create(
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
std::move(pending_remote)));
} else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) {
auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme());
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
ElectronURLLoaderFactory::Create(protocol_handler.first,
protocol_handler.second);
url_loader_factory = network::SharedURLLoaderFactory::Create(
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
std::move(pending_remote)));
} else {
auto* partition = GetDevToolsWebContents()
->GetBrowserContext()
->GetDefaultStoragePartition();
url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess();
}
NetworkResourceLoader::Create(
stream_id, this, resource_request, traffic_annotation,
std::move(url_loader_factory), std::move(callback));
}
void InspectableWebContents::SetIsDocked(DispatchCallback callback,
bool docked) {
if (managed_devtools_web_contents_)
view_->SetIsDocked(docked, activate_);
if (!callback.is_null())
std::move(callback).Run(nullptr);
}
void InspectableWebContents::OpenInNewTab(const std::string& url) {}
void InspectableWebContents::ShowItemInFolder(
const std::string& file_system_path) {
if (file_system_path.empty())
return;
base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
platform_util::OpenPath(path.DirName(),
base::BindOnce(&OnOpenItemComplete, path));
}
void InspectableWebContents::SaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
if (delegate_)
delegate_->DevToolsSaveToFile(url, content, save_as);
}
void InspectableWebContents::AppendToFile(const std::string& url,
const std::string& content) {
if (delegate_)
delegate_->DevToolsAppendToFile(url, content);
}
void InspectableWebContents::RequestFileSystems() {
if (delegate_)
delegate_->DevToolsRequestFileSystems();
}
void InspectableWebContents::AddFileSystem(const std::string& type) {
if (delegate_)
delegate_->DevToolsAddFileSystem(type, base::FilePath());
}
void InspectableWebContents::RemoveFileSystem(
const std::string& file_system_path) {
if (delegate_)
delegate_->DevToolsRemoveFileSystem(
base::FilePath::FromUTF8Unsafe(file_system_path));
}
void InspectableWebContents::UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) {}
void InspectableWebContents::IndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders) {
if (delegate_)
delegate_->DevToolsIndexPath(request_id, file_system_path,
excluded_folders);
}
void InspectableWebContents::StopIndexing(int request_id) {
if (delegate_)
delegate_->DevToolsStopIndexing(request_id);
}
void InspectableWebContents::SearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (delegate_)
delegate_->DevToolsSearchInPath(request_id, file_system_path, query);
}
void InspectableWebContents::SetWhitelistedShortcuts(
const std::string& message) {}
void InspectableWebContents::SetEyeDropperActive(bool active) {
if (delegate_)
delegate_->DevToolsSetEyeDropperActive(active);
}
void InspectableWebContents::ShowCertificateViewer(
const std::string& cert_chain) {}
void InspectableWebContents::ZoomIn() {
double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false);
SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level);
UpdateDevToolsZoomLevel(new_level);
}
void InspectableWebContents::ZoomOut() {
double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true);
SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level);
UpdateDevToolsZoomLevel(new_level);
}
void InspectableWebContents::ResetZoom() {
SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.);
UpdateDevToolsZoomLevel(0.);
}
void InspectableWebContents::SetDevicesDiscoveryConfig(
bool discover_usb_devices,
bool port_forwarding_enabled,
const std::string& port_forwarding_config,
bool network_discovery_enabled,
const std::string& network_discovery_config) {}
void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {}
void InspectableWebContents::PerformActionOnRemotePage(
const std::string& page_id,
const std::string& action) {}
void InspectableWebContents::OpenRemotePage(const std::string& browser_id,
const std::string& url) {}
void InspectableWebContents::OpenNodeFrontend() {}
void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend(
const std::string& message) {
// If the devtools wants to reload the page, hijack the message and handle it
// to the delegate.
if (base::MatchPattern(message,
"{\"id\":*,"
"\"method\":\"Page.reload\","
"\"params\":*}")) {
if (delegate_)
delegate_->DevToolsReloadPage();
return;
}
if (agent_host_)
agent_host_->DispatchProtocolMessage(
this, base::as_bytes(base::make_span(message)));
}
void InspectableWebContents::SendJsonRequest(DispatchCallback callback,
const std::string& browser_id,
const std::string& url) {
std::move(callback).Run(nullptr);
}
void InspectableWebContents::GetPreferences(DispatchCallback callback) {
const base::Value& prefs = pref_service_->GetValue(kDevToolsPreferences);
std::move(callback).Run(&prefs);
}
void InspectableWebContents::GetPreference(DispatchCallback callback,
const std::string& name) {
if (auto* pref = pref_service_->GetDict(kDevToolsPreferences).Find(name)) {
std::move(callback).Run(pref);
return;
}
// Pref wasn't found, return an empty value
base::Value no_pref;
std::move(callback).Run(&no_pref);
}
void InspectableWebContents::SetPreference(const std::string& name,
const std::string& value) {
ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences);
update->Set(name, base::Value(value));
}
void InspectableWebContents::RemovePreference(const std::string& name) {
ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences);
update->Remove(name);
}
void InspectableWebContents::ClearPreferences() {
ScopedDictPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences);
unsynced_update->clear();
}
void InspectableWebContents::GetSyncInformation(DispatchCallback callback) {
base::Value result(base::Value::Type::DICTIONARY);
result.SetBoolKey("isSyncActive", false);
std::move(callback).Run(&result);
}
void InspectableWebContents::ConnectionReady() {}
void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin,
const std::string& script) {
extensions_api_[origin + "/"] = script;
}
void InspectableWebContents::HandleMessageFromDevToolsFrontend(
base::Value::Dict message) {
// TODO(alexeykuzmin): Should we expect it to exist?
if (!embedder_message_dispatcher_) {
return;
}
const std::string* method = message.FindString(kFrontendHostMethod);
base::Value* params = message.Find(kFrontendHostParams);
if (!method || (params && !params->is_list())) {
LOG(ERROR) << "Invalid message was sent to embedder: " << message;
return;
}
const base::Value::List no_params;
const base::Value::List& params_list =
params != nullptr && params->is_list() ? params->GetList() : no_params;
const int id = message.FindInt(kFrontendHostId).value_or(0);
embedder_message_dispatcher_->Dispatch(
base::BindRepeating(&InspectableWebContents::SendMessageAck,
weak_factory_.GetWeakPtr(), id),
*method, params_list);
}
void InspectableWebContents::DispatchProtocolMessage(
content::DevToolsAgentHost* agent_host,
base::span<const uint8_t> message) {
if (!frontend_loaded_)
return;
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()),
message.size());
if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message)));
} else {
size_t total_size = str_message.length();
for (size_t pos = 0; pos < str_message.length();
pos += kMaxMessageChunkSize) {
base::StringPiece str_message_chunk =
str_message.substr(pos, kMaxMessageChunkSize);
CallClientFunction(
"DevToolsAPI", "dispatchMessageChunk",
base::Value(std::string(str_message_chunk)),
base::Value(base::NumberToString(pos ? 0 : total_size)));
}
}
}
void InspectableWebContents::AgentHostClosed(
content::DevToolsAgentHost* agent_host) {}
void InspectableWebContents::RenderFrameHostChanged(
content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->GetParent())
return;
frontend_host_ = content::DevToolsFrontendHost::Create(
new_host, base::BindRepeating(
&InspectableWebContents::HandleMessageFromDevToolsFrontend,
weak_factory_.GetWeakPtr()));
}
void InspectableWebContents::WebContentsDestroyed() {
if (managed_devtools_web_contents_)
managed_devtools_web_contents_->SetDelegate(nullptr);
frontend_loaded_ = false;
external_devtools_web_contents_ = nullptr;
Observe(nullptr);
Detach();
embedder_message_dispatcher_.reset();
if (view_ && view_->GetDelegate())
view_->GetDelegate()->DevToolsClosed();
}
bool InspectableWebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
auto* delegate = web_contents_->GetDelegate();
return !delegate || delegate->HandleKeyboardEvent(source, event);
}
void InspectableWebContents::CloseContents(content::WebContents* source) {
// This is where the devtools closes itself (by clicking the x button).
CloseDevTools();
}
void InspectableWebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
auto* delegate = web_contents_->GetDelegate();
if (delegate)
delegate->RunFileChooser(render_frame_host, std::move(listener), params);
}
void InspectableWebContents::EnumerateDirectory(
content::WebContents* source,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
auto* delegate = web_contents_->GetDelegate();
if (delegate)
delegate->EnumerateDirectory(source, std::move(listener), path);
}
void InspectableWebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
#if defined(TOOLKIT_VIEWS)
if (view_->GetDelegate())
view_->GetDelegate()->DevToolsFocused();
#endif
}
void InspectableWebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsInMainFrame()) {
if (navigation_handle->GetRenderFrameHost() ==
GetDevToolsWebContents()->GetPrimaryMainFrame() &&
frontend_host_) {
return;
}
frontend_host_ = content::DevToolsFrontendHost::Create(
web_contents()->GetPrimaryMainFrame(),
base::BindRepeating(
&InspectableWebContents::HandleMessageFromDevToolsFrontend,
base::Unretained(this)));
return;
}
}
void InspectableWebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsInMainFrame() ||
!navigation_handle->GetURL().SchemeIs("chrome-extension") ||
!navigation_handle->HasCommitted())
return;
content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost();
auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec();
auto it = extensions_api_.find(origin);
if (it == extensions_api_.end())
return;
// Injected Script from devtools frontend doesn't expose chrome,
// most likely bug in chromium.
base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome",
"var chrome = window.chrome ");
auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(),
base::GenerateGUID().c_str());
// Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script);
// should be enough, but it seems to be a noop currently.
frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script),
base::NullCallback());
}
void InspectableWebContents::SendMessageAck(int request_id,
const base::Value* arg) {
if (arg) {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id), arg->Clone());
} else {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id));
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/ui/inspectable_web_contents_delegate.h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
#define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
#include <string>
#include "base/files/file_path.h"
namespace electron {
class InspectableWebContentsDelegate {
public:
virtual ~InspectableWebContentsDelegate() {}
// Requested by WebContents of devtools.
virtual void DevToolsReloadPage() {}
virtual void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {}
virtual void DevToolsAppendToFile(const std::string& url,
const std::string& content) {}
virtual void DevToolsRequestFileSystems() {}
virtual void DevToolsAddFileSystem(const std::string& type,
const base::FilePath& file_system_path) {}
virtual void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {}
virtual void DevToolsIndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders) {}
virtual void DevToolsStopIndexing(int request_id) {}
virtual void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {}
virtual void DevToolsSetEyeDropperActive(bool active) {}
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
docs/api/web-contents.md
|
# webContents
> Render and control web pages.
Process: [Main](../glossary.md#main-process)
`webContents` is an [EventEmitter][event-emitter].
It is responsible for rendering and controlling a web page and is a property of
the [`BrowserWindow`](browser-window.md) object. An example of accessing the
`webContents` object:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('http://github.com')
const contents = win.webContents
console.log(contents)
```
## Methods
These methods can be accessed from the `webContents` module:
```javascript
const { webContents } = require('electron')
console.log(webContents)
```
### `webContents.getAllWebContents()`
Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents
for all windows, webviews, opened devtools, and devtools extension background pages.
### `webContents.getFocusedWebContents()`
Returns `WebContents` | null - The web contents that is focused in this application, otherwise
returns `null`.
### `webContents.fromId(id)`
* `id` Integer
Returns `WebContents` | undefined - A WebContents instance with the given ID, or
`undefined` if there is no WebContents associated with the given ID.
### `webContents.fromFrame(frame)`
* `frame` WebFrameMain
Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or
`undefined` if there is no WebContents associated with the given WebFrameMain.
### `webContents.fromDevToolsTargetId(targetId)`
* `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance.
Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or
`undefined` if there is no WebContents associated with the given TargetID.
When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/),
it can be useful to lookup a WebContents instance based on its assigned TargetID.
```js
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await webContents.fromDevToolsTargetId(targetId)
}
```
## Class: WebContents
> Render and control the contents of a BrowserWindow instance.
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
### Instance Events
#### Event: 'did-finish-load'
Emitted when the navigation is done, i.e. the spinner of the tab has stopped
spinning, and the `onload` event was dispatched.
#### Event: 'did-fail-load'
Returns:
* `event` Event
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
This event is like `did-finish-load` but emitted when the load failed.
The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
#### Event: 'did-fail-provisional-load'
Returns:
* `event` Event
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
This event is like `did-fail-load` but emitted when the load was cancelled
(e.g. `window.stop()` was invoked).
#### Event: 'did-frame-finish-load'
Returns:
* `event` Event
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when a frame has done navigation.
#### Event: 'did-start-loading'
Corresponds to the points in time when the spinner of the tab started spinning.
#### Event: 'did-stop-loading'
Corresponds to the points in time when the spinner of the tab stopped spinning.
#### Event: 'dom-ready'
Emitted when the document in the top-level frame is loaded.
#### Event: 'page-title-updated'
Returns:
* `event` Event
* `title` string
* `explicitSet` boolean
Fired when page title is set during navigation. `explicitSet` is false when
title is synthesized from file url.
#### Event: 'page-favicon-updated'
Returns:
* `event` Event
* `favicons` string[] - Array of URLs.
Emitted when page receives favicon urls.
#### Event: 'content-bounds-updated'
Returns:
* `event` Event
* `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds
Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs.
By default, this will move the window. To prevent that behavior, call
`event.preventDefault()`.
#### Event: 'did-create-window'
Returns:
* `window` BrowserWindow
* `details` Object
* `url` string - URL for the created window.
* `frameName` string - Name given to the created window in the
`window.open()` call.
* `options` BrowserWindowConstructorOptions - The options used to create the
BrowserWindow. They are merged in increasing precedence: parsed options
from the `features` string from `window.open()`, security-related
webPreferences inherited from the parent, and options given by
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
Unrecognized options are not filtered out.
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
passed to the new window. May or may not result in the `Referer` header
being sent, depending on the referrer policy.
* `postBody` [PostBody](structures/post-body.md) (optional) - The post data
that will be sent to the new window, along with the appropriate headers
that will be set. If no post data is to be sent, the value will be `null`.
Only defined when the window is being created by a form that set
`target=_blank`.
* `disposition` string - Can be `default`, `foreground-tab`,
`background-tab`, `new-window`, `save-to-disk` and `other`.
Emitted _after_ successful creation of a window via `window.open` in the renderer.
Not emitted if the creation of the window is canceled from
[`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler).
See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`.
#### Event: 'will-navigate'
Returns:
* `event` Event
* `url` string
Emitted when a user or the page wants to start navigation. It can happen when
the `window.location` object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with
APIs like `webContents.loadURL` and `webContents.back`.
It is also not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
Calling `event.preventDefault()` will prevent the navigation.
#### Event: 'did-start-navigation'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame (including main) starts navigating. `isInPlace` will be
`true` for in-page navigations.
#### Event: 'will-redirect'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when a server side redirect occurs during navigation. For example a 302
redirect.
This event will be emitted after `did-start-navigation` and always before the
`did-redirect-navigation` event for the same navigation.
Calling `event.preventDefault()` will prevent the navigation (not just the
redirect).
#### Event: 'did-redirect-navigation'
Returns:
* `event` Event
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted after a server side redirect occurs during navigation. For example a 302
redirect.
This event cannot be prevented, if you want to prevent redirects you should
checkout out the `will-redirect` event above.
#### Event: 'did-navigate'
Returns:
* `event` Event
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations
Emitted when a main frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
#### Event: 'did-frame-navigate'
Returns:
* `event` Event
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations,
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
#### Event: 'did-navigate-in-page'
Returns:
* `event` Event
* `url` string
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when an in-page navigation happened in any frame.
When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM `hashchange` event is triggered.
#### Event: 'will-prevent-unload'
Returns:
* `event` Event
Emitted when a `beforeunload` event handler is attempting to cancel a page unload.
Calling `event.preventDefault()` will ignore the `beforeunload` event handler
and allow the page to be unloaded.
```javascript
const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBoxSync(win, {
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
const leave = (choice === 0)
if (leave) {
event.preventDefault()
}
})
```
**Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
#### Event: 'crashed' _Deprecated_
Returns:
* `event` Event
* `killed` boolean
Emitted when the renderer process crashes or is killed.
**Deprecated:** This event is superceded by the `render-process-gone` event
which contains more information about why the render process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
#### Event: 'render-process-gone'
Returns:
* `event` Event
* `details` Object
* `reason` string - The reason the render process is gone. Possible values:
* `clean-exit` - Process exited with an exit code of zero
* `abnormal-exit` - Process exited with a non-zero exit code
* `killed` - Process was sent a SIGTERM or otherwise killed externally
* `crashed` - Process crashed
* `oom` - Process ran out of memory
* `launch-failed` - Process never successfully launched
* `integrity-failure` - Windows code integrity checks failed
* `exitCode` Integer - The exit code of the process, unless `reason` is
`launch-failed`, in which case `exitCode` will be a platform-specific
launch failure error code.
Emitted when the renderer process unexpectedly disappears. This is normally
because it was crashed or killed.
#### Event: 'unresponsive'
Emitted when the web page becomes unresponsive.
#### Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
#### Event: 'plugin-crashed'
Returns:
* `event` Event
* `name` string
* `version` string
Emitted when a plugin process has crashed.
#### Event: 'destroyed'
Emitted when `webContents` is destroyed.
#### Event: 'input-event'
Returns:
* `event` Event
* `inputEvent` [InputEvent](structures/input-event.md)
Emitted when an input event is sent to the WebContents. See
[InputEvent](structures/input-event.md) for details.
#### Event: 'before-input-event'
Returns:
* `event` Event
* `input` Object - Input properties.
* `type` string - Either `keyUp` or `keyDown`.
* `key` string - Equivalent to [KeyboardEvent.key][keyboardevent].
* `code` string - Equivalent to [KeyboardEvent.code][keyboardevent].
* `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent].
* `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent].
* `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent].
* `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent].
* `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent].
* `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent].
* `location` number - Equivalent to [KeyboardEvent.location][keyboardevent].
* `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md).
Emitted before dispatching the `keydown` and `keyup` events in the page.
Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events
and the menu shortcuts.
To only prevent the menu shortcuts, use
[`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore):
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when
// Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
```
#### Event: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
#### Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
#### Event: 'zoom-changed'
Returns:
* `event` Event
* `zoomDirection` string - Can be `in` or `out`.
Emitted when the user is requesting to change the zoom level using the mouse wheel.
#### Event: 'blur'
Emitted when the `WebContents` loses focus.
#### Event: 'focus'
Emitted when the `WebContents` gains focus.
Note that on macOS, having focus means the `WebContents` is the first responder
of window, so switching focus between windows would not trigger the `focus` and
`blur` events of `WebContents`, as the first responder of each window is not
changed.
The `focus` and `blur` events of `WebContents` should only be used to detect
focus change between different `WebContents` and `BrowserView` in the same
window.
#### Event: 'devtools-opened'
Emitted when DevTools is opened.
#### Event: 'devtools-closed'
Emitted when DevTools is closed.
#### Event: 'devtools-focused'
Emitted when DevTools is focused / opened.
#### Event: 'certificate-error'
Returns:
* `event` Event
* `url` string
* `error` string - The error code.
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` boolean - Indicates whether the certificate can be considered trusted.
* `isMainFrame` boolean
Emitted when failed to verify the `certificate` for `url`.
The usage is the same with [the `certificate-error` event of
`app`](app.md#event-certificate-error).
#### Event: 'select-client-certificate'
Returns:
* `event` Event
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list.
Emitted when a client certificate is requested.
The usage is the same with [the `select-client-certificate` event of
`app`](app.md#event-select-client-certificate).
#### Event: 'login'
Returns:
* `event` Event
* `authenticationResponseDetails` Object
* `url` URL
* `authInfo` Object
* `isProxy` boolean
* `scheme` string
* `host` string
* `port` Integer
* `realm` string
* `callback` Function
* `username` string (optional)
* `password` string (optional)
Emitted when `webContents` wants to do basic auth.
The usage is the same with [the `login` event of `app`](app.md#event-login).
#### Event: 'found-in-page'
Returns:
* `event` Event
* `result` Object
* `requestId` Integer
* `activeMatchOrdinal` Integer - Position of the active match.
* `matches` Integer - Number of Matches.
* `selectionArea` Rectangle - Coordinates of first match region.
* `finalUpdate` boolean
Emitted when a result is available for
[`webContents.findInPage`](#contentsfindinpagetext-options) request.
#### Event: 'media-started-playing'
Emitted when media starts playing.
#### Event: 'media-paused'
Emitted when media is paused or done playing.
#### Event: 'did-change-theme-color'
Returns:
* `event` Event
* `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set.
Emitted when a page's theme color changes. This is usually due to encountering
a meta tag:
```html
<meta name='theme-color' content='#ff0000'>
```
#### Event: 'update-target-url'
Returns:
* `event` Event
* `url` string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
#### Event: 'cursor-changed'
Returns:
* `event` Event
* `type` string
* `image` [NativeImage](native-image.md) (optional)
* `scale` Float (optional) - scaling factor for the custom cursor.
* `size` [Size](structures/size.md) (optional) - the size of the `image`.
* `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot.
Emitted when the cursor's type changes. The `type` parameter can be `default`,
`crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`,
`ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`,
`ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`,
`row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`,
`s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`,
`cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`,
`not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`.
If the `type` parameter is `custom`, the `image` parameter will hold the custom
cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold
additional information about the custom cursor.
#### Event: 'context-menu'
Returns:
* `event` Event
* `params` Object
* `x` Integer - x coordinate.
* `y` Integer - y coordinate.
* `frame` WebFrameMain - Frame from which the context menu was invoked.
* `linkURL` string - URL of the link that encloses the node the context menu
was invoked on.
* `linkText` string - Text associated with the link. May be an empty
string if the contents of the link are an image.
* `pageURL` string - URL of the top level page that the context menu was
invoked on.
* `frameURL` string - URL of the subframe that the context menu was invoked
on.
* `srcURL` string - Source URL for the element that the context menu
was invoked on. Elements with source URLs are images, audio and video.
* `mediaType` string - Type of the node the context menu was invoked on. Can
be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`.
* `hasImageContents` boolean - Whether the context menu was invoked on an image
which has non-empty contents.
* `isEditable` boolean - Whether the context is editable.
* `selectionText` string - Text of the selection that the context menu was
invoked on.
* `titleText` string - Title text of the selection that the context menu was
invoked on.
* `altText` string - Alt text of the selection that the context menu was
invoked on.
* `suggestedFilename` string - Suggested filename to be used when saving file through 'Save
Link As' option of context menu.
* `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection.
* `selectionStartOffset` number - Start position of the selection text.
* `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked.
* `misspelledWord` string - The misspelled word under the cursor, if any.
* `dictionarySuggestions` string[] - An array of suggested words to show the
user to replace the `misspelledWord`. Only available if there is a misspelled
word and spellchecker is enabled.
* `frameCharset` string - The character encoding of the frame on which the
menu was invoked.
* `inputFieldType` string - If the context menu was invoked on an input
field, the type of that field. Possible values are `none`, `plainText`,
`password`, `other`.
* `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled.
* `menuSourceType` string - Input source that invoked the context menu.
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
* `mediaFlags` Object - The flags for the media element the context menu was
invoked on.
* `inError` boolean - Whether the media element has crashed.
* `isPaused` boolean - Whether the media element is paused.
* `isMuted` boolean - Whether the media element is muted.
* `hasAudio` boolean - Whether the media element has audio.
* `isLooping` boolean - Whether the media element is looping.
* `isControlsVisible` boolean - Whether the media element's controls are
visible.
* `canToggleControls` boolean - Whether the media element's controls are
toggleable.
* `canPrint` boolean - Whether the media element can be printed.
* `canSave` boolean - Whether or not the media element can be downloaded.
* `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture.
* `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture.
* `canRotate` boolean - Whether the media element can be rotated.
* `canLoop` boolean - Whether the media element can be looped.
* `editFlags` Object - These flags indicate whether the renderer believes it
is able to perform the corresponding action.
* `canUndo` boolean - Whether the renderer believes it can undo.
* `canRedo` boolean - Whether the renderer believes it can redo.
* `canCut` boolean - Whether the renderer believes it can cut.
* `canCopy` boolean - Whether the renderer believes it can copy.
* `canPaste` boolean - Whether the renderer believes it can paste.
* `canDelete` boolean - Whether the renderer believes it can delete.
* `canSelectAll` boolean - Whether the renderer believes it can select all.
* `canEditRichly` boolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
#### Event: 'select-bluetooth-device'
Returns:
* `event` Event
* `devices` [BluetoothDevice[]](structures/bluetooth-device.md)
* `callback` Function
* `deviceId` string
Emitted when bluetooth device needs to be selected on call to
`navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api
`webBluetooth` should be enabled. If `event.preventDefault` is not called,
first available device will be selected. `callback` should be called with
`deviceId` to be selected, passing empty string to `callback` will
cancel the request.
If no event listener is added for this event, all bluetooth requests will be cancelled.
```javascript
const { app, BrowserWindow } = require('electron')
let win = null
app.commandLine.appendSwitch('enable-experimental-web-platform-features')
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
const result = deviceList.find((device) => {
return device.deviceName === 'test'
})
if (!result) {
callback('')
} else {
callback(result.deviceId)
}
})
})
```
#### Event: 'paint'
Returns:
* `event` Event
* `dirtyRect` [Rectangle](structures/rectangle.md)
* `image` [NativeImage](native-image.md) - The image data of the whole frame.
Emitted when a new frame is generated. Only the dirty area is passed in the
buffer.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('http://github.com')
```
#### Event: 'devtools-reload-page'
Emitted when the devtools window instructs the webContents to reload
#### Event: 'will-attach-webview'
Returns:
* `event` Event
* `webPreferences` WebPreferences - The web preferences that will be used by the guest
page. This object can be modified to adjust the preferences for the guest
page.
* `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL.
This object can be modified to adjust the parameters of the guest page.
Emitted when a `<webview>`'s web contents is being attached to this web
contents. Calling `event.preventDefault()` will destroy the guest page.
This event can be used to configure `webPreferences` for the `webContents`
of a `<webview>` before it's loaded, and provides the ability to set settings
that can't be set via `<webview>` attributes.
#### Event: 'did-attach-webview'
Returns:
* `event` Event
* `webContents` WebContents - The guest web contents that is used by the
`<webview>`.
Emitted when a `<webview>` has been attached to this web contents.
#### Event: 'console-message'
Returns:
* `event` Event
* `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
* `message` string - The actual console message
* `line` Integer - The line number of the source that triggered this console message
* `sourceId` string
Emitted when the associated window logs a console message.
#### Event: 'preload-error'
Returns:
* `event` Event
* `preloadPath` string
* `error` Error
Emitted when the preload script `preloadPath` throws an unhandled exception `error`.
#### Event: 'ipc-message'
Returns:
* `event` Event
* `channel` string
* `...args` any[]
Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`.
See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents.
#### Event: 'ipc-message-sync'
Returns:
* `event` Event
* `channel` string
* `...args` any[]
Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`.
See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents.
#### Event: 'preferred-size-changed'
Returns:
* `event` Event
* `preferredSize` [Size](structures/size.md) - The minimum size needed to
contain the layout of the document—without requiring scrolling.
Emitted when the `WebContents` preferred size has changed.
This event will only be emitted when `enablePreferredSizeMode` is set to `true`
in `webPreferences`.
#### Event: 'frame-created'
Returns:
* `event` Event
* `details` Object
* `frame` WebFrameMain
Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page.
### Instance Methods
#### `contents.loadURL(url[, options])`
* `url` string
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n".
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see
[`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the `url` in the window. The `url` must contain the protocol prefix,
e.g. the `http://` or `file://`. If the load should bypass http cache then
use the `pragma` header to achieve it.
```javascript
const { webContents } = require('electron')
const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options)
```
#### `contents.loadFile(filePath[, options])`
* `filePath` string
* `options` Object (optional)
* `query` Record<string, string> (optional) - Passed to `url.format()`.
* `search` string (optional) - Passed to `url.format()`.
* `hash` string (optional) - Passed to `url.format()`.
Returns `Promise<void>` - the promise will resolve when the page has finished loading
(see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects
if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)).
Loads the given file in the window, `filePath` should be a path to
an HTML file relative to the root of your application. For instance
an app structure like this:
```sh
| root
| - package.json
| - src
| - main.js
| - index.html
```
Would require code like this
```js
win.loadFile('src/index.html')
```
#### `contents.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url` without navigating. The
`will-download` event of `session` will be triggered.
#### `contents.getURL()`
Returns `string` - The URL of the current web page.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})
```
#### `contents.getTitle()`
Returns `string` - The title of the current web page.
#### `contents.isDestroyed()`
Returns `boolean` - Whether the web page is destroyed.
#### `contents.close([opts])`
* `opts` Object (optional)
* `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event
before closing the page. If the page prevents the unload, the WebContents
will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload)
will be fired if the page requests prevention of unload.
Closes the page, as if the web content had called `window.close()`.
If the page is successfully closed (i.e. the unload is not prevented by the
page, or `waitForBeforeUnload` is false or unspecified), the WebContents will
be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event
will be emitted.
#### `contents.focus()`
Focuses the web page.
#### `contents.isFocused()`
Returns `boolean` - Whether the web page is focused.
#### `contents.isLoading()`
Returns `boolean` - Whether web page is still loading resources.
#### `contents.isLoadingMainFrame()`
Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is
still loading.
#### `contents.isWaitingForResponse()`
Returns `boolean` - Whether the web page is waiting for a first-response from the main
resource of the page.
#### `contents.stop()`
Stops any pending navigation.
#### `contents.reload()`
Reloads the current web page.
#### `contents.reloadIgnoringCache()`
Reloads current page and ignores cache.
#### `contents.canGoBack()`
Returns `boolean` - Whether the browser can go back to previous web page.
#### `contents.canGoForward()`
Returns `boolean` - Whether the browser can go forward to next web page.
#### `contents.canGoToOffset(offset)`
* `offset` Integer
Returns `boolean` - Whether the web page can go to `offset`.
#### `contents.clearHistory()`
Clears the navigation history.
#### `contents.goBack()`
Makes the browser go back a web page.
#### `contents.goForward()`
Makes the browser go forward a web page.
#### `contents.goToIndex(index)`
* `index` Integer
Navigates browser to the specified absolute web page index.
#### `contents.goToOffset(offset)`
* `offset` Integer
Navigates to the specified offset from the "current entry".
#### `contents.isCrashed()`
Returns `boolean` - Whether the renderer process has crashed.
#### `contents.forcefullyCrashRenderer()`
Forcefully terminates the renderer process that is currently hosting this
`webContents`. This will cause the `render-process-gone` event to be emitted
with the `reason=killed || reason=crashed`. Please note that some webContents share renderer
processes and therefore calling this method may also crash the host process
for other webContents as well.
Calling `reload()` immediately after calling this
method will force the reload to occur in a new process. This should be used
when this process is unstable or unusable, for instance in order to recover
from the `unresponsive` event.
```js
contents.on('unresponsive', async () => {
const { response } = await dialog.showMessageBox({
message: 'App X has become unresponsive',
title: 'Do you want to try forcefully reloading the app?',
buttons: ['OK', 'Cancel'],
cancelId: 1
})
if (response === 0) {
contents.forcefullyCrashRenderer()
contents.reload()
}
})
```
#### `contents.setUserAgent(userAgent)`
* `userAgent` string
Overrides the user agent for this web page.
#### `contents.getUserAgent()`
Returns `string` - The user agent for this web page.
#### `contents.insertCSS(css[, options])`
* `css` string
* `options` Object (optional)
* `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'.
Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`.
Injects CSS into the current web page and returns a unique key for the inserted
stylesheet.
```js
contents.on('did-finish-load', () => {
contents.insertCSS('html, body { background-color: #f00; }')
})
```
#### `contents.removeInsertedCSS(key)`
* `key` string
Returns `Promise<void>` - Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from `contents.insertCSS(css)`.
```js
contents.on('did-finish-load', async () => {
const key = await contents.insertCSS('html, body { background-color: #f00; }')
contents.removeInsertedCSS(key)
})
```
#### `contents.executeJavaScript(code[, userGesture])`
* `code` string
* `userGesture` boolean (optional) - Default is `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page.
In the browser window some HTML APIs like `requestFullScreen` can only be
invoked by a gesture from the user. Setting `userGesture` to `true` will remove
this limitation.
Code execution will be suspended until web page stop loading.
```js
contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})
```
#### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])`
* `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here.
* `scripts` [WebSource[]](structures/web-source.md)
* `userGesture` boolean (optional) - Default is `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Works like `executeJavaScript` but evaluates `scripts` in an isolated context.
#### `contents.setIgnoreMenuShortcuts(ignore)`
* `ignore` boolean
Ignore application menu shortcuts while this web contents is focused.
#### `contents.setWindowOpenHandler(handler)`
* `handler` Function<{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}>
* `details` Object
* `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`.
* `frameName` string - Name of the window provided in `window.open()`
* `features` string - Comma separated list of window features provided to `window.open()`.
* `disposition` string - Can be `default`, `foreground-tab`, `background-tab`,
`new-window`, `save-to-disk` or `other`.
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
passed to the new window. May or may not result in the `Referer` header being
sent, depending on the referrer policy.
* `postBody` [PostBody](structures/post-body.md) (optional) - The post data that
will be sent to the new window, along with the appropriate headers that will
be set. If no post data is to be sent, the value will be `null`. Only defined
when the window is being created by a form that set `target=_blank`.
Returns `{action: 'deny'} | {action: 'allow', outlivesOpener?: boolean, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new
window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window.
By default, child windows are closed when their opener is closed. This can be
changed by specifying `outlivesOpener: true`, in which case the opened window
will not be closed when its opener is closed.
Returning an unrecognized value such as a null, undefined, or an object
without a recognized 'action' value will result in a console error and have
the same effect as returning `{action: 'deny'}`.
Called before creating a window a new window is requested by the renderer, e.g.
by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or
submitting a form with `<form target="_blank">`. See
[`window.open()`](window-open.md) for more details and how to use this in
conjunction with `did-create-window`.
#### `contents.setAudioMuted(muted)`
* `muted` boolean
Mute the audio on the current web page.
#### `contents.isAudioMuted()`
Returns `boolean` - Whether this page has been muted.
#### `contents.isCurrentlyAudible()`
Returns `boolean` - Whether audio is currently playing.
#### `contents.setZoomFactor(factor)`
* `factor` Double - Zoom factor; default is 1.0.
Changes the zoom factor to the specified factor. Zoom factor is
zoom percent divided by 100, so 300% = 3.0.
The factor must be greater than 0.0.
#### `contents.getZoomFactor()`
Returns `number` - the current zoom factor.
#### `contents.setZoomLevel(level)`
* `level` number - Zoom level.
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
`scale := 1.2 ^ level`.
> **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the
> zoom level for a specific domain propagates across all instances of windows with
> the same domain. Differentiating the window URLs will make zoom work per-window.
#### `contents.getZoomLevel()`
Returns `number` - the current zoom level.
#### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` number
* `maximumLevel` number
Returns `Promise<void>`
Sets the maximum and minimum pinch-to-zoom level.
> **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call:
>
> ```js
> contents.setVisualZoomLevelLimits(1, 3)
> ```
#### `contents.undo()`
Executes the editing command `undo` in web page.
#### `contents.redo()`
Executes the editing command `redo` in web page.
#### `contents.cut()`
Executes the editing command `cut` in web page.
#### `contents.copy()`
Executes the editing command `copy` in web page.
#### `contents.copyImageAt(x, y)`
* `x` Integer
* `y` Integer
Copy the image at the given position to the clipboard.
#### `contents.paste()`
Executes the editing command `paste` in web page.
#### `contents.pasteAndMatchStyle()`
Executes the editing command `pasteAndMatchStyle` in web page.
#### `contents.delete()`
Executes the editing command `delete` in web page.
#### `contents.selectAll()`
Executes the editing command `selectAll` in web page.
#### `contents.unselect()`
Executes the editing command `unselect` in web page.
#### `contents.replace(text)`
* `text` string
Executes the editing command `replace` in web page.
#### `contents.replaceMisspelling(text)`
* `text` string
Executes the editing command `replaceMisspelling` in web page.
#### `contents.insertText(text)`
* `text` string
Returns `Promise<void>`
Inserts `text` to the focused element.
#### `contents.findInPage(text[, options])`
* `text` string - Content to be searched, must not be empty.
* `options` Object (optional)
* `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`.
* `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
* `matchCase` boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
Returns `Integer` - The request id used for the request.
Starts a request to find all matches for the `text` in the web page. The result of the request
can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event.
#### `contents.stopFindInPage(action)`
* `action` string - Specifies the action to take place when ending
[`webContents.findInPage`](#contentsfindinpagetext-options) request.
* `clearSelection` - Clear the selection.
* `keepSelection` - Translate the selection into a normal selection.
* `activateSelection` - Focus and click the selection node.
Stops any `findInPage` request for the `webContents` with the provided `action`.
```javascript
const { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)
```
#### `contents.capturePage([rect, opts])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.
* `opts` Object (optional)
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page.
The page is considered visible when its browser window is hidden and the capturer count is non-zero.
If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
#### `contents.isBeingCaptured()`
Returns `boolean` - Whether this page is being captured. It returns true when the capturer count
is large then 0.
#### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` _Deprecated_
* `size` [Size](structures/size.md) (optional) - The preferred size for the capturer.
* `stayHidden` boolean (optional) - Keep the page hidden instead of visible.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
Increase the capturer count by one. The page is considered visible when its browser window is
hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true.
This also affects the Page Visibility API.
**Deprecated:** This API's functionality is now handled automatically within `contents.capturePage()`. See [breaking changes](../breaking-changes.md).
#### `contents.decrementCapturerCount([stayHidden, stayAwake])` _Deprecated_
* `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible.
* `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep.
Decrease the capturer count by one. The page will be set to hidden or occluded state when its
browser window is hidden or occluded and the capturer count reaches zero. If you want to
decrease the hidden capturer count instead you should set `stayHidden` to true.
**Deprecated:** This API's functionality is now handled automatically within `contents.capturePage()`.
See [breaking changes](../breaking-changes.md).
#### `contents.getPrinters()` _Deprecated_
Get the system printer list.
Returns [`PrinterInfo[]`](structures/printer-info.md)
**Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API.
#### `contents.getPrintersAsync()`
Get the system printer list.
Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md)
#### `contents.print([options], [callback])`
* `options` Object (optional)
* `silent` boolean (optional) - Don't ask user for print settings. Default is `false`.
* `printBackground` boolean (optional) - Prints the background color and image of
the web page. Default is `false`.
* `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.
* `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`.
* `margins` Object (optional)
* `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`.
* `top` number (optional) - The top margin of the printed web page, in pixels.
* `bottom` number (optional) - The bottom margin of the printed web page, in pixels.
* `left` number (optional) - The left margin of the printed web page, in pixels.
* `right` number (optional) - The right margin of the printed web page, in pixels.
* `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`.
* `scaleFactor` number (optional) - The scale factor of the web page.
* `pagesPerSheet` number (optional) - The number of pages to print per page sheet.
* `collate` boolean (optional) - Whether the web page should be collated.
* `copies` number (optional) - The number of copies of the web page to print.
* `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored.
* `from` number - Index of the first page to print (0-based).
* `to` number - Index of the last page to print (inclusive) (0-based).
* `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`.
* `dpi` Record<string, number> (optional)
* `horizontal` number (optional) - The horizontal dpi.
* `vertical` number (optional) - The vertical dpi.
* `header` string (optional) - string to be printed as page header.
* `footer` string (optional) - string to be printed as page footer.
* `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`.
* `callback` Function (optional)
* `success` boolean - Indicates success of the print call.
* `failureReason` string - Error description called back if the print fails.
When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems.
Prints window's web page. When `silent` is set to `true`, Electron will pick
the system's default printer if `deviceName` is empty and the default settings for printing.
Use `page-break-before: always;` CSS style to force to print to a new page.
Example usage:
```js
const options = {
silent: true,
deviceName: 'My-Printer',
pageRanges: [{
from: 0,
to: 1
}]
}
win.webContents.print(options, (success, errorType) => {
if (!success) console.log(errorType)
})
```
#### `contents.printToPDF(options)`
* `options` Object
* `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false.
* `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false.
* `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false.
* `scale` number(optional) - Scale of the webpage rendering. Defaults to 1.
* `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`,
`A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`.
* `margins` Object (optional)
* `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
* `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
* `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
* `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
* `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
* `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title.
* `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`.
* `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
Returns `Promise<Buffer>` - Resolves with the generated PDF data.
Prints the window's web page as PDF.
The `landscape` will be ignored if `@page` CSS at-rule is used in the web page.
An example of `webContents.printToPDF`:
```javascript
const { BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')
const win = new BrowserWindow()
win.loadURL('http://github.com')
win.webContents.on('did-finish-load', () => {
// Use default printing options
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
win.webContents.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
```
See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information.
#### `contents.addWorkSpace(path)`
* `path` string
Adds the specified path to DevTools workspace. Must be used after DevTools
creation:
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
```
#### `contents.removeWorkSpace(path)`
* `path` string
Removes the specified path from DevTools workspace.
#### `contents.setDevToolsWebContents(devToolsWebContents)`
* `devToolsWebContents` WebContents
Uses the `devToolsWebContents` as the target `WebContents` to show devtools.
The `devToolsWebContents` must not have done any navigation, and it should not
be used for other purposes after the call.
By default Electron manages the devtools by creating an internal `WebContents`
with native view, which developers have very limited control of. With the
`setDevToolsWebContents` method, developers can use any `WebContents` to show
the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>`
tag.
Note that closing the devtools does not destroy the `devToolsWebContents`, it
is caller's responsibility to destroy `devToolsWebContents`.
An example of showing devtools in a `<webview>` tag:
```html
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools" src="about:blank"></webview>
<script>
const { ipcRenderer } = require('electron')
const emittedOnce = (element, eventName) => new Promise(resolve => {
element.addEventListener(eventName, event => resolve(event), { once: true })
})
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
const browserReady = emittedOnce(browserView, 'dom-ready')
const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(() => {
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
```
```js
// Main process
const { ipcMain, webContents } = require('electron')
ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})
```
An example of showing devtools in a `BrowserWindow`:
```js
const { app, BrowserWindow } = require('electron')
let win = null
let devtools = null
app.whenReady().then(() => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({ mode: 'detach' })
})
```
#### `contents.openDevTools([options])`
* `options` Object (optional)
* `mode` string - Opens the devtools with specified dock state, can be
`left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state.
In `undocked` mode it's possible to dock back. In `detach` mode it's not.
* `activate` boolean (optional) - Whether to bring the opened devtools window
to the foreground. The default is `true`.
Opens the devtools.
When `contents` is a `<webview>` tag, the `mode` would be `detach` by default,
explicitly passing an empty `mode` can force using last used dock state.
On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`.
#### `contents.closeDevTools()`
Closes the devtools.
#### `contents.isDevToolsOpened()`
Returns `boolean` - Whether the devtools is opened.
#### `contents.isDevToolsFocused()`
Returns `boolean` - Whether the devtools view is focused .
#### `contents.toggleDevTools()`
Toggles the developer tools.
#### `contents.inspectElement(x, y)`
* `x` Integer
* `y` Integer
Starts inspecting element at position (`x`, `y`).
#### `contents.inspectSharedWorker()`
Opens the developer tools for the shared worker context.
#### `contents.inspectSharedWorkerById(workerId)`
* `workerId` string
Inspects the shared worker based on its ID.
#### `contents.getAllSharedWorkers()`
Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers.
#### `contents.inspectServiceWorker()`
Opens the developer tools for the service worker context.
#### `contents.send(channel, ...args)`
* `channel` string
* `...args` any[]
Send an asynchronous message to the renderer process via `channel`, along with
arguments. Arguments will be serialized with the [Structured Clone
Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
throw an exception.
> **NOTE**: Sending non-standard JavaScript types such as DOM objects or
> special Electron objects will throw an exception.
The renderer process can handle the message by listening to `channel` with the
[`ipcRenderer`](ipc-renderer.md) module.
An example of sending messages from the main process to the renderer process:
```javascript
// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
```
```html
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>
```
#### `contents.sendToFrame(frameId, channel, ...args)`
* `frameId` Integer | \[number, number] - the ID of the frame to send to, or a
pair of `[processId, frameId]` if the frame is in a different process to the
main frame.
* `channel` string
* `...args` any[]
Send an asynchronous message to a specific frame in a renderer process via
`channel`, along with arguments. Arguments will be serialized with the
[Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype
chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or
WeakSets will throw an exception.
> **NOTE:** Sending non-standard JavaScript types such as DOM objects or
> special Electron objects will throw an exception.
The renderer process can handle the message by listening to `channel` with the
[`ipcRenderer`](ipc-renderer.md) module.
If you want to get the `frameId` of a given renderer context you should use
the `webFrame.routingId` value. E.g.
```js
// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)
```
You can also read `frameId` from all incoming IPC messages in the main process.
```js
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
```
#### `contents.postMessage(channel, message, [transfer])`
* `channel` string
* `message` any
* `transfer` MessagePortMain[] (optional)
Send a message to the renderer process, optionally transferring ownership of
zero or more [`MessagePortMain`][] objects.
The transferred `MessagePortMain` objects will be available in the renderer
process by accessing the `ports` property of the emitted event. When they
arrive in the renderer, they will be native DOM `MessagePort` objects.
For example:
```js
// Main process
const { port1, port2 } = new MessageChannelMain()
webContents.postMessage('port', { message: 'hello' }, [port1])
// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
```
#### `contents.enableDeviceEmulation(parameters)`
* `parameters` Object
* `screenPosition` string - Specify the screen type to emulate
(default: `desktop`):
* `desktop` - Desktop screen type.
* `mobile` - Mobile screen type.
* `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile).
* `viewPosition` [Point](structures/point.md) - Position the view on the screen
(screenPosition == mobile) (default: `{ x: 0, y: 0 }`).
* `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to
original device scale factor) (default: `0`).
* `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override)
* `scale` Float - Scale of emulated view inside available space (not in fit to
view mode) (default: `1`).
Enable device emulation with the given parameters.
#### `contents.disableDeviceEmulation()`
Disable device emulation enabled by `webContents.enableDeviceEmulation`.
#### `contents.sendInputEvent(inputEvent)`
* `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md)
Sends an input `event` to the page.
**Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for
`sendInputEvent()` to work.
#### `contents.beginFrameSubscription([onlyDirty ,]callback)`
* `onlyDirty` boolean (optional) - Defaults to `false`.
* `callback` Function
* `image` [NativeImage](native-image.md)
* `dirtyRect` [Rectangle](structures/rectangle.md)
Begin subscribing for presentation events and captured frames, the `callback`
will be called with `callback(image, dirtyRect)` when there is a presentation
event.
The `image` is an instance of [NativeImage](native-image.md) that stores the
captured frame.
The `dirtyRect` is an object with `x, y, width, height` properties that
describes which part of the page was repainted. If `onlyDirty` is set to
`true`, `image` will only contain the repainted area. `onlyDirty` defaults to
`false`.
#### `contents.endFrameSubscription()`
End subscribing for frame presentation events.
#### `contents.startDrag(item)`
* `item` Object
* `file` string - The path to the file being dragged.
* `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field)
* `icon` [NativeImage](native-image.md) | string - The image must be
non-empty on macOS.
Sets the `item` as dragging item for current drag-drop operation, `file` is the
absolute path of the file to be dragged, and `icon` is the image showing under
the cursor when dragging.
#### `contents.savePage(fullPath, saveType)`
* `fullPath` string - The absolute file path.
* `saveType` string - Specify the save type.
* `HTMLOnly` - Save only the HTML of the page.
* `HTMLComplete` - Save complete-html page.
* `MHTML` - Save complete-html page as MHTML.
Returns `Promise<void>` - resolves if the page is saved.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', async () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => {
console.log('Page was saved successfully.')
}).catch(err => {
console.log(err)
})
})
```
#### `contents.showDefinitionForSelection()` _macOS_
Shows pop-up dictionary that searches the selected word on the page.
#### `contents.isOffscreen()`
Returns `boolean` - Indicates whether *offscreen rendering* is enabled.
#### `contents.startPainting()`
If *offscreen rendering* is enabled and not painting, start painting.
#### `contents.stopPainting()`
If *offscreen rendering* is enabled and painting, stop painting.
#### `contents.isPainting()`
Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting.
#### `contents.setFrameRate(fps)`
* `fps` Integer
If *offscreen rendering* is enabled sets the frame rate to the specified number.
Only values between 1 and 240 are accepted.
#### `contents.getFrameRate()`
Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate.
#### `contents.invalidate()`
Schedules a full repaint of the window this web contents is in.
If *offscreen rendering* is enabled invalidates the frame and generates a new
one through the `'paint'` event.
#### `contents.getWebRTCIPHandlingPolicy()`
Returns `string` - Returns the WebRTC IP Handling Policy.
#### `contents.setWebRTCIPHandlingPolicy(policy)`
* `policy` string - Specify the WebRTC IP Handling Policy.
* `default` - Exposes user's public and local IPs. This is the default
behavior. When this policy is used, WebRTC has the right to enumerate all
interfaces and bind them to discover public interfaces.
* `default_public_interface_only` - Exposes user's public IP, but does not
expose user's local IP. When this policy is used, WebRTC should only use the
default route used by http. This doesn't expose any local addresses.
* `default_public_and_private_interfaces` - Exposes user's public and local
IPs. When this policy is used, WebRTC should only use the default route used
by http. This also exposes the associated default private address. Default
route is the route chosen by the OS on a multi-homed endpoint.
* `disable_non_proxied_udp` - Does not expose public or local IPs. When this
policy is used, WebRTC should only use TCP to contact peers or servers unless
the proxy server supports UDP.
Setting the WebRTC IP handling policy allows you to control which IPs are
exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for
more details.
#### `contents.getMediaSourceId(requestWebContents)`
* `requestWebContents` WebContents - Web contents that the id will be registered to.
Returns `string` - The identifier of a WebContents stream. This identifier can be used
with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`.
The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.
#### `contents.getOSProcessId()`
Returns `Integer` - The operating system `pid` of the associated renderer
process.
#### `contents.getProcessId()`
Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can
be compared to the `frameProcessId` passed by frame specific navigation events
(e.g. `did-frame-navigate`)
#### `contents.takeHeapSnapshot(filePath)`
* `filePath` string - Path to the output file.
Returns `Promise<void>` - Indicates whether the snapshot has been created successfully.
Takes a V8 heap snapshot and saves it to `filePath`.
#### `contents.getBackgroundThrottling()`
Returns `boolean` - whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.setBackgroundThrottling(allowed)`
* `allowed` boolean
Controls whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.getType()`
Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`.
#### `contents.setImageAnimationPolicy(policy)`
* `policy` string - Can be `animate`, `animateOnce` or `noAnimation`.
Sets the image animation policy for this webContents. The policy only affects
_new_ images, existing images that are currently being animated are unaffected.
This is a known limitation in Chromium, you can force image animation to be
recalculated with `img.src = img.src` which will result in no network traffic
but will update the animation policy.
This corresponds to the [animationPolicy][] accessibility feature in Chromium.
[animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy
### Instance Properties
#### `contents.ipc` _Readonly_
An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this
WebContents.
IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or
`ipcRenderer.postMessage` will be delivered in the following order:
1. `contents.on('ipc-message')`
2. `contents.mainFrame.on(channel)`
3. `contents.ipc.on(channel)`
4. `ipcMain.on(channel)`
Handlers registered with `invoke` will be checked in the following order. The
first one that is defined will be called, the rest will be ignored.
1. `contents.mainFrame.handle(channel)`
2. `contents.handle(channel)`
3. `ipcMain.handle(channel)`
A handler or event listener registered on the WebContents will receive IPC
messages sent from any frame, including child frames. In most cases, only the
main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames`
option is enabled, it is possible for child frames to send IPC messages also.
In that case, handlers should check the `senderFrame` property of the IPC event
to ensure that the message is coming from the expected frame. Alternatively,
register handlers on the appropriate frame directly using the
[`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface.
#### `contents.audioMuted`
A `boolean` property that determines whether this page is muted.
#### `contents.userAgent`
A `string` property that determines the user agent for this web page.
#### `contents.zoomLevel`
A `number` property that determines the zoom level for this web contents.
The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`.
#### `contents.zoomFactor`
A `number` property that determines the zoom factor for this web contents.
The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
#### `contents.frameRate`
An `Integer` property that sets the frame rate of the web contents to the specified number.
Only values between 1 and 240 are accepted.
Only applicable if *offscreen rendering* is enabled.
#### `contents.id` _Readonly_
A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application.
#### `contents.session` _Readonly_
A [`Session`](session.md) used by this webContents.
#### `contents.hostWebContents` _Readonly_
A [`WebContents`](web-contents.md) instance that might own this `WebContents`.
#### `contents.devToolsWebContents` _Readonly_
A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`.
**Note:** Users should never store this object because it may become `null`
when the DevTools has been closed.
#### `contents.debugger` _Readonly_
A [`Debugger`](debugger.md) instance for this webContents.
#### `contents.backgroundThrottling`
A `boolean` property that determines whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
#### `contents.mainFrame` _Readonly_
A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy.
#### `contents.opener` _Readonly_
A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either
with open(), or by navigating a link with a target attribute.
[keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
[SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
[`MessagePortMain`]: message-port-main.md
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
docs/api/webview-tag.md
|
# `<webview>` Tag
## Warning
Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which
is undergoing dramatic architectural changes. This impacts the stability of `webviews`,
including rendering, navigation, and event routing. We currently recommend to not
use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md),
or an architecture that avoids embedded content altogether.
## Enabling
By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by
setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For
more information see the [BrowserWindow constructor docs](browser-window.md).
## Overview
> Display external web content in an isolated frame and process.
Process: [Renderer](../glossary.md#renderer-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
Use the `webview` tag to embed 'guest' content (such as web pages) in your
Electron app. The guest content is contained within the `webview` container.
An embedded page within your app controls how the guest content is laid out and
rendered.
Unlike an `iframe`, the `webview` runs in a separate process than your
app. It doesn't have the same permissions as your web page and all interactions
between your app and embedded content will be asynchronous. This keeps your app
safe from the embedded content. **Note:** Most methods called on the
webview from the host page require a synchronous call to the main process.
## Example
To embed a web page in your app, add the `webview` tag to your app's embedder
page (this is the app page that will display the guest content). In its simplest
form, the `webview` tag includes the `src` of the web page and css styles that
control the appearance of the `webview` container:
```html
<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>
```
If you want to control the guest content in any way, you can write JavaScript
that listens for `webview` events and responds to those events using the
`webview` methods. Here's sample code with two event listeners: one that listens
for the web page to start loading, the other for the web page to stop loading,
and displays a "loading..." message during the load time:
```html
<script>
onload = () => {
const webview = document.querySelector('webview')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
```
## Internal implementation
Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes).
The `webview` tag is essentially a custom element using shadow DOM to wrap an
`iframe` element inside it.
So the behavior of `webview` is very similar to a cross-domain `iframe`, as
examples:
* When clicking into a `webview`, the page focus will move from the embedder
frame to `webview`.
* You can not add keyboard, mouse, and scroll event listeners to `webview`.
* All reactions between the embedder frame and `webview` are asynchronous.
## CSS Styling Notes
Please note that the `webview` tag's style uses `display:flex;` internally to
ensure the child `iframe` element fills the full height and width of its `webview`
container when used with traditional and flexbox layouts. Please do not
overwrite the default `display:flex;` CSS property, unless specifying
`display:inline-flex;` for inline layout.
## Tag Attributes
The `webview` tag has the following attributes:
### `src`
```html
<webview src="https://www.github.com/"></webview>
```
A `string` representing the visible URL. Writing to this attribute initiates top-level
navigation.
Assigning `src` its own value will reload the current page.
The `src` attribute can also accept data URLs, such as
`data:text/plain,Hello, world!`.
### `nodeintegration`
```html
<webview src="http://www.google.com/" nodeintegration></webview>
```
A `boolean`. When this attribute is present the guest page in `webview` will have node
integration and can use node APIs like `require` and `process` to access low
level system resources. Node integration is disabled by default in the guest
page.
### `nodeintegrationinsubframes`
```html
<webview src="http://www.google.com/" nodeintegrationinsubframes></webview>
```
A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes
inside the `webview`. All your preloads will load for every iframe, you can
use `process.isMainFrame` to determine if you are in the main frame or not.
This option is disabled by default in the guest page.
### `plugins`
```html
<webview src="https://www.github.com/" plugins></webview>
```
A `boolean`. When this attribute is present the guest page in `webview` will be able to use
browser plugins. Plugins are disabled by default.
### `preload`
```html
<!-- from a file -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- or if you want to load from an asar archive -->
<webview src="https://www.github.com/" preload="./app.asar/test.js"></webview>
```
A `string` that specifies a script that will be loaded before other scripts run in the guest
page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because
it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual
directories.
When the guest page doesn't have node integration this script will still have
access to all Node APIs, but global objects injected by Node will be deleted
after this script has finished executing.
### `httpreferrer`
```html
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
```
A `string` that sets the referrer URL for the guest page.
### `useragent`
```html
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
```
A `string` that sets the user agent for the guest page before the page is navigated to. Once the
page is loaded, use the `setUserAgent` method to change the user agent.
### `disablewebsecurity`
```html
<webview src="https://www.github.com/" disablewebsecurity></webview>
```
A `boolean`. When this attribute is present the guest page will have web security disabled.
Web security is enabled by default.
### `partition`
```html
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>
```
A `string` that sets the session used by the page. If `partition` starts with `persist:`, the
page will use a persistent session available to all pages in the app with the
same `partition`. if there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. If the `partition` is unset then default session of the app
will be used.
This value can only be modified before the first navigation, since the session
of an active renderer process cannot change. Subsequent attempts to modify the
value will fail with a DOM exception.
### `allowpopups`
```html
<webview src="https://www.github.com/" allowpopups></webview>
```
A `boolean`. When this attribute is present the guest page will be allowed to open new
windows. Popups are disabled by default.
### `webpreferences`
```html
<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>
```
A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview.
The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions).
The string follows the same format as the features string in `window.open`.
A name by itself is given a `true` boolean value.
A preference can be set to another value by including an `=`, followed by the value.
Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`.
### `enableblinkfeatures`
```html
<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
```
A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`.
The full list of supported feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
### `disableblinkfeatures`
```html
<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
```
A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`.
The full list of supported feature strings can be found in the
[RuntimeEnabledFeatures.json5][runtime-enabled-features] file.
## Methods
The `webview` tag has the following methods:
**Note:** The webview element must be loaded before using the methods.
**Example**
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
```
### `<webview>.loadURL(url[, options])`
* `url` URL
* `options` Object (optional)
* `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url.
* `userAgent` string (optional) - A user agent originating the request.
* `extraHeaders` string (optional) - Extra headers separated by "\n"
* `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional)
* `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files.
Returns `Promise<void>` - The promise will resolve when the page has finished loading
(see [`did-finish-load`](webview-tag.md#event-did-finish-load)), and rejects
if the page fails to load (see
[`did-fail-load`](webview-tag.md#event-did-fail-load)).
Loads the `url` in the webview, the `url` must contain the protocol prefix,
e.g. the `http://` or `file://`.
### `<webview>.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url` without navigating.
### `<webview>.getURL()`
Returns `string` - The URL of guest page.
### `<webview>.getTitle()`
Returns `string` - The title of guest page.
### `<webview>.isLoading()`
Returns `boolean` - Whether guest page is still loading resources.
### `<webview>.isLoadingMainFrame()`
Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is
still loading.
### `<webview>.isWaitingForResponse()`
Returns `boolean` - Whether the guest page is waiting for a first-response for the
main resource of the page.
### `<webview>.stop()`
Stops any pending navigation.
### `<webview>.reload()`
Reloads the guest page.
### `<webview>.reloadIgnoringCache()`
Reloads the guest page and ignores cache.
### `<webview>.canGoBack()`
Returns `boolean` - Whether the guest page can go back.
### `<webview>.canGoForward()`
Returns `boolean` - Whether the guest page can go forward.
### `<webview>.canGoToOffset(offset)`
* `offset` Integer
Returns `boolean` - Whether the guest page can go to `offset`.
### `<webview>.clearHistory()`
Clears the navigation history.
### `<webview>.goBack()`
Makes the guest page go back.
### `<webview>.goForward()`
Makes the guest page go forward.
### `<webview>.goToIndex(index)`
* `index` Integer
Navigates to the specified absolute index.
### `<webview>.goToOffset(offset)`
* `offset` Integer
Navigates to the specified offset from the "current entry".
### `<webview>.isCrashed()`
Returns `boolean` - Whether the renderer process has crashed.
### `<webview>.setUserAgent(userAgent)`
* `userAgent` string
Overrides the user agent for the guest page.
### `<webview>.getUserAgent()`
Returns `string` - The user agent for guest page.
### `<webview>.insertCSS(css)`
* `css` string
Returns `Promise<string>` - A promise that resolves with a key for the inserted
CSS that can later be used to remove the CSS via
`<webview>.removeInsertedCSS(key)`.
Injects CSS into the current web page and returns a unique key for the inserted
stylesheet.
### `<webview>.removeInsertedCSS(key)`
* `key` string
Returns `Promise<void>` - Resolves if the removal was successful.
Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from `<webview>.insertCSS(css)`.
### `<webview>.executeJavaScript(code[, userGesture])`
* `code` string
* `userGesture` boolean (optional) - Default `false`.
Returns `Promise<any>` - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
Evaluates `code` in page. If `userGesture` is set, it will create the user
gesture context in the page. HTML APIs like `requestFullScreen`, which require
user action, can take advantage of this option for automation.
### `<webview>.openDevTools()`
Opens a DevTools window for guest page.
### `<webview>.closeDevTools()`
Closes the DevTools window of guest page.
### `<webview>.isDevToolsOpened()`
Returns `boolean` - Whether guest page has a DevTools window attached.
### `<webview>.isDevToolsFocused()`
Returns `boolean` - Whether DevTools window of guest page is focused.
### `<webview>.inspectElement(x, y)`
* `x` Integer
* `y` Integer
Starts inspecting element at position (`x`, `y`) of guest page.
### `<webview>.inspectSharedWorker()`
Opens the DevTools for the shared worker context present in the guest page.
### `<webview>.inspectServiceWorker()`
Opens the DevTools for the service worker context present in the guest page.
### `<webview>.setAudioMuted(muted)`
* `muted` boolean
Set guest page muted.
### `<webview>.isAudioMuted()`
Returns `boolean` - Whether guest page has been muted.
### `<webview>.isCurrentlyAudible()`
Returns `boolean` - Whether audio is currently playing.
### `<webview>.undo()`
Executes editing command `undo` in page.
### `<webview>.redo()`
Executes editing command `redo` in page.
### `<webview>.cut()`
Executes editing command `cut` in page.
### `<webview>.copy()`
Executes editing command `copy` in page.
### `<webview>.paste()`
Executes editing command `paste` in page.
### `<webview>.pasteAndMatchStyle()`
Executes editing command `pasteAndMatchStyle` in page.
### `<webview>.delete()`
Executes editing command `delete` in page.
### `<webview>.selectAll()`
Executes editing command `selectAll` in page.
### `<webview>.unselect()`
Executes editing command `unselect` in page.
### `<webview>.replace(text)`
* `text` string
Executes editing command `replace` in page.
### `<webview>.replaceMisspelling(text)`
* `text` string
Executes editing command `replaceMisspelling` in page.
### `<webview>.insertText(text)`
* `text` string
Returns `Promise<void>`
Inserts `text` to the focused element.
### `<webview>.findInPage(text[, options])`
* `text` string - Content to be searched, must not be empty.
* `options` Object (optional)
* `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`.
* `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`.
* `matchCase` boolean (optional) - Whether search should be case-sensitive,
defaults to `false`.
Returns `Integer` - The request id used for the request.
Starts a request to find all matches for the `text` in the web page. The result of the request
can be obtained by subscribing to [`found-in-page`](webview-tag.md#event-found-in-page) event.
### `<webview>.stopFindInPage(action)`
* `action` string - Specifies the action to take place when ending
[`<webview>.findInPage`](#webviewfindinpagetext-options) request.
* `clearSelection` - Clear the selection.
* `keepSelection` - Translate the selection into a normal selection.
* `activateSelection` - Focus and click the selection node.
Stops any `findInPage` request for the `webview` with the provided `action`.
### `<webview>.print([options])`
* `options` Object (optional)
* `silent` boolean (optional) - Don't ask user for print settings. Default is `false`.
* `printBackground` boolean (optional) - Prints the background color and image of
the web page. Default is `false`.
* `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.
* `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`.
* `margins` Object (optional)
* `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`.
* `top` number (optional) - The top margin of the printed web page, in pixels.
* `bottom` number (optional) - The bottom margin of the printed web page, in pixels.
* `left` number (optional) - The left margin of the printed web page, in pixels.
* `right` number (optional) - The right margin of the printed web page, in pixels.
* `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`.
* `scaleFactor` number (optional) - The scale factor of the web page.
* `pagesPerSheet` number (optional) - The number of pages to print per page sheet.
* `collate` boolean (optional) - Whether the web page should be collated.
* `copies` number (optional) - The number of copies of the web page to print.
* `pageRanges` Object[] (optional) - The page range to print.
* `from` number - Index of the first page to print (0-based).
* `to` number - Index of the last page to print (inclusive) (0-based).
* `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`.
* `dpi` Record<string, number> (optional)
* `horizontal` number (optional) - The horizontal dpi.
* `vertical` number (optional) - The vertical dpi.
* `header` string (optional) - string to be printed as page header.
* `footer` string (optional) - string to be printed as page footer.
* `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`,
`A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` in microns.
Returns `Promise<void>`
Prints `webview`'s web page. Same as `webContents.print([options])`.
### `<webview>.printToPDF(options)`
* `options` Object
* `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false.
* `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false.
* `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false.
* `scale` number(optional) - Scale of the webpage rendering. Defaults to 1.
* `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`,
`A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`.
* `margins` Object (optional)
* `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
* `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
* `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
* `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
* `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.
* `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title.
* `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`.
* `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
Returns `Promise<Uint8Array>` - Resolves with the generated PDF data.
Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`.
### `<webview>.capturePage([rect])`
* `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured.
Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md)
Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page.
### `<webview>.send(channel, ...args)`
* `channel` string
* `...args` any[]
Returns `Promise<void>`
Send an asynchronous message to renderer process via `channel`, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module.
See [webContents.send](web-contents.md#contentssendchannel-args) for
examples.
### `<webview>.sendToFrame(frameId, channel, ...args)`
* `frameId` \[number, number] - `[processId, frameId]`
* `channel` string
* `...args` any[]
Returns `Promise<void>`
Send an asynchronous message to renderer process via `channel`, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module.
See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for
examples.
### `<webview>.sendInputEvent(event)`
* `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md)
Returns `Promise<void>`
Sends an input `event` to the page.
See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent)
for detailed description of `event` object.
### `<webview>.setZoomFactor(factor)`
* `factor` number - Zoom factor.
Changes the zoom factor to the specified factor. Zoom factor is
zoom percent divided by 100, so 300% = 3.0.
### `<webview>.setZoomLevel(level)`
* `level` number - Zoom level.
Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
`scale := 1.2 ^ level`.
> **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the
> zoom level for a specific domain propagates across all instances of windows with
> the same domain. Differentiating the window URLs will make zoom work per-window.
### `<webview>.getZoomFactor()`
Returns `number` - the current zoom factor.
### `<webview>.getZoomLevel()`
Returns `number` - the current zoom level.
### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` number
* `maximumLevel` number
Returns `Promise<void>`
Sets the maximum and minimum pinch-to-zoom level.
### `<webview>.showDefinitionForSelection()` _macOS_
Shows pop-up dictionary that searches the selected word on the page.
### `<webview>.getWebContentsId()`
Returns `number` - The WebContents ID of this `webview`.
## DOM Events
The following DOM events are available to the `webview` tag:
### Event: 'load-commit'
Returns:
* `url` string
* `isMainFrame` boolean
Fired when a load has committed. This includes navigation within the current
document as well as subframe document-level loads, but does not include
asynchronous resource loads.
### Event: 'did-finish-load'
Fired when the navigation is done, i.e. the spinner of the tab will stop
spinning, and the `onload` event is dispatched.
### Event: 'did-fail-load'
Returns:
* `errorCode` Integer
* `errorDescription` string
* `validatedURL` string
* `isMainFrame` boolean
This event is like `did-finish-load`, but fired when the load failed or was
cancelled, e.g. `window.stop()` is invoked.
### Event: 'did-frame-finish-load'
Returns:
* `isMainFrame` boolean
Fired when a frame has done navigation.
### Event: 'did-start-loading'
Corresponds to the points in time when the spinner of the tab starts spinning.
### Event: 'did-stop-loading'
Corresponds to the points in time when the spinner of the tab stops spinning.
### Event: 'did-attach'
Fired when attached to the embedder web contents.
### Event: 'dom-ready'
Fired when document in the given frame is loaded.
### Event: 'page-title-updated'
Returns:
* `title` string
* `explicitSet` boolean
Fired when page title is set during navigation. `explicitSet` is false when
title is synthesized from file url.
### Event: 'page-favicon-updated'
Returns:
* `favicons` string[] - Array of URLs.
Fired when page receives favicon urls.
### Event: 'enter-html-full-screen'
Fired when page enters fullscreen triggered by HTML API.
### Event: 'leave-html-full-screen'
Fired when page leaves fullscreen triggered by HTML API.
### Event: 'console-message'
Returns:
* `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`.
* `message` string - The actual console message
* `line` Integer - The line number of the source that triggered this console message
* `sourceId` string
Fired when the guest window logs a console message.
The following example code forwards all log messages to the embedder's console
without regard for log level or other properties.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
})
```
### Event: 'found-in-page'
Returns:
* `result` Object
* `requestId` Integer
* `activeMatchOrdinal` Integer - Position of the active match.
* `matches` Integer - Number of Matches.
* `selectionArea` Rectangle - Coordinates of first match region.
* `finalUpdate` boolean
Fired when a result is available for
[`webview.findInPage`](#webviewfindinpagetext-options) request.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test')
console.log(requestId)
```
### Event: 'will-navigate'
Returns:
* `url` string
Emitted when a user or the page wants to start navigation. It can happen when
the `window.location` object is changed or a user clicks a link in the page.
This event will not emit when the navigation is started programmatically with
APIs like `<webview>.loadURL` and `<webview>.back`.
It is also not emitted during in-page navigation, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
Calling `event.preventDefault()` does __NOT__ have any effect.
### Event: 'did-start-navigation'
Returns:
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame (including main) starts navigating. `isInPlace` will be
`true` for in-page navigations.
### Event: 'did-redirect-navigation'
Returns:
* `url` string
* `isInPlace` boolean
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted after a server side redirect occurs during navigation. For example a 302
redirect.
### Event: 'did-navigate'
Returns:
* `url` string
Emitted when a navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
### Event: 'did-frame-navigate'
Returns:
* `url` string
* `httpResponseCode` Integer - -1 for non HTTP navigations
* `httpStatusText` string - empty for non HTTP navigations,
* `isMainFrame` boolean
* `frameProcessId` Integer
* `frameRoutingId` Integer
Emitted when any frame navigation is done.
This event is not emitted for in-page navigations, such as clicking anchor links
or updating the `window.location.hash`. Use `did-navigate-in-page` event for
this purpose.
### Event: 'did-navigate-in-page'
Returns:
* `isMainFrame` boolean
* `url` string
Emitted when an in-page navigation happened.
When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM `hashchange` event is triggered.
### Event: 'close'
Fired when the guest page attempts to close itself.
The following example code navigates the `webview` to `about:blank` when the
guest attempts to close itself.
```javascript
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})
```
### Event: 'ipc-message'
Returns:
* `frameId` \[number, number] - pair of `[processId, frameId]`.
* `channel` string
* `args` any[]
Fired when the guest page has sent an asynchronous message to embedder page.
With `sendToHost` method and `ipc-message` event you can communicate
between guest page and embedder page:
```javascript
// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
```
```javascript
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
```
### Event: 'crashed'
Fired when the renderer process is crashed.
### Event: 'plugin-crashed'
Returns:
* `name` string
* `version` string
Fired when a plugin process is crashed.
### Event: 'destroyed'
Fired when the WebContents is destroyed.
### Event: 'media-started-playing'
Emitted when media starts playing.
### Event: 'media-paused'
Emitted when media is paused or done playing.
### Event: 'did-change-theme-color'
Returns:
* `themeColor` string
Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
```html
<meta name='theme-color' content='#ff0000'>
```
### Event: 'update-target-url'
Returns:
* `url` string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.
### Event: 'devtools-opened'
Emitted when DevTools is opened.
### Event: 'devtools-closed'
Emitted when DevTools is closed.
### Event: 'devtools-focused'
Emitted when DevTools is focused / opened.
[runtime-enabled-features]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/platform/runtime_enabled_features.json5?l=70
[chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/
### Event: 'context-menu'
Returns:
* `params` Object
* `x` Integer - x coordinate.
* `y` Integer - y coordinate.
* `linkURL` string - URL of the link that encloses the node the context menu
was invoked on.
* `linkText` string - Text associated with the link. May be an empty
string if the contents of the link are an image.
* `pageURL` string - URL of the top level page that the context menu was
invoked on.
* `frameURL` string - URL of the subframe that the context menu was invoked
on.
* `srcURL` string - Source URL for the element that the context menu
was invoked on. Elements with source URLs are images, audio and video.
* `mediaType` string - Type of the node the context menu was invoked on. Can
be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`.
* `hasImageContents` boolean - Whether the context menu was invoked on an image
which has non-empty contents.
* `isEditable` boolean - Whether the context is editable.
* `selectionText` string - Text of the selection that the context menu was
invoked on.
* `titleText` string - Title text of the selection that the context menu was
invoked on.
* `altText` string - Alt text of the selection that the context menu was
invoked on.
* `suggestedFilename` string - Suggested filename to be used when saving file through 'Save
Link As' option of context menu.
* `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection.
* `selectionStartOffset` number - Start position of the selection text.
* `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked.
* `misspelledWord` string - The misspelled word under the cursor, if any.
* `dictionarySuggestions` string[] - An array of suggested words to show the
user to replace the `misspelledWord`. Only available if there is a misspelled
word and spellchecker is enabled.
* `frameCharset` string - The character encoding of the frame on which the
menu was invoked.
* `inputFieldType` string - If the context menu was invoked on an input
field, the type of that field. Possible values are `none`, `plainText`,
`password`, `other`.
* `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled.
* `menuSourceType` string - Input source that invoked the context menu.
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
* `mediaFlags` Object - The flags for the media element the context menu was
invoked on.
* `inError` boolean - Whether the media element has crashed.
* `isPaused` boolean - Whether the media element is paused.
* `isMuted` boolean - Whether the media element is muted.
* `hasAudio` boolean - Whether the media element has audio.
* `isLooping` boolean - Whether the media element is looping.
* `isControlsVisible` boolean - Whether the media element's controls are
visible.
* `canToggleControls` boolean - Whether the media element's controls are
toggleable.
* `canPrint` boolean - Whether the media element can be printed.
* `canSave` boolean - Whether or not the media element can be downloaded.
* `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture.
* `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture.
* `canRotate` boolean - Whether the media element can be rotated.
* `canLoop` boolean - Whether the media element can be looped.
* `editFlags` Object - These flags indicate whether the renderer believes it
is able to perform the corresponding action.
* `canUndo` boolean - Whether the renderer believes it can undo.
* `canRedo` boolean - Whether the renderer believes it can redo.
* `canCut` boolean - Whether the renderer believes it can cut.
* `canCopy` boolean - Whether the renderer believes it can copy.
* `canPaste` boolean - Whether the renderer believes it can paste.
* `canDelete` boolean - Whether the renderer believes it can delete.
* `canSelectAll` boolean - Whether the renderer believes it can select all.
* `canEditRichly` boolean - Whether the renderer believes it can edit text richly.
Emitted when there is a new context menu that needs to be handled.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
lib/browser/web-view-events.ts
|
export const webViewEvents: Record<string, readonly string[]> = {
'load-commit': ['url', 'isMainFrame'],
'did-attach': [],
'did-finish-load': [],
'did-fail-load': ['errorCode', 'errorDescription', 'validatedURL', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-frame-finish-load': ['isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-start-loading': [],
'did-stop-loading': [],
'dom-ready': [],
'console-message': ['level', 'message', 'line', 'sourceId'],
'context-menu': ['params'],
'devtools-opened': [],
'devtools-closed': [],
'devtools-focused': [],
'will-navigate': ['url'],
'did-start-navigation': ['url', 'isInPlace', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-redirect-navigation': ['url', 'isInPlace', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-navigate': ['url', 'httpResponseCode', 'httpStatusText'],
'did-frame-navigate': ['url', 'httpResponseCode', 'httpStatusText', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'did-navigate-in-page': ['url', 'isMainFrame', 'frameProcessId', 'frameRoutingId'],
'-focus-change': ['focus'],
close: [],
crashed: [],
'render-process-gone': ['details'],
'plugin-crashed': ['name', 'version'],
destroyed: [],
'page-title-updated': ['title', 'explicitSet'],
'page-favicon-updated': ['favicons'],
'enter-html-full-screen': [],
'leave-html-full-screen': [],
'media-started-playing': [],
'media-paused': [],
'found-in-page': ['result'],
'did-change-theme-color': ['themeColor'],
'update-target-url': ['url']
} as const;
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.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"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
std::string type;
if (ConvertFromV8(isolate, val, &type)) {
if (type == "default") {
*out = printing::mojom::MarginType::kDefaultMargins;
return true;
}
if (type == "none") {
*out = printing::mojom::MarginType::kNoMargins;
return true;
}
if (type == "printableArea") {
*out = printing::mojom::MarginType::kPrintableAreaMargins;
return true;
}
if (type == "custom") {
*out = printing::mojom::MarginType::kCustomMargins;
return true;
}
}
return false;
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "simplex") {
*out = printing::mojom::DuplexMode::kSimplex;
return true;
}
if (mode == "longEdge") {
*out = printing::mojom::DuplexMode::kLongEdge;
return true;
}
if (mode == "shortEdge") {
*out = printing::mojom::DuplexMode::kShortEdge;
return true;
}
}
return false;
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
std::string save_type;
if (!ConvertFromV8(isolate, val, &save_type))
return false;
save_type = base::ToLowerASCII(save_type);
if (save_type == "htmlonly") {
*out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
} else if (save_type == "htmlcomplete") {
*out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
} else if (save_type == "mhtml") {
*out = content::SAVE_PAGE_TYPE_AS_MHTML;
} else {
return false;
}
return true;
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Type = electron::api::WebContents::Type;
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "backgroundPage") {
*out = Type::kBackgroundPage;
} else if (type == "browserView") {
*out = Type::kBrowserView;
} else if (type == "webview") {
*out = Type::kWebView;
#if BUILDFLAG(ENABLE_OSR)
} else if (type == "offscreen") {
*out = Type::kOffScreen;
#endif
} else {
return false;
}
return true;
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
#if BUILDFLAG(ENABLE_OSR)
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
#endif
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
#if BUILDFLAG(ENABLE_OSR)
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
#endif
web_contents = content::WebContents::Create(params);
#if BUILDFLAG(ENABLE_OSR)
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
#endif
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_->HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
return owner_window_ && owner_window_->IsFullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window_)
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::HTML);
exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window_)
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_->mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_->keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
Emit("-audio-state-changed", audible);
}
void WebContents::BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame =
WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId());
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {
if (old_host)
old_host->GetWidget()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
return Emit(event, url, is_same_document, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments) {
TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
auto* target_web_contents = FromID(web_contents_id);
if (target_web_contents) {
content::RenderFrameHost* frame = target_web_contents->MainFrame();
DCHECK(frame);
v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
gin::Handle<WebFrameMain> web_frame_main =
WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
if (!web_frame_main->CheckRenderFrame())
return;
int32_t sender_id = ID();
web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
std::move(arguments), sender_id);
}
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
#if BUILDFLAG(ENABLE_OSR)
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
#endif
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, "", content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICTIONARY);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
#endif
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
#endif
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
// TODO(codebytere): remove in Electron v23.
void WebContents::IncrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.incrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
gfx::Size size;
bool stay_hidden = false;
bool stay_awake = false;
// get size arguments if they exist
args->GetNext(&size);
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
std::ignore = web_contents()
->IncrementCapturerCount(size, stay_hidden, stay_awake)
.Release();
}
// TODO(codebytere): remove in Electron v23.
void WebContents::DecrementCapturerCount(gin::Arguments* args) {
EmitWarning(node::Environment::GetCurrent(args->isolate()),
"webContents.decrementCapturerCount() is deprecated and will be "
"removed in v23",
"electron");
bool stay_hidden = false;
bool stay_awake = false;
// get stayHidden arguments if they exist
args->GetNext(&stay_hidden);
// get stayAwake arguments if they exist
args->GetNext(&stay_awake);
web_contents()->DecrementCapturerCount(stay_hidden, stay_awake);
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const content::WebCursor& webcursor) {
const ui::Cursor& cursor = webcursor.cursor();
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
#if BUILDFLAG(ENABLE_OSR)
return type_ == Type::kOffScreen;
#else
return false;
#endif
}
#if BUILDFLAG(ENABLE_OSR)
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
#endif
void WebContents::Invalidate() {
if (IsOffScreen()) {
#if BUILDFLAG(ENABLE_OSR)
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
#endif
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
base::File file(file_path,
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
if (!file.IsValid()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("takeHeapSnapshot failed");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return html_fullscreen_;
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::NONE;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::HTML;
return html_fullscreen_ || (in_transition && is_html_transition);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
#else
return content::PictureInPictureResult::kNotSupported;
#endif
}
void WebContents::ExitPictureInPicture() {
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
#endif
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
std::unique_ptr<base::Value> parsed_excluded_folders =
base::JSONReader::ReadDeprecated(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window_->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
return gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
#if BUILDFLAG(ENABLE_OSR)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
#endif
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount)
.SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/api/electron_api_web_contents.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "chrome/browser/devtools/devtools_eye_dropper.h"
#include "chrome/browser/devtools/devtools_file_system_indexer.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck
#include "content/common/cursors/webcursor.h"
#include "content/common/frame.mojom.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/keyboard_event_processing_result.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/frame_subscriber.h"
#include "shell/browser/api/save_page_handler.h"
#include "shell/browser/event_emitter_mixin.h"
#include "shell/browser/extended_web_contents_observer.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/pinnable.h"
#include "ui/base/models/image_model.h"
#include "ui/gfx/image/image.h"
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/common/mojom/view_type.mojom.h"
namespace extensions {
class ScriptExecutor;
}
#endif
namespace blink {
struct DeviceEmulationParams;
// enum class PermissionType;
} // namespace blink
namespace gin_helper {
class Dictionary;
}
namespace network {
class ResourceRequestBody;
}
namespace gin {
class Arguments;
}
class ExclusiveAccessManager;
class SkRegion;
namespace electron {
class ElectronBrowserContext;
class ElectronJavaScriptDialogManager;
class InspectableWebContents;
class WebContentsZoomController;
class WebViewGuestDelegate;
class FrameSubscriber;
class WebDialogHelper;
class NativeWindow;
#if BUILDFLAG(ENABLE_OSR)
class OffScreenRenderWidgetHostView;
class OffScreenWebContentsView;
#endif
namespace api {
// Wrapper around the content::WebContents.
class WebContents : public ExclusiveAccessContext,
public gin::Wrappable<WebContents>,
public gin_helper::EventEmitterMixin<WebContents>,
public gin_helper::Constructible<WebContents>,
public gin_helper::Pinnable<WebContents>,
public gin_helper::CleanedUpAtExit,
public content::WebContentsObserver,
public content::WebContentsDelegate,
public content::RenderWidgetHost::InputEventObserver,
public InspectableWebContentsDelegate,
public InspectableWebContentsViewDelegate {
public:
enum class Type {
kBackgroundPage, // An extension background page.
kBrowserWindow, // Used by BrowserWindow.
kBrowserView, // Used by BrowserView.
kRemote, // Thin wrap around an existing WebContents.
kWebView, // Used by <webview>.
kOffScreen, // Used for offscreen rendering
};
// Create a new WebContents and return the V8 wrapper of it.
static gin::Handle<WebContents> New(v8::Isolate* isolate,
const gin_helper::Dictionary& options);
// Create a new V8 wrapper for an existing |web_content|.
//
// The lifetime of |web_contents| will be managed by this class.
static gin::Handle<WebContents> CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Get the api::WebContents associated with |web_contents|. Returns nullptr
// if there is no associated wrapper.
static WebContents* From(content::WebContents* web_contents);
static WebContents* FromID(int32_t id);
// Get the V8 wrapper of the |web_contents|, or create one if not existed.
//
// The lifetime of |web_contents| is NOT managed by this class, and the type
// of this wrapper is always REMOTE.
static gin::Handle<WebContents> FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents);
static gin::Handle<WebContents> CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
static v8::Local<v8::ObjectTemplate> FillObjectTemplate(
v8::Isolate*,
v8::Local<v8::ObjectTemplate>);
const char* GetTypeName() override;
void Destroy();
void Close(absl::optional<gin_helper::Dictionary> options);
base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
bool GetBackgroundThrottling() const;
void SetBackgroundThrottling(bool allowed);
int GetProcessID() const;
base::ProcessId GetOSProcessID() const;
Type GetType() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const gin_helper::Dictionary& options);
void Reload();
void ReloadIgnoringCache();
void DownloadURL(const GURL& url);
GURL GetURL() const;
std::u16string GetTitle() const;
bool IsLoading() const;
bool IsLoadingMainFrame() const;
bool IsWaitingForResponse() const;
void Stop();
bool CanGoBack() const;
void GoBack();
bool CanGoForward() const;
void GoForward();
bool CanGoToOffset(int offset) const;
void GoToOffset(int offset);
bool CanGoToIndex(int index) const;
void GoToIndex(int index);
int GetActiveIndex() const;
void ClearHistory();
int GetHistoryLength() const;
const std::string GetWebRTCIPHandlingPolicy() const;
void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy);
std::string GetMediaSourceID(content::WebContents* request_web_contents);
bool IsCrashed() const;
void ForcefullyCrashRenderer();
void SetUserAgent(const std::string& user_agent);
std::string GetUserAgent();
void InsertCSS(const std::string& css);
v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path,
const content::SavePageType& save_type);
void OpenDevTools(gin::Arguments* args);
void CloseDevTools();
bool IsDevToolsOpened();
bool IsDevToolsFocused();
void ToggleDevTools();
void EnableDeviceEmulation(const blink::DeviceEmulationParams& params);
void DisableDeviceEmulation();
void InspectElement(int x, int y);
void InspectSharedWorker();
void InspectSharedWorkerById(const std::string& workerId);
std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers();
void InspectServiceWorker();
void SetIgnoreMenuShortcuts(bool ignore);
void SetAudioMuted(bool muted);
bool IsAudioMuted();
bool IsCurrentlyAudible();
void SetEmbedder(const WebContents* embedder);
void SetDevToolsWebContents(const WebContents* devtools);
v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const;
void IncrementCapturerCount(gin::Arguments* args);
void DecrementCapturerCount(gin::Arguments* args);
bool IsBeingCaptured();
void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host);
#if BUILDFLAG(ENABLE_PRINTING)
void OnGetDeviceNameToUse(base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info);
void Print(gin::Arguments* args);
// Print current page as PDF.
v8::Local<v8::Promise> PrintToPDF(const base::Value& settings);
void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data);
#endif
void SetNextChildWebPreferences(const gin_helper::Dictionary);
// DevTools workspace api.
void AddWorkSpace(gin::Arguments* args, const base::FilePath& path);
void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path);
// Editing commands.
void Undo();
void Redo();
void Cut();
void Copy();
void Paste();
void PasteAndMatchStyle();
void Delete();
void SelectAll();
void Unselect();
void Replace(const std::u16string& word);
void ReplaceMisspelling(const std::u16string& word);
uint32_t FindInPage(gin::Arguments* args);
void StopFindInPage(content::StopFindAction action);
void ShowDefinitionForSelection();
void CopyImageAt(int x, int y);
// Focus.
void Focus();
bool IsFocused() const;
// Send WebInputEvent to the page.
void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event);
// Subscribe to the frame updates.
void BeginFrameSubscription(gin::Arguments* args);
void EndFrameSubscription();
// Dragging native items.
void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args);
// Captures the page with |rect|, |callback| would be called when capturing is
// done.
v8::Local<v8::Promise> CapturePage(gin::Arguments* args);
// Methods for creating <webview>.
bool IsGuest() const;
void AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id);
void DetachFromOuterFrame();
// Methods for offscreen rendering
bool IsOffScreen() const;
#if BUILDFLAG(ENABLE_OSR)
void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap);
void StartPainting();
void StopPainting();
bool IsPainting() const;
void SetFrameRate(int frame_rate);
int GetFrameRate() const;
#endif
void Invalidate();
gfx::Size GetSizeForNewRenderView(content::WebContents*) override;
// Methods for zoom handling.
void SetZoomLevel(double level);
double GetZoomLevel() const;
void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor);
double GetZoomFactor() const;
// Callback triggered on permission response.
void OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed);
// Create window with the given disposition.
void OnCreateWindow(const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body);
// Returns the preload script path of current WebContents.
std::vector<base::FilePath> GetPreloadPaths() const;
// Returns the web preferences of current WebContents.
v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const;
// Returns the owner window.
v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const;
// Notifies the web page that there is user interaction.
void NotifyUserActivation();
v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate,
const base::FilePath& file_path);
v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate);
// Properties.
int32_t ID() const { return id_; }
v8::Local<v8::Value> Session(v8::Isolate* isolate);
content::WebContents* HostWebContents() const;
v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
content::RenderFrameHost* MainFrame();
content::RenderFrameHost* Opener();
WebContentsZoomController* GetZoomController() { return zoom_controller_; }
void AddObserver(ExtendedWebContentsObserver* obs) {
observers_.AddObserver(obs);
}
void RemoveObserver(ExtendedWebContentsObserver* obs) {
// Trying to remove from an empty collection leads to an access violation
if (!observers_.empty())
observers_.RemoveObserver(obs);
}
bool EmitNavigationEvent(const std::string& event,
content::NavigationHandle* navigation_handle);
// this.emit(name, new Event(sender, message), args...);
template <typename... Args>
bool EmitWithSender(base::StringPiece name,
content::RenderFrameHost* sender,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
Args&&... args) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return false;
v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent(
isolate, wrapper, sender, std::move(callback));
return EmitCustomEvent(name, event, std::forward<Args>(args)...);
}
WebContents* embedder() { return embedder_; }
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ScriptExecutor* script_executor() {
return script_executor_.get();
}
#endif
// Set the window as owner window.
void SetOwnerWindow(NativeWindow* owner_window);
void SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window);
// Returns the WebContents managed by this delegate.
content::WebContents* GetWebContents() const;
// Returns the WebContents of devtools.
content::WebContents* GetDevToolsWebContents() const;
InspectableWebContents* inspectable_web_contents() const {
return inspectable_web_contents_.get();
}
NativeWindow* owner_window() const { return owner_window_.get(); }
bool is_html_fullscreen() const { return html_fullscreen_; }
void set_fullscreen_frame(content::RenderFrameHost* rfh) {
fullscreen_frame_ = rfh;
}
// mojom::ElectronApiIPC
void Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host);
void Invoke(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host);
void ReceivePostMessage(const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host);
void MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host);
void MessageTo(int32_t web_contents_id,
const std::string& channel,
blink::CloneableMessage arguments);
void MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host);
// mojom::ElectronWebContentsUtility
void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host);
void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions);
void SetTemporaryZoomLevel(double level);
void DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback);
void SetImageAnimationPolicy(const std::string& new_policy);
// content::RenderWidgetHost::InputEventObserver:
void OnInputEvent(const blink::WebInputEvent& event) override;
SkRegion* draggable_region() { return draggable_region_.get(); }
// disable copy
WebContents(const WebContents&) = delete;
WebContents& operator=(const WebContents&) = delete;
private:
// Does not manage lifetime of |web_contents|.
WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
// Takes over ownership of |web_contents|.
WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type);
// Creates a new content::WebContents.
WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options);
~WebContents() override;
// Delete this if garbage collection has not started.
void DeleteThisIfAlive();
// Creates a InspectableWebContents object and takes ownership of
// |web_contents|.
void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest);
void InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
gin::Handle<class Session> session,
const gin_helper::Dictionary& options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type);
#endif
// content::WebContentsDelegate:
bool DidAddMessageToConsole(content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) override;
bool IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) override;
content::WebContents* CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) override;
void WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) override;
void AddNewContents(content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override;
content::WebContents* OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) override;
void BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) override;
void SetContentsBounds(content::WebContents* source,
const gfx::Rect& pos) override;
void CloseContents(content::WebContents* source) override;
void ActivateContents(content::WebContents* contents) override;
void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
bool HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
bool PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event);
content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) override;
void ContentsZoomChange(bool zoom_in) override;
void EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) override;
void ExitFullscreenModeForTab(content::WebContents* source) override;
void RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) override;
void RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) override;
bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) override;
void RequestExclusivePointerAccess(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed);
void RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override;
void LostMouseLock() override;
void RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) override;
void CancelKeyboardLockRequest(content::WebContents* web_contents) override;
bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) override;
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) override;
content::JavaScriptDialogManager* GetJavaScriptDialogManager(
content::WebContents* source) override;
void OnAudioStateChanged(bool audible) override;
void UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) override;
// content::WebContentsObserver:
void BeforeUnloadFired(bool proceed,
const base::TimeTicks& proceed_time) override;
void OnBackgroundColorChanged() override;
void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) override;
void FrameDeleted(int frame_tree_node_id) override;
void RenderViewDeleted(content::RenderViewHost*) override;
void PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) override;
void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override;
void DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) override;
void DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url,
int error_code) override;
void DidStartLoading() override;
void DidStopLoading() override;
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override;
void DidRedirectNavigation(
content::NavigationHandle* navigation_handle) override;
void ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
void WebContentsDestroyed() override;
void NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) override;
void TitleWasSet(content::NavigationEntry* entry) override;
void DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) override;
void PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) override;
void MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) override;
void MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) override;
void DidChangeThemeColor() override;
void OnCursorChanged(const content::WebCursor& cursor) override;
void DidAcquireFullscreen(content::RenderFrameHost* rfh) override;
void OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) override;
void OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) override;
void RenderViewHostChanged(content::RenderViewHost* old_host,
content::RenderViewHost* new_host) override;
// InspectableWebContentsDelegate:
void DevToolsReloadPage() override;
// InspectableWebContentsViewDelegate:
void DevToolsFocused() override;
void DevToolsOpened() override;
void DevToolsClosed() override;
void DevToolsResized() override;
ElectronBrowserContext* GetBrowserContext() const;
void OnElectronBrowserConnectionError();
#if BUILDFLAG(ENABLE_OSR)
OffScreenWebContentsView* GetOffScreenWebContentsView() const;
OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
#endif
// Called when received a synchronous message from renderer to
// get the zoom level.
void OnGetZoomLevel(content::RenderFrameHost* frame_host,
IPC::Message* reply_msg);
void InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options);
// content::WebContentsDelegate:
bool CanOverscrollContent() override;
std::unique_ptr<content::EyeDropper> OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) override;
void EnumerateDirectory(content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) override;
// ExclusiveAccessContext:
Profile* GetProfile() override;
bool IsFullscreen() const override;
void EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) override;
void ExitFullscreen() override;
void UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) override;
void OnExclusiveAccessUserInput() override;
content::WebContents* GetActiveWebContents() override;
bool CanUserExitFullscreen() const override;
bool IsExclusiveAccessBubbleDisplayed() const override;
bool IsFullscreenForTabOrPending(const content::WebContents* source) override;
bool TakeFocus(content::WebContents* source, bool reverse) override;
content::PictureInPictureResult EnterPictureInPicture(
content::WebContents* web_contents) override;
void ExitPictureInPicture() override;
// InspectableWebContentsDelegate:
void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) override;
void DevToolsAppendToFile(const std::string& url,
const std::string& content) override;
void DevToolsRequestFileSystems() override;
void DevToolsAddFileSystem(const std::string& type,
const base::FilePath& file_system_path) override;
void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) override;
void DevToolsIndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) override;
void DevToolsStopIndexing(int request_id) override;
void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) override;
void DevToolsSetEyeDropperActive(bool active) override;
// InspectableWebContentsViewDelegate:
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel GetDevToolsWindowIcon() override;
#endif
#if BUILDFLAG(IS_LINUX)
void GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) override;
#endif
void ColorPickedInEyeDropper(int r, int g, int b, int a);
// DevTools index event callbacks.
void OnDevToolsIndexingWorkCalculated(int request_id,
const std::string& file_system_path,
int total_work);
void OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked);
void OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path);
void OnDevToolsSearchCompleted(int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths);
// Set fullscreen mode triggered by html api.
void SetHtmlApiFullscreen(bool enter_fullscreen);
// Update the html fullscreen flag in both browser and renderer.
void UpdateHtmlApiFullscreen(bool fullscreen);
v8::Global<v8::Value> session_;
v8::Global<v8::Value> devtools_web_contents_;
v8::Global<v8::Value> debugger_;
std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_;
std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
std::unique_ptr<FrameSubscriber> frame_subscriber_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
std::unique_ptr<extensions::ScriptExecutor> script_executor_;
#endif
// The host webcontents that may contain this webcontents.
WebContents* embedder_ = nullptr;
// Whether the guest view has been attached.
bool attached_ = false;
// The zoom controller for this webContents.
WebContentsZoomController* zoom_controller_ = nullptr;
// The type of current WebContents.
Type type_ = Type::kBrowserWindow;
int32_t id_;
// Request id used for findInPage request.
uint32_t find_in_page_request_id_ = 0;
// Whether background throttling is disabled.
bool background_throttling_ = true;
// Whether to enable devtools.
bool enable_devtools_ = true;
// Observers of this WebContents.
base::ObserverList<ExtendedWebContentsObserver> observers_;
v8::Global<v8::Value> pending_child_web_preferences_;
// The window that this WebContents belongs to.
base::WeakPtr<NativeWindow> owner_window_;
bool offscreen_ = false;
// Whether window is fullscreened by HTML5 api.
bool html_fullscreen_ = false;
// Whether window is fullscreened by window api.
bool native_fullscreen_ = false;
scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_;
std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_;
std::unique_ptr<DevToolsEyeDropper> eye_dropper_;
ElectronBrowserContext* browser_context_;
// The stored InspectableWebContents object.
// Notice that inspectable_web_contents_ must be placed after
// dialog_manager_, so we can make sure inspectable_web_contents_ is
// destroyed before dialog_manager_, otherwise a crash would happen.
std::unique_ptr<InspectableWebContents> inspectable_web_contents_;
// Maps url to file path, used by the file requests sent from devtools.
typedef std::map<std::string, base::FilePath> PathsMap;
PathsMap saved_files_;
// Map id to index job, used for file system indexing requests from devtools.
typedef std::
map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>>
DevToolsIndexingJobsMap;
DevToolsIndexingJobsMap devtools_indexing_jobs_;
scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
#if BUILDFLAG(ENABLE_PRINTING)
scoped_refptr<base::TaskRunner> print_task_runner_;
#endif
// Stores the frame thats currently in fullscreen, nullptr if there is none.
content::RenderFrameHost* fullscreen_frame_ = nullptr;
std::unique_ptr<SkRegion> draggable_region_;
base::WeakPtrFactory<WebContents> weak_factory_{this};
};
} // namespace api
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/ui/inspectable_web_contents.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "shell/browser/ui/inspectable_web_contents.h"
#include <memory>
#include <utility>
#include "base/base64.h"
#include "base/guid.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/json/string_escape.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/user_agent.h"
#include "ipc/ipc_channel.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/net/asar/asar_url_loader_factory.h"
#include "shell/browser/protocol_registry.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "shell/common/platform_util.h"
#include "third_party/blink/public/common/logging/logging_utils.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#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/permissions/permissions_data.h"
#include "shell/browser/electron_browser_context.h"
#endif
namespace electron {
namespace {
const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9,
1.0, 1.1, 1.25, 1.5, 1.75, 2.0,
2.5, 3.0, 4.0, 5.0};
const char kChromeUIDevToolsURL[] =
"devtools://devtools/bundled/devtools_app.html?"
"remoteBase=%s&"
"can_dock=%s&"
"toolbarColor=rgba(223,223,223,1)&"
"textColor=rgba(0,0,0,1)&"
"experiments=true";
const char kChromeUIDevToolsRemoteFrontendBase[] =
"https://chrome-devtools-frontend.appspot.com/";
const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file";
const char kDevToolsBoundsPref[] = "electron.devtools.bounds";
const char kDevToolsZoomPref[] = "electron.devtools.zoom";
const char kDevToolsPreferences[] = "electron.devtools.preferences";
const char kFrontendHostId[] = "id";
const char kFrontendHostMethod[] = "method";
const char kFrontendHostParams[] = "params";
const char kTitleFormat[] = "Developer Tools - %s";
const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;
// Stores all instances of InspectableWebContents.
InspectableWebContents::List g_web_contents_instances_;
base::Value RectToDictionary(const gfx::Rect& bounds) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetKey("x", base::Value(bounds.x()));
dict.SetKey("y", base::Value(bounds.y()));
dict.SetKey("width", base::Value(bounds.width()));
dict.SetKey("height", base::Value(bounds.height()));
return dict;
}
gfx::Rect DictionaryToRect(const base::Value* dict) {
const base::Value* found = dict->FindKey("x");
int x = found ? found->GetInt() : 0;
found = dict->FindKey("y");
int y = found ? found->GetInt() : 0;
found = dict->FindKey("width");
int width = found ? found->GetInt() : 800;
found = dict->FindKey("height");
int height = found ? found->GetInt() : 600;
return gfx::Rect(x, y, width, height);
}
bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) {
return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) &&
point.y() > rect.y() && point.y() < (rect.height() + rect.y());
}
bool IsPointInScreen(const gfx::Point& point) {
for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) {
if (IsPointInRect(point, display.bounds()))
return true;
}
return false;
}
void SetZoomLevelForWebContents(content::WebContents* web_contents,
double level) {
content::HostZoomMap::SetZoomLevel(web_contents, level);
}
double GetNextZoomLevel(double level, bool out) {
double factor = blink::PageZoomLevelToZoomFactor(level);
size_t size = std::size(kPresetZoomFactors);
for (size_t i = 0; i < size; ++i) {
if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor))
continue;
if (out && i > 0)
return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]);
if (!out && i != size - 1)
return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]);
}
return level;
}
GURL GetRemoteBaseURL() {
return GURL(base::StringPrintf("%s%s/%s/",
kChromeUIDevToolsRemoteFrontendBase,
kChromeUIDevToolsRemoteFrontendPath,
content::GetChromiumGitRevision().c_str()));
}
GURL GetDevToolsURL(bool can_dock) {
auto url_string = base::StringPrintf(kChromeUIDevToolsURL,
GetRemoteBaseURL().spec().c_str(),
can_dock ? "true" : "");
return GURL(url_string);
}
void OnOpenItemComplete(const base::FilePath& path, const std::string& result) {
platform_util::ShowItemInFolder(path);
}
constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250);
constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10);
} // namespace
class InspectableWebContents::NetworkResourceLoader
: public network::SimpleURLLoaderStreamConsumer {
public:
class URLLoaderFactoryHolder {
public:
network::mojom::URLLoaderFactory* get() {
return ptr_.get() ? ptr_.get() : refptr_.get();
}
void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) {
ptr_ = std::move(ptr);
}
void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) {
refptr_ = std::move(refptr);
}
private:
std::unique_ptr<network::mojom::URLLoaderFactory> ptr_;
scoped_refptr<network::SharedURLLoaderFactory> refptr_;
};
static void Create(int stream_id,
InspectableWebContents* bindings,
const network::ResourceRequest& resource_request,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
URLLoaderFactoryHolder url_loader_factory,
DispatchCallback callback,
base::TimeDelta retry_delay = base::TimeDelta()) {
auto resource_loader =
std::make_unique<InspectableWebContents::NetworkResourceLoader>(
stream_id, bindings, resource_request, traffic_annotation,
std::move(url_loader_factory), std::move(callback), retry_delay);
bindings->loaders_.insert(std::move(resource_loader));
}
NetworkResourceLoader(
int stream_id,
InspectableWebContents* bindings,
const network::ResourceRequest& resource_request,
const net::NetworkTrafficAnnotationTag& traffic_annotation,
URLLoaderFactoryHolder url_loader_factory,
DispatchCallback callback,
base::TimeDelta delay)
: stream_id_(stream_id),
bindings_(bindings),
resource_request_(resource_request),
traffic_annotation_(traffic_annotation),
loader_(network::SimpleURLLoader::Create(
std::make_unique<network::ResourceRequest>(resource_request),
traffic_annotation)),
url_loader_factory_(std::move(url_loader_factory)),
callback_(std::move(callback)),
retry_delay_(delay) {
loader_->SetOnResponseStartedCallback(base::BindOnce(
&NetworkResourceLoader::OnResponseStarted, base::Unretained(this)));
timer_.Start(FROM_HERE, delay,
base::BindRepeating(&NetworkResourceLoader::DownloadAsStream,
base::Unretained(this)));
}
NetworkResourceLoader(const NetworkResourceLoader&) = delete;
NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete;
private:
void DownloadAsStream() {
loader_->DownloadAsStream(url_loader_factory_.get(), this);
}
base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) {
if (delta.is_zero()) {
return kInitialBackoffDelay;
} else {
return delta * 1.3;
}
}
void OnResponseStarted(const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
response_headers_ = response_head.headers;
}
void OnDataReceived(base::StringPiece chunk,
base::OnceClosure resume) override {
base::Value chunkValue;
bool encoded = !base::IsStringUTF8(chunk);
if (encoded) {
std::string encoded_string;
base::Base64Encode(chunk, &encoded_string);
chunkValue = base::Value(std::move(encoded_string));
} else {
chunkValue = base::Value(chunk);
}
base::Value id(stream_id_);
base::Value encodedValue(encoded);
bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id),
std::move(chunkValue),
std::move(encodedValue));
std::move(resume).Run();
}
void OnComplete(bool success) override {
if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES &&
retry_delay_ < kMaxBackoffDelay) {
const base::TimeDelta delay =
GetNextExponentialBackoffDelay(retry_delay_);
LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = "
<< stream_id_
<< " failed with insufficient resources, retrying in "
<< delay << "." << std::endl;
NetworkResourceLoader::Create(
stream_id_, bindings_, resource_request_, traffic_annotation_,
std::move(url_loader_factory_), std::move(callback_), delay);
} else {
base::Value response(base::Value::Type::DICT);
response.GetDict().Set(
"statusCode", response_headers_ ? response_headers_->response_code()
: net::HTTP_OK);
base::Value::Dict headers;
size_t iterator = 0;
std::string name;
std::string value;
while (response_headers_ &&
response_headers_->EnumerateHeaderLines(&iterator, &name, &value))
headers.Set(name, value);
response.GetDict().Set("headers", std::move(headers));
std::move(callback_).Run(&response);
}
bindings_->loaders_.erase(bindings_->loaders_.find(this));
}
void OnRetry(base::OnceClosure start_retry) override {}
const int stream_id_;
InspectableWebContents* const bindings_;
const network::ResourceRequest resource_request_;
const net::NetworkTrafficAnnotationTag traffic_annotation_;
std::unique_ptr<network::SimpleURLLoader> loader_;
URLLoaderFactoryHolder url_loader_factory_;
DispatchCallback callback_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
base::OneShotTimer timer_;
base::TimeDelta retry_delay_;
};
// Implemented separately on each platform.
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents);
// static
const InspectableWebContents::List& InspectableWebContents::GetAll() {
return g_web_contents_instances_;
}
// static
void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(kDevToolsBoundsPref,
RectToDictionary(gfx::Rect(0, 0, 800, 600)));
registry->RegisterDoublePref(kDevToolsZoomPref, 0.);
registry->RegisterDictionaryPref(kDevToolsPreferences);
}
InspectableWebContents::InspectableWebContents(
std::unique_ptr<content::WebContents> web_contents,
PrefService* pref_service,
bool is_guest)
: pref_service_(pref_service),
web_contents_(std::move(web_contents)),
is_guest_(is_guest),
view_(CreateInspectableContentsView(this)) {
const base::Value* bounds_dict =
&pref_service_->GetValue(kDevToolsBoundsPref);
if (bounds_dict->is_dict()) {
devtools_bounds_ = DictionaryToRect(bounds_dict);
// Sometimes the devtools window is out of screen or has too small size.
if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) {
devtools_bounds_.set_height(600);
devtools_bounds_.set_width(800);
}
if (!IsPointInScreen(devtools_bounds_.origin())) {
gfx::Rect display;
if (!is_guest && web_contents_->GetNativeView()) {
display = display::Screen::GetScreen()
->GetDisplayNearestView(web_contents_->GetNativeView())
.bounds();
} else {
display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds();
}
devtools_bounds_.set_x(display.x() +
(display.width() - devtools_bounds_.width()) / 2);
devtools_bounds_.set_y(
display.y() + (display.height() - devtools_bounds_.height()) / 2);
}
}
g_web_contents_instances_.push_back(this);
}
InspectableWebContents::~InspectableWebContents() {
g_web_contents_instances_.remove(this);
// Unsubscribe from devtools and Clean up resources.
if (GetDevToolsWebContents())
WebContentsDestroyed();
// Let destructor destroy managed_devtools_web_contents_.
}
InspectableWebContentsView* InspectableWebContents::GetView() const {
return view_.get();
}
content::WebContents* InspectableWebContents::GetWebContents() const {
return web_contents_.get();
}
content::WebContents* InspectableWebContents::GetDevToolsWebContents() const {
if (external_devtools_web_contents_)
return external_devtools_web_contents_;
else
return managed_devtools_web_contents_.get();
}
void InspectableWebContents::InspectElement(int x, int y) {
if (agent_host_)
agent_host_->InspectElement(web_contents_->GetPrimaryMainFrame(), x, y);
}
void InspectableWebContents::SetDelegate(
InspectableWebContentsDelegate* delegate) {
delegate_ = delegate;
}
InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const {
return delegate_;
}
bool InspectableWebContents::IsGuest() const {
return is_guest_;
}
void InspectableWebContents::ReleaseWebContents() {
web_contents_.release();
WebContentsDestroyed();
view_.reset();
}
void InspectableWebContents::SetDockState(const std::string& state) {
if (state == "detach") {
can_dock_ = false;
} else {
can_dock_ = true;
dock_state_ = state;
}
}
void InspectableWebContents::SetDevToolsWebContents(
content::WebContents* devtools) {
if (!managed_devtools_web_contents_)
external_devtools_web_contents_ = devtools;
}
void InspectableWebContents::ShowDevTools(bool activate) {
if (embedder_message_dispatcher_) {
if (managed_devtools_web_contents_)
view_->ShowDevTools(activate);
return;
}
activate_ = activate;
// Show devtools only after it has done loading, this is to make sure the
// SetIsDocked is called *BEFORE* ShowDevTools.
embedder_message_dispatcher_ =
DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this);
if (!external_devtools_web_contents_) { // no external devtools
managed_devtools_web_contents_ = content::WebContents::Create(
content::WebContents::CreateParams(web_contents_->GetBrowserContext()));
managed_devtools_web_contents_->SetDelegate(this);
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
api::WebContents::FromOrCreate(isolate,
managed_devtools_web_contents_.get());
}
Observe(GetDevToolsWebContents());
AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get()));
GetDevToolsWebContents()->GetController().LoadURL(
GetDevToolsURL(can_dock_), content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string());
}
void InspectableWebContents::CloseDevTools() {
if (GetDevToolsWebContents()) {
frontend_loaded_ = false;
if (managed_devtools_web_contents_) {
view_->CloseDevTools();
managed_devtools_web_contents_.reset();
}
embedder_message_dispatcher_.reset();
if (!IsGuest())
web_contents_->Focus();
}
}
bool InspectableWebContents::IsDevToolsViewShowing() {
return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing();
}
void InspectableWebContents::AttachTo(
scoped_refptr<content::DevToolsAgentHost> host) {
Detach();
agent_host_ = std::move(host);
// We could use ForceAttachClient here if problem arises with
// devtools multiple session support.
agent_host_->AttachClient(this);
}
void InspectableWebContents::Detach() {
if (agent_host_)
agent_host_->DetachClient(this);
agent_host_ = nullptr;
}
void InspectableWebContents::Reattach(DispatchCallback callback) {
if (agent_host_) {
agent_host_->DetachClient(this);
agent_host_->AttachClient(this);
}
std::move(callback).Run(nullptr);
}
void InspectableWebContents::CallClientFunction(
const std::string& object_name,
const std::string& method_name,
base::Value arg1,
base::Value arg2,
base::Value arg3,
base::OnceCallback<void(base::Value)> cb) {
if (!GetDevToolsWebContents())
return;
base::Value::List arguments;
if (!arg1.is_none()) {
arguments.Append(std::move(arg1));
if (!arg2.is_none()) {
arguments.Append(std::move(arg2));
if (!arg3.is_none()) {
arguments.Append(std::move(arg3));
}
}
}
GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScriptMethod(
base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name),
std::move(arguments), std::move(cb));
}
gfx::Rect InspectableWebContents::GetDevToolsBounds() const {
return devtools_bounds_;
}
void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) {
pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds));
devtools_bounds_ = bounds;
}
double InspectableWebContents::GetDevToolsZoomLevel() const {
return pref_service_->GetDouble(kDevToolsZoomPref);
}
void InspectableWebContents::UpdateDevToolsZoomLevel(double level) {
pref_service_->SetDouble(kDevToolsZoomPref, level);
}
void InspectableWebContents::ActivateWindow() {
// Set the zoom level.
SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel());
}
void InspectableWebContents::CloseWindow() {
GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */);
}
void InspectableWebContents::LoadCompleted() {
frontend_loaded_ = true;
if (managed_devtools_web_contents_)
view_->ShowDevTools(activate_);
// If the devtools can dock, "SetIsDocked" will be called by devtools itself.
if (!can_dock_) {
SetIsDocked(DispatchCallback(), false);
} else {
if (dock_state_.empty()) {
const base::Value::Dict& prefs =
pref_service_->GetDict(kDevToolsPreferences);
const std::string* current_dock_state =
prefs.FindString("currentDockState");
base::RemoveChars(*current_dock_state, "\"", &dock_state_);
}
std::u16string javascript = base::UTF8ToUTF16(
"UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");");
GetDevToolsWebContents()->GetPrimaryMainFrame()->ExecuteJavaScript(
javascript, base::NullCallback());
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
AddDevToolsExtensionsToClient();
#endif
if (view_->GetDelegate())
view_->GetDelegate()->DevToolsOpened();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void InspectableWebContents::AddDevToolsExtensionsToClient() {
// get main browser context
auto* browser_context = web_contents_->GetBrowserContext();
const extensions::ExtensionRegistry* registry =
extensions::ExtensionRegistry::Get(browser_context);
if (!registry)
return;
base::Value::List results;
for (auto& extension : registry->enabled_extensions()) {
auto devtools_page_url =
extensions::chrome_manifest_urls::GetDevToolsPage(extension.get());
if (devtools_page_url.is_empty())
continue;
// Each devtools extension will need to be able to run in the devtools
// process. Grant the devtools process the ability to request URLs from the
// extension.
content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin(
web_contents_->GetPrimaryMainFrame()->GetProcess()->GetID(),
url::Origin::Create(extension->url()));
base::Value::Dict extension_info;
extension_info.Set("startPage", devtools_page_url.spec());
extension_info.Set("name", extension->name());
extension_info.Set("exposeExperimentalAPIs",
extension->permissions_data()->HasAPIPermission(
extensions::mojom::APIPermissionID::kExperimental));
results.Append(base::Value(std::move(extension_info)));
}
CallClientFunction("DevToolsAPI", "addExtensions",
base::Value(std::move(results)));
}
#endif
void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) {
DevToolsContentsResizingStrategy strategy(rect);
if (contents_resizing_strategy_.Equals(strategy))
return;
contents_resizing_strategy_.CopyFrom(strategy);
if (managed_devtools_web_contents_)
view_->SetContentsResizingStrategy(contents_resizing_strategy_);
}
void InspectableWebContents::InspectElementCompleted() {}
void InspectableWebContents::InspectedURLChanged(const std::string& url) {
if (managed_devtools_web_contents_)
view_->SetTitle(
base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str())));
}
void InspectableWebContents::LoadNetworkResource(DispatchCallback callback,
const std::string& url,
const std::string& headers,
int stream_id) {
GURL gurl(url);
if (!gurl.is_valid()) {
base::Value response(base::Value::Type::DICT);
response.GetDict().Set("statusCode", net::HTTP_NOT_FOUND);
std::move(callback).Run(&response);
return;
}
// Create traffic annotation tag.
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"(
semantics {
sender: "Developer Tools"
description:
"When user opens Developer Tools, the browser may fetch additional "
"resources from the network to enrich the debugging experience "
"(e.g. source map resources)."
trigger: "User opens Developer Tools to debug a web page."
data: "Any resources requested by Developer Tools."
destination: WEBSITE
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting:
"It's not possible to disable this feature from settings."
})");
network::ResourceRequest resource_request;
resource_request.url = gurl;
resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl);
resource_request.headers.AddHeadersFromString(headers);
auto* protocol_registry = ProtocolRegistry::FromBrowserContext(
GetDevToolsWebContents()->GetBrowserContext());
NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory;
if (gurl.SchemeIsFile()) {
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
AsarURLLoaderFactory::Create();
url_loader_factory = network::SharedURLLoaderFactory::Create(
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
std::move(pending_remote)));
} else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) {
auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme());
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
ElectronURLLoaderFactory::Create(protocol_handler.first,
protocol_handler.second);
url_loader_factory = network::SharedURLLoaderFactory::Create(
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
std::move(pending_remote)));
} else {
auto* partition = GetDevToolsWebContents()
->GetBrowserContext()
->GetDefaultStoragePartition();
url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess();
}
NetworkResourceLoader::Create(
stream_id, this, resource_request, traffic_annotation,
std::move(url_loader_factory), std::move(callback));
}
void InspectableWebContents::SetIsDocked(DispatchCallback callback,
bool docked) {
if (managed_devtools_web_contents_)
view_->SetIsDocked(docked, activate_);
if (!callback.is_null())
std::move(callback).Run(nullptr);
}
void InspectableWebContents::OpenInNewTab(const std::string& url) {}
void InspectableWebContents::ShowItemInFolder(
const std::string& file_system_path) {
if (file_system_path.empty())
return;
base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path);
platform_util::OpenPath(path.DirName(),
base::BindOnce(&OnOpenItemComplete, path));
}
void InspectableWebContents::SaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
if (delegate_)
delegate_->DevToolsSaveToFile(url, content, save_as);
}
void InspectableWebContents::AppendToFile(const std::string& url,
const std::string& content) {
if (delegate_)
delegate_->DevToolsAppendToFile(url, content);
}
void InspectableWebContents::RequestFileSystems() {
if (delegate_)
delegate_->DevToolsRequestFileSystems();
}
void InspectableWebContents::AddFileSystem(const std::string& type) {
if (delegate_)
delegate_->DevToolsAddFileSystem(type, base::FilePath());
}
void InspectableWebContents::RemoveFileSystem(
const std::string& file_system_path) {
if (delegate_)
delegate_->DevToolsRemoveFileSystem(
base::FilePath::FromUTF8Unsafe(file_system_path));
}
void InspectableWebContents::UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) {}
void InspectableWebContents::IndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders) {
if (delegate_)
delegate_->DevToolsIndexPath(request_id, file_system_path,
excluded_folders);
}
void InspectableWebContents::StopIndexing(int request_id) {
if (delegate_)
delegate_->DevToolsStopIndexing(request_id);
}
void InspectableWebContents::SearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (delegate_)
delegate_->DevToolsSearchInPath(request_id, file_system_path, query);
}
void InspectableWebContents::SetWhitelistedShortcuts(
const std::string& message) {}
void InspectableWebContents::SetEyeDropperActive(bool active) {
if (delegate_)
delegate_->DevToolsSetEyeDropperActive(active);
}
void InspectableWebContents::ShowCertificateViewer(
const std::string& cert_chain) {}
void InspectableWebContents::ZoomIn() {
double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false);
SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level);
UpdateDevToolsZoomLevel(new_level);
}
void InspectableWebContents::ZoomOut() {
double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true);
SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level);
UpdateDevToolsZoomLevel(new_level);
}
void InspectableWebContents::ResetZoom() {
SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.);
UpdateDevToolsZoomLevel(0.);
}
void InspectableWebContents::SetDevicesDiscoveryConfig(
bool discover_usb_devices,
bool port_forwarding_enabled,
const std::string& port_forwarding_config,
bool network_discovery_enabled,
const std::string& network_discovery_config) {}
void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {}
void InspectableWebContents::PerformActionOnRemotePage(
const std::string& page_id,
const std::string& action) {}
void InspectableWebContents::OpenRemotePage(const std::string& browser_id,
const std::string& url) {}
void InspectableWebContents::OpenNodeFrontend() {}
void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend(
const std::string& message) {
// If the devtools wants to reload the page, hijack the message and handle it
// to the delegate.
if (base::MatchPattern(message,
"{\"id\":*,"
"\"method\":\"Page.reload\","
"\"params\":*}")) {
if (delegate_)
delegate_->DevToolsReloadPage();
return;
}
if (agent_host_)
agent_host_->DispatchProtocolMessage(
this, base::as_bytes(base::make_span(message)));
}
void InspectableWebContents::SendJsonRequest(DispatchCallback callback,
const std::string& browser_id,
const std::string& url) {
std::move(callback).Run(nullptr);
}
void InspectableWebContents::GetPreferences(DispatchCallback callback) {
const base::Value& prefs = pref_service_->GetValue(kDevToolsPreferences);
std::move(callback).Run(&prefs);
}
void InspectableWebContents::GetPreference(DispatchCallback callback,
const std::string& name) {
if (auto* pref = pref_service_->GetDict(kDevToolsPreferences).Find(name)) {
std::move(callback).Run(pref);
return;
}
// Pref wasn't found, return an empty value
base::Value no_pref;
std::move(callback).Run(&no_pref);
}
void InspectableWebContents::SetPreference(const std::string& name,
const std::string& value) {
ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences);
update->Set(name, base::Value(value));
}
void InspectableWebContents::RemovePreference(const std::string& name) {
ScopedDictPrefUpdate update(pref_service_, kDevToolsPreferences);
update->Remove(name);
}
void InspectableWebContents::ClearPreferences() {
ScopedDictPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences);
unsynced_update->clear();
}
void InspectableWebContents::GetSyncInformation(DispatchCallback callback) {
base::Value result(base::Value::Type::DICTIONARY);
result.SetBoolKey("isSyncActive", false);
std::move(callback).Run(&result);
}
void InspectableWebContents::ConnectionReady() {}
void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin,
const std::string& script) {
extensions_api_[origin + "/"] = script;
}
void InspectableWebContents::HandleMessageFromDevToolsFrontend(
base::Value::Dict message) {
// TODO(alexeykuzmin): Should we expect it to exist?
if (!embedder_message_dispatcher_) {
return;
}
const std::string* method = message.FindString(kFrontendHostMethod);
base::Value* params = message.Find(kFrontendHostParams);
if (!method || (params && !params->is_list())) {
LOG(ERROR) << "Invalid message was sent to embedder: " << message;
return;
}
const base::Value::List no_params;
const base::Value::List& params_list =
params != nullptr && params->is_list() ? params->GetList() : no_params;
const int id = message.FindInt(kFrontendHostId).value_or(0);
embedder_message_dispatcher_->Dispatch(
base::BindRepeating(&InspectableWebContents::SendMessageAck,
weak_factory_.GetWeakPtr(), id),
*method, params_list);
}
void InspectableWebContents::DispatchProtocolMessage(
content::DevToolsAgentHost* agent_host,
base::span<const uint8_t> message) {
if (!frontend_loaded_)
return;
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()),
message.size());
if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message)));
} else {
size_t total_size = str_message.length();
for (size_t pos = 0; pos < str_message.length();
pos += kMaxMessageChunkSize) {
base::StringPiece str_message_chunk =
str_message.substr(pos, kMaxMessageChunkSize);
CallClientFunction(
"DevToolsAPI", "dispatchMessageChunk",
base::Value(std::string(str_message_chunk)),
base::Value(base::NumberToString(pos ? 0 : total_size)));
}
}
}
void InspectableWebContents::AgentHostClosed(
content::DevToolsAgentHost* agent_host) {}
void InspectableWebContents::RenderFrameHostChanged(
content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->GetParent())
return;
frontend_host_ = content::DevToolsFrontendHost::Create(
new_host, base::BindRepeating(
&InspectableWebContents::HandleMessageFromDevToolsFrontend,
weak_factory_.GetWeakPtr()));
}
void InspectableWebContents::WebContentsDestroyed() {
if (managed_devtools_web_contents_)
managed_devtools_web_contents_->SetDelegate(nullptr);
frontend_loaded_ = false;
external_devtools_web_contents_ = nullptr;
Observe(nullptr);
Detach();
embedder_message_dispatcher_.reset();
if (view_ && view_->GetDelegate())
view_->GetDelegate()->DevToolsClosed();
}
bool InspectableWebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
auto* delegate = web_contents_->GetDelegate();
return !delegate || delegate->HandleKeyboardEvent(source, event);
}
void InspectableWebContents::CloseContents(content::WebContents* source) {
// This is where the devtools closes itself (by clicking the x button).
CloseDevTools();
}
void InspectableWebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
auto* delegate = web_contents_->GetDelegate();
if (delegate)
delegate->RunFileChooser(render_frame_host, std::move(listener), params);
}
void InspectableWebContents::EnumerateDirectory(
content::WebContents* source,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
auto* delegate = web_contents_->GetDelegate();
if (delegate)
delegate->EnumerateDirectory(source, std::move(listener), path);
}
void InspectableWebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
#if defined(TOOLKIT_VIEWS)
if (view_->GetDelegate())
view_->GetDelegate()->DevToolsFocused();
#endif
}
void InspectableWebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsInMainFrame()) {
if (navigation_handle->GetRenderFrameHost() ==
GetDevToolsWebContents()->GetPrimaryMainFrame() &&
frontend_host_) {
return;
}
frontend_host_ = content::DevToolsFrontendHost::Create(
web_contents()->GetPrimaryMainFrame(),
base::BindRepeating(
&InspectableWebContents::HandleMessageFromDevToolsFrontend,
base::Unretained(this)));
return;
}
}
void InspectableWebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsInMainFrame() ||
!navigation_handle->GetURL().SchemeIs("chrome-extension") ||
!navigation_handle->HasCommitted())
return;
content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost();
auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec();
auto it = extensions_api_.find(origin);
if (it == extensions_api_.end())
return;
// Injected Script from devtools frontend doesn't expose chrome,
// most likely bug in chromium.
base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome",
"var chrome = window.chrome ");
auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(),
base::GenerateGUID().c_str());
// Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script);
// should be enough, but it seems to be a noop currently.
frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script),
base::NullCallback());
}
void InspectableWebContents::SendMessageAck(int request_id,
const base::Value* arg) {
if (arg) {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id), arg->Clone());
} else {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id));
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,715 |
[Bug]: Developer tools click link does not create a new page
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
19.0.17
### What operating system are you using?
Windows
### Operating System Version
windows 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior

click the link should create a new page
### Actual Behavior
but nothing happen
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/36715
|
https://github.com/electron/electron/pull/36774
|
8d008c977df465d3ad96dd6c8c3daa7afd8bea5f
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
| 2022-12-21T01:42:46Z |
c++
| 2023-01-26T08:54:26Z |
shell/browser/ui/inspectable_web_contents_delegate.h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
#define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
#include <string>
#include "base/files/file_path.h"
namespace electron {
class InspectableWebContentsDelegate {
public:
virtual ~InspectableWebContentsDelegate() {}
// Requested by WebContents of devtools.
virtual void DevToolsReloadPage() {}
virtual void DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {}
virtual void DevToolsAppendToFile(const std::string& url,
const std::string& content) {}
virtual void DevToolsRequestFileSystems() {}
virtual void DevToolsAddFileSystem(const std::string& type,
const base::FilePath& file_system_path) {}
virtual void DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {}
virtual void DevToolsIndexPath(int request_id,
const std::string& file_system_path,
const std::string& excluded_folders) {}
virtual void DevToolsStopIndexing(int request_id) {}
virtual void DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {}
virtual void DevToolsSetEyeDropperActive(bool active) {}
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_DELEGATE_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
BUILD.gn
|
import("//build/config/locales.gni")
import("//build/config/ui.gni")
import("//build/config/win/manifest.gni")
import("//components/os_crypt/features.gni")
import("//components/spellcheck/spellcheck_build_features.gni")
import("//content/public/app/mac_helpers.gni")
import("//extensions/buildflags/buildflags.gni")
import("//pdf/features.gni")
import("//ppapi/buildflags/buildflags.gni")
import("//printing/buildflags/buildflags.gni")
import("//testing/test.gni")
import("//third_party/ffmpeg/ffmpeg_options.gni")
import("//tools/generate_library_loader/generate_library_loader.gni")
import("//tools/grit/grit_rule.gni")
import("//tools/grit/repack.gni")
import("//tools/v8_context_snapshot/v8_context_snapshot.gni")
import("//v8/gni/snapshot_toolchain.gni")
import("build/asar.gni")
import("build/extract_symbols.gni")
import("build/npm.gni")
import("build/templated_file.gni")
import("build/tsc.gni")
import("build/webpack/webpack.gni")
import("buildflags/buildflags.gni")
import("electron_paks.gni")
import("filenames.auto.gni")
import("filenames.gni")
import("filenames.hunspell.gni")
import("filenames.libcxx.gni")
import("filenames.libcxxabi.gni")
if (is_mac) {
import("//build/config/mac/rules.gni")
import("//third_party/icu/config.gni")
import("//ui/gl/features.gni")
import("//v8/gni/v8.gni")
import("build/rules.gni")
assert(
mac_deployment_target == "10.13",
"Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change")
}
if (is_linux) {
import("//build/config/linux/pkg_config.gni")
import("//tools/generate_stubs/rules.gni")
pkg_config("gio_unix") {
packages = [ "gio-unix-2.0" ]
}
pkg_config("libnotify_config") {
packages = [
"glib-2.0",
"gdk-pixbuf-2.0",
]
}
generate_library_loader("libnotify_loader") {
name = "LibNotifyLoader"
output_h = "libnotify_loader.h"
output_cc = "libnotify_loader.cc"
header = "<libnotify/notify.h>"
config = ":libnotify_config"
functions = [
"notify_is_initted",
"notify_init",
"notify_get_server_caps",
"notify_get_server_info",
"notify_notification_new",
"notify_notification_add_action",
"notify_notification_set_image_from_pixbuf",
"notify_notification_set_timeout",
"notify_notification_set_urgency",
"notify_notification_set_hint_string",
"notify_notification_show",
"notify_notification_close",
]
}
# Generates electron_gtk_stubs.h header which contains
# stubs for extracting function ptrs from the gtk library.
# Function signatures for which stubs are required should be
# declared in electron_gtk.sigs, currently this file contains
# signatures for the functions used with native file chooser
# implementation. In future, this file can be extended to contain
# gtk4 stubs to switch gtk version in runtime.
generate_stubs("electron_gtk_stubs") {
sigs = [
"shell/browser/ui/electron_gdk_pixbuf.sigs",
"shell/browser/ui/electron_gtk.sigs",
]
extra_header = "shell/browser/ui/electron_gtk.fragment"
output_name = "electron_gtk_stubs"
public_deps = [ "//ui/gtk:gtk_config" ]
logging_function = "LogNoop()"
logging_include = "ui/gtk/log_noop.h"
}
}
declare_args() {
use_prebuilt_v8_context_snapshot = false
}
branding = read_file("shell/app/BRANDING.json", "json")
electron_project_name = branding.project_name
electron_product_name = branding.product_name
electron_mac_bundle_id = branding.mac_bundle_id
electron_version = exec_script("script/print-version.py",
[],
"trim string",
[
".git/packed-refs",
".git/HEAD",
"script/lib/get-version.js",
])
if (is_mas_build) {
assert(is_mac,
"It doesn't make sense to build a MAS build on a non-mac platform")
}
if (enable_pdf_viewer) {
assert(enable_pdf, "PDF viewer support requires enable_pdf=true")
assert(enable_electron_extensions,
"PDF viewer support requires enable_electron_extensions=true")
}
if (enable_electron_extensions) {
assert(enable_extensions,
"Chrome extension support requires enable_extensions=true")
}
config("branding") {
defines = [
"ELECTRON_PRODUCT_NAME=\"$electron_product_name\"",
"ELECTRON_PROJECT_NAME=\"$electron_project_name\"",
]
}
config("electron_lib_config") {
include_dirs = [ "." ]
}
# We generate the definitions twice here, once in //electron/electron.d.ts
# and once in $target_gen_dir
# The one in $target_gen_dir is used for the actual TSC build later one
# and the one in //electron/electron.d.ts is used by your IDE (vscode)
# for typescript prompting
npm_action("build_electron_definitions") {
script = "gn-typescript-definitions"
args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ]
inputs = auto_filenames.api_docs + [ "yarn.lock" ]
outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ]
}
webpack_build("electron_asar_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.asar_bundle_deps
config_file = "//electron/build/webpack/webpack.config.asar.js"
out_file = "$target_gen_dir/js2c/asar_bundle.js"
}
webpack_build("electron_browser_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.browser_bundle_deps
config_file = "//electron/build/webpack/webpack.config.browser.js"
out_file = "$target_gen_dir/js2c/browser_init.js"
}
webpack_build("electron_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.renderer_bundle_deps
config_file = "//electron/build/webpack/webpack.config.renderer.js"
out_file = "$target_gen_dir/js2c/renderer_init.js"
}
webpack_build("electron_worker_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.worker_bundle_deps
config_file = "//electron/build/webpack/webpack.config.worker.js"
out_file = "$target_gen_dir/js2c/worker_init.js"
}
webpack_build("electron_sandboxed_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.sandbox_bundle_deps
config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js"
out_file = "$target_gen_dir/js2c/sandbox_bundle.js"
}
webpack_build("electron_isolated_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.isolated_bundle_deps
config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js"
out_file = "$target_gen_dir/js2c/isolated_bundle.js"
}
webpack_build("electron_utility_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.utility_bundle_deps
config_file = "//electron/build/webpack/webpack.config.utility.js"
out_file = "$target_gen_dir/js2c/utility_init.js"
}
action("electron_js2c") {
deps = [
":electron_asar_bundle",
":electron_browser_bundle",
":electron_isolated_renderer_bundle",
":electron_renderer_bundle",
":electron_sandboxed_renderer_bundle",
":electron_utility_bundle",
":electron_worker_bundle",
]
sources = [
"$target_gen_dir/js2c/asar_bundle.js",
"$target_gen_dir/js2c/browser_init.js",
"$target_gen_dir/js2c/isolated_bundle.js",
"$target_gen_dir/js2c/renderer_init.js",
"$target_gen_dir/js2c/sandbox_bundle.js",
"$target_gen_dir/js2c/utility_init.js",
"$target_gen_dir/js2c/worker_init.js",
]
inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ]
outputs = [ "$root_gen_dir/electron_natives.cc" ]
script = "build/js2c.py"
args = [ rebase_path("//third_party/electron_node") ] +
rebase_path(outputs, root_build_dir) +
rebase_path(sources, root_build_dir)
}
action("generate_config_gypi") {
outputs = [ "$root_gen_dir/config.gypi" ]
script = "script/generate-config-gypi.py"
inputs = [ "//third_party/electron_node/configure.py" ]
args = rebase_path(outputs) + [ target_cpu ]
}
target_gen_default_app_js = "$target_gen_dir/js/default_app"
typescript_build("default_app_js") {
deps = [ ":build_electron_definitions" ]
sources = filenames.default_app_ts_sources
output_gen_dir = target_gen_default_app_js
output_dir_name = "default_app"
tsconfig = "tsconfig.default_app.json"
}
copy("default_app_static") {
sources = filenames.default_app_static_sources
outputs = [ "$target_gen_default_app_js/{{source}}" ]
}
copy("default_app_octicon_deps") {
sources = filenames.default_app_octicon_sources
outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ]
}
asar("default_app_asar") {
deps = [
":default_app_js",
":default_app_octicon_deps",
":default_app_static",
]
root = "$target_gen_default_app_js/electron/default_app"
sources = get_target_outputs(":default_app_js") +
get_target_outputs(":default_app_static") +
get_target_outputs(":default_app_octicon_deps")
outputs = [ "$root_out_dir/resources/default_app.asar" ]
}
grit("resources") {
source = "electron_resources.grd"
outputs = [
"grit/electron_resources.h",
"electron_resources.pak",
]
# Mojo manifest overlays are generated.
grit_flags = [
"-E",
"target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir),
]
deps = [ ":copy_shell_devtools_discovery_page" ]
output_dir = "$target_gen_dir"
}
copy("copy_shell_devtools_discovery_page") {
sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ]
outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ]
}
npm_action("electron_version_args") {
script = "generate-version-json"
outputs = [ "$target_gen_dir/electron_version.args" ]
args = rebase_path(outputs) + [ "$electron_version" ]
inputs = [ "script/generate-version-json.js" ]
}
templated_file("electron_version_header") {
deps = [ ":electron_version_args" ]
template = "build/templates/electron_version.tmpl"
output = "$target_gen_dir/electron_version.h"
args_files = get_target_outputs(":electron_version_args")
}
templated_file("electron_win_rc") {
deps = [ ":electron_version_args" ]
template = "build/templates/electron_rc.tmpl"
output = "$target_gen_dir/win-resources/electron.rc"
args_files = get_target_outputs(":electron_version_args")
}
copy("electron_win_resource_files") {
sources = [
"shell/browser/resources/win/electron.ico",
"shell/browser/resources/win/resource.h",
]
outputs = [ "$target_gen_dir/win-resources/{{source_file_part}}" ]
}
templated_file("electron_version_file") {
deps = [ ":electron_version_args" ]
template = "build/templates/version_string.tmpl"
output = "$root_build_dir/version"
args_files = get_target_outputs(":electron_version_args")
}
group("electron_win32_resources") {
public_deps = [
":electron_win_rc",
":electron_win_resource_files",
]
}
action("electron_fuses") {
script = "build/fuses/build.py"
inputs = [ "build/fuses/fuses.json5" ]
outputs = [
"$target_gen_dir/fuses.h",
"$target_gen_dir/fuses.cc",
]
args = rebase_path(outputs)
}
action("electron_generate_node_defines") {
script = "build/generate_node_defines.py"
inputs = [
"//third_party/electron_node/src/tracing/trace_event_common.h",
"//third_party/electron_node/src/tracing/trace_event.h",
"//third_party/electron_node/src/util.h",
]
outputs = [
"$target_gen_dir/push_and_undef_node_defines.h",
"$target_gen_dir/pop_node_defines.h",
]
args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs)
}
source_set("electron_lib") {
configs += [ "//v8:external_startup_data" ]
configs += [ "//third_party/electron_node:node_internals" ]
public_configs = [
":branding",
":electron_lib_config",
]
deps = [
":electron_fuses",
":electron_generate_node_defines",
":electron_js2c",
":electron_version_header",
":resources",
"buildflags",
"chromium_src:chrome",
"chromium_src:chrome_spellchecker",
"shell/common/api:mojo",
"shell/services/node/public/mojom",
"//base:base_static",
"//base/allocator:buildflags",
"//chrome:strings",
"//chrome/app:command_ids",
"//chrome/app/resources:platform_locale_settings",
"//components/autofill/core/common:features",
"//components/certificate_transparency",
"//components/embedder_support:browser_util",
"//components/language/core/browser",
"//components/net_log",
"//components/network_hints/browser",
"//components/network_hints/common:mojo_bindings",
"//components/network_hints/renderer",
"//components/network_session_configurator/common",
"//components/omnibox/browser:buildflags",
"//components/os_crypt",
"//components/pref_registry",
"//components/prefs",
"//components/security_state/content",
"//components/upload_list",
"//components/user_prefs",
"//components/viz/host",
"//components/viz/service",
"//components/webrtc",
"//content/public/browser",
"//content/public/child",
"//content/public/gpu",
"//content/public/renderer",
"//content/public/utility",
"//device/bluetooth",
"//device/bluetooth/public/cpp",
"//gin",
"//media/capture/mojom:video_capture",
"//media/mojo/mojom",
"//net:extras",
"//net:net_resources",
"//printing/buildflags",
"//services/device/public/cpp/geolocation",
"//services/device/public/cpp/hid",
"//services/device/public/mojom",
"//services/proxy_resolver:lib",
"//services/video_capture/public/mojom:constants",
"//services/viz/privileged/mojom/compositing",
"//skia",
"//third_party/blink/public:blink",
"//third_party/blink/public:blink_devtools_inspector_resources",
"//third_party/blink/public/platform/media",
"//third_party/boringssl",
"//third_party/electron_node:node_lib",
"//third_party/inspector_protocol:crdtp",
"//third_party/leveldatabase",
"//third_party/libyuv",
"//third_party/webrtc_overrides:webrtc_component",
"//third_party/widevine/cdm:headers",
"//third_party/zlib/google:zip",
"//ui/base/idle",
"//ui/events:dom_keycode_converter",
"//ui/gl",
"//ui/native_theme",
"//ui/shell_dialogs",
"//ui/views",
"//v8",
"//v8:v8_libplatform",
]
public_deps = [
"//base",
"//base:i18n",
"//content/public/app",
]
include_dirs = [
".",
"$target_gen_dir",
# TODO(nornagon): replace usage of SchemeRegistry by an actually exported
# API of blink, then remove this from the include_dirs.
"//third_party/blink/renderer",
]
defines = [ "V8_DEPRECATION_WARNINGS" ]
libs = []
if (is_linux) {
defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ]
}
if (!is_mas_build) {
deps += [
"//components/crash/core/app",
"//components/crash/core/browser",
]
}
configs += [ "//electron/build/config:mas_build" ]
sources = filenames.lib_sources
if (is_win) {
sources += filenames.lib_sources_win
}
if (is_mac) {
sources += filenames.lib_sources_mac
}
if (is_posix) {
sources += filenames.lib_sources_posix
}
if (is_linux) {
sources += filenames.lib_sources_linux
}
if (!is_mac) {
sources += filenames.lib_sources_views
}
if (is_component_build) {
defines += [ "NODE_SHARED_MODE" ]
}
if (enable_fake_location_provider) {
sources += [
"shell/browser/fake_location_provider.cc",
"shell/browser/fake_location_provider.h",
]
}
if (is_mac) {
deps += [
"//components/remote_cocoa/app_shim",
"//components/remote_cocoa/browser",
"//content/common:mac_helpers",
"//ui/accelerated_widget_mac",
]
if (!is_mas_build) {
deps += [ "//third_party/crashpad/crashpad/client" ]
}
frameworks = [
"AVFoundation.framework",
"Carbon.framework",
"LocalAuthentication.framework",
"QuartzCore.framework",
"Quartz.framework",
"Security.framework",
"SecurityInterface.framework",
"ServiceManagement.framework",
"StoreKit.framework",
]
weak_frameworks = [ "QuickLookThumbnailing.framework" ]
sources += [
"shell/browser/ui/views/autofill_popup_view.cc",
"shell/browser/ui/views/autofill_popup_view.h",
]
if (is_mas_build) {
sources += [ "shell/browser/api/electron_api_app_mas.mm" ]
sources -= [ "shell/browser/auto_updater_mac.mm" ]
sources -= [
"shell/app/electron_crash_reporter_client.cc",
"shell/app/electron_crash_reporter_client.h",
"shell/common/crash_keys.cc",
"shell/common/crash_keys.h",
]
} else {
frameworks += [
"Squirrel.framework",
"ReactiveObjC.framework",
"Mantle.framework",
]
deps += [
"//third_party/squirrel.mac:reactiveobjc_framework+link",
"//third_party/squirrel.mac:squirrel_framework+link",
]
# ReactiveObjC which is used by Squirrel requires using __weak.
cflags_objcc = [ "-fobjc-weak" ]
}
}
if (is_linux) {
libs = [ "xshmfence" ]
deps += [
":electron_gtk_stubs",
":libnotify_loader",
"//build/config/linux/gtk",
"//components/crash/content/browser",
"//dbus",
"//device/bluetooth",
"//third_party/crashpad/crashpad/client",
"//ui/base/ime/linux",
"//ui/events/devices/x11",
"//ui/events/platform/x11",
"//ui/gtk:gtk_config",
"//ui/linux:linux_ui",
"//ui/linux:linux_ui_factory",
"//ui/views/controls/webview",
"//ui/wm",
]
if (ozone_platform_x11) {
sources += filenames.lib_sources_linux_x11
public_deps += [
"//ui/base/x",
"//ui/ozone/platform/x11",
]
}
configs += [ ":gio_unix" ]
defines += [
# Disable warnings for g_settings_list_schemas.
"GLIB_DISABLE_DEPRECATION_WARNINGS",
]
sources += [
"shell/browser/certificate_manager_model.cc",
"shell/browser/certificate_manager_model.h",
"shell/browser/ui/gtk/menu_util.cc",
"shell/browser/ui/gtk/menu_util.h",
"shell/browser/ui/gtk_util.cc",
"shell/browser/ui/gtk_util.h",
]
}
if (is_win) {
libs += [ "dwmapi.lib" ]
deps += [
"//components/crash/core/app:crash_export_thunks",
"//ui/native_theme:native_theme_browser",
"//ui/views/controls/webview",
"//ui/wm",
"//ui/wm/public",
]
public_deps += [
"//sandbox/win:sandbox",
"//third_party/crashpad/crashpad/handler",
]
}
if (enable_plugins) {
deps += [ "chromium_src:plugins" ]
sources += [
"shell/common/plugin_info.cc",
"shell/common/plugin_info.h",
"shell/renderer/electron_renderer_pepper_host_factory.cc",
"shell/renderer/electron_renderer_pepper_host_factory.h",
"shell/renderer/pepper_helper.cc",
"shell/renderer/pepper_helper.h",
]
}
if (enable_ppapi) {
deps += [
"//ppapi/host",
"//ppapi/proxy",
"//ppapi/shared_impl",
]
}
if (enable_run_as_node) {
sources += [
"shell/app/node_main.cc",
"shell/app/node_main.h",
]
}
if (enable_osr) {
sources += [
"shell/browser/osr/osr_host_display_client.cc",
"shell/browser/osr/osr_host_display_client.h",
"shell/browser/osr/osr_render_widget_host_view.cc",
"shell/browser/osr/osr_render_widget_host_view.h",
"shell/browser/osr/osr_video_consumer.cc",
"shell/browser/osr/osr_video_consumer.h",
"shell/browser/osr/osr_view_proxy.cc",
"shell/browser/osr/osr_view_proxy.h",
"shell/browser/osr/osr_web_contents_view.cc",
"shell/browser/osr/osr_web_contents_view.h",
]
if (is_mac) {
sources += [
"shell/browser/osr/osr_host_display_client_mac.mm",
"shell/browser/osr/osr_web_contents_view_mac.mm",
]
}
deps += [
"//components/viz/service",
"//services/viz/public/mojom",
"//ui/compositor",
]
}
if (enable_desktop_capturer) {
sources += [
"shell/browser/api/electron_api_desktop_capturer.cc",
"shell/browser/api/electron_api_desktop_capturer.h",
]
}
if (enable_views_api) {
sources += [
"shell/browser/api/views/electron_api_image_view.cc",
"shell/browser/api/views/electron_api_image_view.h",
]
}
if (enable_printing) {
sources += [
"shell/browser/printing/print_view_manager_electron.cc",
"shell/browser/printing/print_view_manager_electron.h",
"shell/renderer/printing/print_render_frame_helper_delegate.cc",
"shell/renderer/printing/print_render_frame_helper_delegate.h",
]
deps += [
"//chrome/services/printing/public/mojom",
"//components/printing/common:mojo_interfaces",
]
if (is_mac) {
deps += [ "//chrome/services/mac_notifications/public/mojom" ]
}
}
if (enable_electron_extensions) {
sources += filenames.lib_sources_extensions
deps += [
"shell/browser/extensions/api:api_registration",
"shell/common/extensions/api",
"shell/common/extensions/api:extensions_features",
"//chrome/browser/resources:component_extension_resources",
"//components/update_client:update_client",
"//components/zoom",
"//extensions/browser",
"//extensions/browser/api:api_provider",
"//extensions/browser/updater",
"//extensions/common",
"//extensions/common:core_api_provider",
"//extensions/renderer",
]
}
if (enable_pdf) {
# Printing depends on some //pdf code, so it needs to be built even if the
# pdf viewer isn't enabled.
deps += [
"//pdf",
"//pdf:features",
]
}
if (enable_pdf_viewer) {
deps += [
"//chrome/browser/resources/pdf:resources",
"//components/pdf/browser",
"//components/pdf/browser:interceptors",
"//components/pdf/common",
"//components/pdf/renderer",
"//pdf",
]
sources += [
"shell/browser/electron_pdf_web_contents_helper_client.cc",
"shell/browser/electron_pdf_web_contents_helper_client.h",
]
}
sources += get_target_outputs(":electron_fuses")
if (allow_runtime_configurable_key_storage) {
defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ]
}
}
electron_paks("packed_resources") {
if (is_mac) {
output_dir = "$root_gen_dir/electron_repack"
copy_data_to_bundle = true
} else {
output_dir = root_out_dir
}
}
if (is_mac) {
electron_framework_name = "$electron_product_name Framework"
electron_helper_name = "$electron_product_name Helper"
electron_login_helper_name = "$electron_product_name Login Helper"
electron_framework_version = "A"
mac_xib_bundle_data("electron_xibs") {
sources = [ "shell/common/resources/mac/MainMenu.xib" ]
}
action("fake_v8_context_snapshot_generator") {
script = "build/fake_v8_context_snapshot_generator.py"
args = [
rebase_path("$root_out_dir/$v8_context_snapshot_filename"),
rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"),
]
outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ]
}
bundle_data("electron_framework_resources") {
public_deps = [ ":packed_resources" ]
sources = []
if (icu_use_data_file) {
sources += [ "$root_out_dir/icudtl.dat" ]
public_deps += [ "//third_party/icu:icudata" ]
}
if (v8_use_external_startup_data) {
public_deps += [ "//v8" ]
if (use_v8_context_snapshot) {
if (use_prebuilt_v8_context_snapshot) {
sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ]
public_deps += [ ":fake_v8_context_snapshot_generator" ]
} else {
sources += [ "$root_out_dir/$v8_context_snapshot_filename" ]
public_deps += [ "//tools/v8_context_snapshot" ]
}
} else {
sources += [ "$root_out_dir/snapshot_blob.bin" ]
}
}
outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
}
if (!is_component_build && is_component_ffmpeg) {
bundle_data("electron_framework_libraries") {
sources = []
public_deps = []
sources += [ "$root_out_dir/libffmpeg.dylib" ]
public_deps += [ "//third_party/ffmpeg:ffmpeg" ]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
}
} else {
group("electron_framework_libraries") {
}
}
if (use_egl) {
# Add the ANGLE .dylibs in the Libraries directory of the Framework.
bundle_data("electron_angle_binaries") {
sources = [
"$root_out_dir/egl_intermediates/libEGL.dylib",
"$root_out_dir/egl_intermediates/libGLESv2.dylib",
]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
public_deps = [ "//ui/gl:angle_library_copy" ]
}
# Add the SwiftShader .dylibs in the Libraries directory of the Framework.
bundle_data("electron_swiftshader_binaries") {
sources = [
"$root_out_dir/vk_intermediates/libvk_swiftshader.dylib",
"$root_out_dir/vk_intermediates/vk_swiftshader_icd.json",
]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
public_deps = [ "//ui/gl:swiftshader_vk_library_copy" ]
}
}
group("electron_angle_library") {
if (use_egl) {
deps = [ ":electron_angle_binaries" ]
}
}
group("electron_swiftshader_library") {
if (use_egl) {
deps = [ ":electron_swiftshader_binaries" ]
}
}
bundle_data("electron_crashpad_helper") {
sources = [ "$root_out_dir/chrome_crashpad_handler" ]
outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ]
public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ]
if (is_asan) {
# crashpad_handler requires the ASan runtime at its @executable_path.
sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ]
public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ]
}
}
mac_framework_bundle("electron_framework") {
output_name = electron_framework_name
framework_version = electron_framework_version
framework_contents = [
"Resources",
"Libraries",
]
if (!is_mas_build) {
framework_contents += [ "Helpers" ]
}
public_deps = [
":electron_framework_libraries",
":electron_lib",
]
deps = [
":electron_angle_library",
":electron_framework_libraries",
":electron_framework_resources",
":electron_swiftshader_library",
":electron_xibs",
]
if (!is_mas_build) {
deps += [ ":electron_crashpad_helper" ]
}
info_plist = "shell/common/resources/mac/Info.plist"
extra_substitutions = [
"ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework",
"ELECTRON_VERSION=$electron_version",
]
include_dirs = [ "." ]
sources = filenames.framework_sources
frameworks = []
if (enable_osr) {
frameworks += [ "IOSurface.framework" ]
}
ldflags = [
"-Wl,-install_name,@rpath/$output_name.framework/$output_name",
"-rpath",
"@loader_path/Libraries",
# Required for exporting all symbols of libuv.
"-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a",
]
if (is_component_build) {
ldflags += [
"-rpath",
"@executable_path/../../../../../..",
]
}
# For component ffmpeg under non-component build, it is linked from
# @loader_path. However the ffmpeg.dylib is moved to a different place
# when generating app bundle, and we should change to link from @rpath.
if (is_component_ffmpeg && !is_component_build) {
ldflags += [ "-Wcrl,installnametool,-change,@loader_path/libffmpeg.dylib,@rpath/libffmpeg.dylib" ]
}
}
template("electron_helper_app") {
mac_app_bundle(target_name) {
assert(defined(invoker.helper_name_suffix))
output_name = electron_helper_name + invoker.helper_name_suffix
deps = [
":electron_framework+link",
"//base/allocator:early_zone_registration_mac",
]
if (!is_mas_build) {
deps += [ "//sandbox/mac:seatbelt" ]
}
defines = [ "HELPER_EXECUTABLE" ]
extra_configs = [ "//electron/build/config:mas_build" ]
sources = [
"shell/app/electron_main_mac.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
"shell/common/electron_constants.cc",
]
include_dirs = [ "." ]
info_plist = "shell/renderer/resources/mac/Info.plist"
extra_substitutions =
[ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ]
ldflags = [
"-rpath",
"@executable_path/../../..",
]
if (is_component_build) {
ldflags += [
"-rpath",
"@executable_path/../../../../../..",
]
}
}
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
_helper_bundle_id = helper_params[1]
_helper_suffix = helper_params[2]
electron_helper_app("electron_helper_app_${_helper_target}") {
helper_name_suffix = _helper_suffix
}
}
template("stripped_framework") {
action(target_name) {
assert(defined(invoker.framework))
script = "//electron/build/strip_framework.py"
forward_variables_from(invoker, [ "deps" ])
inputs = [ "$root_out_dir/" + invoker.framework ]
outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ]
args = rebase_path(inputs) + rebase_path(outputs)
}
}
stripped_framework("stripped_mantle_framework") {
framework = "Mantle.framework"
deps = [ "//third_party/squirrel.mac:mantle_framework" ]
}
stripped_framework("stripped_reactiveobjc_framework") {
framework = "ReactiveObjC.framework"
deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ]
}
stripped_framework("stripped_squirrel_framework") {
framework = "Squirrel.framework"
deps = [ "//third_party/squirrel.mac:squirrel_framework" ]
}
bundle_data("electron_app_framework_bundle_data") {
sources = [ "$root_out_dir/$electron_framework_name.framework" ]
if (!is_mas_build) {
sources += get_target_outputs(":stripped_mantle_framework") +
get_target_outputs(":stripped_reactiveobjc_framework") +
get_target_outputs(":stripped_squirrel_framework")
}
outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ]
public_deps = [
":electron_framework+link",
":stripped_mantle_framework",
":stripped_reactiveobjc_framework",
":stripped_squirrel_framework",
]
foreach(helper_params, content_mac_helpers) {
sources +=
[ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ]
public_deps += [ ":electron_helper_app_${helper_params[0]}" ]
}
}
mac_app_bundle("electron_login_helper") {
output_name = electron_login_helper_name
sources = filenames.login_helper_sources
include_dirs = [ "." ]
frameworks = [ "AppKit.framework" ]
info_plist = "shell/app/resources/mac/loginhelper-Info.plist"
extra_substitutions =
[ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ]
}
bundle_data("electron_login_helper_app") {
public_deps = [ ":electron_login_helper" ]
sources = [ "$root_out_dir/$electron_login_helper_name.app" ]
outputs =
[ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ]
}
action("electron_app_lproj_dirs") {
outputs = []
foreach(locale, locales_as_apple_outputs) {
outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ]
}
script = "build/mac/make_locale_dirs.py"
args = rebase_path(outputs)
}
foreach(locale, locales_as_apple_outputs) {
bundle_data("electron_app_strings_${locale}_bundle_data") {
sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ]
outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ]
public_deps = [ ":electron_app_lproj_dirs" ]
}
}
group("electron_app_strings_bundle_data") {
public_deps = []
foreach(locale, locales_as_apple_outputs) {
public_deps += [ ":electron_app_strings_${locale}_bundle_data" ]
}
}
bundle_data("electron_app_resources") {
public_deps = [
":default_app_asar",
":electron_app_strings_bundle_data",
]
sources = [
"$root_out_dir/resources/default_app.asar",
"shell/browser/resources/mac/electron.icns",
]
outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
}
asar_hashed_info_plist("electron_app_plist") {
keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ]
hash_targets = [ ":default_app_asar_header_hash" ]
plist_file = "shell/browser/resources/mac/Info.plist"
}
mac_app_bundle("electron_app") {
output_name = electron_product_name
sources = [
"shell/app/electron_main_mac.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
]
include_dirs = [ "." ]
deps = [
":electron_app_framework_bundle_data",
":electron_app_plist",
":electron_app_resources",
":electron_fuses",
"//base/allocator:early_zone_registration_mac",
"//electron/buildflags",
]
if (is_mas_build) {
deps += [ ":electron_login_helper_app" ]
}
info_plist_target = ":electron_app_plist"
extra_substitutions = [
"ELECTRON_BUNDLE_ID=$electron_mac_bundle_id",
"ELECTRON_VERSION=$electron_version",
]
ldflags = [
"-rpath",
"@executable_path/../Frameworks",
]
extra_configs = [ "//electron/build/config:mas_build" ]
}
if (enable_dsyms) {
extract_symbols("electron_framework_syms") {
binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name"
deps = [ ":electron_framework" ]
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
_helper_bundle_id = helper_params[1]
_helper_suffix = helper_params[2]
extract_symbols("electron_helper_syms_${_helper_target}") {
binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}"
deps = [ ":electron_helper_app_${_helper_target}" ]
}
}
extract_symbols("electron_app_syms") {
binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name"
deps = [ ":electron_app" ]
}
extract_symbols("egl_syms") {
binary = "$root_out_dir/libEGL.dylib"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/libEGL.dylib.dSYM/Contents/Resources/DWARF/libEGL.dylib"
deps = [ "//third_party/angle:libEGL" ]
}
extract_symbols("gles_syms") {
binary = "$root_out_dir/libGLESv2.dylib"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libGLESv2.dylib"
deps = [ "//third_party/angle:libGLESv2" ]
}
extract_symbols("crashpad_handler_syms") {
binary = "$root_out_dir/chrome_crashpad_handler"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler"
deps = [ "//components/crash/core/app:chrome_crashpad_handler" ]
}
group("electron_symbols") {
deps = [
":egl_syms",
":electron_app_syms",
":electron_framework_syms",
":gles_syms",
]
if (!is_mas_build) {
deps += [ ":crashpad_handler_syms" ]
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
deps += [ ":electron_helper_syms_${_helper_target}" ]
}
}
} else {
group("electron_symbols") {
}
}
} else {
windows_manifest("electron_app_manifest") {
sources = [
"shell/browser/resources/win/disable_window_filtering.manifest",
"shell/browser/resources/win/dpi_aware.manifest",
as_invoker_manifest,
common_controls_manifest,
default_compatibility_manifest,
]
}
executable("electron_app") {
output_name = electron_project_name
if (is_win) {
sources = [ "shell/app/electron_main_win.cc" ]
} else if (is_linux) {
sources = [
"shell/app/electron_main_linux.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
]
}
include_dirs = [ "." ]
deps = [
":default_app_asar",
":electron_app_manifest",
":electron_lib",
":electron_win32_resources",
":packed_resources",
"//components/crash/core/app",
"//content:sandbox_helper_win",
"//electron/buildflags",
"//ui/strings",
]
data = []
data_deps = []
data += [ "$root_out_dir/resources.pak" ]
data += [ "$root_out_dir/chrome_100_percent.pak" ]
if (enable_hidpi) {
data += [ "$root_out_dir/chrome_200_percent.pak" ]
}
foreach(locale, platform_pak_locales) {
data += [ "$root_out_dir/locales/$locale.pak" ]
}
if (!is_mac) {
data += [ "$root_out_dir/resources/default_app.asar" ]
}
if (use_v8_context_snapshot) {
public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ]
}
if (is_linux) {
data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ]
}
if (is_win) {
sources += [
"$target_gen_dir/win-resources/electron.rc",
"shell/browser/resources/win/resource.h",
]
deps += [
"//components/browser_watcher:browser_watcher_client",
"//components/crash/core/app:run_as_crashpad_handler",
]
ldflags = []
libs = [
"comctl32.lib",
"uiautomationcore.lib",
"wtsapi32.lib",
]
configs -= [ "//build/config/win:console" ]
configs += [
"//build/config/win:windowed",
"//build/config/win:delayloads",
]
if (current_cpu == "x86") {
# Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by
# Chrome's main thread. This saves significant memory on threads (like
# those in the Windows thread pool, and others) whose stack size we can
# only control through this setting. Because Chrome's main thread needs
# a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses
# fibers to switch to a 1.5 MiB stack before running any other code.
ldflags += [ "/STACK:0x80000" ]
} else {
# Increase the initial stack size. The default is 1MB, this is 8MB.
ldflags += [ "/STACK:0x800000" ]
}
# This is to support renaming of electron.exe. node-gyp has hard-coded
# executable names which it will recognise as node. This module definition
# file claims that the electron executable is in fact named "node.exe",
# which is one of the executable names that node-gyp recognizes.
# See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a
ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ]
inputs = [
"shell/browser/resources/win/electron.ico",
"build/electron.def",
]
}
if (is_linux) {
ldflags = [
"-pie",
# Required for exporting all symbols of libuv.
"-Wl,--whole-archive",
"obj/third_party/electron_node/deps/uv/libuv.a",
"-Wl,--no-whole-archive",
]
if (!is_component_build && is_component_ffmpeg) {
configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ]
}
if (is_linux) {
deps += [ "//sandbox/linux:chrome_sandbox" ]
}
}
}
if (is_official_build) {
if (is_linux) {
_target_executable_suffix = ""
_target_shared_library_suffix = ".so"
} else if (is_win) {
_target_executable_suffix = ".exe"
_target_shared_library_suffix = ".dll"
}
extract_symbols("electron_app_symbols") {
binary = "$root_out_dir/$electron_project_name$_target_executable_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ ":electron_app" ]
}
extract_symbols("egl_symbols") {
binary = "$root_out_dir/libEGL$_target_shared_library_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ "//third_party/angle:libEGL" ]
}
extract_symbols("gles_symbols") {
binary = "$root_out_dir/libGLESv2$_target_shared_library_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ "//third_party/angle:libGLESv2" ]
}
group("electron_symbols") {
deps = [
":egl_symbols",
":electron_app_symbols",
":gles_symbols",
]
}
}
}
test("shell_browser_ui_unittests") {
sources = [
"//electron/shell/browser/ui/accelerator_util_unittests.cc",
"//electron/shell/browser/ui/run_all_unittests.cc",
]
configs += [ ":electron_lib_config" ]
deps = [
":electron_lib",
"//base",
"//base/test:test_support",
"//testing/gmock",
"//testing/gtest",
"//ui/base",
"//ui/strings",
]
}
template("dist_zip") {
_runtime_deps_target = "${target_name}__deps"
_runtime_deps_file =
"$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" +
get_label_info(target_name, "name") + ".runtime_deps"
group(_runtime_deps_target) {
forward_variables_from(invoker,
[
"deps",
"data_deps",
"data",
"testonly",
])
write_runtime_deps = _runtime_deps_file
}
action(target_name) {
script = "//electron/build/zip.py"
deps = [ ":$_runtime_deps_target" ]
forward_variables_from(invoker,
[
"outputs",
"testonly",
])
flatten = false
flatten_relative_to = false
if (defined(invoker.flatten)) {
flatten = invoker.flatten
if (defined(invoker.flatten_relative_to)) {
flatten_relative_to = invoker.flatten_relative_to
}
}
args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [
target_cpu,
target_os,
"$flatten",
"$flatten_relative_to",
]
}
}
copy("electron_license") {
sources = [ "LICENSE" ]
outputs = [ "$root_build_dir/{{source_file_part}}" ]
}
copy("chromium_licenses") {
deps = [ "//components/resources:about_credits" ]
sources = [ "$root_gen_dir/components/resources/about_credits.html" ]
outputs = [ "$root_build_dir/LICENSES.chromium.html" ]
}
group("licenses") {
data_deps = [
":chromium_licenses",
":electron_license",
]
}
dist_zip("electron_dist_zip") {
data_deps = [
":electron_app",
":electron_version_file",
":licenses",
]
if (is_linux) {
data_deps += [ "//sandbox/linux:chrome_sandbox" ]
}
deps = data_deps
outputs = [ "$root_build_dir/dist.zip" ]
}
dist_zip("electron_ffmpeg_zip") {
data_deps = [ "//third_party/ffmpeg" ]
deps = data_deps
outputs = [ "$root_build_dir/ffmpeg.zip" ]
}
electron_chromedriver_deps = [
":licenses",
"//chrome/test/chromedriver:chromedriver_server",
"//electron/buildflags",
]
group("electron_chromedriver") {
testonly = true
public_deps = electron_chromedriver_deps
}
dist_zip("electron_chromedriver_zip") {
testonly = true
data_deps = electron_chromedriver_deps
deps = data_deps
outputs = [ "$root_build_dir/chromedriver.zip" ]
}
mksnapshot_deps = [
":licenses",
"//v8:mksnapshot($v8_snapshot_toolchain)",
]
if (use_v8_context_snapshot) {
mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ]
}
group("electron_mksnapshot") {
public_deps = mksnapshot_deps
}
dist_zip("electron_mksnapshot_zip") {
data_deps = mksnapshot_deps
deps = data_deps
outputs = [ "$root_build_dir/mksnapshot.zip" ]
}
copy("hunspell_dictionaries") {
sources = hunspell_dictionaries + hunspell_licenses
outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ]
}
dist_zip("hunspell_dictionaries_zip") {
data_deps = [ ":hunspell_dictionaries" ]
deps = data_deps
flatten = true
outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ]
}
copy("libcxx_headers") {
sources = libcxx_headers + libcxx_licenses +
[ "//buildtools/third_party/libc++/__config_site" ]
outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ]
}
dist_zip("libcxx_headers_zip") {
data_deps = [ ":libcxx_headers" ]
deps = data_deps
flatten = true
flatten_relative_to = rebase_path(
"$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk",
"$root_out_dir")
outputs = [ "$root_build_dir/libcxx_headers.zip" ]
}
copy("libcxxabi_headers") {
sources = libcxxabi_headers + libcxxabi_licenses
outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ]
}
dist_zip("libcxxabi_headers_zip") {
data_deps = [ ":libcxxabi_headers" ]
deps = data_deps
flatten = true
flatten_relative_to = rebase_path(
"$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk",
"$root_out_dir")
outputs = [ "$root_build_dir/libcxxabi_headers.zip" ]
}
action("libcxx_objects_zip") {
deps = [ "//buildtools/third_party/libc++" ]
script = "build/zip_libcxx.py"
outputs = [ "$root_build_dir/libcxx_objects.zip" ]
args = rebase_path(outputs)
}
group("electron") {
public_deps = [ ":electron_app" ]
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
docs/api/tray.md
|
# Tray
## Class: Tray
> Add icons and context menus to the system's notification area.
Process: [Main](../glossary.md#main-process)
`Tray` is an [EventEmitter][event-emitter].
```javascript
const { app, Menu, Tray } = require('electron')
let tray = null
app.whenReady().then(() => {
tray = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
{ label: 'Item4', type: 'radio' }
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
})
```
__Platform Considerations__
__Linux__
* Tray icon requires support of [StatusNotifierItem](https://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/)
in user's desktop environment.
* The `click` event is emitted when the tray icon receives activation from
user, however the StatusNotifierItem spec does not specify which action would
cause an activation, for some environments it is left mouse click, but for
some it might be double left mouse click.
* In order for changes made to individual `MenuItem`s to take effect,
you have to call `setContextMenu` again. For example:
```javascript
const { app, Menu, Tray } = require('electron')
let appIcon = null
app.whenReady().then(() => {
appIcon = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' }
])
// Make a change to the context menu
contextMenu.items[1].checked = false
// Call this again for Linux because we modified the context menu
appIcon.setContextMenu(contextMenu)
})
```
__MacOS__
* Icons passed to the Tray constructor should be [Template Images](native-image.md#template-image).
* To make sure your icon isn't grainy on retina monitors, be sure your `@2x` image is 144dpi.
* If you are bundling your application (e.g., with webpack for development), be sure that the file names are not being mangled or hashed. The filename needs to end in Template, and the `@2x` image needs to have the same filename as the standard image, or MacOS will not magically invert your image's colors or use the high density image.
* 16x16 (72dpi) and 32x32@2x (144dpi) work well for most icons.
__Windows__
* It is recommended to use `ICO` icons to get best visual effects.
### `new Tray(image, [guid])`
* `image` ([NativeImage](native-image.md) | string)
* `guid` string (optional) _Windows_ - Assigns a GUID to the tray icon. If the executable is signed and the signature contains an organization in the subject line then the GUID is permanently associated with that signature. OS level settings like the position of the tray icon in the system tray will persist even if the path to the executable changes. If the executable is not code-signed then the GUID is permanently associated with the path to the executable. Changing the path to the executable will break the creation of the tray icon and a new GUID must be used. However, it is highly recommended to use the GUID parameter only in conjunction with code-signed executable. If an App defines multiple tray icons then each icon must use a separate GUID.
Creates a new tray icon associated with the `image`.
### Instance Events
The `Tray` module emits the following events:
#### Event: 'click'
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon.
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the tray icon is clicked.
Note that on Linux this event is emitted when the tray icon receives an
activation, which might not necessarily be left mouse click.
#### Event: 'right-click' _macOS_ _Windows_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon.
Emitted when the tray icon is right clicked.
#### Event: 'double-click' _macOS_ _Windows_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `bounds` [Rectangle](structures/rectangle.md) - The bounds of tray icon.
Emitted when the tray icon is double clicked.
#### Event: 'balloon-show' _Windows_
Emitted when the tray balloon shows.
#### Event: 'balloon-click' _Windows_
Emitted when the tray balloon is clicked.
#### Event: 'balloon-closed' _Windows_
Emitted when the tray balloon is closed because of timeout or user manually
closes it.
#### Event: 'drop' _macOS_
Emitted when any dragged items are dropped on the tray icon.
#### Event: 'drop-files' _macOS_
Returns:
* `event` Event
* `files` string[] - The paths of the dropped files.
Emitted when dragged files are dropped in the tray icon.
#### Event: 'drop-text' _macOS_
Returns:
* `event` Event
* `text` string - the dropped text string.
Emitted when dragged text is dropped in the tray icon.
#### Event: 'drag-enter' _macOS_
Emitted when a drag operation enters the tray icon.
#### Event: 'drag-leave' _macOS_
Emitted when a drag operation exits the tray icon.
#### Event: 'drag-end' _macOS_
Emitted when a drag operation ends on the tray or ends at another location.
#### Event: 'mouse-up' _macOS_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the mouse is released from clicking the tray icon.
Note: This will not be emitted if you have set a context menu for your Tray using `tray.setContextMenu`, as a result of macOS-level constraints.
#### Event: 'mouse-down' _macOS_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the mouse clicks the tray icon.
#### Event: 'mouse-enter' _macOS_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the mouse enters the tray icon.
#### Event: 'mouse-leave' _macOS_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the mouse exits the tray icon.
#### Event: 'mouse-move' _macOS_ _Windows_
Returns:
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `position` [Point](structures/point.md) - The position of the event.
Emitted when the mouse moves in the tray icon.
### Instance Methods
The `Tray` class has the following methods:
#### `tray.destroy()`
Destroys the tray icon immediately.
#### `tray.setImage(image)`
* `image` ([NativeImage](native-image.md) | string)
Sets the `image` associated with this tray icon.
#### `tray.setPressedImage(image)` _macOS_
* `image` ([NativeImage](native-image.md) | string)
Sets the `image` associated with this tray icon when pressed on macOS.
#### `tray.setToolTip(toolTip)`
* `toolTip` string
Sets the hover text for this tray icon.
#### `tray.setTitle(title[, options])` _macOS_
* `title` string
* `options` Object (optional)
* `fontType` string (optional) - The font family variant to display, can be `monospaced` or `monospacedDigit`. `monospaced` is available in macOS 10.15+ and `monospacedDigit` is available in macOS 10.11+. When left blank, the title uses the default system font.
Sets the title displayed next to the tray icon in the status bar (Support ANSI colors).
#### `tray.getTitle()` _macOS_
Returns `string` - the title displayed next to the tray icon in the status bar
#### `tray.setIgnoreDoubleClickEvents(ignore)` _macOS_
* `ignore` boolean
Sets the option to ignore double click events. Ignoring these events allows you
to detect every individual click of the tray icon.
This value is set to false by default.
#### `tray.getIgnoreDoubleClickEvents()` _macOS_
Returns `boolean` - Whether double click events will be ignored.
#### `tray.displayBalloon(options)` _Windows_
* `options` Object
* `icon` ([NativeImage](native-image.md) | string) (optional) - Icon to use when `iconType` is `custom`.
* `iconType` string (optional) - Can be `none`, `info`, `warning`, `error` or `custom`. Default is `custom`.
* `title` string
* `content` string
* `largeIcon` boolean (optional) - The large version of the icon should be used. Default is `true`. Maps to [`NIIF_LARGE_ICON`][NIIF_LARGE_ICON].
* `noSound` boolean (optional) - Do not play the associated sound. Default is `false`. Maps to [`NIIF_NOSOUND`][NIIF_NOSOUND].
* `respectQuietTime` boolean (optional) - Do not display the balloon notification if the current user is in "quiet time". Default is `false`. Maps to [`NIIF_RESPECT_QUIET_TIME`][NIIF_RESPECT_QUIET_TIME].
Displays a tray balloon.
[NIIF_NOSOUND]: https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-notifyicondataa#niif_nosound-0x00000010
[NIIF_LARGE_ICON]: https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-notifyicondataa#niif_large_icon-0x00000020
[NIIF_RESPECT_QUIET_TIME]: https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-notifyicondataa#niif_respect_quiet_time-0x00000080
#### `tray.removeBalloon()` _Windows_
Removes a tray balloon.
#### `tray.focus()` _Windows_
Returns focus to the taskbar notification area.
Notification area icons should use this message when they have completed their UI operation.
For example, if the icon displays a shortcut menu, but the user presses ESC to cancel it,
use `tray.focus()` to return focus to the notification area.
#### `tray.popUpContextMenu([menu, position])` _macOS_ _Windows_
* `menu` Menu (optional)
* `position` [Point](structures/point.md) (optional) - The pop up position.
Pops up the context menu of the tray icon. When `menu` is passed, the `menu` will
be shown instead of the tray icon's context menu.
The `position` is only available on Windows, and it is (0, 0) by default.
#### `tray.closeContextMenu()` _macOS_ _Windows_
Closes an open context menu, as set by `tray.setContextMenu()`.
#### `tray.setContextMenu(menu)`
* `menu` Menu | null
Sets the context menu for this icon.
#### `tray.getBounds()` _macOS_ _Windows_
Returns [`Rectangle`](structures/rectangle.md)
The `bounds` of this tray icon as `Object`.
#### `tray.isDestroyed()`
Returns `boolean` - Whether the tray icon is destroyed.
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
filenames.gni
|
filenames = {
default_app_ts_sources = [
"default_app/default_app.ts",
"default_app/main.ts",
"default_app/preload.ts",
]
default_app_static_sources = [
"default_app/icon.png",
"default_app/index.html",
"default_app/package.json",
"default_app/styles.css",
]
default_app_octicon_sources = [
"node_modules/@primer/octicons/build/build.css",
"node_modules/@primer/octicons/build/svg/book-24.svg",
"node_modules/@primer/octicons/build/svg/code-square-24.svg",
"node_modules/@primer/octicons/build/svg/gift-24.svg",
"node_modules/@primer/octicons/build/svg/mark-github-16.svg",
"node_modules/@primer/octicons/build/svg/star-fill-24.svg",
]
lib_sources_linux = [
"shell/browser/browser_linux.cc",
"shell/browser/electron_browser_main_parts_linux.cc",
"shell/browser/lib/power_observer_linux.cc",
"shell/browser/lib/power_observer_linux.h",
"shell/browser/linux/unity_service.cc",
"shell/browser/linux/unity_service.h",
"shell/browser/notifications/linux/libnotify_notification.cc",
"shell/browser/notifications/linux/libnotify_notification.h",
"shell/browser/notifications/linux/notification_presenter_linux.cc",
"shell/browser/notifications/linux/notification_presenter_linux.h",
"shell/browser/relauncher_linux.cc",
"shell/browser/ui/electron_desktop_window_tree_host_linux.cc",
"shell/browser/ui/file_dialog_gtk.cc",
"shell/browser/ui/message_box_gtk.cc",
"shell/browser/ui/tray_icon_gtk.cc",
"shell/browser/ui/tray_icon_gtk.h",
"shell/browser/ui/views/client_frame_view_linux.cc",
"shell/browser/ui/views/client_frame_view_linux.h",
"shell/common/application_info_linux.cc",
"shell/common/language_util_linux.cc",
"shell/common/node_bindings_linux.cc",
"shell/common/node_bindings_linux.h",
"shell/common/platform_util_linux.cc",
]
lib_sources_linux_x11 = [
"shell/browser/ui/views/global_menu_bar_registrar_x11.cc",
"shell/browser/ui/views/global_menu_bar_registrar_x11.h",
"shell/browser/ui/views/global_menu_bar_x11.cc",
"shell/browser/ui/views/global_menu_bar_x11.h",
"shell/browser/ui/x/event_disabler.cc",
"shell/browser/ui/x/event_disabler.h",
"shell/browser/ui/x/x_window_utils.cc",
"shell/browser/ui/x/x_window_utils.h",
]
lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ]
lib_sources_win = [
"shell/browser/api/electron_api_power_monitor_win.cc",
"shell/browser/api/electron_api_system_preferences_win.cc",
"shell/browser/browser_win.cc",
"shell/browser/native_window_views_win.cc",
"shell/browser/notifications/win/notification_presenter_win.cc",
"shell/browser/notifications/win/notification_presenter_win.h",
"shell/browser/notifications/win/windows_toast_notification.cc",
"shell/browser/notifications/win/windows_toast_notification.h",
"shell/browser/relauncher_win.cc",
"shell/browser/ui/certificate_trust_win.cc",
"shell/browser/ui/file_dialog_win.cc",
"shell/browser/ui/message_box_win.cc",
"shell/browser/ui/tray_icon_win.cc",
"shell/browser/ui/views/electron_views_delegate_win.cc",
"shell/browser/ui/views/win_icon_painter.cc",
"shell/browser/ui/views/win_icon_painter.h",
"shell/browser/ui/views/win_frame_view.cc",
"shell/browser/ui/views/win_frame_view.h",
"shell/browser/ui/views/win_caption_button.cc",
"shell/browser/ui/views/win_caption_button.h",
"shell/browser/ui/views/win_caption_button_container.cc",
"shell/browser/ui/views/win_caption_button_container.h",
"shell/browser/ui/win/dialog_thread.cc",
"shell/browser/ui/win/dialog_thread.h",
"shell/browser/ui/win/electron_desktop_native_widget_aura.cc",
"shell/browser/ui/win/electron_desktop_native_widget_aura.h",
"shell/browser/ui/win/electron_desktop_window_tree_host_win.cc",
"shell/browser/ui/win/electron_desktop_window_tree_host_win.h",
"shell/browser/ui/win/jump_list.cc",
"shell/browser/ui/win/jump_list.h",
"shell/browser/ui/win/notify_icon_host.cc",
"shell/browser/ui/win/notify_icon_host.h",
"shell/browser/ui/win/notify_icon.cc",
"shell/browser/ui/win/notify_icon.h",
"shell/browser/ui/win/taskbar_host.cc",
"shell/browser/ui/win/taskbar_host.h",
"shell/browser/win/dark_mode.cc",
"shell/browser/win/dark_mode.h",
"shell/browser/win/scoped_hstring.cc",
"shell/browser/win/scoped_hstring.h",
"shell/common/api/electron_api_native_image_win.cc",
"shell/common/application_info_win.cc",
"shell/common/language_util_win.cc",
"shell/common/node_bindings_win.cc",
"shell/common/node_bindings_win.h",
"shell/common/platform_util_win.cc",
]
lib_sources_mac = [
"shell/app/electron_main_delegate_mac.h",
"shell/app/electron_main_delegate_mac.mm",
"shell/browser/api/electron_api_app_mac.mm",
"shell/browser/api/electron_api_menu_mac.h",
"shell/browser/api/electron_api_menu_mac.mm",
"shell/browser/api/electron_api_native_theme_mac.mm",
"shell/browser/api/electron_api_power_monitor_mac.mm",
"shell/browser/api/electron_api_push_notifications_mac.mm",
"shell/browser/api/electron_api_system_preferences_mac.mm",
"shell/browser/api/electron_api_web_contents_mac.mm",
"shell/browser/auto_updater_mac.mm",
"shell/browser/browser_mac.mm",
"shell/browser/electron_browser_main_parts_mac.mm",
"shell/browser/mac/dict_util.h",
"shell/browser/mac/dict_util.mm",
"shell/browser/mac/electron_application_delegate.h",
"shell/browser/mac/electron_application_delegate.mm",
"shell/browser/mac/electron_application.h",
"shell/browser/mac/electron_application.mm",
"shell/browser/mac/in_app_purchase_observer.h",
"shell/browser/mac/in_app_purchase_observer.mm",
"shell/browser/mac/in_app_purchase_product.h",
"shell/browser/mac/in_app_purchase_product.mm",
"shell/browser/mac/in_app_purchase.h",
"shell/browser/mac/in_app_purchase.mm",
"shell/browser/native_browser_view_mac.h",
"shell/browser/native_browser_view_mac.mm",
"shell/browser/native_window_mac.h",
"shell/browser/native_window_mac.mm",
"shell/browser/notifications/mac/cocoa_notification.h",
"shell/browser/notifications/mac/cocoa_notification.mm",
"shell/browser/notifications/mac/notification_center_delegate.h",
"shell/browser/notifications/mac/notification_center_delegate.mm",
"shell/browser/notifications/mac/notification_presenter_mac.h",
"shell/browser/notifications/mac/notification_presenter_mac.mm",
"shell/browser/relauncher_mac.cc",
"shell/browser/ui/certificate_trust_mac.mm",
"shell/browser/ui/cocoa/delayed_native_view_host.cc",
"shell/browser/ui/cocoa/delayed_native_view_host.h",
"shell/browser/ui/cocoa/electron_bundle_mover.h",
"shell/browser/ui/cocoa/electron_bundle_mover.mm",
"shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h",
"shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm",
"shell/browser/ui/cocoa/electron_menu_controller.h",
"shell/browser/ui/cocoa/electron_menu_controller.mm",
"shell/browser/ui/cocoa/electron_native_widget_mac.h",
"shell/browser/ui/cocoa/electron_native_widget_mac.mm",
"shell/browser/ui/cocoa/electron_ns_window_delegate.h",
"shell/browser/ui/cocoa/electron_ns_window_delegate.mm",
"shell/browser/ui/cocoa/electron_ns_panel.h",
"shell/browser/ui/cocoa/electron_ns_panel.mm",
"shell/browser/ui/cocoa/electron_ns_window.h",
"shell/browser/ui/cocoa/electron_ns_window.mm",
"shell/browser/ui/cocoa/electron_preview_item.h",
"shell/browser/ui/cocoa/electron_preview_item.mm",
"shell/browser/ui/cocoa/electron_touch_bar.h",
"shell/browser/ui/cocoa/electron_touch_bar.mm",
"shell/browser/ui/cocoa/event_dispatching_window.h",
"shell/browser/ui/cocoa/event_dispatching_window.mm",
"shell/browser/ui/cocoa/NSColor+Hex.h",
"shell/browser/ui/cocoa/NSColor+Hex.mm",
"shell/browser/ui/cocoa/NSString+ANSI.h",
"shell/browser/ui/cocoa/NSString+ANSI.mm",
"shell/browser/ui/cocoa/root_view_mac.h",
"shell/browser/ui/cocoa/root_view_mac.mm",
"shell/browser/ui/cocoa/views_delegate_mac.h",
"shell/browser/ui/cocoa/views_delegate_mac.mm",
"shell/browser/ui/cocoa/window_buttons_proxy.h",
"shell/browser/ui/cocoa/window_buttons_proxy.mm",
"shell/browser/ui/drag_util_mac.mm",
"shell/browser/ui/file_dialog_mac.mm",
"shell/browser/ui/inspectable_web_contents_view_mac.h",
"shell/browser/ui/inspectable_web_contents_view_mac.mm",
"shell/browser/ui/message_box_mac.mm",
"shell/browser/ui/tray_icon_cocoa.h",
"shell/browser/ui/tray_icon_cocoa.mm",
"shell/common/api/electron_api_clipboard_mac.mm",
"shell/common/api/electron_api_native_image_mac.mm",
"shell/common/asar/archive_mac.mm",
"shell/common/application_info_mac.mm",
"shell/common/language_util_mac.mm",
"shell/common/mac/main_application_bundle.h",
"shell/common/mac/main_application_bundle.mm",
"shell/common/node_bindings_mac.cc",
"shell/common/node_bindings_mac.h",
"shell/common/platform_util_mac.mm",
]
lib_sources_views = [
"shell/browser/api/electron_api_menu_views.cc",
"shell/browser/api/electron_api_menu_views.h",
"shell/browser/native_browser_view_views.cc",
"shell/browser/native_browser_view_views.h",
"shell/browser/native_window_views.cc",
"shell/browser/native_window_views.h",
"shell/browser/ui/drag_util_views.cc",
"shell/browser/ui/views/autofill_popup_view.cc",
"shell/browser/ui/views/autofill_popup_view.h",
"shell/browser/ui/views/electron_views_delegate.cc",
"shell/browser/ui/views/electron_views_delegate.h",
"shell/browser/ui/views/frameless_view.cc",
"shell/browser/ui/views/frameless_view.h",
"shell/browser/ui/views/inspectable_web_contents_view_views.cc",
"shell/browser/ui/views/inspectable_web_contents_view_views.h",
"shell/browser/ui/views/menu_bar.cc",
"shell/browser/ui/views/menu_bar.h",
"shell/browser/ui/views/menu_delegate.cc",
"shell/browser/ui/views/menu_delegate.h",
"shell/browser/ui/views/menu_model_adapter.cc",
"shell/browser/ui/views/menu_model_adapter.h",
"shell/browser/ui/views/native_frame_view.cc",
"shell/browser/ui/views/native_frame_view.h",
"shell/browser/ui/views/root_view.cc",
"shell/browser/ui/views/root_view.h",
"shell/browser/ui/views/submenu_button.cc",
"shell/browser/ui/views/submenu_button.h",
]
lib_sources = [
"shell/app/command_line_args.cc",
"shell/app/command_line_args.h",
"shell/app/electron_content_client.cc",
"shell/app/electron_content_client.h",
"shell/app/electron_crash_reporter_client.cc",
"shell/app/electron_crash_reporter_client.h",
"shell/app/electron_main_delegate.cc",
"shell/app/electron_main_delegate.h",
"shell/app/uv_task_runner.cc",
"shell/app/uv_task_runner.h",
"shell/browser/api/electron_api_app.cc",
"shell/browser/api/electron_api_app.h",
"shell/browser/api/electron_api_auto_updater.cc",
"shell/browser/api/electron_api_auto_updater.h",
"shell/browser/api/electron_api_base_window.cc",
"shell/browser/api/electron_api_base_window.h",
"shell/browser/api/electron_api_browser_view.cc",
"shell/browser/api/electron_api_browser_view.h",
"shell/browser/api/electron_api_browser_window.cc",
"shell/browser/api/electron_api_browser_window.h",
"shell/browser/api/electron_api_content_tracing.cc",
"shell/browser/api/electron_api_cookies.cc",
"shell/browser/api/electron_api_cookies.h",
"shell/browser/api/electron_api_crash_reporter.cc",
"shell/browser/api/electron_api_crash_reporter.h",
"shell/browser/api/electron_api_data_pipe_holder.cc",
"shell/browser/api/electron_api_data_pipe_holder.h",
"shell/browser/api/electron_api_debugger.cc",
"shell/browser/api/electron_api_debugger.h",
"shell/browser/api/electron_api_dialog.cc",
"shell/browser/api/electron_api_download_item.cc",
"shell/browser/api/electron_api_download_item.h",
"shell/browser/api/electron_api_event.cc",
"shell/browser/api/electron_api_event_emitter.cc",
"shell/browser/api/electron_api_event_emitter.h",
"shell/browser/api/electron_api_global_shortcut.cc",
"shell/browser/api/electron_api_global_shortcut.h",
"shell/browser/api/electron_api_in_app_purchase.cc",
"shell/browser/api/electron_api_in_app_purchase.h",
"shell/browser/api/electron_api_menu.cc",
"shell/browser/api/electron_api_menu.h",
"shell/browser/api/electron_api_native_theme.cc",
"shell/browser/api/electron_api_native_theme.h",
"shell/browser/api/electron_api_net.cc",
"shell/browser/api/electron_api_net_log.cc",
"shell/browser/api/electron_api_net_log.h",
"shell/browser/api/electron_api_notification.cc",
"shell/browser/api/electron_api_notification.h",
"shell/browser/api/electron_api_power_monitor.cc",
"shell/browser/api/electron_api_power_monitor.h",
"shell/browser/api/electron_api_power_save_blocker.cc",
"shell/browser/api/electron_api_power_save_blocker.h",
"shell/browser/api/electron_api_printing.cc",
"shell/browser/api/electron_api_protocol.cc",
"shell/browser/api/electron_api_protocol.h",
"shell/browser/api/electron_api_push_notifications.cc",
"shell/browser/api/electron_api_push_notifications.h",
"shell/browser/api/electron_api_safe_storage.cc",
"shell/browser/api/electron_api_safe_storage.h",
"shell/browser/api/electron_api_screen.cc",
"shell/browser/api/electron_api_screen.h",
"shell/browser/api/electron_api_service_worker_context.cc",
"shell/browser/api/electron_api_service_worker_context.h",
"shell/browser/api/electron_api_session.cc",
"shell/browser/api/electron_api_session.h",
"shell/browser/api/electron_api_system_preferences.cc",
"shell/browser/api/electron_api_system_preferences.h",
"shell/browser/api/electron_api_tray.cc",
"shell/browser/api/electron_api_tray.h",
"shell/browser/api/electron_api_url_loader.cc",
"shell/browser/api/electron_api_url_loader.h",
"shell/browser/api/electron_api_utility_process.cc",
"shell/browser/api/electron_api_utility_process.h",
"shell/browser/api/electron_api_view.cc",
"shell/browser/api/electron_api_view.h",
"shell/browser/api/electron_api_web_contents.cc",
"shell/browser/api/electron_api_web_contents.h",
"shell/browser/api/electron_api_web_contents_impl.cc",
"shell/browser/api/electron_api_web_contents_view.cc",
"shell/browser/api/electron_api_web_contents_view.h",
"shell/browser/api/electron_api_web_frame_main.cc",
"shell/browser/api/electron_api_web_frame_main.h",
"shell/browser/api/electron_api_web_request.cc",
"shell/browser/api/electron_api_web_request.h",
"shell/browser/api/electron_api_web_view_manager.cc",
"shell/browser/api/event.cc",
"shell/browser/api/event.h",
"shell/browser/api/frame_subscriber.cc",
"shell/browser/api/frame_subscriber.h",
"shell/browser/api/gpu_info_enumerator.cc",
"shell/browser/api/gpu_info_enumerator.h",
"shell/browser/api/gpuinfo_manager.cc",
"shell/browser/api/gpuinfo_manager.h",
"shell/browser/api/message_port.cc",
"shell/browser/api/message_port.h",
"shell/browser/api/process_metric.cc",
"shell/browser/api/process_metric.h",
"shell/browser/api/save_page_handler.cc",
"shell/browser/api/save_page_handler.h",
"shell/browser/api/ui_event.cc",
"shell/browser/api/ui_event.h",
"shell/browser/auto_updater.cc",
"shell/browser/auto_updater.h",
"shell/browser/badging/badge_manager.cc",
"shell/browser/badging/badge_manager.h",
"shell/browser/badging/badge_manager_factory.cc",
"shell/browser/badging/badge_manager_factory.h",
"shell/browser/bluetooth/electron_bluetooth_delegate.cc",
"shell/browser/bluetooth/electron_bluetooth_delegate.h",
"shell/browser/browser.cc",
"shell/browser/browser.h",
"shell/browser/browser_observer.h",
"shell/browser/browser_process_impl.cc",
"shell/browser/browser_process_impl.h",
"shell/browser/child_web_contents_tracker.cc",
"shell/browser/child_web_contents_tracker.h",
"shell/browser/cookie_change_notifier.cc",
"shell/browser/cookie_change_notifier.h",
"shell/browser/draggable_region_provider.h",
"shell/browser/electron_api_ipc_handler_impl.cc",
"shell/browser/electron_api_ipc_handler_impl.h",
"shell/browser/electron_autofill_driver.cc",
"shell/browser/electron_autofill_driver.h",
"shell/browser/electron_autofill_driver_factory.cc",
"shell/browser/electron_autofill_driver_factory.h",
"shell/browser/electron_browser_client.cc",
"shell/browser/electron_browser_client.h",
"shell/browser/electron_browser_context.cc",
"shell/browser/electron_browser_context.h",
"shell/browser/electron_browser_main_parts.cc",
"shell/browser/electron_browser_main_parts.h",
"shell/browser/electron_download_manager_delegate.cc",
"shell/browser/electron_download_manager_delegate.h",
"shell/browser/electron_gpu_client.cc",
"shell/browser/electron_gpu_client.h",
"shell/browser/electron_javascript_dialog_manager.cc",
"shell/browser/electron_javascript_dialog_manager.h",
"shell/browser/electron_navigation_throttle.cc",
"shell/browser/electron_navigation_throttle.h",
"shell/browser/electron_permission_manager.cc",
"shell/browser/electron_permission_manager.h",
"shell/browser/electron_speech_recognition_manager_delegate.cc",
"shell/browser/electron_speech_recognition_manager_delegate.h",
"shell/browser/electron_web_contents_utility_handler_impl.cc",
"shell/browser/electron_web_contents_utility_handler_impl.h",
"shell/browser/electron_web_ui_controller_factory.cc",
"shell/browser/electron_web_ui_controller_factory.h",
"shell/browser/event_emitter_mixin.cc",
"shell/browser/event_emitter_mixin.h",
"shell/browser/extended_web_contents_observer.h",
"shell/browser/feature_list.cc",
"shell/browser/feature_list.h",
"shell/browser/file_select_helper.cc",
"shell/browser/file_select_helper.h",
"shell/browser/file_select_helper_mac.mm",
"shell/browser/font_defaults.cc",
"shell/browser/font_defaults.h",
"shell/browser/hid/electron_hid_delegate.cc",
"shell/browser/hid/electron_hid_delegate.h",
"shell/browser/hid/hid_chooser_context.cc",
"shell/browser/hid/hid_chooser_context.h",
"shell/browser/hid/hid_chooser_context_factory.cc",
"shell/browser/hid/hid_chooser_context_factory.h",
"shell/browser/hid/hid_chooser_controller.cc",
"shell/browser/hid/hid_chooser_controller.h",
"shell/browser/javascript_environment.cc",
"shell/browser/javascript_environment.h",
"shell/browser/lib/bluetooth_chooser.cc",
"shell/browser/lib/bluetooth_chooser.h",
"shell/browser/login_handler.cc",
"shell/browser/login_handler.h",
"shell/browser/media/media_capture_devices_dispatcher.cc",
"shell/browser/media/media_capture_devices_dispatcher.h",
"shell/browser/media/media_device_id_salt.cc",
"shell/browser/media/media_device_id_salt.h",
"shell/browser/microtasks_runner.cc",
"shell/browser/microtasks_runner.h",
"shell/browser/native_browser_view.cc",
"shell/browser/native_browser_view.h",
"shell/browser/native_window.cc",
"shell/browser/native_window.h",
"shell/browser/native_window_features.cc",
"shell/browser/native_window_features.h",
"shell/browser/native_window_observer.h",
"shell/browser/net/asar/asar_file_validator.cc",
"shell/browser/net/asar/asar_file_validator.h",
"shell/browser/net/asar/asar_url_loader.cc",
"shell/browser/net/asar/asar_url_loader.h",
"shell/browser/net/asar/asar_url_loader_factory.cc",
"shell/browser/net/asar/asar_url_loader_factory.h",
"shell/browser/net/cert_verifier_client.cc",
"shell/browser/net/cert_verifier_client.h",
"shell/browser/net/electron_url_loader_factory.cc",
"shell/browser/net/electron_url_loader_factory.h",
"shell/browser/net/network_context_service.cc",
"shell/browser/net/network_context_service.h",
"shell/browser/net/network_context_service_factory.cc",
"shell/browser/net/network_context_service_factory.h",
"shell/browser/net/node_stream_loader.cc",
"shell/browser/net/node_stream_loader.h",
"shell/browser/net/proxying_url_loader_factory.cc",
"shell/browser/net/proxying_url_loader_factory.h",
"shell/browser/net/proxying_websocket.cc",
"shell/browser/net/proxying_websocket.h",
"shell/browser/net/resolve_proxy_helper.cc",
"shell/browser/net/resolve_proxy_helper.h",
"shell/browser/net/system_network_context_manager.cc",
"shell/browser/net/system_network_context_manager.h",
"shell/browser/net/url_pipe_loader.cc",
"shell/browser/net/url_pipe_loader.h",
"shell/browser/net/web_request_api_interface.h",
"shell/browser/network_hints_handler_impl.cc",
"shell/browser/network_hints_handler_impl.h",
"shell/browser/notifications/notification.cc",
"shell/browser/notifications/notification.h",
"shell/browser/notifications/notification_delegate.h",
"shell/browser/notifications/notification_presenter.cc",
"shell/browser/notifications/notification_presenter.h",
"shell/browser/notifications/platform_notification_service.cc",
"shell/browser/notifications/platform_notification_service.h",
"shell/browser/plugins/plugin_utils.cc",
"shell/browser/plugins/plugin_utils.h",
"shell/browser/protocol_registry.cc",
"shell/browser/protocol_registry.h",
"shell/browser/relauncher.cc",
"shell/browser/relauncher.h",
"shell/browser/serial/electron_serial_delegate.cc",
"shell/browser/serial/electron_serial_delegate.h",
"shell/browser/serial/serial_chooser_context.cc",
"shell/browser/serial/serial_chooser_context.h",
"shell/browser/serial/serial_chooser_context_factory.cc",
"shell/browser/serial/serial_chooser_context_factory.h",
"shell/browser/serial/serial_chooser_controller.cc",
"shell/browser/serial/serial_chooser_controller.h",
"shell/browser/session_preferences.cc",
"shell/browser/session_preferences.h",
"shell/browser/special_storage_policy.cc",
"shell/browser/special_storage_policy.h",
"shell/browser/ui/accelerator_util.cc",
"shell/browser/ui/accelerator_util.h",
"shell/browser/ui/autofill_popup.cc",
"shell/browser/ui/autofill_popup.h",
"shell/browser/ui/certificate_trust.h",
"shell/browser/ui/devtools_manager_delegate.cc",
"shell/browser/ui/devtools_manager_delegate.h",
"shell/browser/ui/devtools_ui.cc",
"shell/browser/ui/devtools_ui.h",
"shell/browser/ui/drag_util.cc",
"shell/browser/ui/drag_util.h",
"shell/browser/ui/electron_menu_model.cc",
"shell/browser/ui/electron_menu_model.h",
"shell/browser/ui/file_dialog.h",
"shell/browser/ui/inspectable_web_contents.cc",
"shell/browser/ui/inspectable_web_contents.h",
"shell/browser/ui/inspectable_web_contents_delegate.h",
"shell/browser/ui/inspectable_web_contents_view.cc",
"shell/browser/ui/inspectable_web_contents_view.h",
"shell/browser/ui/inspectable_web_contents_view_delegate.cc",
"shell/browser/ui/inspectable_web_contents_view_delegate.h",
"shell/browser/ui/message_box.h",
"shell/browser/ui/tray_icon.cc",
"shell/browser/ui/tray_icon.h",
"shell/browser/ui/tray_icon_observer.h",
"shell/browser/ui/webui/accessibility_ui.cc",
"shell/browser/ui/webui/accessibility_ui.h",
"shell/browser/usb/electron_usb_delegate.cc",
"shell/browser/usb/electron_usb_delegate.h",
"shell/browser/usb/usb_chooser_context.cc",
"shell/browser/usb/usb_chooser_context.h",
"shell/browser/usb/usb_chooser_context_factory.cc",
"shell/browser/usb/usb_chooser_context_factory.h",
"shell/browser/usb/usb_chooser_controller.cc",
"shell/browser/usb/usb_chooser_controller.h",
"shell/browser/web_contents_permission_helper.cc",
"shell/browser/web_contents_permission_helper.h",
"shell/browser/web_contents_preferences.cc",
"shell/browser/web_contents_preferences.h",
"shell/browser/web_contents_zoom_controller.cc",
"shell/browser/web_contents_zoom_controller.h",
"shell/browser/web_view_guest_delegate.cc",
"shell/browser/web_view_guest_delegate.h",
"shell/browser/web_view_manager.cc",
"shell/browser/web_view_manager.h",
"shell/browser/webauthn/electron_authenticator_request_delegate.cc",
"shell/browser/webauthn/electron_authenticator_request_delegate.h",
"shell/browser/window_list.cc",
"shell/browser/window_list.h",
"shell/browser/window_list_observer.h",
"shell/browser/zoom_level_delegate.cc",
"shell/browser/zoom_level_delegate.h",
"shell/common/api/crashpad_support.cc",
"shell/common/api/electron_api_asar.cc",
"shell/common/api/electron_api_clipboard.cc",
"shell/common/api/electron_api_clipboard.h",
"shell/common/api/electron_api_command_line.cc",
"shell/common/api/electron_api_environment.cc",
"shell/common/api/electron_api_key_weak_map.h",
"shell/common/api/electron_api_native_image.cc",
"shell/common/api/electron_api_native_image.h",
"shell/common/api/electron_api_shell.cc",
"shell/common/api/electron_api_testing.cc",
"shell/common/api/electron_api_v8_util.cc",
"shell/common/api/electron_bindings.cc",
"shell/common/api/electron_bindings.h",
"shell/common/api/features.cc",
"shell/common/api/object_life_monitor.cc",
"shell/common/api/object_life_monitor.h",
"shell/common/application_info.cc",
"shell/common/application_info.h",
"shell/common/asar/archive.cc",
"shell/common/asar/archive.h",
"shell/common/asar/asar_util.cc",
"shell/common/asar/asar_util.h",
"shell/common/asar/scoped_temporary_file.cc",
"shell/common/asar/scoped_temporary_file.h",
"shell/common/color_util.cc",
"shell/common/color_util.h",
"shell/common/crash_keys.cc",
"shell/common/crash_keys.h",
"shell/common/electron_command_line.cc",
"shell/common/electron_command_line.h",
"shell/common/electron_constants.cc",
"shell/common/electron_constants.h",
"shell/common/electron_paths.h",
"shell/common/gin_converters/accelerator_converter.cc",
"shell/common/gin_converters/accelerator_converter.h",
"shell/common/gin_converters/base_converter.h",
"shell/common/gin_converters/blink_converter.cc",
"shell/common/gin_converters/blink_converter.h",
"shell/common/gin_converters/callback_converter.h",
"shell/common/gin_converters/content_converter.cc",
"shell/common/gin_converters/content_converter.h",
"shell/common/gin_converters/file_dialog_converter.cc",
"shell/common/gin_converters/file_dialog_converter.h",
"shell/common/gin_converters/file_path_converter.h",
"shell/common/gin_converters/frame_converter.cc",
"shell/common/gin_converters/frame_converter.h",
"shell/common/gin_converters/gfx_converter.cc",
"shell/common/gin_converters/gfx_converter.h",
"shell/common/gin_converters/guid_converter.h",
"shell/common/gin_converters/gurl_converter.h",
"shell/common/gin_converters/hid_device_info_converter.h",
"shell/common/gin_converters/image_converter.cc",
"shell/common/gin_converters/image_converter.h",
"shell/common/gin_converters/media_converter.cc",
"shell/common/gin_converters/media_converter.h",
"shell/common/gin_converters/message_box_converter.cc",
"shell/common/gin_converters/message_box_converter.h",
"shell/common/gin_converters/native_window_converter.h",
"shell/common/gin_converters/net_converter.cc",
"shell/common/gin_converters/net_converter.h",
"shell/common/gin_converters/serial_port_info_converter.h",
"shell/common/gin_converters/std_converter.h",
"shell/common/gin_converters/time_converter.cc",
"shell/common/gin_converters/time_converter.h",
"shell/common/gin_converters/usb_device_info_converter.h",
"shell/common/gin_converters/value_converter.cc",
"shell/common/gin_converters/value_converter.h",
"shell/common/gin_helper/arguments.cc",
"shell/common/gin_helper/arguments.h",
"shell/common/gin_helper/callback.cc",
"shell/common/gin_helper/callback.h",
"shell/common/gin_helper/cleaned_up_at_exit.cc",
"shell/common/gin_helper/cleaned_up_at_exit.h",
"shell/common/gin_helper/constructible.h",
"shell/common/gin_helper/constructor.h",
"shell/common/gin_helper/destroyable.cc",
"shell/common/gin_helper/destroyable.h",
"shell/common/gin_helper/dictionary.h",
"shell/common/gin_helper/error_thrower.cc",
"shell/common/gin_helper/error_thrower.h",
"shell/common/gin_helper/event_emitter.cc",
"shell/common/gin_helper/event_emitter.h",
"shell/common/gin_helper/event_emitter_caller.cc",
"shell/common/gin_helper/event_emitter_caller.h",
"shell/common/gin_helper/function_template.cc",
"shell/common/gin_helper/function_template.h",
"shell/common/gin_helper/function_template_extensions.h",
"shell/common/gin_helper/locker.cc",
"shell/common/gin_helper/locker.h",
"shell/common/gin_helper/microtasks_scope.cc",
"shell/common/gin_helper/microtasks_scope.h",
"shell/common/gin_helper/object_template_builder.cc",
"shell/common/gin_helper/object_template_builder.h",
"shell/common/gin_helper/persistent_dictionary.cc",
"shell/common/gin_helper/persistent_dictionary.h",
"shell/common/gin_helper/pinnable.h",
"shell/common/gin_helper/promise.cc",
"shell/common/gin_helper/promise.h",
"shell/common/gin_helper/trackable_object.cc",
"shell/common/gin_helper/trackable_object.h",
"shell/common/gin_helper/wrappable.cc",
"shell/common/gin_helper/wrappable.h",
"shell/common/gin_helper/wrappable_base.h",
"shell/common/heap_snapshot.cc",
"shell/common/heap_snapshot.h",
"shell/common/key_weak_map.h",
"shell/common/keyboard_util.cc",
"shell/common/keyboard_util.h",
"shell/common/language_util.h",
"shell/common/logging.cc",
"shell/common/logging.h",
"shell/common/mouse_util.cc",
"shell/common/mouse_util.h",
"shell/common/node_bindings.cc",
"shell/common/node_bindings.h",
"shell/common/node_includes.h",
"shell/common/node_util.cc",
"shell/common/node_util.h",
"shell/common/options_switches.cc",
"shell/common/options_switches.h",
"shell/common/platform_util.cc",
"shell/common/platform_util.h",
"shell/common/platform_util_internal.h",
"shell/common/process_util.cc",
"shell/common/process_util.h",
"shell/common/skia_util.cc",
"shell/common/skia_util.h",
"shell/common/thread_restrictions.h",
"shell/common/v8_value_serializer.cc",
"shell/common/v8_value_serializer.h",
"shell/common/world_ids.h",
"shell/renderer/api/context_bridge/object_cache.cc",
"shell/renderer/api/context_bridge/object_cache.h",
"shell/renderer/api/electron_api_context_bridge.cc",
"shell/renderer/api/electron_api_context_bridge.h",
"shell/renderer/api/electron_api_crash_reporter_renderer.cc",
"shell/renderer/api/electron_api_ipc_renderer.cc",
"shell/renderer/api/electron_api_spell_check_client.cc",
"shell/renderer/api/electron_api_spell_check_client.h",
"shell/renderer/api/electron_api_web_frame.cc",
"shell/renderer/browser_exposed_renderer_interfaces.cc",
"shell/renderer/browser_exposed_renderer_interfaces.h",
"shell/renderer/content_settings_observer.cc",
"shell/renderer/content_settings_observer.h",
"shell/renderer/electron_api_service_impl.cc",
"shell/renderer/electron_api_service_impl.h",
"shell/renderer/electron_autofill_agent.cc",
"shell/renderer/electron_autofill_agent.h",
"shell/renderer/electron_render_frame_observer.cc",
"shell/renderer/electron_render_frame_observer.h",
"shell/renderer/electron_renderer_client.cc",
"shell/renderer/electron_renderer_client.h",
"shell/renderer/electron_sandboxed_renderer_client.cc",
"shell/renderer/electron_sandboxed_renderer_client.h",
"shell/renderer/renderer_client_base.cc",
"shell/renderer/renderer_client_base.h",
"shell/renderer/web_worker_observer.cc",
"shell/renderer/web_worker_observer.h",
"shell/services/node/node_service.cc",
"shell/services/node/node_service.h",
"shell/services/node/parent_port.cc",
"shell/services/node/parent_port.h",
"shell/utility/electron_content_utility_client.cc",
"shell/utility/electron_content_utility_client.h",
]
lib_sources_extensions = [
"shell/browser/extensions/api/management/electron_management_api_delegate.cc",
"shell/browser/extensions/api/management/electron_management_api_delegate.h",
"shell/browser/extensions/api/resources_private/resources_private_api.cc",
"shell/browser/extensions/api/resources_private/resources_private_api.h",
"shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc",
"shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h",
"shell/browser/extensions/api/streams_private/streams_private_api.cc",
"shell/browser/extensions/api/streams_private/streams_private_api.h",
"shell/browser/extensions/api/tabs/tabs_api.cc",
"shell/browser/extensions/api/tabs/tabs_api.h",
"shell/browser/extensions/electron_browser_context_keyed_service_factories.cc",
"shell/browser/extensions/electron_browser_context_keyed_service_factories.h",
"shell/browser/extensions/electron_component_extension_resource_manager.cc",
"shell/browser/extensions/electron_component_extension_resource_manager.h",
"shell/browser/extensions/electron_display_info_provider.cc",
"shell/browser/extensions/electron_display_info_provider.h",
"shell/browser/extensions/electron_extension_host_delegate.cc",
"shell/browser/extensions/electron_extension_host_delegate.h",
"shell/browser/extensions/electron_extension_loader.cc",
"shell/browser/extensions/electron_extension_loader.h",
"shell/browser/extensions/electron_extension_message_filter.cc",
"shell/browser/extensions/electron_extension_message_filter.h",
"shell/browser/extensions/electron_extension_system_factory.cc",
"shell/browser/extensions/electron_extension_system_factory.h",
"shell/browser/extensions/electron_extension_system.cc",
"shell/browser/extensions/electron_extension_system.h",
"shell/browser/extensions/electron_extension_web_contents_observer.cc",
"shell/browser/extensions/electron_extension_web_contents_observer.h",
"shell/browser/extensions/electron_extensions_api_client.cc",
"shell/browser/extensions/electron_extensions_api_client.h",
"shell/browser/extensions/electron_extensions_browser_api_provider.cc",
"shell/browser/extensions/electron_extensions_browser_api_provider.h",
"shell/browser/extensions/electron_extensions_browser_client.cc",
"shell/browser/extensions/electron_extensions_browser_client.h",
"shell/browser/extensions/electron_kiosk_delegate.cc",
"shell/browser/extensions/electron_kiosk_delegate.h",
"shell/browser/extensions/electron_messaging_delegate.cc",
"shell/browser/extensions/electron_messaging_delegate.h",
"shell/browser/extensions/electron_navigation_ui_data.cc",
"shell/browser/extensions/electron_navigation_ui_data.h",
"shell/browser/extensions/electron_process_manager_delegate.cc",
"shell/browser/extensions/electron_process_manager_delegate.h",
"shell/common/extensions/electron_extensions_api_provider.cc",
"shell/common/extensions/electron_extensions_api_provider.h",
"shell/common/extensions/electron_extensions_client.cc",
"shell/common/extensions/electron_extensions_client.h",
"shell/common/gin_converters/extension_converter.cc",
"shell/common/gin_converters/extension_converter.h",
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc",
"shell/renderer/extensions/electron_extensions_dispatcher_delegate.h",
"shell/renderer/extensions/electron_extensions_renderer_client.cc",
"shell/renderer/extensions/electron_extensions_renderer_client.h",
]
framework_sources = [
"shell/app/electron_library_main.h",
"shell/app/electron_library_main.mm",
]
login_helper_sources = [ "shell/app/electron_login_helper.mm" ]
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/gtk/menu_gtk.cc
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/gtk/menu_gtk.h
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/status_icon_gtk.cc
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/status_icon_gtk.h
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/tray_icon_gtk.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/tray_icon_gtk.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h"
#include "ui/gfx/image/image_skia_rep.h"
namespace electron {
namespace {
gfx::ImageSkia GetBestImageRep(const gfx::ImageSkia& image) {
image.EnsureRepsForSupportedScales();
float best_scale = 0.0f;
SkBitmap best_rep;
for (const auto& rep : image.image_reps()) {
if (rep.scale() > best_scale) {
best_scale = rep.scale();
best_rep = rep.GetBitmap();
}
}
// All status icon implementations want the image in pixel coordinates, so use
// a scale factor of 1.
return gfx::ImageSkia::CreateFromBitmap(best_rep, 1.0f);
}
} // namespace
TrayIconGtk::TrayIconGtk()
: status_icon_(new StatusIconLinuxDbus),
status_icon_type_(StatusIconType::kDbus) {
status_icon_->SetDelegate(this);
}
TrayIconGtk::~TrayIconGtk() = default;
void TrayIconGtk::SetImage(const gfx::Image& image) {
image_ = GetBestImageRep(image.AsImageSkia());
if (status_icon_)
status_icon_->SetIcon(image_);
}
void TrayIconGtk::SetToolTip(const std::string& tool_tip) {
tool_tip_ = base::UTF8ToUTF16(tool_tip);
if (status_icon_)
status_icon_->SetToolTip(tool_tip_);
}
void TrayIconGtk::SetContextMenu(ElectronMenuModel* menu_model) {
menu_model_ = menu_model;
if (status_icon_)
status_icon_->UpdatePlatformContextMenu(menu_model_);
}
const gfx::ImageSkia& TrayIconGtk::GetImage() const {
return image_;
}
const std::u16string& TrayIconGtk::GetToolTip() const {
return tool_tip_;
}
ui::MenuModel* TrayIconGtk::GetMenuModel() const {
return menu_model_;
}
void TrayIconGtk::OnImplInitializationFailed() {
switch (status_icon_type_) {
case StatusIconType::kDbus:
status_icon_ = nullptr;
status_icon_type_ = StatusIconType::kNone;
return;
case StatusIconType::kNone:
NOTREACHED();
}
}
void TrayIconGtk::OnClick() {
NotifyClicked();
}
bool TrayIconGtk::HasClickAction() {
// Returning true will make the tooltip show as an additional context menu
// item, which makes sense in Chrome but not in most Electron apps.
return false;
}
// static
TrayIcon* TrayIcon::Create(absl::optional<UUID> guid) {
return new TrayIconGtk;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/tray_icon_linux.cc
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
shell/browser/ui/tray_icon_linux.h
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 36,602 |
[Bug]: No Tray icon for Arch Linux
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux, Manjaro
### What arch are you using?
x64
### Last Known Working Electron version
22.0.0
### Expected Behavior
Be able to use Electron [tray API](https://www.electronjs.org/docs/latest/api/tray)
### Actual Behavior
I cannot have any Tray icon showing up since the last release of Electron 22.0.0. I believe we change the underlying implementation for Tray API with [this PR](https://github.com/electron/electron/pull/36333).
With Electron <= 21, it worked fine
Here's the info of OS we're using
```
$ uname -a
Linux tower 6.0.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 02 Dec 2022 17:25:31 +0000 x86_64 GNU/Linux
```
or
```
$ uname -a
Linux manjaro 5.15.60-1-MANJARO #1 SMP PREEMPT Thu Aug 11 13:14:05 UTC 2022 x86_64 GNU/Linux
```
I attached the minimum reproduction example here. Steps:
- `yarn install`
- then `yarn start`
- cannot see the Tray icon
- `yarn add --dev [email protected]`
- `yarn start` again
- then we see the Tray icon again (should be a T-shirt png)
[electron-tray-22.zip](https://github.com/electron/electron/files/10175635/electron-tray-22.zip)
### Testcase Gist URL
_No response_
### Additional Information
We don't experience this issue for Mac, Windows and Ubuntu
|
https://github.com/electron/electron/issues/36602
|
https://github.com/electron/electron/pull/36815
|
7d46d3ec9d5f30138777d1bd12890ebe28ba6c31
|
c303135b02fa5829459c816cd5bb75dd0e6e4aeb
| 2022-12-07T11:48:18Z |
c++
| 2023-01-26T10:15:55Z |
BUILD.gn
|
import("//build/config/locales.gni")
import("//build/config/ui.gni")
import("//build/config/win/manifest.gni")
import("//components/os_crypt/features.gni")
import("//components/spellcheck/spellcheck_build_features.gni")
import("//content/public/app/mac_helpers.gni")
import("//extensions/buildflags/buildflags.gni")
import("//pdf/features.gni")
import("//ppapi/buildflags/buildflags.gni")
import("//printing/buildflags/buildflags.gni")
import("//testing/test.gni")
import("//third_party/ffmpeg/ffmpeg_options.gni")
import("//tools/generate_library_loader/generate_library_loader.gni")
import("//tools/grit/grit_rule.gni")
import("//tools/grit/repack.gni")
import("//tools/v8_context_snapshot/v8_context_snapshot.gni")
import("//v8/gni/snapshot_toolchain.gni")
import("build/asar.gni")
import("build/extract_symbols.gni")
import("build/npm.gni")
import("build/templated_file.gni")
import("build/tsc.gni")
import("build/webpack/webpack.gni")
import("buildflags/buildflags.gni")
import("electron_paks.gni")
import("filenames.auto.gni")
import("filenames.gni")
import("filenames.hunspell.gni")
import("filenames.libcxx.gni")
import("filenames.libcxxabi.gni")
if (is_mac) {
import("//build/config/mac/rules.gni")
import("//third_party/icu/config.gni")
import("//ui/gl/features.gni")
import("//v8/gni/v8.gni")
import("build/rules.gni")
assert(
mac_deployment_target == "10.13",
"Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change")
}
if (is_linux) {
import("//build/config/linux/pkg_config.gni")
import("//tools/generate_stubs/rules.gni")
pkg_config("gio_unix") {
packages = [ "gio-unix-2.0" ]
}
pkg_config("libnotify_config") {
packages = [
"glib-2.0",
"gdk-pixbuf-2.0",
]
}
generate_library_loader("libnotify_loader") {
name = "LibNotifyLoader"
output_h = "libnotify_loader.h"
output_cc = "libnotify_loader.cc"
header = "<libnotify/notify.h>"
config = ":libnotify_config"
functions = [
"notify_is_initted",
"notify_init",
"notify_get_server_caps",
"notify_get_server_info",
"notify_notification_new",
"notify_notification_add_action",
"notify_notification_set_image_from_pixbuf",
"notify_notification_set_timeout",
"notify_notification_set_urgency",
"notify_notification_set_hint_string",
"notify_notification_show",
"notify_notification_close",
]
}
# Generates electron_gtk_stubs.h header which contains
# stubs for extracting function ptrs from the gtk library.
# Function signatures for which stubs are required should be
# declared in electron_gtk.sigs, currently this file contains
# signatures for the functions used with native file chooser
# implementation. In future, this file can be extended to contain
# gtk4 stubs to switch gtk version in runtime.
generate_stubs("electron_gtk_stubs") {
sigs = [
"shell/browser/ui/electron_gdk_pixbuf.sigs",
"shell/browser/ui/electron_gtk.sigs",
]
extra_header = "shell/browser/ui/electron_gtk.fragment"
output_name = "electron_gtk_stubs"
public_deps = [ "//ui/gtk:gtk_config" ]
logging_function = "LogNoop()"
logging_include = "ui/gtk/log_noop.h"
}
}
declare_args() {
use_prebuilt_v8_context_snapshot = false
}
branding = read_file("shell/app/BRANDING.json", "json")
electron_project_name = branding.project_name
electron_product_name = branding.product_name
electron_mac_bundle_id = branding.mac_bundle_id
electron_version = exec_script("script/print-version.py",
[],
"trim string",
[
".git/packed-refs",
".git/HEAD",
"script/lib/get-version.js",
])
if (is_mas_build) {
assert(is_mac,
"It doesn't make sense to build a MAS build on a non-mac platform")
}
if (enable_pdf_viewer) {
assert(enable_pdf, "PDF viewer support requires enable_pdf=true")
assert(enable_electron_extensions,
"PDF viewer support requires enable_electron_extensions=true")
}
if (enable_electron_extensions) {
assert(enable_extensions,
"Chrome extension support requires enable_extensions=true")
}
config("branding") {
defines = [
"ELECTRON_PRODUCT_NAME=\"$electron_product_name\"",
"ELECTRON_PROJECT_NAME=\"$electron_project_name\"",
]
}
config("electron_lib_config") {
include_dirs = [ "." ]
}
# We generate the definitions twice here, once in //electron/electron.d.ts
# and once in $target_gen_dir
# The one in $target_gen_dir is used for the actual TSC build later one
# and the one in //electron/electron.d.ts is used by your IDE (vscode)
# for typescript prompting
npm_action("build_electron_definitions") {
script = "gn-typescript-definitions"
args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ]
inputs = auto_filenames.api_docs + [ "yarn.lock" ]
outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ]
}
webpack_build("electron_asar_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.asar_bundle_deps
config_file = "//electron/build/webpack/webpack.config.asar.js"
out_file = "$target_gen_dir/js2c/asar_bundle.js"
}
webpack_build("electron_browser_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.browser_bundle_deps
config_file = "//electron/build/webpack/webpack.config.browser.js"
out_file = "$target_gen_dir/js2c/browser_init.js"
}
webpack_build("electron_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.renderer_bundle_deps
config_file = "//electron/build/webpack/webpack.config.renderer.js"
out_file = "$target_gen_dir/js2c/renderer_init.js"
}
webpack_build("electron_worker_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.worker_bundle_deps
config_file = "//electron/build/webpack/webpack.config.worker.js"
out_file = "$target_gen_dir/js2c/worker_init.js"
}
webpack_build("electron_sandboxed_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.sandbox_bundle_deps
config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js"
out_file = "$target_gen_dir/js2c/sandbox_bundle.js"
}
webpack_build("electron_isolated_renderer_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.isolated_bundle_deps
config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js"
out_file = "$target_gen_dir/js2c/isolated_bundle.js"
}
webpack_build("electron_utility_bundle") {
deps = [ ":build_electron_definitions" ]
inputs = auto_filenames.utility_bundle_deps
config_file = "//electron/build/webpack/webpack.config.utility.js"
out_file = "$target_gen_dir/js2c/utility_init.js"
}
action("electron_js2c") {
deps = [
":electron_asar_bundle",
":electron_browser_bundle",
":electron_isolated_renderer_bundle",
":electron_renderer_bundle",
":electron_sandboxed_renderer_bundle",
":electron_utility_bundle",
":electron_worker_bundle",
]
sources = [
"$target_gen_dir/js2c/asar_bundle.js",
"$target_gen_dir/js2c/browser_init.js",
"$target_gen_dir/js2c/isolated_bundle.js",
"$target_gen_dir/js2c/renderer_init.js",
"$target_gen_dir/js2c/sandbox_bundle.js",
"$target_gen_dir/js2c/utility_init.js",
"$target_gen_dir/js2c/worker_init.js",
]
inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ]
outputs = [ "$root_gen_dir/electron_natives.cc" ]
script = "build/js2c.py"
args = [ rebase_path("//third_party/electron_node") ] +
rebase_path(outputs, root_build_dir) +
rebase_path(sources, root_build_dir)
}
action("generate_config_gypi") {
outputs = [ "$root_gen_dir/config.gypi" ]
script = "script/generate-config-gypi.py"
inputs = [ "//third_party/electron_node/configure.py" ]
args = rebase_path(outputs) + [ target_cpu ]
}
target_gen_default_app_js = "$target_gen_dir/js/default_app"
typescript_build("default_app_js") {
deps = [ ":build_electron_definitions" ]
sources = filenames.default_app_ts_sources
output_gen_dir = target_gen_default_app_js
output_dir_name = "default_app"
tsconfig = "tsconfig.default_app.json"
}
copy("default_app_static") {
sources = filenames.default_app_static_sources
outputs = [ "$target_gen_default_app_js/{{source}}" ]
}
copy("default_app_octicon_deps") {
sources = filenames.default_app_octicon_sources
outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ]
}
asar("default_app_asar") {
deps = [
":default_app_js",
":default_app_octicon_deps",
":default_app_static",
]
root = "$target_gen_default_app_js/electron/default_app"
sources = get_target_outputs(":default_app_js") +
get_target_outputs(":default_app_static") +
get_target_outputs(":default_app_octicon_deps")
outputs = [ "$root_out_dir/resources/default_app.asar" ]
}
grit("resources") {
source = "electron_resources.grd"
outputs = [
"grit/electron_resources.h",
"electron_resources.pak",
]
# Mojo manifest overlays are generated.
grit_flags = [
"-E",
"target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir),
]
deps = [ ":copy_shell_devtools_discovery_page" ]
output_dir = "$target_gen_dir"
}
copy("copy_shell_devtools_discovery_page") {
sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ]
outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ]
}
npm_action("electron_version_args") {
script = "generate-version-json"
outputs = [ "$target_gen_dir/electron_version.args" ]
args = rebase_path(outputs) + [ "$electron_version" ]
inputs = [ "script/generate-version-json.js" ]
}
templated_file("electron_version_header") {
deps = [ ":electron_version_args" ]
template = "build/templates/electron_version.tmpl"
output = "$target_gen_dir/electron_version.h"
args_files = get_target_outputs(":electron_version_args")
}
templated_file("electron_win_rc") {
deps = [ ":electron_version_args" ]
template = "build/templates/electron_rc.tmpl"
output = "$target_gen_dir/win-resources/electron.rc"
args_files = get_target_outputs(":electron_version_args")
}
copy("electron_win_resource_files") {
sources = [
"shell/browser/resources/win/electron.ico",
"shell/browser/resources/win/resource.h",
]
outputs = [ "$target_gen_dir/win-resources/{{source_file_part}}" ]
}
templated_file("electron_version_file") {
deps = [ ":electron_version_args" ]
template = "build/templates/version_string.tmpl"
output = "$root_build_dir/version"
args_files = get_target_outputs(":electron_version_args")
}
group("electron_win32_resources") {
public_deps = [
":electron_win_rc",
":electron_win_resource_files",
]
}
action("electron_fuses") {
script = "build/fuses/build.py"
inputs = [ "build/fuses/fuses.json5" ]
outputs = [
"$target_gen_dir/fuses.h",
"$target_gen_dir/fuses.cc",
]
args = rebase_path(outputs)
}
action("electron_generate_node_defines") {
script = "build/generate_node_defines.py"
inputs = [
"//third_party/electron_node/src/tracing/trace_event_common.h",
"//third_party/electron_node/src/tracing/trace_event.h",
"//third_party/electron_node/src/util.h",
]
outputs = [
"$target_gen_dir/push_and_undef_node_defines.h",
"$target_gen_dir/pop_node_defines.h",
]
args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs)
}
source_set("electron_lib") {
configs += [ "//v8:external_startup_data" ]
configs += [ "//third_party/electron_node:node_internals" ]
public_configs = [
":branding",
":electron_lib_config",
]
deps = [
":electron_fuses",
":electron_generate_node_defines",
":electron_js2c",
":electron_version_header",
":resources",
"buildflags",
"chromium_src:chrome",
"chromium_src:chrome_spellchecker",
"shell/common/api:mojo",
"shell/services/node/public/mojom",
"//base:base_static",
"//base/allocator:buildflags",
"//chrome:strings",
"//chrome/app:command_ids",
"//chrome/app/resources:platform_locale_settings",
"//components/autofill/core/common:features",
"//components/certificate_transparency",
"//components/embedder_support:browser_util",
"//components/language/core/browser",
"//components/net_log",
"//components/network_hints/browser",
"//components/network_hints/common:mojo_bindings",
"//components/network_hints/renderer",
"//components/network_session_configurator/common",
"//components/omnibox/browser:buildflags",
"//components/os_crypt",
"//components/pref_registry",
"//components/prefs",
"//components/security_state/content",
"//components/upload_list",
"//components/user_prefs",
"//components/viz/host",
"//components/viz/service",
"//components/webrtc",
"//content/public/browser",
"//content/public/child",
"//content/public/gpu",
"//content/public/renderer",
"//content/public/utility",
"//device/bluetooth",
"//device/bluetooth/public/cpp",
"//gin",
"//media/capture/mojom:video_capture",
"//media/mojo/mojom",
"//net:extras",
"//net:net_resources",
"//printing/buildflags",
"//services/device/public/cpp/geolocation",
"//services/device/public/cpp/hid",
"//services/device/public/mojom",
"//services/proxy_resolver:lib",
"//services/video_capture/public/mojom:constants",
"//services/viz/privileged/mojom/compositing",
"//skia",
"//third_party/blink/public:blink",
"//third_party/blink/public:blink_devtools_inspector_resources",
"//third_party/blink/public/platform/media",
"//third_party/boringssl",
"//third_party/electron_node:node_lib",
"//third_party/inspector_protocol:crdtp",
"//third_party/leveldatabase",
"//third_party/libyuv",
"//third_party/webrtc_overrides:webrtc_component",
"//third_party/widevine/cdm:headers",
"//third_party/zlib/google:zip",
"//ui/base/idle",
"//ui/events:dom_keycode_converter",
"//ui/gl",
"//ui/native_theme",
"//ui/shell_dialogs",
"//ui/views",
"//v8",
"//v8:v8_libplatform",
]
public_deps = [
"//base",
"//base:i18n",
"//content/public/app",
]
include_dirs = [
".",
"$target_gen_dir",
# TODO(nornagon): replace usage of SchemeRegistry by an actually exported
# API of blink, then remove this from the include_dirs.
"//third_party/blink/renderer",
]
defines = [ "V8_DEPRECATION_WARNINGS" ]
libs = []
if (is_linux) {
defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ]
}
if (!is_mas_build) {
deps += [
"//components/crash/core/app",
"//components/crash/core/browser",
]
}
configs += [ "//electron/build/config:mas_build" ]
sources = filenames.lib_sources
if (is_win) {
sources += filenames.lib_sources_win
}
if (is_mac) {
sources += filenames.lib_sources_mac
}
if (is_posix) {
sources += filenames.lib_sources_posix
}
if (is_linux) {
sources += filenames.lib_sources_linux
}
if (!is_mac) {
sources += filenames.lib_sources_views
}
if (is_component_build) {
defines += [ "NODE_SHARED_MODE" ]
}
if (enable_fake_location_provider) {
sources += [
"shell/browser/fake_location_provider.cc",
"shell/browser/fake_location_provider.h",
]
}
if (is_mac) {
deps += [
"//components/remote_cocoa/app_shim",
"//components/remote_cocoa/browser",
"//content/common:mac_helpers",
"//ui/accelerated_widget_mac",
]
if (!is_mas_build) {
deps += [ "//third_party/crashpad/crashpad/client" ]
}
frameworks = [
"AVFoundation.framework",
"Carbon.framework",
"LocalAuthentication.framework",
"QuartzCore.framework",
"Quartz.framework",
"Security.framework",
"SecurityInterface.framework",
"ServiceManagement.framework",
"StoreKit.framework",
]
weak_frameworks = [ "QuickLookThumbnailing.framework" ]
sources += [
"shell/browser/ui/views/autofill_popup_view.cc",
"shell/browser/ui/views/autofill_popup_view.h",
]
if (is_mas_build) {
sources += [ "shell/browser/api/electron_api_app_mas.mm" ]
sources -= [ "shell/browser/auto_updater_mac.mm" ]
sources -= [
"shell/app/electron_crash_reporter_client.cc",
"shell/app/electron_crash_reporter_client.h",
"shell/common/crash_keys.cc",
"shell/common/crash_keys.h",
]
} else {
frameworks += [
"Squirrel.framework",
"ReactiveObjC.framework",
"Mantle.framework",
]
deps += [
"//third_party/squirrel.mac:reactiveobjc_framework+link",
"//third_party/squirrel.mac:squirrel_framework+link",
]
# ReactiveObjC which is used by Squirrel requires using __weak.
cflags_objcc = [ "-fobjc-weak" ]
}
}
if (is_linux) {
libs = [ "xshmfence" ]
deps += [
":electron_gtk_stubs",
":libnotify_loader",
"//build/config/linux/gtk",
"//components/crash/content/browser",
"//dbus",
"//device/bluetooth",
"//third_party/crashpad/crashpad/client",
"//ui/base/ime/linux",
"//ui/events/devices/x11",
"//ui/events/platform/x11",
"//ui/gtk:gtk_config",
"//ui/linux:linux_ui",
"//ui/linux:linux_ui_factory",
"//ui/views/controls/webview",
"//ui/wm",
]
if (ozone_platform_x11) {
sources += filenames.lib_sources_linux_x11
public_deps += [
"//ui/base/x",
"//ui/ozone/platform/x11",
]
}
configs += [ ":gio_unix" ]
defines += [
# Disable warnings for g_settings_list_schemas.
"GLIB_DISABLE_DEPRECATION_WARNINGS",
]
sources += [
"shell/browser/certificate_manager_model.cc",
"shell/browser/certificate_manager_model.h",
"shell/browser/ui/gtk/menu_util.cc",
"shell/browser/ui/gtk/menu_util.h",
"shell/browser/ui/gtk_util.cc",
"shell/browser/ui/gtk_util.h",
]
}
if (is_win) {
libs += [ "dwmapi.lib" ]
deps += [
"//components/crash/core/app:crash_export_thunks",
"//ui/native_theme:native_theme_browser",
"//ui/views/controls/webview",
"//ui/wm",
"//ui/wm/public",
]
public_deps += [
"//sandbox/win:sandbox",
"//third_party/crashpad/crashpad/handler",
]
}
if (enable_plugins) {
deps += [ "chromium_src:plugins" ]
sources += [
"shell/common/plugin_info.cc",
"shell/common/plugin_info.h",
"shell/renderer/electron_renderer_pepper_host_factory.cc",
"shell/renderer/electron_renderer_pepper_host_factory.h",
"shell/renderer/pepper_helper.cc",
"shell/renderer/pepper_helper.h",
]
}
if (enable_ppapi) {
deps += [
"//ppapi/host",
"//ppapi/proxy",
"//ppapi/shared_impl",
]
}
if (enable_run_as_node) {
sources += [
"shell/app/node_main.cc",
"shell/app/node_main.h",
]
}
if (enable_osr) {
sources += [
"shell/browser/osr/osr_host_display_client.cc",
"shell/browser/osr/osr_host_display_client.h",
"shell/browser/osr/osr_render_widget_host_view.cc",
"shell/browser/osr/osr_render_widget_host_view.h",
"shell/browser/osr/osr_video_consumer.cc",
"shell/browser/osr/osr_video_consumer.h",
"shell/browser/osr/osr_view_proxy.cc",
"shell/browser/osr/osr_view_proxy.h",
"shell/browser/osr/osr_web_contents_view.cc",
"shell/browser/osr/osr_web_contents_view.h",
]
if (is_mac) {
sources += [
"shell/browser/osr/osr_host_display_client_mac.mm",
"shell/browser/osr/osr_web_contents_view_mac.mm",
]
}
deps += [
"//components/viz/service",
"//services/viz/public/mojom",
"//ui/compositor",
]
}
if (enable_desktop_capturer) {
sources += [
"shell/browser/api/electron_api_desktop_capturer.cc",
"shell/browser/api/electron_api_desktop_capturer.h",
]
}
if (enable_views_api) {
sources += [
"shell/browser/api/views/electron_api_image_view.cc",
"shell/browser/api/views/electron_api_image_view.h",
]
}
if (enable_printing) {
sources += [
"shell/browser/printing/print_view_manager_electron.cc",
"shell/browser/printing/print_view_manager_electron.h",
"shell/renderer/printing/print_render_frame_helper_delegate.cc",
"shell/renderer/printing/print_render_frame_helper_delegate.h",
]
deps += [
"//chrome/services/printing/public/mojom",
"//components/printing/common:mojo_interfaces",
]
if (is_mac) {
deps += [ "//chrome/services/mac_notifications/public/mojom" ]
}
}
if (enable_electron_extensions) {
sources += filenames.lib_sources_extensions
deps += [
"shell/browser/extensions/api:api_registration",
"shell/common/extensions/api",
"shell/common/extensions/api:extensions_features",
"//chrome/browser/resources:component_extension_resources",
"//components/update_client:update_client",
"//components/zoom",
"//extensions/browser",
"//extensions/browser/api:api_provider",
"//extensions/browser/updater",
"//extensions/common",
"//extensions/common:core_api_provider",
"//extensions/renderer",
]
}
if (enable_pdf) {
# Printing depends on some //pdf code, so it needs to be built even if the
# pdf viewer isn't enabled.
deps += [
"//pdf",
"//pdf:features",
]
}
if (enable_pdf_viewer) {
deps += [
"//chrome/browser/resources/pdf:resources",
"//components/pdf/browser",
"//components/pdf/browser:interceptors",
"//components/pdf/common",
"//components/pdf/renderer",
"//pdf",
]
sources += [
"shell/browser/electron_pdf_web_contents_helper_client.cc",
"shell/browser/electron_pdf_web_contents_helper_client.h",
]
}
sources += get_target_outputs(":electron_fuses")
if (allow_runtime_configurable_key_storage) {
defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ]
}
}
electron_paks("packed_resources") {
if (is_mac) {
output_dir = "$root_gen_dir/electron_repack"
copy_data_to_bundle = true
} else {
output_dir = root_out_dir
}
}
if (is_mac) {
electron_framework_name = "$electron_product_name Framework"
electron_helper_name = "$electron_product_name Helper"
electron_login_helper_name = "$electron_product_name Login Helper"
electron_framework_version = "A"
mac_xib_bundle_data("electron_xibs") {
sources = [ "shell/common/resources/mac/MainMenu.xib" ]
}
action("fake_v8_context_snapshot_generator") {
script = "build/fake_v8_context_snapshot_generator.py"
args = [
rebase_path("$root_out_dir/$v8_context_snapshot_filename"),
rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"),
]
outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ]
}
bundle_data("electron_framework_resources") {
public_deps = [ ":packed_resources" ]
sources = []
if (icu_use_data_file) {
sources += [ "$root_out_dir/icudtl.dat" ]
public_deps += [ "//third_party/icu:icudata" ]
}
if (v8_use_external_startup_data) {
public_deps += [ "//v8" ]
if (use_v8_context_snapshot) {
if (use_prebuilt_v8_context_snapshot) {
sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ]
public_deps += [ ":fake_v8_context_snapshot_generator" ]
} else {
sources += [ "$root_out_dir/$v8_context_snapshot_filename" ]
public_deps += [ "//tools/v8_context_snapshot" ]
}
} else {
sources += [ "$root_out_dir/snapshot_blob.bin" ]
}
}
outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
}
if (!is_component_build && is_component_ffmpeg) {
bundle_data("electron_framework_libraries") {
sources = []
public_deps = []
sources += [ "$root_out_dir/libffmpeg.dylib" ]
public_deps += [ "//third_party/ffmpeg:ffmpeg" ]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
}
} else {
group("electron_framework_libraries") {
}
}
if (use_egl) {
# Add the ANGLE .dylibs in the Libraries directory of the Framework.
bundle_data("electron_angle_binaries") {
sources = [
"$root_out_dir/egl_intermediates/libEGL.dylib",
"$root_out_dir/egl_intermediates/libGLESv2.dylib",
]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
public_deps = [ "//ui/gl:angle_library_copy" ]
}
# Add the SwiftShader .dylibs in the Libraries directory of the Framework.
bundle_data("electron_swiftshader_binaries") {
sources = [
"$root_out_dir/vk_intermediates/libvk_swiftshader.dylib",
"$root_out_dir/vk_intermediates/vk_swiftshader_icd.json",
]
outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ]
public_deps = [ "//ui/gl:swiftshader_vk_library_copy" ]
}
}
group("electron_angle_library") {
if (use_egl) {
deps = [ ":electron_angle_binaries" ]
}
}
group("electron_swiftshader_library") {
if (use_egl) {
deps = [ ":electron_swiftshader_binaries" ]
}
}
bundle_data("electron_crashpad_helper") {
sources = [ "$root_out_dir/chrome_crashpad_handler" ]
outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ]
public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ]
if (is_asan) {
# crashpad_handler requires the ASan runtime at its @executable_path.
sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ]
public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ]
}
}
mac_framework_bundle("electron_framework") {
output_name = electron_framework_name
framework_version = electron_framework_version
framework_contents = [
"Resources",
"Libraries",
]
if (!is_mas_build) {
framework_contents += [ "Helpers" ]
}
public_deps = [
":electron_framework_libraries",
":electron_lib",
]
deps = [
":electron_angle_library",
":electron_framework_libraries",
":electron_framework_resources",
":electron_swiftshader_library",
":electron_xibs",
]
if (!is_mas_build) {
deps += [ ":electron_crashpad_helper" ]
}
info_plist = "shell/common/resources/mac/Info.plist"
extra_substitutions = [
"ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework",
"ELECTRON_VERSION=$electron_version",
]
include_dirs = [ "." ]
sources = filenames.framework_sources
frameworks = []
if (enable_osr) {
frameworks += [ "IOSurface.framework" ]
}
ldflags = [
"-Wl,-install_name,@rpath/$output_name.framework/$output_name",
"-rpath",
"@loader_path/Libraries",
# Required for exporting all symbols of libuv.
"-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a",
]
if (is_component_build) {
ldflags += [
"-rpath",
"@executable_path/../../../../../..",
]
}
# For component ffmpeg under non-component build, it is linked from
# @loader_path. However the ffmpeg.dylib is moved to a different place
# when generating app bundle, and we should change to link from @rpath.
if (is_component_ffmpeg && !is_component_build) {
ldflags += [ "-Wcrl,installnametool,-change,@loader_path/libffmpeg.dylib,@rpath/libffmpeg.dylib" ]
}
}
template("electron_helper_app") {
mac_app_bundle(target_name) {
assert(defined(invoker.helper_name_suffix))
output_name = electron_helper_name + invoker.helper_name_suffix
deps = [
":electron_framework+link",
"//base/allocator:early_zone_registration_mac",
]
if (!is_mas_build) {
deps += [ "//sandbox/mac:seatbelt" ]
}
defines = [ "HELPER_EXECUTABLE" ]
extra_configs = [ "//electron/build/config:mas_build" ]
sources = [
"shell/app/electron_main_mac.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
"shell/common/electron_constants.cc",
]
include_dirs = [ "." ]
info_plist = "shell/renderer/resources/mac/Info.plist"
extra_substitutions =
[ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ]
ldflags = [
"-rpath",
"@executable_path/../../..",
]
if (is_component_build) {
ldflags += [
"-rpath",
"@executable_path/../../../../../..",
]
}
}
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
_helper_bundle_id = helper_params[1]
_helper_suffix = helper_params[2]
electron_helper_app("electron_helper_app_${_helper_target}") {
helper_name_suffix = _helper_suffix
}
}
template("stripped_framework") {
action(target_name) {
assert(defined(invoker.framework))
script = "//electron/build/strip_framework.py"
forward_variables_from(invoker, [ "deps" ])
inputs = [ "$root_out_dir/" + invoker.framework ]
outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ]
args = rebase_path(inputs) + rebase_path(outputs)
}
}
stripped_framework("stripped_mantle_framework") {
framework = "Mantle.framework"
deps = [ "//third_party/squirrel.mac:mantle_framework" ]
}
stripped_framework("stripped_reactiveobjc_framework") {
framework = "ReactiveObjC.framework"
deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ]
}
stripped_framework("stripped_squirrel_framework") {
framework = "Squirrel.framework"
deps = [ "//third_party/squirrel.mac:squirrel_framework" ]
}
bundle_data("electron_app_framework_bundle_data") {
sources = [ "$root_out_dir/$electron_framework_name.framework" ]
if (!is_mas_build) {
sources += get_target_outputs(":stripped_mantle_framework") +
get_target_outputs(":stripped_reactiveobjc_framework") +
get_target_outputs(":stripped_squirrel_framework")
}
outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ]
public_deps = [
":electron_framework+link",
":stripped_mantle_framework",
":stripped_reactiveobjc_framework",
":stripped_squirrel_framework",
]
foreach(helper_params, content_mac_helpers) {
sources +=
[ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ]
public_deps += [ ":electron_helper_app_${helper_params[0]}" ]
}
}
mac_app_bundle("electron_login_helper") {
output_name = electron_login_helper_name
sources = filenames.login_helper_sources
include_dirs = [ "." ]
frameworks = [ "AppKit.framework" ]
info_plist = "shell/app/resources/mac/loginhelper-Info.plist"
extra_substitutions =
[ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ]
}
bundle_data("electron_login_helper_app") {
public_deps = [ ":electron_login_helper" ]
sources = [ "$root_out_dir/$electron_login_helper_name.app" ]
outputs =
[ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ]
}
action("electron_app_lproj_dirs") {
outputs = []
foreach(locale, locales_as_apple_outputs) {
outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ]
}
script = "build/mac/make_locale_dirs.py"
args = rebase_path(outputs)
}
foreach(locale, locales_as_apple_outputs) {
bundle_data("electron_app_strings_${locale}_bundle_data") {
sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ]
outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ]
public_deps = [ ":electron_app_lproj_dirs" ]
}
}
group("electron_app_strings_bundle_data") {
public_deps = []
foreach(locale, locales_as_apple_outputs) {
public_deps += [ ":electron_app_strings_${locale}_bundle_data" ]
}
}
bundle_data("electron_app_resources") {
public_deps = [
":default_app_asar",
":electron_app_strings_bundle_data",
]
sources = [
"$root_out_dir/resources/default_app.asar",
"shell/browser/resources/mac/electron.icns",
]
outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
}
asar_hashed_info_plist("electron_app_plist") {
keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ]
hash_targets = [ ":default_app_asar_header_hash" ]
plist_file = "shell/browser/resources/mac/Info.plist"
}
mac_app_bundle("electron_app") {
output_name = electron_product_name
sources = [
"shell/app/electron_main_mac.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
]
include_dirs = [ "." ]
deps = [
":electron_app_framework_bundle_data",
":electron_app_plist",
":electron_app_resources",
":electron_fuses",
"//base/allocator:early_zone_registration_mac",
"//electron/buildflags",
]
if (is_mas_build) {
deps += [ ":electron_login_helper_app" ]
}
info_plist_target = ":electron_app_plist"
extra_substitutions = [
"ELECTRON_BUNDLE_ID=$electron_mac_bundle_id",
"ELECTRON_VERSION=$electron_version",
]
ldflags = [
"-rpath",
"@executable_path/../Frameworks",
]
extra_configs = [ "//electron/build/config:mas_build" ]
}
if (enable_dsyms) {
extract_symbols("electron_framework_syms") {
binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name"
deps = [ ":electron_framework" ]
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
_helper_bundle_id = helper_params[1]
_helper_suffix = helper_params[2]
extract_symbols("electron_helper_syms_${_helper_target}") {
binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}"
deps = [ ":electron_helper_app_${_helper_target}" ]
}
}
extract_symbols("electron_app_syms") {
binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name"
deps = [ ":electron_app" ]
}
extract_symbols("egl_syms") {
binary = "$root_out_dir/libEGL.dylib"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/libEGL.dylib.dSYM/Contents/Resources/DWARF/libEGL.dylib"
deps = [ "//third_party/angle:libEGL" ]
}
extract_symbols("gles_syms") {
binary = "$root_out_dir/libGLESv2.dylib"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libGLESv2.dylib"
deps = [ "//third_party/angle:libGLESv2" ]
}
extract_symbols("crashpad_handler_syms") {
binary = "$root_out_dir/chrome_crashpad_handler"
symbol_dir = "$root_out_dir/breakpad_symbols"
dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler"
deps = [ "//components/crash/core/app:chrome_crashpad_handler" ]
}
group("electron_symbols") {
deps = [
":egl_syms",
":electron_app_syms",
":electron_framework_syms",
":gles_syms",
]
if (!is_mas_build) {
deps += [ ":crashpad_handler_syms" ]
}
foreach(helper_params, content_mac_helpers) {
_helper_target = helper_params[0]
deps += [ ":electron_helper_syms_${_helper_target}" ]
}
}
} else {
group("electron_symbols") {
}
}
} else {
windows_manifest("electron_app_manifest") {
sources = [
"shell/browser/resources/win/disable_window_filtering.manifest",
"shell/browser/resources/win/dpi_aware.manifest",
as_invoker_manifest,
common_controls_manifest,
default_compatibility_manifest,
]
}
executable("electron_app") {
output_name = electron_project_name
if (is_win) {
sources = [ "shell/app/electron_main_win.cc" ]
} else if (is_linux) {
sources = [
"shell/app/electron_main_linux.cc",
"shell/app/uv_stdio_fix.cc",
"shell/app/uv_stdio_fix.h",
]
}
include_dirs = [ "." ]
deps = [
":default_app_asar",
":electron_app_manifest",
":electron_lib",
":electron_win32_resources",
":packed_resources",
"//components/crash/core/app",
"//content:sandbox_helper_win",
"//electron/buildflags",
"//ui/strings",
]
data = []
data_deps = []
data += [ "$root_out_dir/resources.pak" ]
data += [ "$root_out_dir/chrome_100_percent.pak" ]
if (enable_hidpi) {
data += [ "$root_out_dir/chrome_200_percent.pak" ]
}
foreach(locale, platform_pak_locales) {
data += [ "$root_out_dir/locales/$locale.pak" ]
}
if (!is_mac) {
data += [ "$root_out_dir/resources/default_app.asar" ]
}
if (use_v8_context_snapshot) {
public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ]
}
if (is_linux) {
data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ]
}
if (is_win) {
sources += [
"$target_gen_dir/win-resources/electron.rc",
"shell/browser/resources/win/resource.h",
]
deps += [
"//components/browser_watcher:browser_watcher_client",
"//components/crash/core/app:run_as_crashpad_handler",
]
ldflags = []
libs = [
"comctl32.lib",
"uiautomationcore.lib",
"wtsapi32.lib",
]
configs -= [ "//build/config/win:console" ]
configs += [
"//build/config/win:windowed",
"//build/config/win:delayloads",
]
if (current_cpu == "x86") {
# Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by
# Chrome's main thread. This saves significant memory on threads (like
# those in the Windows thread pool, and others) whose stack size we can
# only control through this setting. Because Chrome's main thread needs
# a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses
# fibers to switch to a 1.5 MiB stack before running any other code.
ldflags += [ "/STACK:0x80000" ]
} else {
# Increase the initial stack size. The default is 1MB, this is 8MB.
ldflags += [ "/STACK:0x800000" ]
}
# This is to support renaming of electron.exe. node-gyp has hard-coded
# executable names which it will recognise as node. This module definition
# file claims that the electron executable is in fact named "node.exe",
# which is one of the executable names that node-gyp recognizes.
# See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a
ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ]
inputs = [
"shell/browser/resources/win/electron.ico",
"build/electron.def",
]
}
if (is_linux) {
ldflags = [
"-pie",
# Required for exporting all symbols of libuv.
"-Wl,--whole-archive",
"obj/third_party/electron_node/deps/uv/libuv.a",
"-Wl,--no-whole-archive",
]
if (!is_component_build && is_component_ffmpeg) {
configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ]
}
if (is_linux) {
deps += [ "//sandbox/linux:chrome_sandbox" ]
}
}
}
if (is_official_build) {
if (is_linux) {
_target_executable_suffix = ""
_target_shared_library_suffix = ".so"
} else if (is_win) {
_target_executable_suffix = ".exe"
_target_shared_library_suffix = ".dll"
}
extract_symbols("electron_app_symbols") {
binary = "$root_out_dir/$electron_project_name$_target_executable_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ ":electron_app" ]
}
extract_symbols("egl_symbols") {
binary = "$root_out_dir/libEGL$_target_shared_library_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ "//third_party/angle:libEGL" ]
}
extract_symbols("gles_symbols") {
binary = "$root_out_dir/libGLESv2$_target_shared_library_suffix"
symbol_dir = "$root_out_dir/breakpad_symbols"
deps = [ "//third_party/angle:libGLESv2" ]
}
group("electron_symbols") {
deps = [
":egl_symbols",
":electron_app_symbols",
":gles_symbols",
]
}
}
}
test("shell_browser_ui_unittests") {
sources = [
"//electron/shell/browser/ui/accelerator_util_unittests.cc",
"//electron/shell/browser/ui/run_all_unittests.cc",
]
configs += [ ":electron_lib_config" ]
deps = [
":electron_lib",
"//base",
"//base/test:test_support",
"//testing/gmock",
"//testing/gtest",
"//ui/base",
"//ui/strings",
]
}
template("dist_zip") {
_runtime_deps_target = "${target_name}__deps"
_runtime_deps_file =
"$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" +
get_label_info(target_name, "name") + ".runtime_deps"
group(_runtime_deps_target) {
forward_variables_from(invoker,
[
"deps",
"data_deps",
"data",
"testonly",
])
write_runtime_deps = _runtime_deps_file
}
action(target_name) {
script = "//electron/build/zip.py"
deps = [ ":$_runtime_deps_target" ]
forward_variables_from(invoker,
[
"outputs",
"testonly",
])
flatten = false
flatten_relative_to = false
if (defined(invoker.flatten)) {
flatten = invoker.flatten
if (defined(invoker.flatten_relative_to)) {
flatten_relative_to = invoker.flatten_relative_to
}
}
args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [
target_cpu,
target_os,
"$flatten",
"$flatten_relative_to",
]
}
}
copy("electron_license") {
sources = [ "LICENSE" ]
outputs = [ "$root_build_dir/{{source_file_part}}" ]
}
copy("chromium_licenses") {
deps = [ "//components/resources:about_credits" ]
sources = [ "$root_gen_dir/components/resources/about_credits.html" ]
outputs = [ "$root_build_dir/LICENSES.chromium.html" ]
}
group("licenses") {
data_deps = [
":chromium_licenses",
":electron_license",
]
}
dist_zip("electron_dist_zip") {
data_deps = [
":electron_app",
":electron_version_file",
":licenses",
]
if (is_linux) {
data_deps += [ "//sandbox/linux:chrome_sandbox" ]
}
deps = data_deps
outputs = [ "$root_build_dir/dist.zip" ]
}
dist_zip("electron_ffmpeg_zip") {
data_deps = [ "//third_party/ffmpeg" ]
deps = data_deps
outputs = [ "$root_build_dir/ffmpeg.zip" ]
}
electron_chromedriver_deps = [
":licenses",
"//chrome/test/chromedriver:chromedriver_server",
"//electron/buildflags",
]
group("electron_chromedriver") {
testonly = true
public_deps = electron_chromedriver_deps
}
dist_zip("electron_chromedriver_zip") {
testonly = true
data_deps = electron_chromedriver_deps
deps = data_deps
outputs = [ "$root_build_dir/chromedriver.zip" ]
}
mksnapshot_deps = [
":licenses",
"//v8:mksnapshot($v8_snapshot_toolchain)",
]
if (use_v8_context_snapshot) {
mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ]
}
group("electron_mksnapshot") {
public_deps = mksnapshot_deps
}
dist_zip("electron_mksnapshot_zip") {
data_deps = mksnapshot_deps
deps = data_deps
outputs = [ "$root_build_dir/mksnapshot.zip" ]
}
copy("hunspell_dictionaries") {
sources = hunspell_dictionaries + hunspell_licenses
outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ]
}
dist_zip("hunspell_dictionaries_zip") {
data_deps = [ ":hunspell_dictionaries" ]
deps = data_deps
flatten = true
outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ]
}
copy("libcxx_headers") {
sources = libcxx_headers + libcxx_licenses +
[ "//buildtools/third_party/libc++/__config_site" ]
outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ]
}
dist_zip("libcxx_headers_zip") {
data_deps = [ ":libcxx_headers" ]
deps = data_deps
flatten = true
flatten_relative_to = rebase_path(
"$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk",
"$root_out_dir")
outputs = [ "$root_build_dir/libcxx_headers.zip" ]
}
copy("libcxxabi_headers") {
sources = libcxxabi_headers + libcxxabi_licenses
outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ]
}
dist_zip("libcxxabi_headers_zip") {
data_deps = [ ":libcxxabi_headers" ]
deps = data_deps
flatten = true
flatten_relative_to = rebase_path(
"$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk",
"$root_out_dir")
outputs = [ "$root_build_dir/libcxxabi_headers.zip" ]
}
action("libcxx_objects_zip") {
deps = [ "//buildtools/third_party/libc++" ]
script = "build/zip_libcxx.py"
outputs = [ "$root_build_dir/libcxx_objects.zip" ]
args = rebase_path(outputs)
}
group("electron") {
public_deps = [ ":electron_app" ]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.