《Electron 45.2.3 内核解剖》第 13 章 视图系统与合成:从 WebContentsView 到屏幕像素
第 12 章结束时,页面脚本已经跑起来了。但那一刻屏幕上一片空白——脚本跑起来和像素出现在屏幕上,中间还隔着三层抽象、两个进程和一个 GPU。
这一章讲的就是这一段。它有个很容易被误解的地方:new BrowserWindow() 看起来是"创建了一个窗口,窗口里有网页",但实际发生的是三棵完全不同的树被同时创建,然后被三个不同的桥接点缝在一起。第一棵是 views::View 的逻辑树,管布局和命中测试;第二棵是 ui::Layer 的绘制树,管画什么和哪些能单独动画;第三棵是平台原生视图树(Windows/Linux 上是 aura::Window,macOS 上是 NSView),这才是操作系统真正认识的东西。网页的像素不由这三棵树里任何一棵产生——它由一个完全独立的、属于 content 层的 RenderWidgetHostView 产生,然后被"挂"进第三棵树。
本章的主线:"把网页放进窗口"跨了三层抽象和两个进程,而每一层的交接点都有一份需要手工维护的所有权约定,这些约定出错的方式各不相同,且大多不会报错,只会画错。
13.0 本章的地形:三棵树、四个桥、四条路径
先把文件摆出来。这一章的代码集中在 shell/browser/api/(JS 包装层)、shell/browser/ui/(视图与 DevTools 容器)、shell/browser/osr/(离屏渲染),加上 shell/browser/native_window*(窗口)。
| 区域 | 文件 | 行数 | 职责 |
|---|---|---|---|
| JS 视图包装 | electron_api_view.cc / .h | 638 / 90 | View 类:子视图管理、布局、圆角、动画 |
| 网页容器视图 | electron_api_web_contents_view.cc / .h | 342 / 89 | WebContentsView:把 WebContents 挂进视图树 |
| DevTools 容器 | inspectable_web_contents_view.cc / .h | 344 / 113 | 双 views::WebView(网页 + DevTools)+ 停靠布局 |
| Windows/Linux 根视图 | views/root_view.cc / .h | 197 / 76 | 菜单栏 + main_view(BoxLayout) |
| macOS 根视图 | cocoa/root_view_mac.mm:16 / .h | 29 / 35 | 只有 FillLayout,没有菜单栏子视图 |
| 窗口(views 实现) | native_window_views.cc / .h | 2140 / 439 | views::Widget、InitParams、content_view |
| 窗口基类 | native_window.cc / .h | 1209 / 662 | 命中测试聚合、节流聚合、视图持有 |
| 离屏渲染 | 见 13.10(osr/ 四个文件,约 1600 行) | — | 自己的 ui::Compositor 与显示客户端 |
编译进二进制的补丁里,本章要用到六份,它们揭示了 Electron 改了 Chromium 合成链的哪些环节:
| 补丁 | 改了什么 |
|---|---|
disable_compositor_recycling.patch | macOS 上把"视图没挂窗口"当成隐藏条件,阻止合成器回收资源 |
disable_hidden.patch | 给 RenderWidgetHostImpl 加 disable_hidden_;改 RWHVAura::DidNavigate 的休眠判定 |
allow_disabling_blink_scheduler_throttling_per_renderview.patch | 给 PageBroadcast 加 SetSchedulerThrottling,给 WebViewImpl 加强制可见 |
fix_disabling_background_throttling_in_compositor.patch | 给 ui::Compositor 加 SetBackgroundThrottling |
feat_enable_offscreen_rendering_with_viz_compositor.patch | 让 HostDisplayClient::CreateLayeredWindowUpdater 跳出 IS_WIN,新增 software_output_device_proxy |
osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch | OSR 的 D3D11 纹理去掉 keyed mutex |
三棵树
┌─────────────────────────────────────────────────────────────┐
│ 第一棵:views::View 树(逻辑) │
│ RootView │
│ ├─ MenuBar (Win/Linux 才有) │
│ └─ main_view ← NativeWindow::GetContentsView() │
│ ├─ WebContentsView.view() ← z 序 0(BrowserWindow) │
│ │ └─ InspectableWebContentsView │
│ │ ├─ devtools_web_view_(views::WebView) │
│ │ └─ contents_web_view_(views::WebView) │
│ └─ BaseWindow.contentView ← z 序 1 │
│ └─ 用户 addChildView 加的一切 │
└─────────────────────────────────────────────────────────────┘
│
NativeViewHost(桥 1)
▼
┌─────────────────────────────────────────────────────────────┐
│ 第三棵:平台原生视图树 │
│ aura::Window(根)→ aura::Window(WebContentsViewAura) │
│ → aura::Window(RWHVAura) │
│ 或 NSWindow → NSView(WebContentsViewCocoa) │
│ → BridgedContentView(RWHVCocoa) │
└─────────────────────────────────────────────────────────────┘
│
viz FrameSinkId(桥 2)
▼
┌─────────────────────────────────────────────────────────────┐
│ 第二棵:ui::Layer 树(合成)—— 注意它不在上面两棵树的正下方 │
│ 渲染进程 cc::LayerTreeHost → CompositorFrame │
│ → SurfaceId → 浏览器 DelegatedFrameHost 的 SurfaceLayer │
│ → 浏览器 ui::Compositor → 显示合成器(GPU 进程) │
└─────────────────────────────────────────────────────────────┘
这张图有一个刻意画错的地方需要点出来:第二棵树在位置上不是第一棵和第三棵的子节点,而是与它们平行的。ui::Layer 挂在 views::View 上(通过 View::layer()),但 Layer 树最终被 ui::Compositor 拿去提交,而网页的 CompositorFrame 走的是完全另一条路——直接进显示合成器。两者在显示合成器里才汇合。这就是为什么网页内容永远画在所有 views::View 之上(或之下),而你无法用 views 的 z 序去调整网页内部的层级。
四个桥
| 桥 | 连接 | 建立点 | 断开点 |
|---|---|---|---|
NativeViewHost | views::View → 原生视图 | views::WebView::SetWebContents | SetWebContents(nullptr) |
DelegatedFrameHost | 浏览器合成器 → 渲染进程 surface | RenderWidgetHostView 创建 | 视图销毁 |
SetOwnerWindow | WebContents → NativeWindow | OnViewAddedToWidget | ~WebContents |
BackgroundThrottlingSource | WebContents → 窗口合成器 | SetOwnerWindow | RemoveBackgroundThrottlingSource |
四条路径
同一个 webPreferences 可以让像素走四条完全不同的路:Aura(Windows/Linux 默认,浏览器 ui::Compositor 的 SurfaceLayer 嵌入渲染进程 surface)、macOS(CALayerParams 直投 CoreAnimation)、OSR 软件(LayeredWindowUpdater → 共享内存 → SkBitmap)、OSR 共享纹理(FrameSinkVideoCapturer → GpuMemoryBuffer)。前两条共享"渲染进程 → 显示合成器"这一段,后两条不共享任何一段。13.6 讲前两条,13.10 讲后两条。
13.1 第一棵树:views::View 的逻辑结构
13.1.1 RootView:一个只有两层的布局
RootView 是 Electron 自己写的(不是 Chromium 的 views::View),构造只有十一行:
root_view.cc:29-39
RootView::RootView(NativeWindow* window)
: window_{raw_ref<NativeWindow>::from_ptr(window)},
main_view_{raw_ref<views::View>::from_ptr(
AddChildView(std::make_unique<views::View>()))} {
set_owned_by_client(OwnedByClientPassKey{});
views::BoxLayout* layout =
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical));
main_view_->SetUseDefaultFillLayout(true);
layout->SetFlexForView(&main_view_.get(), 1);
}
三层信息:
第一层,set_owned_by_client。 views::View 默认由父视图持有(AddChildView 时转移所有权),但 set_owned_by_client 把它改成"由 client 持有"——这里的 client 是 NativeWindowViews,它有一个 RootView root_view_ 成员(值语义)。为什么要改?因为如果不改,views::Widget 析构时会试图 delete 它的 contents_view(由 WidgetDelegate::GetContentsView 返回),而那个指针指向 NativeWindowViews 的成员——双重释放。这个 PassKey 参数是 Chromium 用来防误用的编译期门禁:只有显式声明"我知道自己在干什么"的调用点才拿得到。
第二层,布局。 BoxLayout 垂直排列,main_view_ 的 flex 是 1(占满剩余空间),SetUseDefaultFillLayout(true) 表示 main_view_ 内部只有一个子视图时它自动铺满。于是 RootView 的实际行为是:
RootView(BoxLayout vertical)
├─ MenuBar 高度 = GetPreferredSize().height()
└─ main_view_ flex=1,吃掉剩下的全部高度
└─ content_view_ (FillLayout,铺满 main_view_)
main_view_ 这一层看起来是多余的——为什么不直接把 content_view_ 加进 RootView?因为菜单栏是可增删的:SetMenuBarVisibility(false) 时 RemoveChildView(menu_bar_.get()),true 时 AddChildViewAt(menu_bar_.get(), 0)(root_view.cc:88、:90)。如果 content_view_ 直接是 RootView 的子视图,那么"菜单栏在最上面、内容在下面"这个关系就得靠 AddChildViewAt 的下标手工维护,而菜单栏增删两次之后下标就不可靠了。中间插一层 main_view_ 把"菜单栏"和"内容"变成两个独立槽位,BoxLayout 自动算高度。这是视图树里最常见的一种设计:加一层容器,换掉一段容易出错的索引运算。
第三层,GetMinimumSize / GetMaximumSize 转发(:162-168)。RootView 自己不乐意算最小尺寸,直接问窗口。views::Widget 在 OnSizeConstraintsChanged 时会调这两个函数。
macOS 上的对等物完全没有菜单栏这一层:
root_view_mac.mm:12-16
RootViewMac::RootViewMac(NativeWindow* window) : window_(window) {
set_owned_by_client(OwnedByClientPassKey{});
SetLayoutManager(std::make_unique<views::FillLayout>());
}
三十四行的文件。原因是 macOS 的菜单栏是应用级的(一个 NSMenuBar 挂在 NSApplication 上),不属于任何窗口。于是 RootViewMac 只需要一个 FillLayout,content_view_ 直接铺满。
这个差异会在 13.1.3 复现一次:BrowserWindow 把 WebContentsView 插到 window()->GetContentsView() 的 index 0,而 GetContentsView() 在 Windows/Linux 上返回 main_view_、在 macOS 上返回 root_view_ 本身。两个平台插进去的"父"不是一个东西,但因为两个父都是"铺满的容器",效果一样。
13.1.2 窗口的客户区:SetContentView 的所有权转移
BaseWindow 构造时的最后一步是造一个空视图当占位:
electron_api_base_window.cc:155
SetContentView(View::Create(isolate));
View::Create 是静态工厂(electron_api_view.cc:592-601):拿构造函数、NewInstance、再把结果转回 gin_helper::Handle<View>。这一行同时做了三件事——创建 C++ 的 views::View、创建 JS 包装对象、把两者用 gin 的 internal field 绑在一起(细节见第 7 章)。
然后 SetContentView 干两件事:
electron_api_base_window.cc:417-420
void BaseWindow::SetContentView(gin_helper::Handle<View> view) {
content_view_.Reset(JavascriptEnvironment::GetIsolate(), view.ToV8());
window_->SetContentView(view->view());
}
第一行是 JS 侧的强引用。content_view_ 是一个 v8::Global<v8::Value>,Reset 之后这个 JS 对象不会被 GC——即使 JS 代码里对它的引用全部消失,win.contentView 仍然能拿回同一个对象。这一点和一般的 Electron 包装对象不一样(对比第 11 章讲的 WebContents:JS 侧可以被 GC,C++ 侧还活着,于是 Emit 静默失败)。窗口的 content view 是"JS 侧永不被 GC"的那一类,因为它没有别的可达路径——如果 JS 包装没了,views::View* 就再也没法从 JS 拿回来了。
第二行把裸 views::View* 交给 NativeWindow::SetContentView。两个平台实现不同,但骨架相同:
native_window_views.cc:567-580
void NativeWindowViews::SetContentView(views::View* view) {
if (views::View* old_view = content_view()) {
set_content_view(nullptr);
focused_view_ = nullptr;
if (old_view->owned_by_client())
root_view_.GetMainView()->RemoveChildView(old_view);
else
root_view_.GetMainView()->RemoveChildViewT(old_view);
}
set_content_view(view);
focused_view_ = view;
root_view_.GetMainView()->AddChildViewRaw(content_view());
FlushPendingRootLayout(root_view_.GetMainView());
}
四个动作,每个都有一个坑:
坑一,owned_by_client() 分两支。 RemoveChildView 只摘不删,RemoveChildViewT 摘下来装进 unique_ptr 然后销毁(T 是 "take")。判断依据是"这个视图由谁持有":如果它是由 JS 的 View 包装持有的(也就是 View::View 构造函数里 set_owned_by_client 过的),那么 C++ 侧不能删,否则 JS 包装会持有野指针;反之如果它是 NativeWindowViews 自己 new 出来的占位视图,就得删。这段代码没有任何注释解释,但它是整个视图系统所有权模型的核心。
坑二,set_content_view(nullptr) 必须在 RemoveChildView 之前。 因为 RemoveChildView 会触发 OnChildViewRemoved 观察者回调,而 NativeWindow 那边的 OnChildViewRemoved(如果有)可能会去读 content_view()。先清空再摘,保证回调期间拿到的是一致状态。
坑三,focused_view_ 要清。 这是 NativeWindowViews 的成员,记的是"上一次有焦点的视图",用于窗口重新获得焦点时恢复。如果不清理,窗口切回来时会试图给一个已经不在树上的视图设焦点——views::FocusManager 会 DCHECK。
坑四,AddChildViewRaw 而不是 AddChildView。 Raw 后缀在 views 里的意思是"不转移所有权,只建立父子关系"。因为 content_view_ 的所有权已经在 BaseWindow::content_view_(那个 v8::Global)和 View::view_(raw_ptr + delete_view_)两处记着了,再加一次就是三重。
FlushPendingRootLayout 在 native_window.cc:320:
void NativeWindow::FlushPendingRootLayout(views::View* view) {
view->InvalidateLayout();
if (views::Widget* widget = view->GetWidget())
widget->LayoutRootViewIfNecessary();
}
两行,但回答了"为什么 setContentView 之后同一个 tick 里 getBounds() 就是对的"。views 的布局是延迟的:InvalidateLayout 只置一个脏标记,真正的 Layout() 要等下一轮 Widget 的 layout pass。LayoutRootViewIfNecessary() 强制立刻跑一遍。注意条件是"有 Widget"——窗口还没 Init 时 GetWidget() 返回空,此时布局不跑,等 widget()->Init() 时统一跑。这就是为什么 BrowserWindow 的构造函数里 AddChildViewAt 之后要显式 DeprecatedLayoutImmediately()(13.1.3)。
macOS 的版本多了一行关键的东西:
native_window_mac.mm:327-334
// shell/browser/native_window_mac.mm:327-345(节选)
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
/* ...摘旧的... */
set_content_view(view);
// Make content_view_ hit-test-transparent where it has no covering child
// so events fall through to the sibling WebContentsView in BrowserWindow.
view->SetEventTargeter(std::make_unique<views::ViewTargeter>(
std::make_unique<ContentViewTargeterDelegate>()));
root_view->AddChildViewRaw(content_view());
FlushPendingRootLayout(root_view);
}
这两行是 macOS 独有的,原因在 13.5.3 讲——它解决的是"content_view_ 铺满整个窗口,于是所有鼠标事件都被它吃掉,永远到不了它下面的 WebContentsView"这个问题。
13.1.3 BrowserWindow 的 z 序把戏
BrowserWindow 不是"一个带网页的窗口",而是"一个 BaseWindow 加上一个挂在它客户区里的 WebContentsView"。构造顺序是这样的:
electron_api_browser_window.cc:70-77
// shell/browser/api/electron_api_browser_window.cc:69-102(节选)
// Creates the WebContentsView.
gin_helper::Handle<WebContentsView> web_contents_view =
WebContentsView::Create(isolate, web_preferences);
DCHECK(web_contents_view.get());
window()->AddDraggableRegionProvider(web_contents_view.get());
window()->InitPrimaryWebContentsView(
static_cast<InspectableWebContentsView*>(web_contents_view->view()));
web_contents_view_.Reset(isolate, web_contents_view.ToV8());
/* ...拿 webContents、SetOwnerWindow... */
InitWithArgs(args);
// Install the content view after BaseWindow's JS code is initialized.
// The WebContentsView is added a sibling of BaseWindow's contentView (before
// it in the paint order) so that any views added to BrowserWindow's
// contentView will be painted on top of the BrowserWindow's WebContentsView.
// See https://github.com/electron/electron/pull/41256.
// Note that |GetContentsView|, confusingly, does not refer to the same thing
// as |BaseWindow::GetContentView|.
window()->GetContentsView()->AddChildViewAt(web_contents_view->view(), 0);
window()->GetContentsView()->DeprecatedLayoutImmediately();
// Init window after everything has been setup.
window()->InitFromOptions(options);
这里有四个必须按顺序理解的点。
其一,为什么是 AddChildViewAt(..., 0) 而不是 AddChildView。 因为要让它在 z 序上低于 BaseWindow 的 contentView。views::View 的绘制顺序是"先画自己,再按 children() 的顺序画子视图"——下标 0 的先画。所以 main_view_ 的子视图顺序是:
main_view_
[0] WebContentsView.view() ← 网页,先画(在下面)
[1] BaseWindow.contentView ← 用户视图,后画(在上面)
注释里那句 "so that any views added to BrowserWindow's contentView will be painted on top of the BrowserWindow's WebContentsView" 就是这个意思。PR #41256 之前是反的:contentView 先加,WebContentsView 后加,于是用户在 contentView 里加的任何东西都被网页盖住了。这个改动是个破坏性的语义变更——升级到那个版本之后,以前"加在 contentView 里看不见"的代码突然能看见了,而依赖"看不见"的代码会失效。
其二,为什么 InitWithArgs(args) 必须在这之前。 InitWithArgs 会跑 JavaScript 侧的子类构造逻辑(BrowserWindow.prototype._init 在 browser-window.ts:6)。那段 JS 会读 this.id、往 this 上挂 webContents、注册一堆事件转发。如果此时 WebContentsView 还没挂进视图树,this.contentView 还是那个空占位视图——而 JS 侧如果在这期间往 contentView 里加了东西,那些东西会正确地落在 index 1(因为 index 0 还没被占)。顺序反过来就会导致 WebContentsView 插到用户视图前面,网页盖住用户视图。
其三,DeprecatedLayoutImmediately() 与 FlushPendingRootLayout 的区别。 前者是 views::View 的方法,直接从根往下递归 Layout();后者是 Electron 自己的 helper,只调 widget->LayoutRootViewIfNecessary()。此处的窗口还没 InitFromOptions(widget()->Init() 在 NativeWindowViews 构造函数里已经跑过了,但 InitFromOptions 里还有 SetSize、Center 这些会改尺寸的动作),所以 Widget 是存在的,DeprecatedLayoutImmediately 能立刻生效。这个名字里的 Deprecated 是 Chromium 加的,意思是"别在新代码里用它,用 InvalidateLayout + 等 layout pass"——但这里就是要同步生效,所以用了。
其四,InitFromOptions 在最后。 因为它里面的 SetSize 会触发 Widget 的 resize → RootView 的 Layout → InspectableWebContentsView::Layout → contents_web_view_->SetBoundsRect → RenderWidgetHostView::SetSize。这一串要求视图树已经完整。顺序错了的结果是网页用错误的尺寸渲染第一帧,然后要等下一次 resize 才纠正——在不可缩放的小窗口上,这意味着永久错误。
13.1.4 三个 GetContentsView,三个不同的东西
这一节的标题就是那个陷阱。同一个名字,三个类,三个完全不同的返回值:
| 类 | 函数 | 返回 | 声明 |
|---|---|---|---|
api::BaseWindow | GetContentView() | 用户设置的 content view(JS 包装) | electron_api_base_window.h:275 |
NativeWindow | GetContentsView() | root_view_.GetMainView() 或 root_view_ | native_window_views.cc:1993 |
InspectableWebContentsView | GetContentsView() | 那个装网页的 views::WebView | inspectable_web_contents_view.cc:338 |
三个的语义:
- 第一个是用户的东西:
win.contentView。 - 第二个是窗口的客户区容器:菜单栏之下、整个窗口之内的那块矩形。
- 第三个是网页本身:
InspectableWebContentsView里的contents_web_view_(第 13.3.1 讲它为什么叫这个名字)。
BrowserWindow 的注释里那句 "Note that GetContentsView, confusingly, does not refer to the same thing as BaseWindow::GetContentView" 就是在警告第二个和第一个的区别。第三个和第二个重名更狠:window()->GetContentsView()->AddChildViewAt(web_contents_view->view(), 0) 里的 web_contents_view->view() 是一个 InspectableWebContentsView,而它内部又有自己的 GetContentsView()。两个名字在同一个表达式里出现,指的是不同的两件事。
为什么会有这种命名?因为这三个函数分别来自三个不同的上游:GetContentView 是 Electron 的 JS API(BrowserWindow 从很早的版本就有);NativeWindow::GetContentsView 重写的是 views::WidgetDelegate::GetContentsView()(Chromium 的接口,语义是"客户区那个视图");InspectableWebContentsView::GetContentsView 抄自 Chromium 的 DevToolsContentsResizingStrategy 生态(Chrome 的 DevTools 代码里同样有这个命名)。
记法:ContentView(驼峰,无 s)是 JS API;ContentsView(有 s)是 C++ 内部;InspectableWebContentsView::GetContentsView 是"网页所在的视图",只在 DevTools 停靠布局里用。
13.2 JS 包装层:api::View
api::View 是 Electron 对 views::View 的 JS 包装,638 行实现、90 行头文件。它是整个视图系统里唯一被 JS 直接操作的部分。
13.2.1 为什么不直接暴露 views::View
views::View 有几百个公开方法。如果全暴露,Electron 就得为每一个维护 ABI 兼容性,而且其中很多方法在 JS 的调用模型下是危险的(比如 RemoveChildViewT 会立即 delete)。所以 api::View 只挑了十一个:
electron_api_view.cc:604-619
void View::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(gin::StringToV8(isolate, "View"));
gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetMethod<&View::AddChildViewAt>("addChildView")
.SetMethod<&View::RemoveChildView>("removeChildView")
.SetProperty<&View::GetChildren>("children")
.SetMethod<&View::SetBounds>("setBounds")
.SetMethod<&View::GetBounds>("getBounds")
.SetMethod<&View::SetBackgroundColor>("setBackgroundColor")
.SetMethod<&View::SetBorderRadius>("setBorderRadius")
.SetMethod<&View::SetBackgroundBlur>("setBackgroundBlur")
.SetMethod<&View::SetLayout>("setLayout")
.SetMethod<&View::SetVisible>("setVisible")
.SetMethod<&View::GetVisible>("setVisible"); // getter 同名
}
十一个 API 覆盖了四件事:结构(add/remove/children)、几何(bounds)、外观(背景色/圆角/模糊)、布局(setLayout)、可见性。没有滚动容器、没有文本控件、没有列表——那些要用 <webview> 或者 BrowserView。Electron 的视图 API 不是"在 JS 里写原生 UI"的通用方案,它只解决"把一个网页矩形摆到某个位置并给它圆角"这一类问题。
13.2.2 所有权:owned_by_client 与 delete_view_
api::View 有两个构造函数,一个接已有的原生视图,一个自己造一个:
electron_api_view.cc:198-211
View::View(views::View* view) : view_(view) {
view_->set_owned_by_client(views::View::OwnedByClientPassKey{});
view_->AddObserver(this);
}
View::View() : View(new views::View()) {}
View::~View() {
if (!view_)
return;
view_->RemoveObserver(this);
if (delete_view_)
view_.ClearAndDelete();
}
关键在两个布尔:
owned_by_client(原生视图侧):告诉views框架"这个视图的生死不归父视图管"。所有api::View包过的原生视图都会被置上,因为它的生死归api::View管。delete_view_(包装侧,默认true):告诉api::View析构时要不要delete原生视图。默认true(自己new的当然自己删),但WebContentsView构造时置false:
electron_api_web_contents_view.cc:38-43
WebContentsView::WebContentsView(v8::Isolate* isolate,
gin_helper::Handle<WebContents> web_contents)
: View(web_contents->inspectable_web_contents()->GetView()),
web_contents_(isolate, web_contents.ToV8()),
api_web_contents_(web_contents->GetWeakPtr()) {
set_delete_view(false);
因为 InspectableWebContentsView 的生命周期属于 InspectableWebContents(view_(new InspectableWebContentsView(this)) 在 inspectable_web_contents.cc:348 的构造函数里),而 InspectableWebContents 属于 api::WebContents。如果 api::View 的析构去删它,就会和 ~InspectableWebContents 里的 view_.reset() 双重释放。所以 delete_view_ = false 的意思是"我只借用,不拥有"——但它同时意味着 api::View 析构后,如果 InspectableWebContents 还活着,那个原生视图还活着,只是再也没人能从 JS 拿到它了。
这个不对称在 ~WebContentsView 里被补了一次:
electron_api_web_contents_view.cc:55-59
WebContentsView::~WebContentsView() {
StopObservingWindow();
if (api_web_contents_) // destroy() called without closing WebContents
api_web_contents_->Destroy();
}
api_web_contents_ 是 base::WeakPtr<api::WebContents>。如果它还有效,说明 JS 侧的 WebContentsView 被 GC 了但 WebContents 还活着——此时主动 Destroy() 它。这是一条"级联销毁"规则:视图没了,网页也不该留着。 第 11 章讲过 Destroy() 的三个分支,这里走的是"非 guest、非 emitting"那支,会 PostTask 延后删。
13.2.3 三份记账:为什么 child_views_ 要另存 v8::Global
electron_api_view.h:69
using ChildPair = std::pair<raw_ptr<views::View>, v8::Global<v8::Object>>;
子视图在三个地方被记着:
views::View::children_(Chromium 内部):raw_ptr<View>的 vector,管绘制和布局。api::View::child_views_(Electron):(raw_ptr, v8::Global)的 vector,管 JS 侧的对应关系。- V8 堆:
v8::Global<v8::Object>让 JS 包装对象不被 GC。
为什么需要第 2、3 份?因为 views::View::children_ 只存 C++ 指针,从 C++ 指针反查 JS 对象需要 gin 的 wrapper 反查机制,而那个机制在对象已被 GC 时返回空。于是 getChildren() 会返回一堆 undefined。
第 3 份(v8::Global)解决了这个:只要父视图活着,所有子视图的 JS 包装都强引用着,不会被 GC。这也是为什么 View 的 children 属性返回的是一个全新的 JS 数组(electron_api_view.cc:472-482 每次 ret.push_back(global.Get(isolate))),而不是复用一个持久数组——数组本身是临时的,元素是持久的。
代价:子视图不能被独立 GC。parent.removeChildView(child) 会 child_views_.erase(it),那一刻 v8::Global 析构,JS 包装才可能被回收。在此之前,即使 JS 代码里对 child 的所有引用都消失了,它仍然活着。这是个容易造成内存泄漏的形状:父视图活着 → 所有后代活着。
13.2.4 ReorderChildView 的 rotate 技巧
addChildView(child, index) 遇到"child 已在树上"时不报错,而是重排(electron_api_view.cc:258-267),重排在 ReorderChildView(:213-234)里用两行 std::rotate 完成:
const auto pos = std::next(child_views_.begin(),
static_cast<ptrdiff_t>(std::min(index, child_views_.size() - 1)));
if (i == pos) return;
if (pos < i) std::rotate(pos, i, std::next(i)); // 往前挪
else std::rotate(i, std::next(i), std::next(pos)); // 往后挪
rotate(first, middle, last) 的语义是"把 [middle, last) 转到 [first, middle) 前面"。往前挪时区间只有 i 一个元素,效果是"插到 pos 前面、[pos, i) 整体后移";往后挪时区间是 [i, pos],效果是"i+1..pos 前移一位、i 落到 pos"。
没有 erase + insert(那会失效迭代器并复制 v8::Global),也没有临时 vector。std::min(index, size() - 1) 的钳制是因为 rotate 的 last 必须可解引用:index == size() 会算出 end(),std::next(end()) 就越界。这个 -1 在集合非空时安全,因为调用点已 DCHECK(child 在集合里)。
13.2.5 setBounds 的动画:为什么必须动 clip rect
setBounds(bounds) 默认是瞬时的。setBounds(bounds, { animate: true }) 会走动画路径,这条路径几乎是全章最绕的一段:
electron_api_view.cc:325-332
// shell/browser/api/electron_api_view.cc:325-419(骨架)
void View::SetBounds(const gfx::Rect& bounds, gin::Arguments* const args) {
bool animate = false;
int duration = 250;
gfx::Tween::Type easing = gfx::Tween::LINEAR;
/* ...解析 args.animate,布尔或 {duration, easing}... */
if (!animate) { view_->SetBoundsRect(bounds); return; }
ui::Layer* layer = GetLayer();
gfx::Rect current_bounds = view_->bounds();
if (bounds.size() == current_bounds.size()) {
// 尺寸不变,只动位置
views::AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.OnEnded(...view->SetBoundsRect(final_bounds)...)
.Once().SetDuration(base::Milliseconds(duration))
.SetBounds(view_, bounds, easing);
return;
}
gfx::Rect target_size = gfx::Rect(0, 0, bounds.width(), bounds.height());
gfx::Rect max_size = gfx::Rect(current_bounds.x(), current_bounds.y(),
std::max(current_bounds.width(), bounds.width()),
std::max(current_bounds.height(), bounds.height()));
if (view_->width() < bounds.width() || view_->height() < bounds.height()) {
view_->SetBoundsRect(max_size); // 立刻扩到目标尺寸,让内容重新布局
if (layer)
layer->SetClipRect(gfx::Rect(0, 0, current_bounds.width(),
current_bounds.height())); // 只露旧尺寸
}
views::AnimationBuilder()
.SetPreemptionStrategy(...)
.OnEnded(... { view->SetBoundsRect(final_bounds); layer->SetClipRect({}); } ...)
.Once().SetDuration(...)
.SetBounds(view_, bounds, easing)
.SetClipRect(view_, target_size, easing);
}
三条不同的路径,对应三种情况:
路径一(尺寸不变):直接 SetBounds 动画。views::AnimationBuilder 的 SetBounds 是动 ui::Layer 的 bounds,不是 View 的。动画结束后才把 View::SetBoundsRect 一次性设成终值。这意味着动画期间 view->bounds() 是旧值,而屏幕上显示的是新值——两者不同步。 任何在动画期间读 bounds() 的代码(比如 OnViewBoundsChanged 里算圆角)拿到的都是旧尺寸。
路径二(变大):这是需要 clip rect 的原因。假设从 100×100 变到 300×300。ui::Layer 的动画只能插值 bounds,如果直接把 View::SetBoundsRect(300×300) 再动画 layer 的 bounds,那么 layer 的显示区域会从"100×100 拉伸到 300×300"——里面画的内容被放大,而不是"露出更多"。正确做法是:
- 先把
View的 bounds 立刻设成max_size(300×300),让内容按 300×300 重新布局(内容区域真的变大了)。 - 把 layer 的 clip rect 设成旧的 100×100——只露出左上角 100×100。
- 动画 layer 的 bounds(从 100×100 到 300×300)同时动画 clip rect(从 100×100 到 300×300)。
于是视觉效果是"裁剪窗口在放大,露出越来越多的内容",而不是"内容被拉伸"。
路径三(变小):view_->width() < bounds.width() 为假,不预先扩 bounds,但 clip rect 仍要动画——它和路径二共用同一段代码,只是那个 if 不进去。
.SetPreemptionStrategy(IMMEDIATELY_ANIMATE_TO_NEW_TARGET) 两处都有,含义是:如果上一次动画还没跑完就来了新目标,直接从当前插值位置跳到新目标,而不是排队或者跳到旧目标的终点。默认策略是 ENQUEUE_NEW_ANIMATION(排队),对窗口 resize 这种高频输入会积压。
最后那句注释值得抄下来:
// We have to set the clip rect independently of the
// bounds, because animating the bounds of the layer
// will not animate the underlying view's bounds.
根因是 views::View 和 ui::Layer 的 bounds 是两套独立的状态。 View::SetBoundsRect 会同步 layer->SetBounds,但反过来不会;而 AnimationBuilder::SetBounds(view_, ...) 动的是 layer 那一侧。所以要"让视图看起来在变形",必须同时驱动两套状态,而 layers 的 bounds 动画会自动跟着 View 的布局走——除非你把内容区域和可见区域解耦,也就是 clip rect。
13.2.6 setLayout:把 JS 函数塞进布局管线
setLayout 接受两种输入:
electron_api_view.cc:427-434
// shell/browser/api/electron_api_view.cc:427-470(骨架)
void View::SetLayout(v8::Isolate* isolate, v8::Local<v8::Object> value) {
gin_helper::Dictionary dict(isolate, value);
LayoutCallback calculate_proposed_layout;
if (dict.Get("calculateProposedLayout", &calculate_proposed_layout)) {
view_->SetLayoutManager(std::make_unique<JSLayoutManager>(
std::move(calculate_proposed_layout)));
} else {
auto* layout =
view_->SetLayoutManager(std::make_unique<views::FlexLayout>());
/* ...把 orientation/mainAxisAlignment/... 十几个字段逐个搬进去... */
}
}
第一种是声明式的:{ orientation: 'horizontal', mainAxisAlignment: 'center', ... },Electron 把它翻译成一个 views::FlexLayout——基本上是把 CSS flexbox 的一个子集搬到了 views 的布局系统上。转换函数在 :115-130(FlexAllocationOrder)、:92-113(LayoutAlignment)、:75-90(LayoutOrientation),每个都是字符串→枚举的 FromV8。
第二种是把 JS 函数当布局算法:
electron_api_view.cc:180-196
class JSLayoutManager : public views::LayoutManagerBase {
public:
explicit JSLayoutManager(LayoutCallback layout_callback)
: layout_callback_(std::move(layout_callback)) {}
views::ProposedLayout CalculateProposedLayout(
const views::SizeBounds& size_bounds) const override {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
return layout_callback_.Run(size_bounds);
}
CalculateProposedLayout 是 views::LayoutManagerBase 的唯一纯虚函数(LayoutManager 从 LayoutManagerBase 派生,后者用一套 "proposed layout → 应用" 的两阶段模型)。它的返回值 views::ProposedLayout 里有 host_size 和一组 ChildLayout{child_view, bounds, visible}。JS 函数要返回的就是这个结构的 JS 版本,由 Converter<views::ProposedLayout>(:57-73)和 Converter<views::ChildLayout>(:36-55)翻译成 C++。
这两段 Converter 有几个细节:
electron_api_view.cc:44-52
gin_helper::Handle<electron::api::View> view;
if (!dict.Get("view", &view))
return false;
out->child_view = view->view();
if (dict.Has("bounds"))
dict.Get("bounds", &out->bounds);
out->visible = true;
if (dict.Has("visible"))
dict.Get("visible", &out->visible);
visible 的默认值是 true——JS 返回的 layout 里如果一个子视图没写 visible,它会被显示。这和 views::ChildLayout 的 C++ 默认值一致(默认构造里 visible = true)。bounds 不写则留空矩形,等于"位置在 0,0 尺寸为 0"。
代价与风险。 CalculateProposedLayout 是 const 方法,但它在里面拿 isolate、跑 JS,于是有三个后果:
- 布局 pass 期间会跑任意 JS。JS 可以在这个回调里
setBounds、addChildView、甚至销毁当前视图,而views正在遍历children()——树被改了会崩,或者更糟,静默错位。 - 没有异常边界。抛异常时
layout_callback_.Run返回默认构造的ProposedLayout(host_size为 0),views按 0×0 布局,表现为"窗口突然全白",错误只在 console 里一行。 - 性能。每次布局 pass 一次跨语言调用 + 一次 JS 执行 + 一次结构转换。深度 5、每层 10 个子视图的树,一次 resize 可能跑几十次 JS。
13.2.7 布局的两条触发路径
views 的布局是"标记脏 → 等 pass"的两段式。Electron 侧有两个地方把这个两段式压成一段:
native_window.cc:320-325
void NativeWindow::FlushPendingRootLayout(views::View* view) {
view->InvalidateLayout();
if (views::Widget* widget = view->GetWidget())
widget->LayoutRootViewIfNecessary();
}
以及 inspectable_web_contents_view.cc:34-39 里一个几乎相同的匿名命名空间函数:
void FlushPendingRootLayout(views::View* view) {
view->InvalidateLayout();
if (views::Widget* widget = view->GetWidget())
widget->LayoutRootViewIfNecessary();
}
两份一模一样的代码,一份在 electron 命名空间里作为成员函数,一份在匿名命名空间里作为自由函数。原因很简单:InspectableWebContentsView 不属于 NativeWindow,拿不到那个成员函数,而它又需要同样的行为。这是 Electron 里"同一个 helper 写两遍"的典型——没有共享的 util 层,因为这两处的依赖方向相反(native_window 依赖 inspectable_web_contents_view,反之不行)。
LayoutRootViewIfNecessary 的 IfNecessary 是关键:如果 Widget 认为布局不脏,它什么都不做。所以 InvalidateLayout() 必须在前面——这两行的顺序不能换,换了就是"检查要不要布局(此时不脏)→ 标记脏 → 什么都没发生"。一个非常容易在重构时引入的死 bug。
第二条触发路径是 views 自己的机制:View::SetBoundsRect 会调 InvalidateLayout(),Widget 在下一个 BeginFrame 里跑 Layout。所以正常 resize 不需要显式 flush。
13.3 WebContentsView:把网页挂进视图树
WebContentsView 是 Electron 45 新增的类(替代了被废弃的 BrowserView),342 行,是"网页"和"视图树"之间的接缝。
13.3.1 InspectableWebContentsView:为什么是两个 views::WebView
InspectableWebContentsView 这个名字里没有 "DevTools",但它整个存在意义就是 DevTools。构造函数:
inspectable_web_contents_view.cc:90-108
InspectableWebContentsView::InspectableWebContentsView(
InspectableWebContents* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->is_guest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
no_contents_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildViewRaw(devtools_web_view_.get());
AddChildViewRaw(GetContentsView());
}
四个信息:
其一,它有两个 views::WebView。 一个是网页(contents_web_view_),一个是 DevTools 前端(devtools_web_view_)。DevTools 前端本身也是一个网页,跑在一个独立的 WebContents 里,所以它也需要一个 views::WebView 来承载。平时 devtools_web_view_ 不可见(SetVisible(false)),打开 DevTools 时置可见并 SetWebContents(GetDevToolsWebContents())。
其二,那个 is_guest() && GetNativeView() 判断。 三种情况会走到 else 分支,创建一个 views::Label 显示 "No content under offscreen mode":
-
OSR 的
WebContents:离屏渲染的WebContents没有原生视图(OffScreenWebContentsView::GetNativeView()在没挂窗口时返回空),所以没法用views::WebView承载——WebView的本质是NativeViewHost::Attach(原生视图),没有原生视图就没东西可 attach。但这个判断只看
GetNativeView()是否非空,不看IsOffScreen()。一个刚创建、还没挂到窗口上的 OSRWebContents,其GetNativeView()恰好返回空(osr_web_contents_view.cc:86-91里if (!native_window_) return {};),于是走else。等它挂上窗口(SetNativeWindow)之后就有原生视图了,但此时InspectableWebContentsView已经构造完了,contents_web_view_永远是空的。这是一个"构造函数只跑一次,但条件会变"的典型陷阱:OSR 窗口必须先有NativeWindow才能用WebContentsView,否则网页那块永远是个 label。 -
<webview>的 guest:is_guest()为真,走else。guest 的视图由 embedder 那边的WebContentsViewChildFrame管,不需要InspectableWebContentsView再提供一个views::WebView。 -
<webview>嵌套 OSR:两者都真。
其三,AddChildViewRaw 的顺序与 z 序。 devtools_web_view_ 先加(index 0,先画,在下),contents_web_view_ 后加(index 1,后画,在上)。看起来是反的——DevTools 应该在上面才对?不。因为 Layout() 里(:309-336)当 DevTools 可见时,两个视图的 bounds 是互斥分割的(ApplyDevToolsContentsResizingStrategy 算出两块不相交的矩形),不存在重叠。z 序只在"分割线两边有 1px 重叠"时才有意义,那时候让网页在上更符合直觉(网页是主体)。
其四,title_(u"Developer Tools")。 这是 DevTools 独立窗口的标题,在构造时就设好了默认值。SetTitle 只在 devtools_window_ 存在(也就是 undocked)时才更新它(:261-266)。
13.3.2 views::WebView 与 NativeViewHost:桥在哪
这是整章最关键的一节。views::WebView 不是一个自己绘制内容的视图,它内部持有一个 views::NativeViewHost,后者负责把"别人家的原生视图"塞进自己的位置。views 里这个模式只有几个使用者:WebView(网页)、NativeViewHost 的直用(macOS 的 vibrancy)、以及 views::NativeViewHost 本身(作为通用容器)。
NativeViewHost 的核心是三个状态:
Attach(native_view) → 记住 native_view,如果已挂到 Widget 就立刻 SetParent
Detach() → 从父原生视图上摘下来,但记住它
native_view() → 返回记住的那个(wrapped 之前的)
它的 Layout() 会把自己的 bounds 转换成原生视图的 bounds(含 device_scale_factor 换算),然后调 SetBounds。所以在 views 的世界里,NativeViewHost 是一个"占位符"——占住位置,让真正的原生视图待在那。
对 views::WebView 来说,「原生视图」就是 content::WebContents::GetNativeView() 返回的东西。这个值在三个平台上意味着三种不同的东西:
| 平台 | WebContents::GetNativeView() 返回 |
|---|---|
| Windows / Linux | aura::Window*(WebContentsViewAura 创建的容器窗口) |
| macOS | NSView*(WebContentsViewCocoa) |
| OSR | 空 或 NativeWindow::GetNativeView() |
注意第一行:它不是 RWHV 的原生视图,而是一个中间容器。 完整链条是:
views::WebView
└─ NativeViewHost (views 层)
└─ aura::Window(WebContentsViewAura 的容器) (平台层,第 1 跳)
└─ aura::Window(RenderWidgetHostViewAura) (平台层,第 2 跳)
多这一跳的原因是输入事件的坐标空间:WebContentsViewAura 的窗口负责把 views 的坐标系(相对窗口客户区)翻译成"相对网页内容区"的坐标,再转发给 RWHV。如果直接挂 RWHV 的窗口,那么 DevTools 停靠、BrowserView 偏移这些情况下坐标会错。macOS 上对应的是 WebContentsViewCocoa 这个 NSView,它同样只做坐标翻译和事件转发。
所以"桥"其实有两段:NativeViewHost 把 views 的坐标系接到 WebContentsViewAura/Cocoa 上,后者再把坐标系接到 RWHV 上。本章说的"桥 1"指第一段。
13.3.3 桥的建立:OnViewAddedToWidget
NativeViewHost::Attach 有一个前提:它自己得先挂到某个 Widget 上,才知道该把原生视图插到哪个原生父视图下。views 用 ViewObserver::OnViewAddedToWidget 这个回调做通知。
WebContentsView 的实现在这里承担了三件事:
electron_api_web_contents_view.cc:135-152
void WebContentsView::OnViewAddedToWidget(views::View* observed_view) {
DCHECK_EQ(observed_view, view());
NativeWindow* native_window = NativeWindow::FromWidget(view()->GetWidget());
if (!native_window)
return;
// We don't need to call SetOwnerWindow(nullptr) in OnViewRemovedFromWidget
// because that's handled in the WebContents dtor called prior.
api_web_contents_->SetOwnerWindow(native_window);
native_window->AddDraggableRegionProvider(this);
StopObservingWindow();
observed_window_ = native_window->GetWeakPtr();
native_window->AddObserver(this);
ApplyBorderRadius();
if (HasLivePage())
ScheduleWindowControlsOverlayUpdate();
}
第一件,SetOwnerWindow。 这一步把 WebContents 和一个 NativeWindow 绑起来。它做两件事(electron_api_web_contents.cc:3057-3078):
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else { /* ...清空... */ }
/* ...OSR 的 SetNativeWindow... */
}
AddBackgroundThrottlingSource 是 13.8.5 的主题。这里先记住:SetOwnerWindow 是 WebContents 第一次知道"我在哪个窗口里"的时刻,它发生在视图被挂进 Widget 的那一刻,而不是 WebContents 创建的那一刻。BrowserWindow 的构造函数里虽然也调了一次 web_contents->SetOwnerWindow(window())(:87),但那是在 AddChildViewAt 之前——那时视图还没进 Widget。两次调用,第二次是权威的。
第二件,AddDraggableRegionProvider。 把 this 注册为窗口的拖拽区域提供者,这样 NativeWindow::NonClientHitTest(13.3.6)会调它。
第三件,ApplyBorderRadius()。 因为圆角只有在视图有 Widget 之后才能设(inspectable_web_contents_view.cc:89 里 view()->GetWidget() 是前提条件),所以必须等到这一刻。
第四件,ScheduleWindowControlsOverlayUpdate()。 这个 if (HasLivePage()) 是个精确的时序判断:
electron_api_web_contents_view.cc:175-180
bool WebContentsView::HasLivePage() {
// Before the first navigation there is nothing to update; the window
// notifies us again from WebContents::DidFinishNavigation.
return observed_window_ && web_contents() &&
web_contents()->GetPrimaryMainFrame()->IsRenderFrameLive();
}
"主帧的 RenderFrame 活着"意味着渲染进程里已经有对应的 RenderFrameImpl,UpdateWindowControlsOverlay 的 IPC 才有人接。在此之前推过去的消息会落进虚空。
13.3.4 桥的拆除:一个刻意的不对称
OnViewRemovedFromWidget(:154-164)只做两件事:
electron_api_web_contents_view.cc:154-160
void WebContentsView::OnViewRemovedFromWidget(views::View* observed_view) {
DCHECK_EQ(observed_view, view());
StopObservingWindow();
NativeWindow* native_window = NativeWindow::FromWidget(view()->GetWidget());
if (!native_window)
return;
native_window->RemoveDraggableRegionProvider(this);
}
它没有调 SetOwnerWindow(nullptr)。注释在 OnViewAddedToWidget 里解释了原因:
// We don't need to call SetOwnerWindow(nullptr) in OnViewRemovedFromWidget
// because that's handled in the WebContents dtor called prior.
拆解一下这个不对称:
- 加的时候,视图先挂进
Widget,然后才SetOwnerWindow。因为此时WebContents一定活着(视图是它的容器)。 - 拆的时候,
WebContents的析构函数里已经调了SetOwnerWindow(nullptr)(electron_api_web_contents.cc:1372附近),然后才轮到视图被摘。所以拆的时候owner_window_已经是空的,再调一次是无害但无意义的——而不调可以省掉一次RemoveBackgroundThrottlingSource的DCHECK(native_window.cc:807里如果 source 不在集合里会DCHECK失败)。
这个不对称是一个隐患:如果调用方不遵循"先销毁 WebContents 再摘视图"的顺序(比如 JS 里 parent.removeChildView(wcvView) 但 wcvView.webContents 还活着),那么 owner_window_ 不会被清空,窗口会一直持有一个指向已摘视图的 BackgroundThrottlingSource。它的 GetBackgroundThrottling() 仍然可调(对象没死),于是窗口的节流状态取决于一个不在窗口里的网页——结果是"明明窗口在前台,某个不该节流的后台网页却把整个窗口的合成器冻住了"。
更稳的写法是在 OnViewRemovedFromWidget 里判断 observed_window_ 是否还等于当前窗口,如果是就清掉。但当前代码没这么做,注释里的"that's handled in the WebContents dtor called prior"是一个依赖调用顺序的假设,不是一个保证。
13.3.5 OnContentsBoundsChanging:在 resize 之前推
这是本章第二绕的时序问题,只有一个函数和一条注释,但背后的分析很值:
electron_api_web_contents_view.cc:166-173
// Our bounds changed and the RenderWidgetHostView is about to be resized to
// match. Push the re-clipped overlay rect now so that it rides along with the
// resize in a single VisualProperties update, rather than trailing it (where it
// could sit behind the resize's pending ack).
void WebContentsView::OnContentsBoundsChanging() {
if (HasLivePage())
SendWindowControlsOverlay();
}
这个回调从哪来?WebContentsView 构造函数里:
electron_api_web_contents_view.cc:44-47
// See OnContentsBoundsChanging().
web_contents->inspectable_web_contents()->GetView()->SetBoundsChangedCallback(
base::BindRepeating(&WebContentsView::OnContentsBoundsChanging,
weak_factory_.GetWeakPtr()));
而 SetBoundsChangedCallback 设的回调在 InspectableWebContentsView::OnBoundsChanged 里被调用(inspectable_web_contents_view.cc:303-307)——这个 OnBoundsChanged 是 views::View 的虚函数,在 bounds 改变后、子视图被重新布局前触发。
于是时序是:
InspectableWebContentsView 的 bounds 变了
→ OnBoundsChanged ← 回调在这里,layout 还没跑
→ SendWindowControlsOverlay() ← 推 WCO 的矩形
→ Layout()
→ SetContentsViewBounds() → contents_web_view_->SetBoundsRect()
→ NativeViewHost::Layout → RWHV::SetSize
→ 产生一次 VisualProperties IPC
关键在于 VisualProperties 是有 ack 的。浏览器发给渲染进程一个 VisualProperties(含 size、window_controls_overlay_rect、screen_info 等),渲染进程要回一个 ack,浏览器才会认为这次同步完成。如果 WCO 的矩形在 SetSize 之后才推,就是第二次 VisualProperties——它排在第一次的 ack 后面,于是屏幕上会先看到"尺寸变大但 WCO 还是旧矩形"的一帧,然后才纠正。这一帧的视觉表现是标题栏按钮和网页内容错位。
注释里 "rather than trailing it (where it could sit behind the resize's pending ack)" 说的就是这个。
SendWindowControlsOverlay(:202-217)本身还有一个坐标系陷阱:
electron_api_web_contents_view.cc:206-213
const auto bounding_rect = observed_window_->GetWindowControlsOverlayRect();
if (!bounding_rect)
return;
views::View* window_view = observed_window_->GetContentsView();
if (!window_view || !window_view->Contains(view()))
return;
gfx::Rect local_rect =
views::View::ConvertRectToTarget(window_view, view(), *bounding_rect);
local_rect.Intersect(view()->GetLocalBounds());
web_contents()->UpdateWindowControlsOverlay(local_rect);
GetWindowControlsOverlayRect 返回的是相对窗口客户区的矩形,而 env(titlebar-area-*) 要的是相对网页内容区的矩形。中间走一次 ConvertRectToTarget,再和网页自己的 bounds 求交——求交是因为"网页可能只遮住了标题栏的一部分"(比如一个半宽的 BrowserView),此时网页侧应该看到的是一个被截断的矩形,而不是一个超出自己边界的矩形。CSS 那边拿到超界的值会算错 titlebar-area-width。
window_view->Contains(view()) 那个判断更微妙:如果这个 WebContentsView 已经被摘出窗口树(Contains 为假),直接返回。否则 ConvertRectToTarget 会在两棵不相关的树之间做坐标转换,views 对此的 DCHECK 是"必须同属一个 Widget"——在 release 构建里不检查,于是算出一个毫无意义的矩形。
ScheduleWindowControlsOverlayUpdate(:190-197)是另一条路:一个 bool 去重,PostTask 延后。 延后是必需的——UpdateWindowControlsOverlay 从 frame view 的布局里触发(见 :183-188 注释),那一刻 view()->GetLocalBounds() 还是旧值。bool 在 SendWindowControlsOverlay 第一行就置回 false,同时承担"去重"与"允许下一次调度";如果把它放在 early return 之后,WCO 就永久停止更新。
13.3.6 拖拽区域:命中测试的跨树穿透
Electron 的无边框窗口靠 CSS 的 -webkit-app-region: drag 实现"拖动标题栏"。这个 CSS 属性在渲染进程里被翻译成一个 SkRegion(draggable_region_),通过 DraggableRegionsChanged 的 IPC 送到浏览器,然后由窗口的非客户区命中测试消费。
消费点在 WebContentsView::NonClientHitTest:
electron_api_web_contents_view.cc:95-128
int WebContentsView::NonClientHitTest(const gfx::Point& point) {
if (!view() || !view()->GetVisible())
return HTNOWHERE;
if (api_web_contents_) {
auto* iwc = api_web_contents_->inspectable_web_contents();
if (!iwc)
return HTNOWHERE;
// Convert the point to the contents view's coordinate space rather than
// the InspectableWebContentsView's coordinate space, because the draggable
// region is relative to the web content area. When DevTools is docked
// (e.g. to the left), the contents view is offset within the parent,
// so we need to account for that offset.
auto* inspectable_view = iwc->GetView();
if (!inspectable_view)
return HTNOWHERE;
auto* contents_view = inspectable_view->GetContentsView();
gfx::Point local_point(point);
views::View::ConvertPointFromWidget(contents_view, &local_point);
SkRegion* region = api_web_contents_->draggable_region();
if (region) {
auto* debugger = api_web_contents_->draggable_region_debugger();
std::optional<base::ElapsedTimer> timer;
if (debugger)
timer.emplace();
const bool hit = region->contains(local_point.x(), local_point.y());
if (debugger)
debugger->OnHitTest(timer->Elapsed(), hit);
if (hit)
return HTCAPTION;
}
}
return HTNOWHERE;
}
四个要点:
其一,HTCAPTION 是操作系统的窗口管理协议。 Windows 上返回 HTCAPTION 意味着"这块区域是标题栏",于是 WM_NCHITTEST 的默认处理会把拖动、双击最大化、右键系统菜单全都接上——不需要 Electron 自己实现拖动。Linux 上(X11/Wayland)走的是 _NET_WM_MOVERESIZE 那套,但 views 层已经抽象好了。macOS 上这个机制不存在,所以 macOS 的拖拽走的是另一条路(NativeWindowMac 里的 performWindowDragWithEvent:)。
其二,坐标系是 contents_view(网页),不是 inspectable_view。 这正是注释讲的:CSS 里的 -webkit-app-region 是相对于网页视口的,DevTools 停靠在左边时 contents_view 在 inspectable_view 内部有偏移。用错坐标系,拖拽区域会整体偏移 DevTools 的宽度。
其三,ConvertPointFromWidget 而不是 ConvertPointToTarget。 前者的语义是"把 widget 坐标系的点转成 view 的局部坐标",正好匹配 point 的来源(NativeWindow::NonClientHitTest),比找到"从哪个视图开始转"更直接。
其四,debugger 的惰性计时。 timer 是 std::optional<base::ElapsedTimer>,只在 debugger 存在时才 emplace()——用可选对象的构造/析构把"是否诊断"的判断收敛到两处,而不是把计时逻辑散在 if (debug) 里。
NativeWindow::NonClientHitTest(native_window.cc:749-780)是聚合点:
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
#if !BUILDFLAG(IS_MAC)
/* ...无边框可缩放窗口的边框命中... */
#endif
// This is to disable dragging in HTML5 full screen mode.
// Details: https://github.com/electron/electron/issues/41002
if (widget()->IsFullscreen())
return HTNOWHERE;
for (DraggableRegionProvider* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
在 HTML5 全屏时直接返回 HTNOWHERE(#41002)。这个判断放在 provider 循环之前,所以它压过了所有网页自己声明的拖拽区域。为什么需要这个特例:HTML5 全屏(element.requestFullscreen())时,网页铺满整个屏幕,如果页面里恰好有一个 -webkit-app-region: drag 的元素(比如一个自绘的顶栏),用户在全屏视频上拖动时窗口会被拖走——而全屏窗口不应该能被拖动。这是"CSS 声明的意图"和"用户当前的模式"冲突时,后者胜出的例子。
draggable_region_providers_ 是个 std::list(native_window.h:587),支持多个 provider 是因为一个窗口里可以有多个 WebContentsView——每个都可能声明自己的拖拽区域。它们的优先级是注册顺序,先注册的先问。(AddDraggableRegionProvider 用 std::ranges::contains 去重,RemoveDraggableRegionProvider 用 remove_if——注意后者不检查是否真的删除了,所以重复移除是静默的,不像 RemoveBackgroundThrottlingSource 会 DCHECK。)
13.4 第二棵树:ui::Layer
views::View 和 ui::Layer 是多对零或一的:一个视图可以完全没有层,也可以有恰好一个。层的作用有三个——独立动画(改层的 transform/opacity 不影响父层重绘)、独立合成(可以有自己的 cc::Layer 和 render surface)、裁剪(SetClipRect 是在层上做的,不是在视图上)。
13.4.1 GetLayer() 的隐式层化
api::View::GetLayer 只有十五行,但它是整章唯一一个"调用就改变状态"的 getter:
electron_api_view.cc:309-323
ui::Layer* View::GetLayer() {
if (!view_)
return nullptr;
if (view_->layer())
return view_->layer();
view_->SetPaintToLayer();
ui::Layer* layer = view_->layer();
layer->SetFillsBoundsOpaquely(false);
return layer;
}
名字叫 Get,实际做的是"没有就造一个"。SetPaintToLayer() 是 views::View 的公开方法,它做四件事:
- 创建一个
ui::Layer(默认是ui::LAYER_TEXTURED)。 - 把
View::Paint()的输出重定向到layer->SetPaintToLayer之后的绘制路径——views会创建一个cc::PaintCanvas作为层的DisplayItemList,View::OnPaint画进去。 - 把层挂到父视图的层树上(或成为子树根)。
- 让
View::SetBoundsRect之后同步layer->SetBounds。
SetFillsBoundsOpaquely(false) 是必要的:views 默认认为一个层是不透明的(因为多数 views 控件画满自己的边界),但 JS 里用 setBackgroundBlur / setBorderRadius 的视图显然是部分透明的。如果不设 false,合成器会跳过层的下方内容,圆角外和模糊边缘会显示成黑色(或被跳过的父内容)。这一行是"圆角看起来像黑角"这个经典 bug 的修复。
13.4.2 层化的代价
| 代价 | 说明 |
|---|---|
| 额外一次离屏渲染 | 视图不再画进父树的 display list,而是先画进自己的层 |
可能多一个 RenderSurface | 层有 opacity < 1 或 SetMasksToBounds 时,cc 为它单独分配 render pass |
| 一次纹理上传 | 层的输出是一块纹理 |
| 断掉子像素对齐 | 层 bounds 是整数像素,跨层边界的内容失去子像素定位 |
api::View 只在两处隐式调 GetLayer():setBounds({animate: true}) 与 setBackgroundBlur()。setBorderRadius() 走 SetClipPath,不需要层。
这就是 setBorderRadius 与 setBackgroundBlur 不能混用的原因:前者在视图绘制阶段裁,后者在合成阶段模糊,顺序是"先模糊层背景,再裁路径",边缘会被裁掉——看起来没问题。但与 setBounds 动画叠加时,层的 bounds 在动、SetClipPath 用的 view_->bounds() 还是旧值,圆角会在动画期间错位,OnEnded 之后才跳正。
13.4.3 圆角的三条路
Electron 里"圆角"这个词指三种不同的东西,走三条不同的实现:
| 哪里的圆角 | API | 实现 | 谁裁 |
|---|---|---|---|
JS View 的圆角 | view.setBorderRadius(n) | views::View::SetClipPath(SkPath) | 视图自己的 paint |
WebContentsView 的圆角 | wcv.setBorderRadius(n) | NativeViewHost::SetNativeViewCornerRadii | 合成器(层) |
| 窗口的圆角 | BaseWindow({ roundedCorners: true }) / 系统 | DwmSetWindowAttribute / 系统 | 窗口管理器 |
第二条是关键,因为网页内容不是一个 views::View 的绘制输出,它是一块由渲染进程产出的独立纹理。SetClipPath 对它无效——那个 path 只影响 views 自己的 display list。必须让合成器在合成那一刻裁。
实现:
electron_api_web_contents_view.cc:83-93
void WebContentsView::SetBorderRadius(int radius) {
View::SetBorderRadius(radius);
ApplyBorderRadius();
}
void WebContentsView::ApplyBorderRadius() {
if (border_radius().has_value() && api_web_contents_ && view()->GetWidget()) {
auto* view = api_web_contents_->inspectable_web_contents()->GetView();
view->SetCornerRadii(gfx::RoundedCornersF(border_radius().value()));
}
}
WebContentsView::SetBorderRadius 先调 View::SetBorderRadius(那会走 SetClipPath),再调 ApplyBorderRadius(那会走 inspector->SetCornerRadii)。两条路都走,是因为:
SetClipPath负责裁InspectableWebContentsView这个父视图自己的绘制(比如它画的 DevTools 分割线、背景)。SetNativeViewCornerRadii负责裁网页那块原生纹理。
只走一条会漏。 只走 SetClipPath:网页纹理会溢出圆角(这是最常见的 bug 报告)。只走 SetCornerRadii:InspectableWebContentsView 自己画的东西会溢出。
InspectableWebContentsView::SetCornerRadii 里有一个 Aura 专属的补丁:
inspectable_web_contents_view.cc:123-140
void InspectableWebContentsView::SetCornerRadii(
const gfx::RoundedCornersF& corner_radii) {
// WebView won't exist for offscreen rendering.
if (contents_web_view_) {
contents_web_view_->holder()->SetNativeViewCornerRadii(corner_radii);
#if defined(USE_AURA)
// Aura calls SetIsFastRoundedCorner(true) which clips each tile separately.
// This creates a jagged edge at fractional DPI if the view is taller than
// one tile, so we use the slow method for a smooth edge at the cost
// of an extra render surface.
if (auto* native_view = contents_web_view_->holder()->native_view()) {
if (auto* layer = native_view->layer())
layer->SetIsFastRoundedCorner(false);
}
#endif
}
}
这是本章信息密度最高的一段注释。展开:
"Aura calls SetIsFastRoundedCorner(true)":ui::Layer 有一个 is_fast_rounded_corner_ 标志。为 true 时,cc 在光栅化每个 tile 的时候就把圆角裁掉——对每个 tile 单独做一次圆角矩形裁剪。这很快(不需要额外 render surface),但如果视图的高度超过一个 tile(通常是 256 或 512 像素),每个 tile 都会独立地被裁一次圆角,于是 tile 之间的接缝处会出现阶梯状的锯齿。
在整数 DPI 下这个问题几乎看不出来(tile 边界和像素边界对齐)。在分数 DPI(125%、150%)下,device_scale_factor 是 1.25/1.5,tile 的边界落在半像素上,锯齿就明显了。
"so we use the slow method":SetIsFastRoundedCorner(false) 让 cc 改用另一种实现——给这个层分配一个独立的 RenderSurface,在合成阶段用 mask 层做整体裁剪。多一次离屏渲染和一次纹理,但边缘是抗锯齿的。
这段代码只在 USE_AURA(Windows / Linux)下存在,因为 macOS 的圆角走的是 CALayer.cornerRadius,由 CoreAnimation 自己做,ui::Layer 的那套标志在 macOS 上没有对应物。
一个隐藏的坑:native_view->layer() 可能为空。aura::Window 默认是 LAYER_NOT_DRAWN,只有在需要绘制时才创建 ui::Layer。如果这里返回 nullptr,SetIsFastRoundedCorner 就不会被调用,于是圆角会退回 fast 模式,在分数 DPI 下又是锯齿。这个 if 没有 else,也没有重试机制。在窗口刚创建、还没开始绘制的时候设圆角,就会踩到这条路径。
13.4.4 setBackgroundBlur 的真实含义
electron_api_view.cc:523-536
void View::SetBackgroundBlur(int blur_radius) {
if (!view_)
return;
if (blur_radius < 0)
blur_radius = 0;
ui::Layer* layer = GetLayer();
if (!layer)
return;
layer->SetBackgroundBlur(blur_radius);
}
这是"背景模糊",不是"模糊这个视图"。 ui::Layer::SetBackgroundBlur 的语义是:在这个层后面的内容上应用高斯模糊,然后把层的内容画在模糊之上。所以:
- 它需要一个能读到后面的内容的合成上下文——也就是说这个层必须是"半透明"的(这就是
SetFillsBoundsOpaquely(false)的原因)。 - 它需要后面的内容在同一个合成器里。如果后面是另一个进程的纹理(比如另一个
WebContents),模糊也能工作,因为显示合成器会把它们聚合在一起——但这个依赖是有条件的,在某些 GPU 驱动上跨 surface 的 backdrop filter 会失败。 - 它不会模糊这个层自己的内容。想模糊自己,得用 CSS 的
filter: blur()或者backdrop-filter。
blur_radius < 0 被钳到 0 而不是报错,这是 Electron 的通用风格:API 尽量不抛,静默钳制。代价是错误配置不会被告知。
13.4.5 setBorderRadius 的两层钳制
electron_api_view.cc:500-507
// shell/browser/api/electron_api_view.cc:500-520(节选)
auto size = view_->bounds().size();
// Restrict border radius to the constraints set in the path builder class.
// If the constraints are exceeded, the builder will crash.
int radius;
{ float r = border_radius_.value() * 1.f;
r = std::min(r, size.width() / 2.f);
r = std::min(r, size.height() / 2.f);
r = std::max(r, 0.f);
radius = std::floor(r); }
// RoundedRectCutoutPathBuilder has a minimum size of 32 x 32.
if (radius > 0 && size.width() >= 32 && size.height() >= 32) {
auto builder = ash::RoundedRectCutoutPathBuilder(gfx::SizeF(size));
builder.CornerRadius(radius);
view_->SetClipPath(builder.Build());
} else {
view_->SetClipPath(SkPath());
}
钳制一:radius ≤ min(width, height) / 2。 超过半宽半高的圆角在几何上退化成椭圆,而 ash::RoundedRectCutoutPathBuilder 的选择是直接 CHECK 崩溃。std::floor 而非 round,是为了不让浮点误差把值推过界。
钳制二:视图至少 32×32。 小于它时清空 clip path,也就是"没有圆角"——不是按比例缩小。于是 20×20 的视图设 borderRadius: 10(理论上该是个圆)实际是直角;视图从 40×40 缩到 20×20 时圆角消失、放大回来又出现。这个跳变在窗口尺寸动画里是可感知的。
另外 border_radius_ 是 std::optional<int>,但 SetBorderRadius 的参数是 int——没有"取消圆角"的 API,只有"设成 0"。
13.5 第三棵树:平台原生视图
13.5.1 aura::Window:一个不是窗口的窗口
aura(Aura UI Resource Assembly)是 Chromium 的跨平台 UI 层,它的 aura::Window 是平台窗口的抽象容器,不是 HWND 也不是 XID。一个 aura::Window 有三重身份:
- 视图树节点:有 parent 和 children,可以做树操作。
- 绘制单元:默认带一个
ui::Layer(LAZY或NOT_DRAWN,取决于类型),参与层树合成。 - 事件目标:参与
ui::EventTarget的分发,有 bounds、有可见性、有hit-test。
RenderWidgetHostViewAura 创建的 aura::Window 主要用第三种身份:它基本不绘制(网页内容由 DelegatedFrameHost 的 SurfaceLayer 提供),作用是给 ui::EventTargeter 一个节点,以及给 NativeViewHost 一个可以 SetParent 的东西。建它的是 RenderWidgetHostViewAura::CreateAuraWindow,Electron 不参与;Electron 参与的是它之上的两层——WebContentsViewAura 的容器窗口(WebContents::GetNativeView() 返回的那个)和 NativeViewHost 的 attach 时机。
13.5.2 macOS:被吃掉的鼠标事件
macOS 没有 Aura。Electron 在 macOS 上仍然用 views(views::Widget + NativeWidgetMac),但底层是 NSView 而不是 aura::Window。这个差异导致一个结构性问题,就是 13.1.2 里那两行 SetEventTargeter 要解决的。
问题长这样。BrowserWindow 的视图结构(macOS):
RootViewMac(FillLayout)
├─ [0] InspectableWebContentsView ← 网页
└─ [1] content_view_ ← 用户视图,铺满整个窗口
content_view_ 铺满整个窗口,并且在 z 序上更高。当用户点击网页时,views 的命中测试从根往下走:先问 content_view_(后画的先问),它的 bounds 包含点击点 → 返回自己 → 事件被 content_view_ 处理,永远到不了 InspectableWebContentsView。
在 Aura 上这不是问题,因为 RenderWidgetHostViewAura 会直接订阅 aura::Window 的事件——事件分发走的是 aura::Window 树,不是 views::View 树,两者独立。macOS 上事件分发走的就是 views::View 树(NSView 的 hitTest: 最终会走到 views::View 的 HitTestPoint),所以 views 的 z 序直接决定谁能收到鼠标。
Electron 的解法是给 content_view_ 一个自定义的 ViewTargeter:
content_view_targeter_delegate.cc:14-31
bool ContentViewTargeterDelegate::DoesIntersectRect(
const views::View* target,
const gfx::Rect& rect) const {
if (!views::ViewTargeterDelegate::DoesIntersectRect(target, rect)) {
return false;
}
for (const views::View* child : target->children()) {
if (!child->GetVisible() || !child->GetCanProcessEventsWithinSubtree()) {
continue;
}
gfx::RectF rect_in_child(rect);
views::View::ConvertRectToTarget(target, child, &rect_in_child);
if (child->HitTestRect(gfx::ToEnclosingRect(rect_in_child))) {
return true;
}
}
return false;
}
它把"我的 bounds 包含这个点"改成了"我的某个子视图真的盖住了这个点"。 于是当 content_view_ 里没有任何子视图覆盖点击位置时,DoesIntersectRect 返回 false,父级 TargetForRect 的循环跳过它,继续问下一个兄弟——也就是 InspectableWebContentsView。
头文件里的注释把整条链路讲完了(content_view_targeter_delegate.h:22-40):
// ... the parent's default TargetForRect loop skips content_view_ and falls
// through to the sibling, ultimately resolving to the WebContentsView's
// NativeViewHost so BridgedContentView::hitTest: routes the event to
// RenderWidgetHostViewCocoa.
BridgedContentView 是 Chromium 在 macOS 上的关键类:它是 RWHV 的 NSView 子类,它的 hitTest: 是"事件进入 content 层的唯一入口"。所以这条链是:NSWindow → views 的 HitTestPoint → NativeViewHost → BridgedContentView::hitTest: → RenderWidgetHostViewCocoa → 转成 blink::WebMouseEvent → IPC 到渲染进程。
注释里还有一段"不要这么做"的历史:
// This must never affect TargetForRect's contract — it only narrows
// HitTestRect, which the default loop already handles by skipping the child.
// Returning nullptr from TargetForRect (the previous approach) violated the
// contract and crashed RootView::UpdateCursor (see #51576).
上一个实现是重写 TargetForRect 返回 nullptr。 这违反了 TargetForRect 的契约——它的契约是"返回一个 View*,且该 View 必须能处理这个事件"。返回 nullptr 让调用方(UpdateCursor)拿到了空指针。改成"只缩窄 HitTestRect"之后,TargetForRect 的默认实现自然地跳过这个子视图,契约保持。这是一个"用更小的改动满足同一个需求"的经典案例:缩窄而不是推翻。
13.5.3 三棵树的交汇点:NativeViewHost
把三条线索收在一起,NativeViewHost 的角色可以精确表述:
| 它做什么 | 怎么做 |
|---|---|
| 占位 | 自己是 views::View,参与布局,GetPreferredSize 转发给原生视图 |
| 挂载 | Attach(native_view) 记住目标;挂到 Widget 后 SetParent 到 GetNativeViewContainer() |
| 跟随 | 重写 Layout(),把自己的 bounds 换算成原生视图的 bounds |
| 裁剪 | SetNativeViewCornerRadii / SetClippingInsets 把圆角/裁剪传给原生视图的层 |
| 卸载 | Detach() 从父原生视图摘下,但不销毁 |
GetNativeViewContainer() 是 views::View 的虚函数,默认返回 GetWidget()->GetNativeView()。InspectableWebContentsView 不重写它,所以 NativeViewHost 会把网页挂到窗口的原生视图上——注意是"窗口",不是"InspectableWebContentsView 自己的原生视图",因为它没有。然后 NativeViewHost::Layout() 用 ConvertRectToWidget 把自己在视图树里的位置换算成窗口坐标,SetBounds 给原生视图。这就是"views 坐标系 → 平台坐标系"的翻译点,也是整个视图系统里唯一一处需要做这种翻译的地方。
一个直接后果:NativeViewHost 的祖先链不能有 transform。 views::View 支持 SetTransform(通过层),但 NativeViewHost::Layout 只做坐标平移和缩放,不做旋转/斜切。如果祖先有旋转,原生视图不会跟着转——因为原生视图不在 views 的层树里,它是由平台合成器直接管的。这是 views::WebView 与 CSS transform 无法共存于同一棵视图树上的根本原因。
13.6 合成:像素怎么上屏
前五节讲的是"结构"。这一节讲"像素",而像素的路径完全不在这三棵树里。
13.6.1 渲染进程那一半
渲染进程主线程跑 Blink,把 DOM 变成 cc::Layer 树;cc::LayerTreeHost 在合成线程上把它变成 CompositorFrame——一组 RenderPass、每个里若干 DrawQuad、外加一组 TransferableResource 引用。
CompositorFrame 不是位图。 DrawQuad 是"用这个纹理、这个变换、这个混合模式画这个矩形"的指令,真正的光栅化在 GPU 进程——渲染进程的合成线程从不产生像素,只产生"怎么画"的描述。
CompositorFrame 经 mojom::CompositorFrameSink 提交(每个 FrameSinkId 一个接口)。FrameSinkId 分两段:client_id(渲染进程的编号)与 sink_id(进程内序号)。一个 RenderWidgetHost 对应一个 FrameSinkId,它在浏览器进程分配、渲染进程使用、GPU 进程消费——三方共享的唯一定位符。
提交之后渲染进程收到 CompositorFrameAck(含被释放的 resource)才能复用那些 TransferableResource。这个 ack 就是背压的来源:GPU 处理不过来时 ack 迟迟不来,资源池耗尽,开始丢帧——这是 requestAnimationFrame 在重负载下"跳帧"而不是"变慢"的机制根源。
13.6.2 浏览器进程那一半
CompositorFrame 到达 GPU 进程后,被 viz::Display 消费。但一个窗口的屏幕上不止有网页——还有标题栏、按钮、菜单、其他 views 控件。那些东西的像素由谁产生?
答案:由浏览器进程的 ui::Compositor 产生另一份 CompositorFrame。ui::Compositor 是 views 世界的合成器,它把 ui::Layer 树光栅化成语义相同的 CompositorFrame,也提交给 GPU 进程的显示合成器。
于是显示合成器要做的事是聚合两份(或更多份)CompositorFrame,产出一帧最终的画面。聚合的机制是 SurfaceId 嵌入:
浏览器 ui::Compositor 的帧
RenderPass 0
DrawQuad: 标题栏(本地纹理)
DrawQuad: 内容区
SurfaceLayer → 引用 SurfaceId(renderer, local_surface_id)
▼
GPU 进程显示合成器
把 SurfaceId 引用的那份渲染进程帧插进来 → 一份完整的 RenderPass 列表 → 光栅化 → 上屏
DelegatedFrameHost 就是"引用者"这一侧的实现:它持有一个 SurfaceLayer,把它嵌进浏览器合成器的层树,并管理被引用那一侧的 SurfaceId(分配、推进 LocalSurfaceId、处理 SurfaceObserver 的回调)。
这就是为什么"网页内容无法被 views 的 z 序穿插" —— 网页不是一棵子树,它是一个被整体嵌入的 surface。content_view_ 要么在它上面,要么在它下面,没有"中间"。
13.6.3 Aura 路径的完整链路
把上面两段接起来,Windows / Linux 上的一次绘制是:
1. 渲染进程主线程:DOM 变更 → 重新布局/绘制 → cc::Layer 树更新
2. 渲染进程合成线程:LayerTreeHost → 光栅化 tile(可能委托 GPU)→ CompositorFrame
3. Mojo 提交:CompositorFrameSink::SubmitCompositorFrame(SurfaceId, frame)
4. GPU 进程:viz::Display 收到子 surface 更新,标记"需要聚合"
5. 浏览器进程(可能同时):ui::Compositor 因为某个 views 层变了,产生自己的帧
6. GPU 进程:Display::DrawAndSwap → 把浏览器 surface 和网页 surface 聚合
7. GPU 进程:光栅化成最终帧 → 通过 GL/Vulkan/D3D 呈现到系统的 surface
8. 系统合成器(DWM / X11 compositor / Wayland compositor)→ 屏幕
八个步骤里 Electron 只在第 5 步参与(通过 views 和 ui::Layer)。第 1–4 步、第 6–8 步全是 Chromium 的。
第 8 步值得单独说一下:Windows 上 DWM 会再做一次合成(所以"透明窗口"能工作),Linux 上取决于有没有 compositor(X11 没有 compositor 时窗口无法真正透明),Wayland 上一定有。这意味着"Electron 窗口的最终像素"至少被合成两次,某些情况三次(DWM + GPU 进程 + Electron 的 ui::Compositor)。
13.6.4 macOS 路径:完全不同
macOS 上架构换了。浏览器进程不做合成,ui::Compositor 在 macOS 上仍然存在(views 需要它来驱动动画和层树),但它提交的帧最终不通过 SurfaceLayer 聚合,而是:
1. 渲染进程:CompositorFrame(同 Aura)
2. GPU 进程:显示合成器聚合,产出 CALayerTree
3. GPU 进程 → 浏览器进程:mojom::DisplayClient::OnDisplayReceivedCALayerParams
4. 浏览器进程:BrowserCompositorMac 把 CALayerParams 应用到自己的 CALayer 树
5. AppKit / CoreAnimation:合成 CALayer 树 → 屏幕
关键差异在第 3 步:跨进程传的不是位图,是 CALayerParams —— 一组"这个 CALayer 用这个 IOSurface、这个 transform、这个背景色"的描述。IOSurface 是 macOS 的跨进程 GPU 纹理共享机制,可以被多个进程同时映射。
这个设计的后果:
- CoreAnimation 承担了最终合成。所以 Electron 里
setBackgroundBlur走的是NSVisualEffectView那条路(native_window_mac.mm里的 vibrancy),不是ui::Layer的 backdrop filter。 - 每个
CALayer是独立的。这就是为什么 macOS 上"给网页加圆角"必须设CALayer.cornerRadius(SetNativeViewCornerRadii在 macOS 上最终落到这里),而不是做一个 mask。 ui::Compositor在 macOS 上仍然必要,因为views的动画(AnimationBuilder)由它驱动。但它的输出被"降级"成CALayer属性,而不是一份独立的 surface。
这个分叉解释了 disable_compositor_recycling.patch 为什么只改 macOS:
host()->WasHidden();
- browser_compositor_->SetRenderWidgetHostIsHidden(true);
+ // Consider the RWHV occluded only if it is not attached to a window
+ // (e.g. unattached BrowserView). Otherwise we treat it as visible to
+ // prevent unnecessary compositor recycling.
+ const bool unattached = ![GetInProcessNSView() window];
+ browser_compositor_->SetRenderWidgetHostIsHidden(unattached);
补丁的提交信息把动机写得很清楚:
Compositor recycling is useful for Chrome because there can be many tabs and spinning up a compositor for each one would be costly. In practice, Chrome uses the parent compositor code path of
browser_compositor_view_mac.mm; the NSView of each tab is detached when it's hidden and attached when it's shown. For Electron, there is no parent compositor, so we're forced into the "own compositor" code path, which seems to be non-optimal and pretty ruthless in terms of the release of resources. Electron has no real concept of multiple tabs per window, so it should be okay to disable this ruthless recycling altogether in Electron.
"Electron has no real concept of multiple tabs per window" 这句是关键:Chrome 的回收策略是为"一百个标签页共享一个窗口"优化的,Electron 的窗口通常只有一个网页。同一个策略在两种使用模式下代价完全不同——这是"上游为上游的场景优化,下游要为自己的场景改回来"的教科书案例。
SetRenderWidgetHostIsHidden(false) 的实际效果是阻止 BrowserCompositorMac 释放它持有的 IOSurface 和 CALayer。代价是内存(隐藏窗口保留纹理),收益是"隐藏再显示时的第一帧不会闪白"。
13.6.5 四条路径的对照
| Aura(Win/Linux) | macOS | OSR 软件 | OSR 共享纹理 | |
|---|---|---|---|---|
| 渲染进程产物 | CompositorFrame | 同 | 同 | 同 |
| 跨进程传什么 | Mojo + TransferableResource | CALayerParams + IOSurface | 共享内存位图 | GpuMemoryBuffer 句柄 |
| 浏览器进程合成 | ui::Compositor 参与 | 不参与(只应用属性) | ui::Compositor 独占 | FrameSinkVideoCapturer |
| 谁做最终合成 | GPU 进程 + 系统 | CoreAnimation | Electron(CPU) | 调用方(GPU) |
| 每次绘制的拷贝次数 | 0(纹理直传) | 0 | 1(共享内存→SkBitmap) | 0 |
| 需要窗口 | 是 | 是 | 否 | 否 |
| 帧率控制 | 系统 vsync | 系统 vsync | frameRate 定时器 | frameRate + 捕获器 |
"每次绘制的拷贝次数"这一行是选择 OSR 与否的核心权衡。 软件 OSR 每次绘制都要把共享内存里的像素读进 SkBitmap(osr_host_display_client.cc:76-82 的 canvas_->peekPixels + bitmap.installPixels 其实不拷贝,但 OnPaint 里的 bitmap.readPixels(backing_->pixmap()) 是拷贝)。1080p 一帧是 8 MB,60fps 就是 480 MB/s 的内存带宽。共享纹理路径省掉这次拷贝,代价是调用方必须自己处理 GPU 同步。
13.7 可见性:WasShown / WasHidden / WasOccluded
可见性看起来是个布尔,实际是三个状态加一个"我是否还在画"的独立布尔。
content::WebContents 的可见性 API 有三个:
void WasShown(); // 变成可见
void WasHidden(); // 变成不可见
void WasOccluded(); // 被遮挡(可见性上的第三态)
第三个是 Chromium 为"窗口还在屏幕上,但被别的窗口盖住了"设计的。它的语义是"可见但不需要画"——OC(occlusion)检测在 Windows 上靠 DwmGetWindowAttribute(DWMWA_CLOAKED) 加矩形相交,在 macOS 上靠 NSWindow.occlusionState,在 Linux 上基本不工作(没有统一协议)。
13.7.1 三个入口在 Electron 里
Electron 只在 BrowserWindow 上调它们:
electron_api_browser_window.cc:292-304
void BrowserWindow::OnWindowShow() {
if (!web_contents_shown_) {
web_contents()->WasShown();
web_contents_shown_ = true;
}
BaseWindow::OnWindowShow();
}
void BrowserWindow::OnWindowHide() {
web_contents()->WasOccluded();
web_contents_shown_ = false;
BaseWindow::OnWindowHide();
}
注意两处不对称:
其一,Show() 有 if (!web_contents_shown_) 守卫,OnWindowHide() 没有。 因为 Show() 可能被反复调用(win.show() 在一个已显示的窗口上),而 OnWindowShow 是系统通知,只在真正变化时来。但 OnWindowHide 里没有守卫意味着如果系统发两次 hide 通知,WasOccluded() 会被调两次——WebContents::WasOccluded 是幂等的,所以无害。
其二,隐藏时调的是 WasOccluded() 而不是 WasHidden()。 content::Visibility 是三态(VISIBLE/OCCLUDED/HIDDEN),WasOccluded 走的是"在被遮挡"这一支:页面不绘制,但不会进入完整的 hidden 生命周期(不触发 visibilitychange、不暂停 media 的可见性判定)。Electron 选它是为了不触发 visibilitychange——很多应用在那里做重活(保存状态、断开连接),窗口最小化就触发一次会让这些应用行为异常。代价是页面自己不知道"我被藏起来了",document.visibilityState 仍然是 'visible',依赖它做省电的应用会继续跑。
Show() / ShowInactive() 里的 WasShown() 是无条件的:
electron_api_browser_window.cc:306-319
void BrowserWindow::Show() {
web_contents()->WasShown();
web_contents_shown_ = true;
BaseWindow::Show();
}
void BrowserWindow::ShowInactive() {
// This method doesn't make sense for modal window.
if (IsModal())
return;
web_contents()->WasShown();
web_contents_shown_ = true;
BaseWindow::ShowInactive();
}
因为 BrowserWindow 可能在 show: false 下创建,此时 OnWindowShow 从未来过,web_contents_shown_ 是 false——但 WasShown() 还是得调。Show() 调它是因为"我要显示了",OnWindowShow 调它是因为"系统告诉我显示了",两条路都要覆盖。
13.7.2 paintWhenInitiallyHidden
这是 BrowserWindow 的一个选项,默认 true。它的实现方式很间接——不是"不调 WasShown",而是把 show 偏好传给 WebContents:
electron_api_browser_window.cc:50-58
// Copy the show setting to webContents, but only if we don't want to paint
// when initially hidden
bool paint_when_initially_hidden = true;
options.Get(options::kPaintWhenInitiallyHidden, &paint_when_initially_hidden);
if (!paint_when_initially_hidden) {
bool show = true;
options.Get(options::kShow, &show);
web_preferences.Set(options::kShow, show);
}
于是 webPreferences.show 这个字段在 WebContents::Create 里被读到,如果是 false,WebContents 创建时就不会 WasShown()。换句话说,"不画"是通过"创建时就不认为可见"实现的,不是通过"创建后隐藏"。
paintWhenInitiallyHidden: false 的典型用途是"先在后台把页面加载好,等 ready-to-show 再 show()"——这样用户看不到白屏。但它有个副作用:页面在隐藏状态下创建的合成器可能没有分配 surface,第一次 show() 时会有一次完整的"创建 surface → 分配 tile → 光栅化 → 上屏"的延迟。在低端机上这一帧可能是 100ms 以上。
13.7.3 macOS 遮挡的三次修正
macOS 上"窗口隐藏时创建、之后显示"这个组合打破了 Chromium 的两个假设,需要一份专门的补丁。补丁信息把两个假设列得很清楚:
updateWebContentsVisibilityonly checks-[NSWindow isOccluded], which defaults toNOfor never-shown windows, soviewDidMoveToWindowincorrectly reportskVisiblefor hidden windows.windowChangedOcclusionState:only responds to checker-originated notifications, butsetOccluded:early-returns whenisOccludeddoesn't change. A hidden window'sisOccludedisNOand staysNOaftershow(), so no checker notification fires on show and the view never updates tokVisible.
翻译成因果链:
假设一:"窗口至少在视图被 attach 的同一时刻已经显示过了。" 于是 Chromium 只查 isOccluded——一个从未显示过的窗口 isOccluded 返回 NO("没被遮挡"),于是被判定为 kVisible。一个没显示过的窗口被当成可见,于是渲染进程开始画——画了也没人看。
假设二:"isOccluded 变了,就一定有通知。" Chromium 的遮挡检测器(WebContentsOcclusionCheckerMac)只在 isOccluded 变化时发通知(setOccluded: 里 if (new == old) return;)。一个隐藏窗口的 isOccluded 是 NO,show() 之后还是 NO(因为显示不等于被遮挡状态变化),于是不会有任何通知,视图永远停在"隐藏"。
于是补丁改两处:
- else if ([[self window] isOccluded])
+ else if ([[self window] isOccluded] ||
+ !([[self window] occlusionState] & NSWindowOcclusionStateVisible))
visibility = Visibility::kOccluded;
第一处:同时看 isOccluded("被别的窗口盖住")和 occlusionState & NSWindowOcclusionStateVisible("我是否真的在屏幕上")。后者能正确反映"没显示过"。
- NSDictionary* userInfo = [aNotification userInfo];
- NSString* occlusionCheckerKey = [WebContentsOcclusionCheckerMac className];
- if (userInfo[occlusionCheckerKey] != nil)
- [self updateWebContentsVisibility];
+ // Respond to occlusion notifications from both macOS and the occlusion
+ // checker. ...
+ [self updateWebContentsVisibility];
第二处:不再过滤通知来源,任何遮挡状态变化都重新计算。开销是每次系统遮挡通知都跑一遍 updateWebContentsVisibility(几个布尔判断,可以忽略)。
补丁信息最后一句:"This patch can be removed if the changes are upstreamed to Chromium." —— Electron 的很多补丁都是这个形状:不是"Electron 需要这个能力",而是"Electron 的使用模式和 Chrome 不同,暴露了上游的一个隐含假设"。
13.7.4 WasShown 的连锁反应
调一次 WasShown() 会发生什么,值得完整走一遍(这是排查"页面卡住不动"类问题的必需品):
WebContents::WasShown()
→ WebContentsImpl::WasShown() → 通知所有 WebContentsObserver::WasShown()
→ RenderWidgetHost::WasShown()(对每个 RWH)
→ disable_hidden_ 为真则 return(13.8.1)
→ RenderWidgetHostView::Show() → RWHVAura::ShowImpl()
→ aura::Window::Show() → DelegatedFrameHost::WasShown()
→ 告诉 GPU 进程"surface 可见了,可以分配资源"
→ 渲染进程 SetPageLifecycleState(visible)
→ visibilityState='visible'、visibilitychange、rAF 恢复
→ media 恢复播放、IntersectionObserver 重新计算
注意 WasHidden 那一侧是不对称的:WasHidden() 会先 cancel 指针锁请求、暂停 media、停 rAF,而 WasShown() 只是"恢复"。所以"隐藏→显示"的往返不是幂等的:某些状态(比如 media 的播放位置、IntersectionObserver 的观察者状态)在隐藏期间会变,显示之后不会自动恢复。这就是"窗口最小化再恢复之后,视频从 0 开始播"这类 bug 的来源——但责任在应用侧,Electron 只是传递了 Chromium 的语义。
13.8 后台节流:一个选项,四处打开
webPreferences.backgroundThrottling 默认是 true。设成 false 之后,被隐藏或被遮挡的窗口仍然以 60fps 跑 requestAnimationFrame。这是 Electron 里少数几个"一行配置影响整条渲染管线"的例子,因为 Chromium 的节流不是一处开关,而是四层,每一层都得单独关掉:
| 层 | 位置 | 关掉之后 |
|---|---|---|
| 1 | RenderWidgetHostImpl::WasHidden | 宿主不会认为自己被隐藏 |
| 2 | RenderViewHost::SetSchedulerThrottling | Blink 的 page scheduler 不降频 |
| 3 | ui::Compositor::SetBackgroundThrottling | 浏览器合成器的 display 不进入不可见状态 |
| 4 | WebViewImpl::SetVisibilityState | 页面永远被告知 visibilityState === 'visible' |
四层对应四个不同的"隐藏"概念,混起来就出错:
- 第 1 层管的是"
WebContents是否认为窗口可见"——它影响RenderWidgetHostView::Hide是否真的把 surface 标记为隐藏。 - 第 2 层管的是 Blink 的调度器——
PageScheduler会在隐藏时把定时器合并、把rAF停掉、降低requestIdleCallback的频率。 - 第 3 层管的是浏览器进程的合成器——
viz::DisplayScheduler在不可见时"drop frame draws and swaps"(补丁注释原话),也就是根本不提交帧。 - 第 4 层管的是页面看到的状态——
document.visibilityState、visibilitychange事件、document.hidden。
为什么四层都要? 因为它们的失效方式各不相同:
- 只关第 1 层:
WasHidden不生效,但 Blink 的 scheduler 收到的是PageLifecycleState,那是第 2 层的事——页面还是被降频。 - 只关第 2 层:页面在跑
rAF,但浏览器合成器的 display 不可见,产出的帧被丢掉——CPU 在烧,屏幕没变。这是最坏的情况。 - 只关第 3 层:浏览器愿意提交帧,但页面不产生帧——白关。
- 只关第 4 层:页面以为可见,调度器仍然降频——
visibilityState是'visible'但rAF每秒只跑 1 次。这个组合最难排查,因为页面自己看到的状态是对的。
13.8.1 第一层:RenderWidgetHostImpl::disable_hidden_
disable_hidden.patch 加了两处。
第一处是一个早退:
void RenderWidgetHostImpl::WasHidden() {
/* ...if (hidden) return; ... */
+ if (disable_hidden_) {
+ return;
+ }
WasHidden() 的原有逻辑是"标记隐藏、取消指针锁、通知视图、暂停 media"。加了这一行之后,整个函数在 disable_hidden_ 为真时什么都不做。注意它放在"是否已经隐藏"的判断之后——所以第一次隐藏仍然会走完整个流程之外的部分?不,是直接 return。
第二处改的是 RenderWidgetHostViewAura::DidNavigate:
- if (!IsShowing()) {
+ // Electron: a widget that Electron keeps visible while its native view is
+ // hidden is still producing frames, so treat it as showing here. Otherwise
+ // the next VisualProperties update is sent without a LocalSurfaceId and the
+ // renderer stops producing frames until the view is shown. This matches
+ // RenderWidgetHostViewMac, which keys this off the host's visibility.
+ if (!IsShowing() && host()->IsHidden()) {
// Navigating while hidden should not allocate a new LocalSurfaceID...
这一处比第一处精妙得多。原逻辑:"如果视图不在显示中,导航时不要分配新的 LocalSurfaceId"——因为隐藏的视图不需要新 surface,省点资源。
问题在于:Electron 可以做到"host() 认为可见,但 IsShowing() 为假"。这是个不一致状态,由 paintWhenInitiallyHidden: false + backgroundThrottling: false 制造:WasShown 被跳过(所以 IsShowing() 假),但 disable_hidden_ 让 host() 保持在可见状态。
在这个不一致状态下,导航发生时原逻辑会不分配 LocalSurfaceId,然后下一次 VisualProperties 更新就带着空的 LocalSurfaceId 发给渲染进程——渲染进程拿到空的 surface id,会认为"我还没有 surface",于是把主帧推迟到视图真正显示。也就是说:页面卡住不画,直到你 show() 窗口。
补丁的修法是把条件从"视图在显示中"改成"视图在显示中 或 host 认为可见",与 macOS 的实现对齐(注释里明说 "This matches RenderWidgetHostViewMac,which keys this off the host's visibility")。这是一个"平台之间本该一致但实际不一致,Electron 借机把 Aura 拉齐到 mac"的例子。
同样的不一致也影响了 HideImpl:
- if (!host()->IsHidden()) {
+ if (!host()->IsHidden() && !host()->disable_hidden_) {
host()->WasHidden();
因为 disable_hidden_ 让 host()->WasHidden() 变成 no-op,host()->IsHidden() 永远为假,于是 HideImpl 里那段"从父 window 摘掉子 window、释放 surface"的逻辑永远不跑。这看起来是想要的效果("我不隐藏"),但它同时意味着 aura::Window 不会真的隐藏——SetVisible(false) 的效果被绕过了。这是"关掉节流"和"窗口真的被隐藏"之间无法两全的地方:disable_hidden_ 是"假装没隐藏",而假装的结果是真的没隐藏。
13.8.2 第二层:SetSchedulerThrottling
allow_disabling_blink_scheduler_throttling_per_renderview.patch 加了一条从浏览器到渲染进程的广播:
interface PageBroadcast {
SetSupportsDraggableRegions(bool supports_draggable_regions);
+ // Whether to enable the Renderer scheduler background throttling.
+ SetSchedulerThrottling(bool allowed);
};
为什么挂在 PageBroadcast 而不是 Frame? 因为节流是页级概念——一个页面里有多个 frame(主 frame + 同进程 iframe),它们共享一个 PageScheduler。PageBroadcast 的语义就是"发给这个页面的所有 frame",正好对应。
RenderViewHostImpl 的实现只有三行:
void RenderViewHostImpl::SetSchedulerThrottling(bool allowed) {
if (auto& broadcast = GetAssociatedPageBroadcast())
broadcast->SetSchedulerThrottling(allowed);
}
GetAssociatedPageBroadcast() 可能返回空(页面还没建好),所以有 if。这也是为什么 SetBackgroundThrottling 必须在 HandleNewRenderFrame 里再调一次(13.8.5):WebContents 创建时页面可能还不存在,那次调用是空转。
渲染进程侧的实现在 WebViewImpl:
void WebViewImpl::SetSchedulerThrottling(bool allowed) {
DCHECK(GetPage());
scheduler_throttling_allowed_ = allowed;
// Re-apply the visibility the browser last reported: forced to kVisible
// while throttling is disallowed, back to the real state once it is allowed
// again. Without this, toggling the setting on a page that is already
// hidden only took effect at the next visibility change.
SetVisibilityState(browser_visibility_state_, /*is_initial_state=*/false);
}
注释里那句 "Without this, toggling the setting on a page that is already hidden only took effect at the next visibility change" 点出了一个真实的 bug:如果你在一个已经隐藏的窗口上把 backgroundThrottling 从 true 改成 false,什么都不发生——因为 SetVisibilityState 只在可见性变化时被调,而可见性没变。修法是记住浏览器最后一次报告的可见性(browser_visibility_state_),在切换开关时用它重新跑一次。
于是有了第 4 层的核心:
allow_disabling_blink_scheduler_throttling_per_renderview.patch:158-164
void WebViewImpl::SetVisibilityState(
mojom::blink::PageVisibilityState visibility_state,
bool is_initial_state) {
DCHECK(GetPage());
// If backgroundThrottling is disabled, the page (and everything observing
// its visibility, e.g. media) is told it is visible.
if (!scheduler_throttling_allowed_)
visibility_state = mojom::blink::PageVisibilityState::kVisible;
GetPage()->SetVisibilityState(visibility_state, is_initial_state);
这一行 visibility_state = kVisible 是整章最"暴力"的一行代码:它把"页面以为自己可见"当成了"页面真的可见"。副作用是一连串的:document.visibilityState 永远是 'visible',visibilitychange 永不触发,document.hidden 永远是 false,media 永远认为自己在可见页面上播放(于是不做"后台降低码率"的优化)。
这就是 backgroundThrottling: false 的真实语义:它不是"关掉节流",而是"骗页面说它一直可见"。 所有依赖可见性的 Chromium 优化都会失效,包括你其实想要的(如 video 在后台的自适应码率)。
还有一个更隐蔽的副作用在 SetPageLifecycleStateInternal 里:
// If backgroundThrottling is disabled, the page is always visible. Remember
// what the browser asked for so it can be re-applied if throttling is
// allowed again while the page is still in that state.
browser_visibility_state_ = new_state->visibility;
if (!scheduler_throttling_allowed_)
new_state->visibility = mojom::blink::PageVisibilityState::kVisible;
browser_visibility_state_ 保存真实值,new_state->visibility 被改写成假值。这个"记真值、传真值"的模式是整个补丁的关键——没有它,SetSchedulerThrottling(true) 之后页面就没法回到正确的可见性状态,因为真值已经被覆盖了。
顺序上有个容易担心但实际不成立的问题:browser_visibility_state_ 在 SetPageLifecycleStateInternal 里无条件写、kVisible 无条件覆盖,所以 SetSchedulerThrottling 与 SetPageLifecycleState 谁先谁后都对;只有从 false 切回 true 时才依赖它是最新值,而那时它一定最新。
13.8.3 第三层:ui::Compositor::SetBackgroundThrottling
fix_disabling_background_throttling_in_compositor.patch 只改了 ui/compositor,但改动的影响面比看起来大:
void Compositor::SetVisible(bool visible) {
if (display_private_)
- display_private_->SetDisplayVisible(visible);
+ // Invisible display is throttling itself.
+ display_private_->SetDisplayVisible(
+ background_throttling_ ? visible : true);
display_private_ 是 viz::mojom::DisplayPrivate,浏览器进程用它告诉 GPU 进程"这个 display 可见吗"。改成 true 意味着始终告诉 GPU 进程"我可见",于是 viz::DisplayScheduler 不会进入"drop frame draws and swaps"的状态。
新增的方法:
void Compositor::SetBackgroundThrottling(bool background_throttling_enabled) {
background_throttling_ = background_throttling_enabled;
if (display_private_) {
// Invisible display is throttling itself.
display_private_->SetDisplayVisible(
background_throttling_ ? host_->IsVisible() : true);
}
}
注意 host_->IsVisible() 而不是直接 true:当 background_throttling_ 为真(默认)时,行为和原来一致(跟随 host 的可见性);为假时才强制 true。这是一个**"不改变默认路径"的补丁**——所有没碰 backgroundThrottling 的应用完全不受影响。
SetLayerTreeFrameSink 里也加了一处同样的逻辑(:367-372):当 display_private_ 重新绑定(比如 GPU 进程崩溃后重启)时,立刻按当前设置推一次可见性。如果不加这一行,GPU 进程重启之后 display 会以默认的 host_->IsVisible() 初始化,于是节流"自己回来了"——用户体验是"GPU 崩过一次之后,后台节流就不受 backgroundThrottling: false 控制了"。
13.8.4 第四层在前面已经讲过,但它还有个调用点
WebContents::SetBackgroundThrottling(electron_api_web_contents.cc:3139-3175)是四层的"总开关",它的实现值得完整看:
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) owner_window_->UpdateBackgroundThrottlingState();
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh) return;
auto* rwhv = rfh->GetView();
if (!rwhv) return;
if (!static_cast<content::RenderWidgetHostImpl*>(
rwhv->GetRenderWidgetHost())) return;
// HandleNewRenderFrame() applied the setting to every frame, so every local
// root (cross-process iframe) has its own widget and RenderView carrying it;
// update them all, but leave inner WebContents (guests) to their own setting.
rfh->ForEachRenderFrameHostWithAction(
[this, allowed](content::RenderFrameHost* frame) {
if (content::WebContents::FromRenderFrameHost(frame) != web_contents())
return content::RenderFrameHost::FrameIterationAction::kSkipChildren;
if (auto* view = frame->GetView())
if (auto* rwh = static_cast<content::RenderWidgetHostImpl*>(
view->GetRenderWidgetHost()))
rwh->disable_hidden_ = !allowed;
frame->GetRenderViewHost()->SetSchedulerThrottling(allowed);
return content::RenderFrameHost::FrameIterationAction::kContinue;
});
四个要点:
其一,owner_window_ 先更新。 第三层(ui::Compositor)是通过窗口走的(13.8.5),所以先通知窗口。这一句在 rfh 为空时也会执行——顺序是对的,因为窗口层的更新不依赖 frame。
其二,ForEachRenderFrameHostWithAction 遍历所有 frame,但遇到"别的 WebContents 的 frame"就 kSkipChildren。 那个判断是给 <webview> 用的:一个 <webview> 的 guest WebContents 有自己的一套节流设置,embedder 遍历时不能越过边界去改它。kSkipChildren 而不是 kContinue,是因为 guest 的子树也属于 guest。
其三,disable_hidden_ 在每个 frame 上设,SetSchedulerThrottling 也是每个 frame 调一次。 注释解释了为什么不能用一次调用搞定:"每一个 local root(跨进程 iframe)都有自己的 widget 和 RenderView"。跨进程 iframe(OOPIF)有独立的 RenderWidgetHost,所以 disable_hidden_ 得逐个设。
其四,早退的位置。 三个 if (!xxx) return; 都在 background_throttling_ = allowed 之后,所以即使 frame 还没建好(rfh 空),background_throttling_ 也已经被记住,owner_window_ 也已经更新。等 frame 建好之后,HandleNewRenderFrame 会用这个记住的值补上第一、二层(electron_api_web_contents.cc:2303-2309)。
13.8.5 BackgroundThrottlingSource:多源聚合
一个窗口里可能有多个 WebContents:主网页、BrowserView、<webview> 的 guest、DevTools 前端。每一个都有自己的 backgroundThrottling 设置。窗口只有一个合成器,所以必须把这多个布尔聚合成一个。
聚合的实现是一个接口加一个集合:
background_throttling_source.h:10-16
class BackgroundThrottlingSource {
public:
virtual ~BackgroundThrottlingSource() = default;
virtual bool GetBackgroundThrottling() const = 0;
};
native_window.cc:796-829
void NativeWindow::AddBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.insert(source);
DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::RemoveBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.erase(source);
DCHECK(result == 1)
<< "Tried to remove non existing BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!widget() || !widget()->GetCompositor()) {
return;
}
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
widget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
聚合规则是"全部为真才节流",也就是逻辑与。语义上正确:只要有一个 WebContents 说"我需要在后台继续跑",窗口的合成器就不能停。
三个细节:
其一,std::set 而不是 vector。 background_throttling_sources_ 是集合,insert 返回 pair<iterator, bool>,erase 返回删除个数。两个 DCHECK 都依赖这个返回值——重复添加和重复移除都会被检查出来。 对比 draggable_region_providers_ 用的是 std::list 且移除时不检查(13.3.6),两处的严谨程度不同。
其二,每次增删都重算全量。 没有增量更新,没有缓存。N 个 WebContents 时每次增删 O(N),N 通常是 1–5,可以忽略。但 GetBackgroundThrottling() 是虚函数调用,如果某个实现里做了重活,这里会被放大。
其三,if (!widget() || !widget()->GetCompositor()) return;。 窗口还没建到合成器阶段时直接返回——此时的状态不会被记住。所以如果 AddBackgroundThrottlingSource 在 widget()->Init() 之前被调用(BrowserWindow 构造函数里确实可能),那一次 SetBackgroundThrottling 是空转,要等下一次增删或者窗口初始化才生效。这是一个"丢事件"的窗口期,实际上被 HandleNewRenderFrame 里的重复应用救了回来(13.8.1)。
WebContents 作为 source 的实现就是返回成员:
electron_api_web_contents.cc:3135-3136
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
一行。而这个成员在构造时从 webPreferences 读(electron_api_web_contents.cc:1033:options.Get("backgroundThrottling", &background_throttling_))。
一个值得注意的不对称:SetOwnerWindow 在 owner_window 为空时会 RemoveBackgroundThrottlingSource,但不会在窗口侧重算——不,它会(RemoveBackgroundThrottlingSource 里调了 UpdateBackgroundThrottlingState)。这个是对的。真正的不对称在 13.3.4 讲的那处:视图被摘但 WebContents 还活着时,source 不会被移除。
13.9 首屏:从导航提交到第一帧
13.9.1 ready-to-show 的真实触发点
ready-to-show 是 Electron 文档里"最先被用到、最少被理解"的事件。它的实现只有一个函数:
electron_api_web_contents.cc:2672-2696
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
v8::Isolate* const isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
// One callback scope around both emits: the window's listeners run before
// microtasks queued by the WebContents', as when it was a nextTick.
node::CallbackScope callback_scope{isolate, wrapper,
node::async_context{0, 0}};
// The owner as it is before any listener runs, as the first listener saw.
v8::Local<v8::Value> owner =
owner_window() ? BrowserWindow::From(isolate, owner_window())
: v8::Local<v8::Value>(v8::Null(isolate));
const bool notify_owner =
owner->IsObject() &&
!gin_helper::Destroyable::IsDestroyed(owner.As<v8::Object>());
Emit("ready-to-show");
// Then the window showing it, as BrowserWindow documents.
if (notify_owner)
gin_helper::EmitEvent(isolate, owner.As<v8::Object>(), "ready-to-show");
}
}
它的名字是 OnFirstNonEmptyLayout,不是 OnFirstPaint。 触发者是渲染进程的 ElectronRenderFrameObserver::DidMeaningfulLayout(electron_render_frame_observer.cc:194-203),后者转发 Blink 的 WebFrameClient::DidMeaningfulLayout——语义是"第一次完成了有意义的布局"(有非空内容、尺寸稳定),不是"第一帧已经出现在屏幕上"。
这个差别是 ready-to-show 所有问题的根源:
- 在
ready-to-show里show()窗口,用户看到的可能仍然是一帧空白——因为布局完成时,光栅化和合成还没开始,show()之后的那一帧可能仍然是白的。 - 在
ready-to-show里show()之后立刻capturePage(),可能拿到空白图——因为 surface 还没分配。
为什么不用真正的"第一帧"? 因为"上屏"发生在 GPU 进程的 Display::DrawAndSwap 之后,那个事件没有回传到浏览器进程的公开接口。Electron 只能选一个略早但可靠的信号,文档里 "when the web page has been rendered" 这个措辞掩盖了它的不精确。
13.9.2 双发的顺序与 CallbackScope
那段代码里有三处与"顺序"有关的细节:
其一,双发的顺序是"先 WebContents 后 BrowserWindow"。 Emit("ready-to-show") 发在 this(WebContents)上,然后 gin_helper::EmitEvent(isolate, owner, "ready-to-show") 发在窗口上。注释说 "as BrowserWindow documents"——文档里确实说了这个顺序。
其二,owner 在发第一个事件之前就取好了。
electron_api_web_contents.cc:2685-2687
// The owner as it is before any listener runs, as the first listener saw.
v8::Local<v8::Value> owner =
owner_window() ? BrowserWindow::From(isolate, owner_window())
: v8::Local<v8::Value>(v8::Null(isolate));
如果 WebContents 的 ready-to-show 监听器里调了 win.destroy(),那么 owner_window_ 会变成空(~WebContents 里清的),第二个事件就没法发了。先取后发保证"只要窗口在事件开始时还活着,第二个事件就会发给它"——即使第一个监听器把它销毁了。 这是"事件双发"的通用模式:快照参数,再分发。
notify_owner 的判断里还有 !Destroyable::IsDestroyed(owner)——一个"已被标记销毁但对象还在"的窗口不该再收事件。
其三,一个 node::CallbackScope 包住两次 emit。
node::CallbackScope callback_scope{isolate, wrapper, node::async_context{0, 0}};
CallbackScope 的作用是给 process.nextTick 和 queueMicrotask 一个"当前属于谁"的上下文。包住两次 emit 意味着:第一个监听器里排的微任务,会在第二个监听器之后执行,而不是在第一个监听器返回时立刻执行。 注释说 "as when it was a nextTick",指的是这个行为与早期版本用 process.nextTick 实现时一致。这是一个兼容性约束:如果有人依赖"ready-to-show 里 nextTick 排在 BrowserWindow 的监听器之后",那么改成两个独立的 CallbackScope 就会破坏它。
13.9.3 首屏的完整时序
把这一章的内容按时间排一遍,就是一次"从 loadURL 到用户看到内容"的完整路径:
t0 loadURL()
→ 导航开始,浏览器进程发 RequestNavigation
t1 ReadyToCommitNavigation
→ 推送 RendererStartupData(第 12 章)
→ 传递 RenderFrameHost 的初始 VisualProperties(含 size)
t2 CommitNavigation
→ 渲染进程创建 Document、开始解析 HTML
t3 解析 CSS → 首次布局 → DidMeaningfulLayout
→ OnFirstNonEmptyLayout
→ Emit('ready-to-show') ← 此刻布局完成,尚无像素
t4 首次绘制(paint)→ 层树构建 → 光栅化 tile
t5 CompositorFrame 提交 → GPU 进程
t6 Display 聚合 → 上屏
→ 第一帧真的可见
t3 到 t6 之间的时间差就是"闪白"的时长。 在一台普通机器上是 16–50ms(一到三帧),在低端设备上可能 200ms 以上(GPU 进程要初始化、纹理要分配)。
ready-to-show 在 t3,所以它之后的 show() 至少有一帧的空窗。这就是为什么"ready-to-show + show()"仍然是 Electron 里最常见的闪白来源——它不是实现错误,是 API 语义本身的精度限制。
更精确的做法有两个:
paintWhenInitiallyHidden: false+ready-to-show+ 延迟一帧show():用setTimeout(win.show, 0)或requestAnimationFrame等一帧,让t4–t5走完。仍然不保证。win.show()之后用webContents.once('paint'):Electron 有paint事件(OSR 用),但非 OSR 窗口上它不触发。所以对普通窗口没有"第一帧上屏"的可靠信号。
13.10 OSR:第四条路径
离屏渲染(Off-screen Rendering)是把"上屏"这一步整个拿掉,只保留"产生帧"。它替换的不是合成器,而是两个工厂:
// shell/browser/osr/osr_web_contents_view.cc(CreateViewForWidget 附近)
content::RenderWidgetHostViewBase*
OffScreenWebContentsView::CreateViewForWidget(...)
和 RenderWidgetHostView::CreateHostDisplayClient(osr_render_widget_host_view.cc:616)。前者让 Chromium 用 OffScreenRenderWidgetHostView 而不是平台默认的 RWHV,后者让 GPU 进程把合成结果交给 Electron 的 OffScreenHostDisplayClient 而不是系统窗口。
这两个替换点穷举了"像素最终去哪"的唯一两个出口,所以 OSR 能完全接管。但这也意味着 OSR 必须自己重建被替换掉的那一整套基础设施——这就是 osr_render_widget_host_view.cc:180-187 有 1043 行的原因。
13.10.1 自己造一个 ui::Compositor
OSR 的构造函数做了正常路径下 Chromium 替你做的一切:
osr_render_widget_host_view.cc:180-187
// shell/browser/osr/osr_render_widget_host_view.cc:187-215(节选)
delegated_frame_host_client_{
std::make_unique<ElectronDelegatedFrameHostClient>(this)},
delegated_frame_host_{std::make_unique<content::DelegatedFrameHost>(
AllocateFrameSinkId(),
delegated_frame_host_client_.get(),
true /* should_register_frame_sink_id */)},
cursor_manager_(std::make_unique<input::CursorManager>(this)),
mouse_wheel_phase_handler_(this),
backing_(std::make_unique<SkBitmap>()) {
DCHECK(render_widget_host_);
DCHECK(!render_widget_host_->GetView());
delegated_frame_host_allocator_.GenerateId();
delegated_frame_host_surface_id_ =
delegated_frame_host_allocator_.GetCurrentLocalSurfaceId();
compositor_allocator_.GenerateId();
compositor_surface_id_ = compositor_allocator_.GetCurrentLocalSurfaceId();
root_layer_ = std::make_unique<ui::LayerSurface>();
root_layer()->SetFallbackBackgroundColor(
SkColor4f::FromColor(background_color_));
ui::ContextFactory* context_factory = content::GetContextFactory();
compositor_ = std::make_unique<ui::Compositor>(
context_factory->AllocateFrameSinkId(), context_factory,
base::SingleThreadTaskRunner::GetCurrentDefault(),
false /* enable_pixel_canvas */,
false /* use_external_begin_frame_control */);
compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget);
compositor_->SetDelegate(this);
compositor_->SetRootLayer(root_layer_.get());
ResizeRootLayer(false);
render_widget_host_->SetView(this);
五个关键点:
其一,ui::Compositor 的第一个参数是 AllocateFrameSinkId()。 正常路径下,ui::Compositor 的 frame sink id 由 aura::Window 或 NativeWidgetMac 分配——它属于"窗口的合成器"。OSR 没有窗口,所以自己分配一个 ID。 这个 ID 和网页自己的 FrameSinkId 是两个不同的 ID:前者是"Electron 这一侧的合成器",后者是"渲染进程的 surface"。
其二,SetAcceleratedWidget(gfx::kNullAcceleratedWidget)。 这是"我没有原生窗口"的显式声明。GPU 进程据此知道不该尝试绑定到 HWND/XID。
其三,root_layer_ 是一个 ui::LayerSurface。 ui::Layer 的派生类,专门用作合成器的根层。它存在的唯一目的是"给 DelegatedFrameHost 一个可以嵌入的父层"——DelegatedFrameHost 会创建自己的 SurfaceLayer 并 Add 到根层上。
其四,两个 LocalSurfaceIdAllocator。 delegated_frame_host_allocator_ 管网页 surface 的 ID(它从渲染进程的 RenderFrameMetadata.local_surface_id 同步,见 :230-240),compositor_allocator_ 管 Electron 自己那个 ui::Compositor 的 surface ID。两个分配器不能混用,因为它们描述的是两个不同层级的 surface,混用会导致 SurfaceId 冲突——GPU 进程会认为是同一个 surface 被两个地方更新,触发 CHECK。
其五,render_widget_host_->SetView(this) 放在最后。 因为 SetView 会让 RenderWidgetHost 开始往这个视图上推 VisualProperties、CompositorFrame 等——先得把 compositor_ 和 delegated_frame_host_ 都建好。
13.10.2 软件路径:LayeredWindowUpdater
软件路径的链路是"GPU 进程光栅化到共享内存 → 共享内存映射成 SkBitmap → 回调给 JS"。
GPU 进程那一侧,HostDisplayClient 被要求创建一个 LayeredWindowUpdater:
-#if BUILDFLAG(IS_WIN)
void HostDisplayClient::CreateLayeredWindowUpdater(
mojo::PendingReceiver<mojom::LayeredWindowUpdater> receiver) {
+#if BUILDFLAG(IS_WIN)
if (!NeedsToUseLayerWindow(widget_)) {
DLOG(ERROR) << "HWND shouldn't be using a layered window";
return;
}
layered_window_updater_ =
std::make_unique<LayeredWindowUpdaterImpl>(widget_, std::move(receiver));
+#else
+ // Outside Windows only Electron's offscreen display client provides a
+ // LayeredWindowUpdater; drop the request for any other window.
+ DLOG(ERROR) << "CreateLayeredWindowUpdater called for a non-OSR window";
+#endif
}
这个补丁把 CreateLayeredWindowUpdater 从 IS_WIN 里提出来,成为所有平台都有的虚函数——因为 "分层窗口"这个概念在 Linux/macOS 上不存在,只有 OSR 需要这个机制。注释里 "Outside Windows only Electron's offscreen display client provides a LayeredWindowUpdater" 就是在说这件事。
Electron 侧的实现:
osr_host_display_client.cc:34-41
// shell/browser/osr/osr_host_display_client.cc:33-84(节选)
void LayeredWindowUpdater::OnAllocatedSharedMemory(
const gfx::Size& pixel_size,
base::UnsafeSharedMemoryRegion region) {
canvas_.reset();
if (!region.IsValid()) return;
std::optional<size_t> expected_bytes = SharedMemorySizeForSharedImageFormat(
viz::SinglePlaneFormat::kRGBA_8888, pixel_size);
if (!expected_bytes || region.GetSize() < *expected_bytes) {
DLOG(ERROR) << "Shared memory region too small for pixel_size "
<< pixel_size.ToString();
return;
}
#if defined(WIN32)
canvas_ = skia::CreatePlatformCanvasWithSharedSection(...);
#else
shm_mapping_ = region.Map();
if (!shm_mapping_.IsValid() || shm_mapping_.size() < *expected_bytes) { ... }
canvas_ = skia::CreatePlatformCanvasWithPixels(...);
#endif
}
那段安全校验值得单独说:共享内存是跨进程的,pixel_size 和 region 来自 GPU 进程,理论上不可信。 如果 pixel_size 是 10000×10000(400 MB)而 region 只有 1 MB,SkCanvas 会按 pixel_size 的 stride 去写——越界写进共享内存映射之外,段错误或者更糟。所以先算"这个尺寸需要多少字节",再和 region.GetSize() 比。这是 Electron 里少见的显式防御跨进程输入的地方,值得当作范式记住。
Draw 是实际出帧的地方:
osr_host_display_client.cc:72-79
void LayeredWindowUpdater::Draw(const gfx::Rect& damage_rect,
DrawCallback draw_callback) {
SkPixmap pixmap;
SkBitmap bitmap;
if (active_ && canvas_ && canvas_->peekPixels(&pixmap)) {
bitmap.installPixels(pixmap);
callback_.Run(damage_rect, bitmap, {});
}
std::move(draw_callback).Run();
}
active_ 是 OSR 版的"可见性"——SetActive(false) 之后 Draw 不再回调,但仍然会 std::move(draw_callback).Run()。这个必须有:draw_callback 是 GPU 进程那边等着的"画完了"通知,不调它 GPU 进程就永远不放这个 buffer,几帧之后共享内存池耗尽,整个 GPU 侧的合成停摆。这是一个"可以不出帧,但必须回 ack"的契约。
bitmap.installPixels(pixmap) 是零拷贝——把 SkBitmap 的像素指针指向共享内存。但调用方拿到这个 SkBitmap 之后通常要把它变成 JS 可用的 NativeImage,那一步要拷贝(因为 JS 侧的生命周期不受控)。
13.10.3 共享纹理路径:FrameSinkVideoCapturer
共享纹理路径完全不走 LayeredWindowUpdater,它走的是 viz 的视频捕获设施:
osr_video_consumer.h:37-38
std::unique_ptr<viz::ClientFrameSinkVideoCapturer> video_capturer_;
osr_render_widget_host_view.cc:221-226
if (content::GpuDataManager::GetInstance()->HardwareAccelerationEnabled()) {
video_consumer_ = std::make_unique<OffScreenVideoConsumer>(
this, base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint,
weak_ptr_factory_.GetWeakPtr()));
video_consumer_->SetActive(is_painting());
video_consumer_->SetFrameRate(this->frame_rate());
}
为什么复用视频捕获而不是自己搞一条纹理通路? 因为"把一个 surface 的像素以某种可共享的形式取出来"这件事,FrameSinkVideoCapturer 已经做得非常完整了:它处理 GpuMemoryBuffer 的分配与复用、跨进程句柄传递(D3D11 NT handle / IOSurface / dmabuf fd)、帧的引用计数(通过 FrameSinkVideoConsumerFrameCallbacks 的 Release)、以及格式协商。自己实现这些是几千行的活,而且极易出错。
代价是:捕获路径的语义是"视频帧",不是"显示帧"。 它有自己的节奏(SetFrameRate)、自己的丢帧策略(min_frame_rate / max_frame_rate / 内容变化检测)、自己的元数据(content_rect、capture_update_rect)。所以 OSR 的共享纹理路径和软件路径在时序上不等价:软件路径的 Draw 是"每次 Display::DrawAndSwap 后调一次",共享纹理路径是"捕获器认为需要新帧时才调"。
OnFrameCaptured 收到的数据结构(osr_paint_event.h:55-105)里有一个关键字段:
// Releaser holder
raw_ptr<OffscreenReleaserHolder> releaser_holder;
配套的结构:
osr_paint_event.h:39-42
struct OffscreenReleaserHolder {
gfx::GpuMemoryBufferHandle gmb_handle;
// Releaser, hold this to prevent FrameSinkVideoCapturer recycle frame
mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
releaser;
};
这是引用计数的显式暴露。 捕获器分配的 GpuMemoryBuffer 是有限的池子(通常 2–3 个)。如果调用方拿到纹理之后一直不释放,池子耗尽,捕获就停了。所以 Electron 把 releaser(一个 Mojo remote)交给调用方,调用方必须在用完纹理之后调它的 Release()。不调的结果是"OSR 共享纹理跑着跑着突然不更新了"——一个非常常见的报告。
这也是共享纹理路径比软件路径难用的根本原因:软件路径的 SkBitmap 是拷贝出来的,调用方随便用;共享纹理路径的句柄是借的,有生命周期。
13.10.4 HoldResize:OSR 独有的重入保护
CompositeFrame(:671-712)里有一对调用:
void OffScreenRenderWidgetHostView::CompositeFrame(const gfx::Rect& damage_rect) {
HoldResize();
/* ...拼帧(可能把 popup 和 proxy view 的内容画进去)... */
callback_.Run(gfx::IntersectRects(gfx::Rect(size_in_pixels), damage_rect),
frame, {});
ReleaseResize();
}
HoldResize / ReleaseResize(:725-743):
void OffScreenRenderWidgetHostView::HoldResize() {
if (!hold_resize_)
hold_resize_ = true;
}
void OffScreenRenderWidgetHostView::ReleaseResize() {
if (!hold_resize_)
return;
hold_resize_ = false;
if (pending_resize_) {
pending_resize_ = false;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&OffScreenRenderWidgetHostView::SynchronizeVisualProperties,
weak_factory_.GetWeakPtr()));
}
}
为什么需要? 因为 callback_.Run(...) 是跑到用户代码里的——JS 的 paint 监听器。用户代码完全可能在 paint 里调 win.setSize(...),那会触发 SynchronizeVisualProperties → ResizeRootLayer → 重设 root_layer_ 的 bounds 和 LocalSurfaceId。而这个时刻 CompositeFrame 正在用 GetViewBounds() 算出来的 size_in_pixels 拼帧——合成器状态在拼帧过程中被改了。
HoldResize 的作用是把这个 resize 推迟:SynchronizeVisualProperties 检查 hold_resize_,为真就只置 pending_resize_ 然后返回;ReleaseResize 之后用 PostTask 补跑一次。用 PostTask 而不是直接调,是为了不在 ReleaseResize 的调用栈里做 resize——那样会紧跟着 CompositeFrame 的 SkCanvas 析构跑,时序仍然不可控。
这个模式在 Chromium 里叫 "re-entrancy guard",Electron 里只在这一处出现。它是"把控制权交给用户代码之前必须先冻结自己的状态"这条原则的实现,代价是多一个 bool 和一个延迟任务。
13.10.5 两条 OSR 路径的时序不等价
软件路径的 Draw 是"每次 Display::DrawAndSwap 后调一次",共享纹理路径是"捕获器认为需要新帧时才调"——后者有自己的丢帧策略与内容变化检测。所以在两条路径之间切换会改变帧的节奏,而不只是画质。 另外 OSR 的帧率来自定时器而非显示器 vsync:frameRate: 60 遇到 75Hz 屏幕时帧与扫描线不同步,调用方若要上屏必须自己做一次对齐。
13.11 失败模式手册
按"症状 → 根因 → 层"排。这张表的价值在于每一行的症状都长得不像它的原因。
| 症状 | 根因 | 层 |
|---|---|---|
| 圆角四角是黑的 | 隐式层化时没设 SetFillsBoundsOpaquely(false) | ui::Layer |
| 圆角在分数 DPI 下有锯齿 | SetIsFastRoundedCorner(true) 时每 tile 独立裁剪 | ui::Layer |
| 圆角在动画期间错位 | setBounds 动画动的是 layer,OnViewBoundsChanged 不触发 | api::View |
| 20×20 的视图设了圆角但是直角 | RoundedRectCutoutPathBuilder 需要 ≥32×32,否则清空 path | api::View |
| 网页溢出圆角 | 只调了 SetClipPath,没调 SetNativeViewCornerRadii | 桥 1 |
用户加在 contentView 里的东西看不见 | WebContentsView 被加到了 index 0 之后(或 z 序反了) | 视图树 |
| macOS 上点网页没反应 | content_view_ 吃掉了事件,缺 ContentViewTargeterDelegate | 第三棵树 |
macOS 上 UpdateCursor 崩溃 | TargetForRect 返回了 nullptr(#51576) | 第三棵树 |
| 窗口最小化时页面在后台跑满 CPU | 只关了第 4 层,没关第 3 层(display 不可见但页面在产帧) | 节流 |
backgroundThrottling: false 后媒体不走后台码率 | 第 4 层强制 visibilityState === 'visible' | 节流 |
一个后台 BrowserView 冻住了整个窗口 | SetOwnerWindow 的 source 没被移除(13.3.4) | 节流 |
ready-to-show 之后仍然闪白一帧 | 该事件在布局完成时触发,早于第一帧上屏 | 时序 |
| OSR 共享纹理跑一会儿就不更新 | 没释放 OffscreenReleaserHolder::releaser | OSR |
OSR 在 paint 里 setSize 之后画面错乱 | HoldResize 没覆盖到(或从别的路径进的 resize) | OSR |
setLayout({calculateProposedLayout}) 之后窗口全白 | JS 抛异常,返回 0×0 的 ProposedLayout,异常被吞 | api::View |
| 全屏视频上拖动把窗口拖走了 | NativeWindow::NonClientHitTest 的 IsFullscreen() 早退被绕过 | 第三棵树 |
三行值得单独展开。
"圆角四角是黑的":这个 bug 的机制是——ui::Layer 默认 FillsBoundsOpaquely(true),合成器据此认为"这个层的内容覆盖了它的整个 bounds",于是跳过层后面的内容。圆角外的四个角实际上没有被层的内容覆盖,但因为"不透明"的声明,父层的内容也不会画在那里——结果是窗口背景色(通常是黑)透出来。修法就是那一行 SetFillsBoundsOpaquely(false),但它的代价是合成器不再能跳过层的下方,多一次绘制。
"20×20 的视图设了圆角但是直角":ApplyBorderRadius 里 size.width() >= 32 && size.height() >= 32 是硬条件。小于它就走 else 清空 path。这里没有日志、没有警告、没有部分生效——完全静默。 而且它是动态的:视图从 40×40 缩到 20×20 时圆角消失,缩回去又出现。
"setLayout({calculateProposedLayout}) 之后窗口全白":JS 抛出异常时,LayoutCallback 的 gin 转换返回一个默认构造的 views::ProposedLayout(host_size 是 0×0)。views 按这个布局,所有子视图被设成 0×0,屏幕上什么都不画。异常本身被 gin 的 callback 适配层捕获并打到 console,但它在 CalculateProposedLayout 那个 const 方法里抛出,栈上已经跨了三层 views 的布局代码——控制流回到 views 时它不知道出过异常。
13.12 性能账本
本章涉及的每一项都有明确的量化代价。数字来自代码里的常量、注释和可推算的结构,不是实测值。
启动与首屏
| 项 | 量级 | 依据 |
|---|---|---|
NativeWindowViews 构造(含 Widget::Init) | 20–60 ms | 平台窗口 + 原生 view 树 |
空 RootView 的布局 pass | < 1 ms | 两层 BoxLayout |
ready-to-show → 第一帧上屏 | 16–50 ms | 1–3 帧 |
paintWhenInitiallyHidden: false 后首次 show() | +50–150 ms | surface 从头分配 |
布局与绘制
| 项 | 量级 | 依据 |
|---|---|---|
setBounds 动画(改尺寸) | 一次额外 render surface | clip rect + bounds 双动画 |
SetPaintToLayer | 一次离屏渲染 + 一次纹理上传 | 隐式层化 |
SetIsFastRoundedCorner(false) | 一次额外 render surface | 全局 mask 而非逐 tile |
JS calculateProposedLayout | 0.1–1 ms/次 | 跨语言 + JS 执行 + 结构转换 |
合成
| 项 | 量级 | 依据 |
|---|---|---|
| 1080p 一帧的软件 OSR 拷贝 | 8 MB | 1920×1080×4 |
| 60fps 软件 OSR 的内存带宽 | 480 MB/s | 8 MB × 60 |
disable_hidden_ 打开的代价 | 隐藏时仍然 60fps 绘制 | 纯 CPU/GPU 消耗 |
| macOS 关闭合成器回收 | 隐藏窗口保留 IOSurface | 内存换"不闪白" |
三条最值得记住的
其一,SetPaintToLayer 的代价不是线性的。 一个层化的小视图(比如 100×100 的图标)很便宜;但一个层化的大视图(1920×1080 的视频容器)意味着多一整块全屏纹理 + 一次全屏合成。这就是为什么"给网页容器加圆角"要用 SetNativeViewCornerRadii(在合成器里裁,不需要新纹理)而不是 SetPaintToLayer + mask(需要)。
其二,backgroundThrottling: false 的价格是"隐藏时仍然跑满帧"。 一个隐藏窗口 60fps 跑 rAF,加上合成,在笔记本上大约是 5–15% 的单核占用 + 持续 GPU 活动。这意味着电池续航会明显变差。这个选项的正当用途很窄:<webview> 里跑视频会议、后台需要保持动画状态的计算。用"为了保险"的态度打开它是错的。
其三,OSR 软件路径的 480 MB/s 是下限,不是上限。 那个数字只算了一次拷贝(共享内存 → SkBitmap)。实际链路里还有:GPU 进程光栅化到共享内存(一次写)、SkBitmap → NativeImage(一次拷贝,因为 JS 侧生命周期不受控)、NativeImage → 用户的 canvas/纹理(可能又一次)。4K 60fps 下这条链路的总带宽在 3–5 GB/s,是纯粹的浪费——这就是共享纹理路径存在的全部理由。
13.13 练习题
13.1(入门) 写一个 BaseWindow + 两个 WebContentsView,把它们上下分屏。然后用 addChildView(view, 0) 把下面的那个挪到最上面,观察 z 序变化。解释为什么 ReorderChildView 用的是 std::rotate 而不是 erase + insert(13.2.4)。
13.2(入门) 在一个 WebContentsView 上设 setBorderRadius(20),然后打开 DevTools 并停靠在左边。观察圆角是否还正确。如果错位,说明 NonClientHitTest 的坐标系问题和圆角问题是否同源(13.3.6、13.4.3)。
13.3(进阶) 复现"圆角四角是黑的":临时把 GetLayer() 里的 SetFillsBoundsOpaquely(false) 注释掉,设一个 setBackgroundBlur(10) + 深色背景,观察四角。然后解释为什么这个 bug 只在"层化 + 半透明 + 父层有内容"三个条件同时满足时出现(13.11)。
13.4(进阶) 在 macOS 上构造"窗口隐藏时创建、attach 后显示"的场景,确认 ready-to-show 会触发但窗口不响应鼠标。然后用 13.7.3 的两个补丁点解释:去掉任意一处,行为分别坏在哪里。
13.5(挑战) 给 api::View 加一个 setTransform(matrix):走 SetPaintToLayer() + layer->SetTransform()。然后测试三种情况——(a) 普通视图,(b) WebContentsView,(c) 有 NativeViewHost 子视图的容器。解释为什么 (b) 和 (c) 会失败,以及要让它工作必须改哪里(13.5.3)。
13.14 下线:三棵树之外还有第四棵树
这一章把"像素怎么上屏"讲完了,但有一个东西从头到尾没被讨论:输入。鼠标点击怎么从操作系统的窗口变成渲染进程里的 blink::WebMouseEvent,键盘事件怎么在 before-input-event 里被拦截,ImeComposition 怎么穿过三层视图树——这些是"反方向"的同一套结构,但机制完全不同(事件分发走的是 aura::Window 树和 NSView 树,不是 views::View 树,也不经过合成器)。
更重要的是,输入的正确性依赖这一章讲的所有坐标换算。ConvertPointFromWidget、ConvertRectToTarget、ConvertPointToTarget 这三个函数在本章出现了四次,每次都是为了把一个坐标系里的矩形翻译到另一个坐标系。输入路径上同样的翻译要做五六次,且方向相反。
所以第 14 章从 IPC 讲起,但真正的入口是这里留下的问题:一个鼠标事件从 NSWindow 到渲染进程,要穿过几次坐标系、几次进程边界、几次类型转换?
一句话预告第 14 章的立论:Electron 的 IPC 不是"两个进程之间传消息",是"两套完全不同的对象模型之间做序列化"——主进程那侧是 V8 + gin + C++ 三层的对象,渲染进程那侧是 V8 + Blink + 另一份 gin,中间还有 Mojo 的类型系统、结构化克隆的值语义,以及一层为 Electron 专门生成的路由表。一次 ipcRenderer.invoke 的往返,穿过了七个类型系统。
13.15 本章源码落点索引
下列位置全部来自本仓库源码树,按实现层归集;每个
路径:行号指向该文件中与本章论述对应的声明或实现行,可逐条复核。
- 浏览器进程 C++ 层:
osr_web_contents_view_mac.mm:9 inspectable_web_contents_view.h:18 inspectable_web_contents_view_delegate.cc:10 inspectable_web_contents_view_delegate.h:15 electron_api_web_contents_view.h:17 osr_web_contents_view.h:20 root_view_mac.h:13 inspectable_web_contents.h:28 -
inspectable_web_contents_delegate.h:12 electron_api_base_window_mac.mm:15 electron_api_web_contents.h:61 electron_api_web_contents_impl.cc:19 electron_api_web_contents_mac.mm:16 child_web_contents_tracker.cc:13 child_web_contents_tracker.h:16 electron_web_contents_utility_handler_impl.cc:23 -
electron_web_contents_utility_handler_impl.h:15 extended_web_contents_observer.h:13 native_window_mac.h:22 native_window_mac_remote.h:25 native_window_mac_remote.mm:46 native_window_observer.h:19 native_window_views.h:33 native_window_views_win.cc:49 -
root_view.h:16 web_contents_permission_helper.cc:35 web_contents_permission_helper.h:20 web_contents_preferences.cc:41 web_contents_preferences.h:22 web_contents_zoom_controller.cc:27 web_contents_zoom_controller.h:19 web_contents_zoom_observer.h:15 -
electron_extension_web_contents_observer.cc:10 electron_extension_web_contents_observer.h:14 file_system_access_web_contents_helper.cc:11 file_system_access_web_contents_helper.h:11 osr_host_display_client.h:16 osr_host_display_client_mac.mm:14 osr_render_widget_host_view.h:36 electron_native_widget_mac.h:15 -
electron_native_widget_mac.mm:14 devtools_context_menu.cc:32 - API 文档与类型:
web-contents-view.md:5 - JS 门面与运行时:
base-window.ts:4 web-contents.ts:20 - 其他相关位置:
api-web-contents-view.spec.ts:12 - shell 其余实现:
native_window_converter.h:14 web_contents_utility.mojom:8