《Electron 45.2.3 内核解剖》第 19 章 打印、PDF、离屏渲染与桌面捕获
19.0 四条取像素的路径
这一章把四个看起来互不相干的 API 放在一起讲,因为它们解决的是同一个问题:把浏览器合成器已经画好的东西,以某种形式交到 JS 手里。区别在于"交给谁""在什么时刻""以什么格式"。
| API | 取的是谁的画面 | 走的链路 | 交付格式 | 由谁发起 |
|---|---|---|---|---|
webContents.print() | 一个 RenderFrameHost 的打印布局 | PrintViewManagerElectron::PrintNow → 系统打印机 | 无(副作用) | 主进程 |
webContents.printToPDF() | 一个 RenderFrameHost 的打印布局 | PdfQueue → PdfPrintJob::StartJob → renderer 重排 | Buffer(PDF 字节) | 主进程 |
webContents.capturePage() | RenderWidgetHostView 的当前合成表面 | CopyFromSurface 一次性拷贝 | NativeImage | 主进程 |
offscreen 的 paint 事件 | RenderWidgetHostView 的每一帧合成表面 | FrameSinkVideoCapturer 持续捕获 | NativeImage 或共享纹理句柄 | 合成器持续推送 |
beginFrameSubscription() | 同上,但独立订阅 | 另一个 FrameSinkVideoCapturer | NativeImage 回调 | 合成器持续推送 |
desktopCapturer.getSources() | 操作系统的窗口/屏幕(不是 Chromium 的合成器) | webrtc DesktopCapturer + NativeDesktopMediaList | 源列表 + 缩略图 NativeImage | 操作系统 |
表里最后一行是个例外,也是最容易混淆的一行:desktopCapturer 只负责枚举和缩略图,它根本不给视频流。真正的视频流是 getUserMedia({video: {mandatory: {chromeMediaSource: 'desktop'}}}) 走的,两者通过 id 这个字符串对接。19.5 会把这条接缝完整拆开。
三条贯穿全章的判据,先钉在这里:
- 打印类 API 不截屏,而是让 renderer 重新排版一次。
print()和printToPDF()都会触发 Chromium 的打印布局(@page、分页、page-break-*、页眉页脚),拿到的是 Skia 绘制出的 PDF/打印作业,而不是屏幕上那 1920×1080 的像素。所以动画停在哪一帧、devicePixelRatio是多少、窗口有没有被遮住,对结果都没有影响。 capturePage()和 OSR 拿的是"合成表面",因此受可见性、遮挡、GPU 状态影响。capturePage()甚至专门提供了stayHidden/stayAwake两个选项来对抗窗口被隐藏后的合成暂停。- 离屏渲染不是"把窗口藏起来",是换掉整个视图实现。
OffScreenWebContentsView替代了content::WebContentsView,OffScreenRenderWidgetHostView替代了RenderWidgetHostView,连GetNativeView()都返回空或宿主窗口的句柄。窗口从来没有被创建又被隐藏,它从一开始就不存在。
理解这三条,就能解释本章里几乎所有"为什么这个设置不生效"的问题。剩下的是逐条把源码摊开。
19.1 webContents.print():一条走系统打印机的长参数通道
print() 是本章里唯一一个没有返回值的 API(回调可选),也是唯一一个把设置一路传到操作系统打印机驱动的 API。它的实现在 electron_api_web_contents.cc:4071,整个参数通道长约 200 行,中间跨了一次线程切换。
19.1.1 两个 API、两套单位、两张互不相同的纸张表
先把最容易踩的坑放在最前面。Electron 里有两个打印入口,pageSize 的单位和取值完全不同:
webContents.print() | webContents.printToPDF() | |
|---|---|---|
| 定义位置 | electron_api_web_contents.cc:554 MediaSizeFromPageSize | print_to_pdf.cc:93 ReadPageSize |
| 名字表 | kStockMediaSizes[](10 项) | kPaperFormats(11 项) |
| 单位 | 微米(215900 = Letter 宽) | 英寸(8.5 = Letter 宽) |
| 对象形式 | {width, height},单位微米 | {width, height},单位英寸 |
| 名字大小写 | 区分,stock.key == name 直接比 | 不区分,base::ToLowerASCII(name) |
| 表的键 | "Letter", "Legal", "Tabloid", "A0"… | "letter", "legal", "tabloid", "ledger", "a0"… |
这不是文档措辞的差异,是两份独立代码。print() 的 kStockMediaSizes 里 "Tabloid" 对应 NA_LEDGER,没有 "Ledger" 这一项;printToPDF() 的 kPaperFormats 里 tabloid 是 {11, 17}、ledger 是 {17, 11},是两个独立条目。于是 'Ledger' 在 print() 里既不匹配字符串、也不会被当成对象(它是字符串),最终 MediaSizeFromPageSize 返回默认值——静默地用系统默认纸型打印,不抛错。
反过来,把 printToPDF() 的 {width: 8.27, height: 11.7} 直接抄到 print() 里,会得到一张约 8 微米 × 12 微米的纸。MediaSizeFromPageSize 甚至专门留了一条注释(electron_api_web_contents.cc:583):
// Microns; Chromium needs at least one point (printing/units.h), i.e.
// more than 352 of them, or printing silently fails.
double height;
double width;
if (!height_value->NumberValue(context).To(&height) ||
!width_value->NumberValue(context).To(&width)) {
return std::nullopt;
}
height = std::ceil(height);
width = std::ceil(width);
"silently fails" 是关键词:小于 352 微米的尺寸不会报错,打印作业就是不出来。std::ceil 也不是无害的取整——它把 210000.1 变成 210001,因为 Chromium 的 DictValue 在这里要求整数范围内才写成 int,SetNumber 还专门复刻了老 JS 实现 "整数写 int、否则写 double、非有限值直接不写" 的行为:
electron_api_web_contents.cc:524-531
void SetNumber(base::DictValue& dict, std::string_view key, double value) {
if (!std::isfinite(value))
return;
if (base::IsValueInRangeForNumericType<int>(value) &&
value == static_cast<int>(value)) {
dict.Set(key, static_cast<int>(value));
} else {
dict.Set(key, value);
}
}
连 NaN 都按"这个键不存在"处理。这类代码的意图不是校验,是逐字节维持旧版 JS 层曾经产生过的 base::Value 形状——一旦形状变了,下游 print_settings_conversion.cc 的行为就会漂。本章后面会反复看到这种模式。
19.1.2 参数解析的顺序本身就是规范
Print() 开头(electron_api_web_contents.cc:4071-4107)做了三件按顺序发生的事:
void WebContents::Print(gin::Arguments* const args) {
v8::Isolate* const isolate = args->isolate();
auto options = gin_helper::Dictionary::CreateEmpty(isolate);
v8::Local<v8::Value> options_value;
if (args->GetNext(&options_value) && !options_value->IsUndefined() &&
(options_value->IsFunction() ||
!gin::ConvertFromV8(isolate, options_value, &options))) {
args->ThrowTypeError(
"webContents.print(): Invalid print settings specified.");
return;
}
// `const {pageSize, usePrinterDefaultPageSize} = options`: a throwing
// getter throws out of print() before anything happens.
v8::Local<v8::Value> page_size;
v8::Local<v8::Value> use_default;
if (!options.GetHandle()->Get(context, gin::StringToV8(isolate, "pageSize"))
.ToLocal(&page_size) ||
!options.GetHandle()->Get(context, gin::StringToV8(isolate, kUseDefaultPrinterPageSize))
.ToLocal(&use_default)) {
return;
}
...
}
三个细节:
- 第一个参数如果是函数,会直接抛 TypeError。这是在兼容旧签名
print(options, callback)被误写成print(callback)的情况——但代价是传任何函数都报错,包括一个本来想当this的东西。 - 注释明确写了它模拟的是 JS 解构
const {pageSize, usePrinterDefaultPageSize} = options。两个属性都被无条件读取,即使你只设置了其中一个。这意味着给options装一个会抛异常的usePrinterDefaultPageSizegetter,光是调用print()就会把异常扔出来,而且"before anything happens"——打印机还没有被碰过。 pageSize与usePrinterDefaultPageSize互斥,同时给会抛"usePrinterDefaultPageSize cannot be combined with pageSize"。这个检查发生在MediaSizeFromPageSize之前。
紧接着是那条很特殊的短路(electron_api_web_contents.cc:4113-4129):
base::DictValue settings;
if (!media_size && options.IsEmptyObject()) {
content::RenderFrameHost* rfh = GetRenderFrameHostToUse(web_contents());
if (!rfh)
return;
auto* print_view_manager = PrintViewManagerElectron::FromWebContents(
content::WebContents::FromRenderFrameHost(rfh));
if (!print_view_manager)
return;
print_view_manager->PrintNow(rfh, std::move(settings), std::move(callback));
return;
}
print() 无参数调用时,传入的是一个完全空的 settings 字典,而不是"填好默认值的字典"。所有默认值(彩色、纵向、1 份、默认边距……)都留给 Chromium 的 PrintViewManagerBase::PrintNow 去补。但只要你传了任何一个选项——哪怕只是 {silent: false}——就会走下面那条把所有默认值显式写进去的长路径。两条路径的默认值来源不同,这是"传了个无关选项后打印效果变了"这类问题的根源。
19.1.3 二十多个设置项,以及三个"不许用户开但必须设"的项
从 electron_api_web_contents.cc:4131 到 :4270,代码逐项把 JS 选项搬进 base::DictValue settings。把它整理成一张表,重点是键名的错配和静默补全:
| JS 选项 | 写入的 Chromium 键 | 缺省值 / 特殊处理 |
|---|---|---|
silent | kSilent(Electron 自定义键) | false |
printBackground | kSettingShouldPrintBackgrounds | 先找 printBackground,找不到再找 Chromium 原生键,false |
margins.marginType | kSettingMarginsType | kDefaultMargins;只有 kCustomMargins 时才写四个边距 |
margins.{top,bottom,left,right} | kSettingMarginsCustom 嵌套字典 | 各自缺省 0 |
color(布尔) | kSettingColor | true → kColor,false → kGray |
landscape | kSettingLandscape | false |
deviceName | kSettingDeviceName | 空串 → 后面异步查默认打印机 |
scaleFactor | kSettingScaleFactor | 100(百分比,与 printToPDF 的 scale 0–2 不同) |
pagesPerSheet | kSettingPagesPerSheet | 1 |
collate | kSettingCollate | true |
copies | kSettingCopies | 1 |
header / footer | kSettingHeaderFooterTitle / kSettingHeaderFooterURL | 见下 |
pageRanges | kSettingPageRange | 见下 |
duplexMode | kSettingDuplexMode | kUnknownDuplexMode |
pageSize / mediaSize | kSettingMediaSize | 见 19.1.4 |
dpi | kSettingDpiHorizontal / kSettingDpiVertical | 各 72,且兼容 JS 名 horizontal/vertical 与内部键 |
header / footer 这一项值得单独拎出来:
electron_api_web_contents.cc:4207-4212
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);
}
JS 侧的 header 被写进 Chromium 的 title 槽,footer 被写进 URL 槽。也就是说这两个字符串不是"页眉 HTML / 页脚 HTML",而是被塞进打印页眉页脚模板里的两个变量位——真正的模板由 Chromium 决定。它们只在两者都为空时才关闭页眉页脚;只传 header 时 footer 是空串,但 kSettingHeaderFooterEnabled 已经是 true,URL 那一行仍会被渲染(内容为空)。这与 printToPDF() 的 headerTemplate / footerTemplate 是完全不同的机制,后者是真正的 HTML 模板,还能用 pageNumber / totalPages / date / title / url 这些类。
pageRanges 有一处 +1:
electron_api_web_contents.cc:4232-4233
// 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);
JS 侧用 0 基(与 printToPDF() 的 pageRanges: '1-3,5' 字符串那种 1 基写法也不一样),{from: 0, to: 2} 表示前三页。缺 from 或缺 to 的条目被 continue 静默跳过;如果全部条目都被跳过,kSettingPageRange 这个键根本不写,等于打印全部页。
再看那三个被注释点名的项(:4216-4221):
electron_api_web_contents.cc:4218-4221
// 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);
printerType 恒为 kLocal——print() 不能"打印到 PDF";shouldPrintSelectionOnly 恒为 false,尽管 19.1.5 会看到 GetRenderFrameHostToUse 会优先挑有选中的焦点帧,但那只是选帧,不是"只打选中内容";rasterizePdf 恒 false。这三行是防御性的:下游 PrintSettingsFromJobSettings 对缺失键会 CHECK,宁可显式写死也不能省。
printBackground 那一行还有个兼容层:先查 JS 名 printBackground,没有再查 Chromium 内部键名 shouldPrintBackgrounds。这是从"设置字典曾经由 JS 层直接构造"过渡到"C++ 构造"留下的痕迹,等价于允许内部键名漏到 JS。
19.1.4 打印机名要跨线程查,纸张默认 A4
Print() 最后不是直接调 PrintNow,而是发到 print_task_runner_ 上(:4272-4278):
electron_api_web_contents.cc:4273-4276
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&OnGetDeviceNameToUse, web_contents()->GetWeakPtr(),
std::move(settings), std::move(callback)));
print_task_runner_ 由 printing_utils.cc:176 的 CreatePrinterHandlerTaskRunner() 产生,三平台不同:
#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::TaskPriority::USER_VISIBLE});
#else
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
Windows 上打印机驱动不是线程安全的,所以"异步"其实仍在 UI 线程跑,ScopedAllowBlockingForElectron 就是为了允许这次阻塞。这也解释了为什么在无响应打印机上调用 print() 会卡住整个 UI:它不是后台任务,是一次带 MayBlock 许可的 UI 线程同步调用。
GetDeviceNameToUse(printing_utils.cc:133-172)的逻辑是:给了 deviceName 就校验它存在(mac 走 PMPrinterCreateFromPrinterID,其他平台走 PrintBackend::IsValidPrinter),没给就依次尝试 GetDefaultPrinterName → EnumeratePrinters → 取列表第一项。注意它对"取不到默认打印机"的处理是只打日志不返回,因为有些设备本来就没有默认打印机;直到列表也为空才返回 "No printers available on the network"。这个字符串会通过 OnGetDeviceNameToUse 变成回调的失败原因:
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
OnGetDeviceNameToUse(electron_api_web_contents.cc:3993-4067)补三件事:
- 把查到的设备名写回
settings。回调签名是(success: boolean, failureReason: string),success为 false 时第二个参数就是上面那些英文错误串。 - 如果没显式给 DPI,用
GetDefaultPrinterDPI(device_name):mac 恒kDefaultMacDpi;Windows 用CreateDC(L"WINSPOOL", ...)+GetDeviceCaps(LOGPIXELSX/Y),失败退kDefaultPdfDpi;Linux 用gtk_print_settings_get_resolution(),小于等于 0 时退kDefaultPdfDpi。Linux 这条尤其隐蔽:它读的是一份新建的空GtkPrintSettings,不是实际打印机配置,所以通常拿到 GTK 的全局默认分辨率。 - 如果没给
mediaSize,按usePrinterDefaultPageSize决定:为 true 时查GetPrinterDefaultPaperSize(PrintBackend::GetPrinterSemanticCapsAndDefaults),查不到就退回写死的297000 × 210000——A4。也就是说print()不传pageSize时默认纸型是 A4,而printToPDF()不传pageSize时默认纸型是 Letter(PaperSize paper{8.5, 11})。两个 API 连默认纸张都不一样。
那个 make_media_size lambda 里还有一组看起来写反了的坐标(:4018-4027):
electron_api_web_contents.cc:4032-4039
auto make_media_size = [](int height_microns, int width_microns) {
return base::DictValue()
.Set(printing::kSettingMediaSizeHeightMicrons, height_microns)
.Set(printing::kSettingMediaSizeWidthMicrons, width_microns)
.Set(printing::kSettingsImageableAreaLeftMicrons, 0)
.Set(printing::kSettingsImageableAreaTopMicrons, height_microns)
.Set(printing::kSettingsImageableAreaRightMicrons, width_microns)
.Set(printing::kSettingsImageableAreaBottomMicrons, 0)
.Set(printing::kSettingMediaSizeIsDefault, true);
};
top = height、bottom = 0 不是笔误:Chromium 的 imageable area 用的是自底向上的坐标,top 是从下边缘量起的距离。所以这就是"整张纸都可打印、零边距"的写法。MediaSizeDict 里同样是这组值。
19.1.5 打印的到底是哪一帧
所有打印路径最终都会问 GetRenderFrameHostToUse(printing_utils.cc:111-131),它抄自 Chromium 的 print_view_manager_common.cc,但加了 PDF viewer 的处理:
content::RenderFrameHost* GetRenderFrameHostToUse(
content::WebContents* contents) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
content::RenderFrameHost* full_page_pdf_embedder_host =
chrome_pdf::features::IsOopifPdfEnabled()
? pdf_frame_util::FindFullPagePdfExtensionHost(contents)
: GetFullPagePlugin(contents);
content::RenderFrameHost* pdf_rfh = pdf_frame_util::FindPdfChildFrame(
full_page_pdf_embedder_host ? full_page_pdf_embedder_host
: contents->GetPrimaryMainFrame());
if (pdf_rfh) {
return pdf_rfh;
}
#endif
auto* focused_frame = contents->GetFocusedFrame();
return (focused_frame && focused_frame->HasSelection())
? focused_frame
: contents->GetPrimaryMainFrame();
}
优先级是 PDF viewer 子帧 > 有选中的焦点帧 > 主帧。两个后果:
- 用 Electron 的 PDF viewer 打开一个 PDF 再调
print(),打的是 PDF 插件帧,不是包裹它的页面。 - 页面里选中一段文字后,打印目标帧会切到焦点帧。但 19.1.3 里
kSettingShouldPrintSelectionOnly被写死为 false,所以并不会只打选中内容,只是换了打印的 frame(例如 iframe 里的选中会让打印目标变成那个 iframe)。这是"选了字再打印,结果整个 iframe 被打了"的原因。
printToPDF() 也用这个函数,但它在 PdfQueue::Start 里通过 PrintToPDFFrame 回调延迟到任务真正启动时才调用(见 19.2.7),而 print() 是同步路径里直接调。这个时机差异会在页面导航时体现出来。
19.1.6 PrintViewManagerElectron:用 cookie 把"打印"和"生成 PDF"分开
print_view_manager_electron.cc:103-109 只有 295 行,文件开头一行注释交代了它的出身:
// This file subclasses printing::PrintViewManagerBase
// but the implementations are duplicated from
// components/printing/browser/print_to_pdf/pdf_print_manager.cc.
它是 WebContentsUserData,一个 WebContents 一份。核心是一个 std::vector<int32_t> pdf_jobs_,里面装的是 PDF 作业的 document_cookie。Chromium 的打印管线里,renderer 会通过 PrintManagerHost 反过来向浏览器进程要打印参数(GetDefaultPrintSettings / ScriptedPrint / DidGetPrintedPagesCount),而 printToPDF 走的是 PdfPrintJob::StartJob 自己发参数,不需要 renderer 回问。两类请求在同一个 mojo 接口上,靠 cookie 区分:
print_view_manager_electron.cc:103-109
void PrintViewManagerElectron::GetDefaultPrintSettings(
GetDefaultPrintSettingsCallback callback) {
// This isn't ideal, but we're not able to access the document cookie here.
if (pdf_jobs_.size() > 0) {
LOG(ERROR) << "Scripted print is not supported";
std::move(callback).Run(printing::mojom::PrintParams::New());
} else {
PrintViewManagerBase::GetDefaultPrintSettings(std::move(callback));
}
}
注释承认了限制:这个回调拿不到 cookie,只能看 pdf_jobs_ 是否非空。只要有任何 PDF 作业在跑,页面里的 window.print() 就会拿到一份空的 PrintParams,同时日志里打一行 "Scripted print is not supported"。ScriptedPrint 那条路能拿到 params->cookie,于是精确判断:
print_view_manager_electron.cc:117-123
if (!std::ranges::contains(pdf_jobs_, params->cookie)) {
PrintViewManagerBase::ScriptedPrint(std::move(params), std::move(callback));
return;
}
auto default_param = printing::mojom::PrintPagesParams::New();
default_param->params = printing::mojom::PrintParams::New();
LOG(ERROR) << "Scripted print is not supported";
std::move(callback).Run(std::move(default_param));
DidGetPrintedPagesCount 同样按 cookie 过滤,避免 PDF 作业的页数被算进普通打印作业。也就是说:在 printToPDF() 进行期间调用页面的 window.print(),不会弹打印对话框,也不会报错给页面,只是静默失败并留一行 ERROR 日志。这是并发调用两类打印 API 时最容易遇到的现象。
ENABLE_PRINT_PREVIEW 那段还有四个函数直接 mojo::ReportBadMessage:
print_view_manager_electron.cc:264-271
void PrintViewManagerElectron::SetupScriptedPrintPreview(
SetupScriptedPrintPreviewCallback callback) {
mojo::ReportBadMessage(kInvalidSetupScriptedPrintPreviewCall);
}
void PrintViewManagerElectron::ShowScriptedPrintPreview() {
mojo::ReportBadMessage(kInvalidShowScriptedPrintPreviewCall);
}
void PrintViewManagerElectron::RequestPrintPreview(
printing::mojom::RequestPrintPreviewParamsPtr params) {
mojo::ReportBadMessage(kInvalidRequestPrintPreviewCall);
}
ReportBadMessage 是杀 renderer 级别的响应,不是返回错误。Electron 没有 print preview UI,所以从 renderer 发来的 preview 请求一律视为协议违规。CheckForCancel 则恒返回 false(没有可取消的 UI)。
而 PrintToPdf() 本身非常薄:
print_view_manager_electron.cc:93-100
int cookie = print_pages_params->params->document_cookie;
pdf_jobs_.emplace_back(cookie);
print_to_pdf::PdfPrintJob::StartJob(
web_contents(), rfh, GetPrintRenderFrame(rfh), page_ranges,
std::move(print_pages_params),
base::BindOnce(&PrintViewManagerElectron::DidPrintToPdf,
weak_factory_.GetWeakPtr(), cookie, std::move(callback)));
// ...
void PrintViewManagerElectron::DidPrintToPdf(
int cookie, PrintToPdfCallback callback,
print_to_pdf::PdfPrintResult result,
scoped_refptr<base::RefCountedMemory> memory) {
std::erase(pdf_jobs_, cookie);
std::move(callback).Run(result, memory);
}
std::erase 会删掉所有同值 cookie(不只是第一个),而 print_to_pdf.cc:250 的 request_id 是进程级单调递增的 ++next_request_id,所以正常情况不会撞;但如果同一个 WebContents 上有多个 frame tree 的作业并发,它们共用这一份 pdf_jobs_,19.1.6 的 pdf_jobs_.size() > 0 判据就会互相影响。这是 19.2.7 那个队列必须存在的原因之一。
最后补一个编译期分支:当 ENABLE_PRINTING 关闭(BUILD.gn:829 控制)时,Print() 只打一行 LOG(ERROR),PrintToPDF() 直接 reject "Printing feature is disabled",getPrintersAsync() 返回空数组(:4314-4330)。这三条是同一套 API 在非打印构建里的完整降级行为——JS 层看不出构建差异,只能从结果推断。
19.1.7 getPrintersAsync() 是另一条独立的枚举链路
webContents.getPrintersAsync()(:5893)与 19.1.4 的 GetDeviceNameToUse 都会枚举系统打印机,但走的是两套代码。electron_api_printing.cc 全文 95 行,是一个独立的 Node 绑定:
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_printing, Initialize)
...
void Initialize(v8::Local<v8::Object> exports, ...) {
v8::Isolate* const isolate = electron::JavascriptEnvironment::GetIsolate();
gin_helper::Dictionary dict{isolate, exports};
#if BUILDFLAG(ENABLE_PRINTING)
dict.SetMethod("getPrinterListAsync",
base::BindRepeating(&GetPrinterListAsync));
#endif
}
注意 #if 包的是 SetMethod 本身:非打印构建里 electron_browser_printing 这个绑定导出的是一个空对象,连 getPrinterListAsync 这个方法都不存在。而 webContents.getPrintersAsync() 在 C++ 侧仍然被 SetMethod 注册,只是实现走 :4327 的 LOG(ERROR) + resolve 空数组。同一个功能在两种构建里的降级层次不一样:一个方法消失,一个方法还在但返回空。
GetPrinterListAsync(:46-70):
electron_api_printing.cc:47-54
gin_helper::Promise<printing::PrinterList> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
base::BindOnce([]() {
printing::PrinterList printers;
auto print_backend = printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
printing::mojom::ResultCode code =
print_backend->EnumeratePrinters(printers);
if (code != printing::mojom::ResultCode::kSuccess)
LOG(INFO) << "Failed to enumerate printers";
return printers;
}),
base::BindOnce(
[](gin_helper::Promise<printing::PrinterList> promise,
const printing::PrinterList& printers) {
promise.Resolve(printers);
},
std::move(promise)));
return handle;
四个可观察点:
EnumeratePrinters失败只打一行LOG(INFO),然后照常 resolve,此时列表可能是空的或部分填充的。所以getPrintersAsync()永远不会 reject——拿不到打印机和"系统里一台打印机都没有"在 JS 侧完全无法区分。- 它直接用
base::ThreadPool的{USER_VISIBLE, MayBlock()},而 19.1.4 的print()用CreatePrinterHandlerTaskRunner()。Windows 上后者会落到 UI 线程,前者仍在线程池。同一个PrintBackend::CreateInstance在不同 API 里跑在不同线程上,这是"枚举打印机不卡、打印卡"的原因。 PrintBackend::CreateInstance(g_browser_process->GetApplicationLocale())传的是应用 locale,不是系统 locale。打印机名称/描述的本地化结果因此跟随 Electron 应用的语言设置,而不是操作系统区域。CUPS 上尤其明显。gin::Converter<printing::PrinterBasicInfo>(:27-38)只导出四个字段:name、displayName、description、options。没有isDefault、没有打印机状态、没有 URI。想知道哪台是默认打印机,只能回到 19.1.4 那条GetDefaultPrinterName路径(它没有对 JS 暴露)。
getPrintersAsync 的实现是 static 的,源码注释写着 // static: does not need the WebContents, destroyed or not.。它挂在 WebContents 上只是历史沿革,实际与任何 WebContents 状态无关——窗口关掉之后照样能调。
19.2 printToPDF():一份按 frame tree 排队的作业调度器
print_to_pdf.cc 是这一章里最值得逐行读的文件,440 行,版权头写的是 Copyright (c) 2026 Anthropic, PBC.——它是这个版本里新重写的实现。它做的事情远不止"把选项转成打印参数",而是一个带验证、带排队、带销毁兜底的作业调度器,并且大量代码用于逐字复刻旧版 JS 层的行为。
19.2.1 两个入口,同一个队列
printToPDF 有两个 JS 入口:webContents.printToPDF()(electron_api_web_contents.cc:4280)和 webFrameMain.printToPDF()(electron_api_web_frame_main.cc:324)。两者都调到同一个自由函数 electron::PrintToPDF(),区别只在"怎么找到要打印的帧"和"帧没了报什么错":
electron_api_web_contents.cc:4280
v8::Local<v8::Promise> WebContents::PrintToPDF(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
v8::Local<v8::Object> holder;
WebContents* self = nullptr;
if (!args->GetHolder(&holder) ||
gin_helper::Destroyable::IsDestroyed(holder) ||
!gin::ConvertFromV8(isolate, holder, &self) || !self ||
!self->web_contents()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
promise.Reject(v8::Exception::TypeError(
gin::StringToV8(isolate, "Object has been destroyed")));
return handle;
}
...
return electron::PrintToPDF(
isolate,
self->web_contents()->GetPrimaryMainFrame()->GetFrameTreeNodeId().value(),
base::BindRepeating(
[](base::WeakPtr<WebContents> self) -> content::RenderFrameHost* {
if (!self || !self->web_contents())
return nullptr;
return GetRenderFrameHostToUse(self->web_contents());
},
self->GetWeakPtr()),
{"Object has been destroyed", /*type_error=*/true}, options);
}
上面那段判空有个很明确的设计意图,源码注释写着 // static: a destroyed WebContents rejects rather than throws.:对象已销毁时返回 rejected promise,不抛同步异常。所以 await wc.printToPDF() 在窗口被关掉后走 catch,而不是让整段代码被 throw 打断。这与 19.1 的 print() 不同——后者是无返回值的同步 API,销毁时只是静默 return。
webFrameMain 那边用的不是 WeakPtr,而是 cppgc::WeakPersistent<WebFrameMain>:
electron_api_web_frame_main.cc:335-342
return electron::PrintToPDF(
isolate, frame_tree,
base::BindRepeating(
[](cppgc::WeakPersistent<WebFrameMain> self)
-> content::RenderFrameHost* {
return self && self->HasRenderFrame() ? self->render_frame_host()
: nullptr;
},
cppgc::WeakPersistent<WebFrameMain>(this)),
{"Render frame was disposed before WebFrameMain could be accessed"},
options);
frame_gone 的 type_error 默认 false,所以 WebFrameMain 这条路 reject 的是普通 Error,WebContents 那条路是 TypeError。同一个 API 在不同对象上调用,失败时的异常类型不同,做统一错误处理时要注意。
这个入口是 static 的(.h:160 声明处也能看出),意味着它不依赖 this。GetPrintersAsync 同样是 static,注释还专门写了 // static: does not need the WebContents, destroyed or not.。
19.2.2 frame_tree 是排队键,不是帧标识
PrintToPDF() 的第二个参数叫 frame_tree,头文件 print_to_pdf.h:24-30 解释了它的语义:
// webContents.printToPDF(options) / webFrameMain.printToPDF(options).
// Validates |options| (which may be empty) and returns a promise for the PDF
// data as a Buffer, rejected with the same errors the API documents for bad
// options. PDF jobs in one frame tree conflict in the renderer, so a job waits
// for earlier ones with the same |frame_tree| key (the tree's top
// FrameTreeNode id) to settle, then prints whatever |frame| returns at that
// point; if that is null the promise is rejected with |frame_gone| ...
"PDF jobs in one frame tree conflict in the renderer" 是整份队列存在的唯一理由。renderer 的打印状态是按 frame tree 共享的,两个作业同时进行会互相踩 document_cookie 与打印参数。WebContents 传的是 GetPrimaryMainFrame()->GetFrameTreeNodeId(),WebFrameMain 传的是:
electron_api_web_frame_main.cc:331-334
const int frame_tree =
HasRenderFrame()
? render_frame_host()->GetMainFrame()->GetFrameTreeNodeId().value()
: FrameTreeNodeID().value();
任何一个 frame 上的 printToPDF(),排队键都是主帧的 id。也就是说同一个页面里主帧和子帧并发调用会串行;两个不同 WebContents 的调用则并发。这个粒度和 19.1.6 里 pdf_jobs_ 是「每个 WebContents 一份」并不矛盾:队列解决的是渲染器内部的冲突,pdf_jobs_ 解决的是 mojo 回调的分流。
关键在 then prints whatever |frame| returns at that point——帧是在作业真正启动时才取的,不是调用时取的。所以:
const p = wc.printToPDF(); // 排队,此时还没取帧
await wc.loadURL('other'); // 导航发生
const buf = await p; // 打的是导航后的页面
这不是 bug,是头文件里写明的语义。同理,如果在排队期间关掉窗口,作业启动时 PrintToPDFFrame 返回 nullptr,promise 用 frame_gone 里那段消息 reject。
19.2.3 ReadPdfRequest:验证顺序即兼容契约
PdfRequest 结构体(print_to_pdf.cc:72-90)列出了这个 API 真正认的全部字段:
struct PdfRequest {
int request_id = 0;
bool landscape = false;
bool display_header_footer = false;
std::string header_template;
std::string footer_template;
bool print_background = false;
std::optional<double> scale = 1.0;
std::optional<double> paper_width = 8.5;
std::optional<double> paper_height = 11;
std::optional<double> margin_top = 0.4;
std::optional<double> margin_bottom = 0.4;
std::optional<double> margin_left = 0.4;
std::optional<double> margin_right = 0.4;
std::string page_ranges;
bool prefer_css_page_size = false;
bool generate_tagged_pdf = false;
bool generate_document_outline = false;
};
注意默认值:纸张 8.5 × 11 是 Letter,四边边距 0.4 英寸(约 1cm),scale = 1.0。这张表和 19.1.3 那张 print() 表几乎每一项都对不上:一个是英寸/0–2 缩放/1 基字符串页码,一个是微米/百分比缩放/0 基对象页码。
ReadPdfRequest(:178-252)的读取顺序被注释点名:
// Reads and validates printToPDF's options in the order, and with the
// messages, the API has always reported them.
顺序是:margins 对象先取出(不是对象或函数 → "margins must be a object" 这个带冠词的 TypeError)→ pageSize → 四个 margin 的越界检查 → 其余 13 项逐个 Get → 全部数值做 DropIfNotFinite → 分配 request_id。
这带来两个反直觉结果:
- 越界检查发生在数值转换之前。也就是说
margins.top可以是个带valueOf的对象,检查阶段会调用它做比较,转换阶段还会再调一次。margins里的 getter 可能被调用多次。 pageSize的校验早于scale等字段。一个既有非法pageSize又有非法scale的 options,报的永远是 pageSize 的错,错误顺序是固定的。
pageSize 的解析(ReadPageSize,:93-125)与 19.1.1 的 MediaSizeFromPageSize 完全独立:字符串查 kPaperFormats(先 ToLowerASCII,所以 'A4'/'a4'/'LeTtEr' 都行),查不到报 "Invalid pageSize <name>"(普通 Error);对象必须同时有 width/height 且都是 IsNumber()——注意是必须是 number 类型,'8.5' 这种字符串会直接报 "width and height properties are required for pageSize"(TypeError),不会做数字强制转换。这与 margins 那边截然相反。
19.2.4 MarginExceeds:用 C++ 逐字复刻 JS 的 <=
这是整份文件里最能说明"兼容旧行为"到什么程度的一段(:127-153):
print_to_pdf.cc:130-137
// The JavaScript `margin !== undefined && !(margin <= limit)` this replaces,
// with `<=`'s coercion (null is 0, BigInt compares exactly, anything
// unconvertible throws); type checking proper comes after.
bool MarginExceeds(const OptionsReader& margins,
v8::Local<v8::Value> value,
double limit) {
if (margins.failed() || value.IsEmpty() || value->IsUndefined())
return false;
if (value->IsBigInt()) {
bool lossless;
int64_t as_int = value.As<v8::BigInt>()->Int64Value(&lossless);
if (!lossless) {
// Beyond int64: only its sign matters against a finite limit.
int sign_bit = 0;
int word_count = 0;
value.As<v8::BigInt>()->ToWordsArray(&sign_bit, &word_count, nullptr);
return sign_bit == 0;
}
return !(as_int <= limit);
}
double number;
if (!value->NumberValue(margins.isolate()->GetCurrentContext()).To(&number)) {
margins.error().Fail("Exception reading margins");
return true;
}
return !(number <= limit);
}
它复刻的是旧 JS 实现里 margin <= pageSize 这一行。为了做到语义一致,专门处理了三种情况:
undefined直接放行(margin !== undefined的短路),margins.failed()时也不再读。- BigInt 参与关系运算是合法的,而且 JS 允许 BigInt 与 Number 直接比较、精度不能丢。所以先试
Int64Value(&lossless);超出 int64 时只需要判断符号——对一个有限的limit,正的巨大 BigInt 一定越界,负的一定不越界。代码用ToWordsArray只取sign_bit,连word_count都没用。 - 其他值走
NumberValue(),这一句会触发valueOf/toString,null变成 0、字符串按数字解析、Symbol 会抛;抛了就margins.error().Fail("Exception reading margins")。
而 !(number <= limit) 的写法不是 number > limit:NaN 时 <= 为 false,取反为 true,会判定越界;如果写 > 就会漏掉 NaN。这是刻意保留的 JS 语义。
四个 margin 不是边读边查,而是 ReadMargin 一次性全取出来(:155-169,注释写 // const {top, bottom, left, right} = margins: all four read up front),然后:
print_to_pdf.cc:212-219
const bool bad_height = MarginExceeds(*margins, top, paper.height) ||
MarginExceeds(*margins, bottom, paper.height);
const bool bad_width = MarginExceeds(*margins, left, paper.width) ||
MarginExceeds(*margins, right, paper.width);
if (error.failed()) // a coercion threw
return std::nullopt;
if (bad_height || bad_width) {
error.Fail("margins must be less than or equal to pageSize");
return std::nullopt;
}
|| 的短路意味着每一对只报到第一个越界的边:top 越界时 bottom 的 getter 副作用根本不会发生。但 bad_height 与 bad_width 是两个独立表达式,所以纵向已经越界时横向仍会被检查一遍。错误信息统一是 "margins must be less than or equal to pageSize",不告诉你是哪条边。
有意思的是判据本身:top 与 bottom 各自被拿来和整张纸的高度比,而不是 top + bottom <= height。所以 {top: 6, bottom: 6} 在 A4(11.7 英寸)上是合法的,尽管上下边距加起来 12 英寸已经超过纸高。真正的内容区为负会发生什么,由下游 GetPrintPagesParams 决定。
19.2.5 非有限数值不是错误,是"这个选项没给"
print_to_pdf.cc:242-249
for (std::optional<double>* number :
{&request.scale, &request.paper_width, &request.paper_height,
&request.margin_top, &request.margin_bottom, &request.margin_left,
&request.margin_right}) {
DropIfNotFinite(*number);
}
// static
void DropIfNotFinite(std::optional<double>& value) {
if (value && !std::isfinite(*value))
value.reset();
}
结构体注释解释了为什么这些字段是 std::optional<double> 而不是 double:
// Numbers are optional only so that a non-finite value can fall back to the
// print_to_pdf default, as it did when it was dropped crossing into a
// base::Value.
旧实现里 options 会经过 base::Value,Infinity / NaN / -Infinity 在跨边界时被丢掉,下游就采用 Chromium 自己的默认值。现在改成直接读 V8 值,如果不专门 reset(),就会把 NaN 传给 GetPrintPagesParams。所以 printToPDF({scale: Infinity}) 不报错,等价于没传 scale——只是回退值可能不是 1.0,而是 Chromium 那份默认值。
page_ranges、generateTaggedPDF、generateDocumentOutline 三项没有对应的 C++ 校验:page_ranges 是字符串,原样传到 PdfPrintJob::StartJob 里由 Chromium 的 PageRange 解析;两个 generate* 是布尔,直接进 GetPrintPagesParams。pageRanges 因此是唯一一个格式错误不会被 Electron 层报出来的选项——'1-3,foo' 里非法段的处理完全在 Chromium 侧。
19.2.6 选项读取时抛的异常,统一变成 rejected promise
print_to_pdf.cc:413-420
v8::Local<v8::Promise> PrintToPDF(v8::Isolate* isolate,
int frame_tree,
PrintToPDFFrame frame,
PrintToPDFFrameGone frame_gone,
v8::Local<v8::Value> options) {
auto job = std::make_unique<PdfJob>(isolate, std::move(frame), frame_gone);
v8::Local<v8::Promise> handle = job->promise.GetHandle();
ConversionError error;
// Reading the options can run getters and coercions that throw; that is a
// rejection too, not an exception from printToPDF().
v8::TryCatch try_catch(isolate);
std::optional<PdfRequest> request = ReadPdfRequest(isolate, options, error);
if (try_catch.HasCaught()) {
v8::Local<v8::Value> exception = try_catch.Exception();
try_catch.Reset();
job->promise.Reject(exception);
return handle;
}
if (!request) {
job->promise.Reject(error.ToException(isolate));
return handle;
}
job->request = std::move(*request);
PdfQueue::Get().Add(frame_tree, std::move(job));
return handle;
}
v8::TryCatch 包住整个 ReadPdfRequest。因为 19.2.4 里会调 NumberValue()、会读 getter,任何用户代码抛出的异常都会被捕获并原样作为 rejection 的 reason(job->promise.Reject(exception),不是转成字符串)。所以:
await wc.printToPDF({ get scale() { throw new Error('boom'); } });
// catch 到的就是那个 Error('boom') 对象
而 Electron 自己发现的验证错误(非法 pageSize、margin 越界、margins 不是对象)走 error.ToException(isolate),由 ConversionError::Kind 决定是 TypeError 还是 Error。两条 reject 路径的异常来源不同但都是 rejection,printToPDF() 永远不会同步抛异常。
19.2.7 PdfQueue:按 frame tree 串行、跨 tree 并发
print_to_pdf.cc:274-281
// Serialises printToPDF jobs per frame tree. Jobs in different trees run
// concurrently.
class PdfQueue {
public:
static PdfQueue& Get() {
static base::NoDestructor<PdfQueue> queue;
return *queue;
}
void Add(int frame_tree, std::unique_ptr<PdfJob> job) {
base::circular_deque<std::unique_ptr<PdfJob>>& jobs = queues_[frame_tree];
jobs.push_back(std::move(job));
if (jobs.size() == 1)
PostStart(frame_tree);
}
private:
std::map<int, base::circular_deque<std::unique_ptr<PdfJob>>> queues_;
};
又一处 base::NoDestructor:这个队列是进程级单例,永不析构(第 17 章 ContextMap() 也是这个套路)。Add 只在队列从空变非空时投递启动任务,后续作业由 Pop 接棒。
Start()(:319-367)是真正干活的地方,它把前面所有环节串起来:
print_to_pdf.cc:319-326
void Start(int frame_tree) {
PdfJob& job = *queues_[frame_tree].front();
content::RenderFrameHost* rfh = job.frame.Run(); // 此刻才取帧
if (!rfh) { /* reject frame_gone, Pop */ }
const PdfRequest& r = job.request;
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> params =
print_to_pdf::GetPrintPagesParams(
rfh->GetLastCommittedURL(), r.landscape, r.display_header_footer,
r.print_background, r.scale, r.paper_width, r.paper_height,
r.margin_top, r.margin_bottom, r.margin_left, r.margin_right,
r.header_template, r.footer_template, r.prefer_css_page_size,
r.generate_tagged_pdf, r.generate_document_outline);
if (absl::holds_alternative<std::string>(params)) {
job.promise.RejectWithErrorMessage(base::StrCat(
{"Invalid print parameters: ", absl::get<std::string>(params)}));
return Pop(frame_tree);
}
auto* manager = PrintViewManagerElectron::FromWebContents(...);
if (!manager) { /* "Failed to find print manager", Pop */ }
// PdfPrintJob reports this too, but only after the print manager has
// CHECKed it.
if (!rfh->IsRenderFrameLive()) {
job.promise.RejectWithErrorMessage(...kPrintFailure...);
return Pop(frame_tree);
}
pages->params->document_cookie = r.request_id;
manager->PrintToPdf(rfh, r.page_ranges, std::move(pages),
base::BindOnce(&Completion::Run,
std::make_unique<Completion>(this, frame_tree)));
}
几个要点:
GetPrintPagesParams的第一个参数是rfh->GetLastCommittedURL()。页眉页脚模板里的url取的是"作业启动那一刻已提交的 URL",不是调用printToPDF()时的 URL,也不是options里的任何东西。这又是 19.2.2 那条"延迟取帧"的连带效果。- 参数构造返回的是
variant<PrintPagesParamsPtr, std::string>,字符串分支是 Chromium 侧的校验失败,错误前缀"Invalid print parameters: "。 IsRenderFrameLive()这一句检查被注释点名:PdfPrintJob自己也会报这个错,但要等到 print manager 先CHECK过之后,所以 Electron 提前拦一道。这是纯防御性代码,防止一个"帧树还在但 render frame 已死"的窗口把浏览器进程带崩。document_cookie = r.request_id,而request_id来自static int next_request_id = 0; request.request_id = ++next_request_id;(:249-250)。进程级递增,从 1 开始,与 Chromium 的PrintSettings::NewCookie()那套编号不同源。19.1.6 里pdf_jobs_装的正是这个值。
Finish()(:369-388)把结果兑现:
print_to_pdf.cc:375-382
} else if (*result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
job.promise.RejectWithErrorMessage(
base::StrCat({"Failed to generate PDF: ",
print_to_pdf::PdfPrintResultToString(*result)}));
} else {
v8::Isolate* isolate = job.promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(job.promise.GetContext());
job.promise.Resolve(
electron::Buffer::Copy(isolate, *data).ToLocalChecked());
}
Pop(frame_tree);
成功时复制一份 RefCountedMemory 到 V8 Buffer(Buffer::Copy),不是零拷贝包装。所以大 PDF 会有一份完整的内存副本;ToLocalChecked() 说明这里假定分配必然成功。因为回调可能来自非 JS 线程上下文,显式加了 Locker + HandleScope + Context::Scope 三件套。
19.2.8 任务永远从"新任务"启动,以及一个可能永远 pending 的 promise
PostStart 的注释解释了为什么不能就地启动(:399-406):
print_to_pdf.cc:402-405
// Jobs start from a fresh task, never from inside printToPDF() or a
// previous job's completion (which can arrive mid-teardown of a frame), as
// they did when a promise reaction started them.
void PostStart(int frame_tree) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&PdfQueue::Start, base::Unretained(this), frame_tree));
}
"as they did when a promise reaction started them" 说明旧实现是用 promise 的 .then 启动下一个作业的,而完成回调有可能在 frame 拆卸到一半时到达,那时再启动下一个作业会踩到正在销毁的对象。现在改成 PostTask,把启动推到下一个消息循环任务。base::Unretained(this) 之所以安全,正是因为 PdfQueue 是 NoDestructor 进程级单例。
更微妙的是 Completion(:295-317):
print_to_pdf.cc:295-302
class Completion {
public:
Completion(PdfQueue* queue, int frame_tree)
: queue_(queue), frame_tree_(frame_tree) {}
~Completion() {
// Un-run: the frame's WebContents is being torn down; move on once
// that is over.
if (queue_) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&PdfQueue::Finish, base::Unretained(queue_.get()),
frame_tree_, std::nullopt, nullptr));
}
}
void Run(print_to_pdf::PdfPrintResult result,
scoped_refptr<base::RefCountedMemory> data) {
std::exchange(queue_, nullptr)->Finish(frame_tree_, result, data);
}
private:
raw_ptr<PdfQueue> queue_; // process-lifetime
int frame_tree_;
};
Completion 被包在 base::BindOnce 里交给 PrintViewManagerElectron,而后者用 weak_factory_.GetWeakPtr() 绑定 DidPrintToPdf。如果 WebContents 在 PDF 生成期间被销毁,weak ptr 失效,回调连同这个 Completion 一起被丢弃——Run() 永远不会被调用。析构函数发现 queue_ 还在(说明没有 Run 过),就 PostTask 一个 result = std::nullopt 的 Finish,让队列继续往下走。
而 Finish 对 std::nullopt 的处理是(:373-374):
if (!result) {
// Dropped un-run: leave the promise unsettled, as before.
}
这个 promise 永远不会被 settle。不是 reject,不是 resolve,就一直 pending。源码注释里的 "as before" 表明这是刻意保留的旧行为。实际后果:如果页面在 printToPDF() 进行中被关掉,await 会永远挂住,连 finally 都不会执行;Promise.race 加超时是唯一可靠的兜底。这是本章最值得记住的一条。
Pop()(:390-397)在队列空时 queues_.erase(it),否则再 PostStart,形成一条不会在栈上递归的链。
19.2.9 把这一节压缩成一条时序
把 19.2 的全部环节按发生顺序排出来:
| 步骤 | 位置 | 可能的结果 |
|---|---|---|
| 1 | WebContents::PrintToPDF | 对象已销毁 → reject TypeError |
| 2 | PrintToPDF() 建 PdfJob,TryCatch 包住 ReadPdfRequest | getter 抛错 → reject 原异常;验证失败 → reject error.ToException |
| 3 | PdfQueue::Add(frame_tree, job) | 队列从空变非空 → PostStart |
| 4 | 下一个任务:Start() 调 job.frame.Run() | 帧没了 → reject frame_gone |
| 5 | GetPrintPagesParams(rfh->GetLastCommittedURL(), ...) | 参数非法 → reject "Invalid print parameters: ..." |
| 6 | FromWebContents / IsRenderFrameLive 检查 | manager 缺失或帧已死 → reject |
| 7 | document_cookie = ++next_request_id,manager->PrintToPdf | renderer 重排、生成 PDF |
| 8 | DidPrintToPdf → Completion::Run → Finish | 失败 → reject "Failed to generate PDF: <result>";成功 → resolve Buffer |
| — | 中途 WebContents 被销毁 | Completion 析构 → Finish(nullopt) → promise 永久 pending |
19.1 的 print() 是"同步拼字典 → 跨线程查打印机 → PrintNow",19.2 的 printToPDF() 是"验证 → 排队 → 延迟取帧 → 生成"。两条路径只在 PrintViewManagerElectron 和 GetRenderFrameHostToUse 上交汇;19.1.6 那个 pdf_jobs_ 就是它们交汇时唯一的状态。
19.3 离屏渲染:换掉整个视图实现,而不是隐藏窗口
19.3.1 构造期一次性决定,运行期不可切换
offscreen 不是 BrowserWindow 上的一个显示选项,而是 WebContents 的类型。electron_api_web_contents.cc:1042-1061 在构造时读它:
v8::Local<v8::Value> use_offscreen;
if (options.Get(options::kOffscreen, &use_offscreen)) {
if (use_offscreen->IsBoolean()) {
bool b = false;
if (options.Get(options::kOffscreen, &b) && b) {
type_ = Type::kOffScreen;
}
} else if (use_offscreen->IsObject()) {
type_ = Type::kOffScreen;
auto use_offscreen_dict =
gin_helper::Dictionary::CreateEmpty(options.isolate());
options.Get(options::kOffscreen, &use_offscreen_dict);
use_offscreen_dict.Get(options::kUseSharedTexture,
&offscreen_use_shared_texture_);
use_offscreen_dict.Get(options::kSharedTexturePixelFormat,
&offscreen_shared_texture_pixel_format_);
use_offscreen_dict.Get(options::kDeviceScaleFactor,
&offscreen_device_scale_factor_);
}
}
两个细节:
offscreen: {}也会开启离屏渲染,因为分支只看IsObject(),不看里面有没有true。同理offscreen: {useSharedTexture: false}也是开启。- 三个子选项
useSharedTexture/sharedTexturePixelFormat/deviceScaleFactor只在对象形式里被读取。传offscreen: true时它们全部保持成员默认值。这三项随后被原样传给OffScreenWebContentsView的构造函数,而后者把它们存成const成员(osr_web_contents_view.h:120-123)——运行期无法修改。
一旦 type_ == kOffScreen,构造路径就换成(:1119-1130):
electron_api_web_contents.cc:1123-1130
content::WebContents::CreateParams params{browser_context};
auto* view = new OffScreenWebContentsView(
transparent, offscreen_use_shared_texture_,
offscreen_shared_texture_pixel_format_,
offscreen_device_scale_factor_,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
params.enable_wake_locks = !disable_wake_locks;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
params.view 与 params.delegate_view 都指向同一个 OffScreenWebContentsView。它同时实现 content::WebContentsView 和 content::RenderViewHostDelegateView——也就是说 Chromium 那一侧所有"这个 view 长什么样、有多大、怎么创建子 widget"的问题,从此由 Electron 的类回答。
transparent 的取值也值得看一眼,注释交代得很清楚(:1113-1116):
electron_api_web_contents.cc:1118-1121
// 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_str;
options.GetHidden(options::kBackgroundColor, &background_color_str);
SkColor bc = ParseCSSColor(background_color_str).value_or(SK_ColorWHITE);
bool transparent = bc == SK_ColorTRANSPARENT;
backgroundColor 是 BrowserWindow 的选项,被藏进 hidden 选项里,这里再取出来解析 CSS 颜色,只有恰好等于 SK_ColorTRANSPARENT 才算透明。半透明色不算。OffScreenRenderWidgetHostView::OnPaint 里 backing_->allocN32Pixels(..., !transparent_) 会用这个布尔决定要不要不透明分配。
19.3.2 一个必须挂在窗口上的"无窗口"视图
OffScreenWebContentsView::GetSize()(osr_web_contents_view.cc:69-71):
gfx::Size OffScreenWebContentsView::GetSize() const {
return native_window_ ? native_window_->GetSize() : gfx::Size();
}
没有宿主窗口时尺寸是 0×0。native_window_ 只在 WebContents::SetOwnerWindow() 里被设置(electron_api_web_contents.cc:3078):
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
所以离屏渲染仍然需要一个 BrowserWindow(通常写成 new BrowserWindow({show: false, webPreferences: {offscreen: true}}))来提供尺寸与 NativeWindowObserver。SetNativeWindow 里会调 OnWindowResize(),后者显式 view->SetSize(GetSize())——因为离屏模式没有原生窗口事件来驱动尺寸更新,只能靠这个 observer 手动推:
osr_web_contents_view.cc:68-70
void OffScreenWebContentsView::OnWindowResize() {
// In offscreen mode call RenderWidgetHostView's SetSize explicitly
if (auto* view = GetView())
view->SetSize(GetSize());
}
注释里的 "explicitly" 是重点:正常窗口由 OS 的 resize 事件驱动合成器,离屏模式必须主动告诉 RenderWidgetHostView 新尺寸。于是"改了 BrowserWindow.setContentSize() 但离屏画面没变"这类问题,第一站就是查这条 observer 链有没有断(例如 native_window_ 被 OnWindowClosed 置空之后)。
GetNativeView() / GetContentNativeView() / GetTopLevelNativeWindow() 在 OSR 里返回的也是 native_window_ 的句柄,没有窗口时返回空(:74-92)。所以那些依赖 GetNativeView() 的功能(19.4 的 capturePage 就是其一)在纯离屏 WebContents 上会拿不到视图。
19.3.3 两条完全不同的捕获路径,由 GPU 开关决定
OffScreenRenderWidgetHostView 构造末尾(osr_render_widget_host_view.cc:218-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());
}
只有硬件加速开启时才创建 OffScreenVideoConsumer。否则走 OffScreenHostDisplayClient 那条路(:615-622):
host_display_client_ = std::make_unique<OffScreenHostDisplayClient>(
gfx::kNullAcceleratedWidget,
base::BindRepeating(&OffScreenRenderWidgetHostView::OnPaint, ...));
...
host_display_client_->SetActive(is_painting());
两条路在 SetPainting 里被 if / else if 明确二选一:
osr_render_widget_host_view.cc:886-889
if (video_consumer_) {
video_consumer_->SetActive(is_painting());
} else if (host_display_client_) {
host_display_client_->SetActive(is_painting());
}
这是理解 OSR 最重要的一张分叉图:
video_consumer_ 路径 | host_display_client_ 路径 | |
|---|---|---|
| 触发条件 | HardwareAccelerationEnabled() | 其余情况(含 --disable-gpu) |
| 底层 | FrameSinkVideoCapturer + VideoCaptureOracle | viz::HostDisplayClient 的 LayeredWindowUpdater |
| 帧来源 | 合成器主动推送捕获帧 | GPU 进程把像素写进共享内存 canvas 后调 Draw |
| 支持共享纹理 | 是(kPreferMappableSharedImage) | 否,只有 RGBA_8888 共享内存 |
SetFrameRate 生效 | 是(SetMinCapturePeriod) | 否(SetPainting 里只动 video_consumer_) |
| 帧率控制 | VideoCaptureOracle 限频 | Draw 每次都发,靠 active_ 开关 |
换句话说:用 --disable-gpu 启动的 Electron,离屏渲染走的是另一套代码,setFrameRate() 对它不起作用,useSharedTexture 也不会产生纹理。README 里那整篇 "Life of an Offscreen Frame" 只描述前者,文件里明确写了 "This only applies to the GPU-accelerated mode with shared texture"。
OffScreenHostDisplayClient 的 Draw(osr_host_display_client.cc:72-83)非常薄:
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();
}
第三个参数恒为空的 OffscreenSharedTexture{},与 video_consumer_ 路径在共享内存模式下传空纹理是一致的。
19.3.4 OffScreenVideoConsumer 的六个构造设置
osr_video_consumer.cc:62-98 这段每句都有因果,值得逐条看:
OffScreenVideoConsumer::OffScreenVideoConsumer(
OffScreenRenderWidgetHostView* view, OnPaintCallback callback)
: callback_(callback),
view_(view),
video_capturer_(view->CreateVideoCapturer()) {
video_capturer_->SetAutoThrottlingEnabled(false);
video_capturer_->SetMinSizeChangePeriod(base::TimeDelta());
auto format = GetTargetPixelFormatFromOption(
view->offscreen_shared_texture_pixel_format());
video_capturer_->SetFormat(format);
// https://crrev.org/c/6438681
// Disable capturer's animation lock-in feature for offscreen capture to
// avoid output stutter.
video_capturer_->SetAnimationFpsLockIn(false, 1);
// ... 关于分辨率约束的长注释 ...
video_capturer_->SetResolutionConstraints(
gfx::Size(1, 1),
gfx::Size(media::limits::kMaxDimension, media::limits::kMaxDimension),
false);
SetFrameRate(view_->frame_rate());
}
SetAutoThrottlingEnabled(false):不让 capturer 根据"画面有没有变化"自动降频。OSR 的消费者自己控制节奏。SetMinSizeChangePeriod(base::TimeDelta()):尺寸变化立即生效,不设冷却。- 像素格式(
:22-34)只有三种被识别:"argb"→PIXEL_FORMAT_ARGB,"rgbaf16"→PIXEL_FORMAT_RGBAF16,"nv12"→PIXEL_FORMAT_NV12;其他任何字符串都静默回落到 ARGB。拼错sharedTexturePixelFormat: 'rgba'不会报错,只会拿到 ARGB。 SetAnimationFpsLockIn(false, 1):注释指向 crrev 的一个改动,关掉 capturer 的动画帧率锁定以避免输出抖动。- 分辨率约束设为
1×1到kMaxDimension,等于不约束。那段被删掉的旧逻辑会把约束设成视图大小,注释解释了为什么要删:窗口尺寸频繁变化时,约束可能赶不上内部帧尺寸变化,capturer 会把新尺寸缩放到旧约束尺寸,产生模糊输出("小窗口突然最大化,实际输出一张被放大的小图")。现在改成尺寸变化时自然产生新帧。 SetFrameRate就是video_capturer_->SetMinCapturePeriod(base::Seconds(1) / frame_rate)(:114-116)。frame_rate为 0 在这里会除零,所以 19.3.7 的SetFrameRate会先把它夹到 1。
SetActive 里的一个参数决定了共享纹理是否启用(:102-112):
osr_video_consumer.cc:104-108
video_capturer_->Start(
this,
view_->offscreen_use_shared_texture()
? viz::mojom::BufferFormatPreference::kPreferMappableSharedImage
: viz::mojom::BufferFormatPreference::kDefault);
README 里写的是 kPreferGpuMemoryBuffer,这个版本已经改成 kPreferMappableSharedImage(Chromium 正在把 GpuMemoryBuffer 概念迁到 MappableSharedImage,README 自己也提到了)。以代码为准,不要照 README 里的名字去猜行为。
19.3.5 共享内存路径:一次 mmap、一个 releaseProc、一道越界防线
OnFrameCaptured(osr_video_consumer.cc:118-260)分两半。非共享纹理那一半先做类型与尺寸校验:
if (!data->is_read_only_shmem_region() ||
(info->pixel_format != media::PIXEL_FORMAT_ARGB &&
info->pixel_format != media::PIXEL_FORMAT_ABGR)) {
return;
}
const auto& data_region = data->get_read_only_shmem_region();
if (!data_region.IsValid()) return;
base::ReadOnlySharedMemoryMapping mapping = data_region.Map();
if (!mapping.IsValid()) { DLOG(ERROR) << "Shared memory mapping failed."; return; }
if (mapping.size() <
media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) {
DLOG(ERROR) << "Shared memory size was less than expected.";
return;
}
格式不是 ARGB/ABGR 就整帧丢弃,且不通知 JS。所以若把 sharedTexturePixelFormat 设成 nv12/rgbaf16 却忘了开 useSharedTexture,paint 事件会直接不再触发——不是拿到错误格式的数据,是没有数据。
接着是一段安全校验(:206-225),注释把它讲得很直白:
// |content_rect| and |info->coded_size| arrive from the GPU process over
// Mojo. The bitmap below is sized from |content_rect| but backed by the
// shared-memory mapping, so a hostile peer could send a tiny region with an
// oversized |content_rect| and have us read past the mapping. Clamp both the
// geometry and the resulting byte size to the mapping before wrapping it.
const size_t row_bytes =
media::VideoFrame::RowBytes(media::VideoFrame::Plane::kARGB,
info->pixel_format, info->coded_size.width());
const SkImageInfo image_info = SkImageInfo::MakeN32(
content_rect.width(), content_rect.height(), kPremul_SkAlphaType);
const size_t required_bytes = image_info.computeByteSize(row_bytes);
if (!gfx::Rect(info->coded_size).Contains(content_rect) ||
SkImageInfo::ByteSizeOverflowed(required_bytes) ||
required_bytes > mapping.size()) {
DLOG(ERROR) << "content_rect " << content_rect.ToString()
<< " is not bounded by coded_size " << info->coded_size.ToString()
<< " / mapping size " << mapping.size();
return;
}
content_rect 与 coded_size 是从 GPU 进程经 Mojo 传来的,不是本地可信数据。三个条件(几何包含、字节数溢出、字节数超过映射大小)缺一不可。这是把跨进程数据直接包成 SkBitmap 时必须做的边界检查。
通过之后,帧的生命周期被交给 SkBitmap::installPixels 的 release 回调(:227-250):
osr_video_consumer.cc:229-236
// The SkBitmap's pixels will be marked as immutable, but the installPixels()
// API requires a non-const pointer. So, cast away the const.
void* const pixels = const_cast<void*>(mapping.memory());
struct FramePinner {
// Keeps the shared memory that backs |frame_| mapped.
base::ReadOnlySharedMemoryMapping mapping;
// Prevents FrameSinkVideoCapturer from recycling the shared memory that
// backs |frame_|.
mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks>
releaser;
};
SkBitmap bitmap;
bitmap.installPixels(
image_info, pixels, row_bytes,
[](void* addr, void* context) {
delete static_cast<FramePinner*>(context);
},
new FramePinner{std::move(mapping), std::move(callbacks)});
bitmap.setImmutable();
这里没有一次像素拷贝:SkBitmap 直接指向共享内存映射。FramePinner 同时持有映射和 mojo releaser;只要 JS 侧还持有那个 NativeImage,这两个资源就一直被占着。回调注释(:124-127)解释了为什么不需要显式调 mojo 的 Done():
// Since we don't call ProvideFeedback, just need Done to release the frame,
// there's no need to call the callbacks, see in_flight_frame_delivery.cc
// The destructor will call Done for us once the pipe closed.
管道断开时析构函数会替我们调 Done。最后 update_rect 为空时退化成整张 content_rect(:254-257),callback_.Run(*update_rect, bitmap, {}) 把脏矩形和位图送出去。
19.3.6 共享纹理路径:句柄、帧池与"必须自己合成"
前半段(:128-178)先做三重过滤:
if (view_->offscreen_use_shared_texture()) {
if (!data->is_gpu_memory_buffer_handle() ||
!IsSupportedSharedTextureFormat(info->pixel_format)) {
return;
}
auto& orig_handle = data->get_gpu_memory_buffer_handle();
if (!IsPlatformSharedTextureHandle(orig_handle)) {
return;
}
auto gmb_handle = orig_handle.Clone();
...
}
IsSupportedSharedTextureFormat 认 ARGB / ABGR / RGBAF16 / NV12 四种;IsPlatformSharedTextureHandle(:46-56)按平台只认一种句柄类型:Windows DXGI_SHARED_HANDLE、Apple IO_SURFACE_BUFFER、Linux NATIVE_PIXMAP,其他平台恒 false。任何一项不匹配都是静默丢帧。
gmb_handle.Clone() 是让句柄在回调返回后继续存活的关键;OffscreenReleaserHolder 同时持有克隆后的句柄与 mojo callbacks:
texture.releaser_holder = new OffscreenReleaserHolder(std::move(gmb_handle),
std::move(callbacks));
callback_.Run(content_rect, {}, std::move(texture));
注意第二个参数是空的 SkBitmap。顺着 OffScreenRenderWidgetHostView::OnPaint(:645-659):
if (texture.has_value()) {
callback_.Run(damage_rect, {}, texture);
return;
}
一路传到 WebContents::OnPaint(electron_api_web_contents.cc:4698-4715):
void WebContents::OnPaint(const gfx::Rect& dirty_rect,
const SkBitmap& bitmap,
const OffscreenSharedTexture& tex) {
...
if (offscreen_use_shared_texture_) {
dict.Set("texture", tex);
}
EmitWithoutEvent("paint", event_object, dirty_rect,
gfx::Image::CreateFrom1xBitmap(bitmap));
}
useSharedTexture: true 时 paint 事件的第二个参数是一个空 NativeImage,第三个参数(event)上多一个 texture 属性。所有像素都要从 event.texture.textureInfo.handle 自己去读。而且共享纹理路径直接 return,跳过了 19.3.9 的 CompositeFrame——osr_paint_event.h:74 里那行注释说得很明确:// It is user's responsibility to compose popup widget textures.。下拉菜单、<select> 弹窗、guest view 的纹理不会自动叠到主纹理上,全都要按 widgetType("popup" / "frame")自己合成。这是共享纹理模式与共享内存模式最大的功能差异,README 里也重复了这一点。
句柄在不同平台上被拆成不同形状(osr_video_consumer.cc:156-171):Windows 取 dxgi_handle().buffer_handle() 转 uintptr_t;macOS 取 io_surface().get();Linux 则把 native_pixmap 的每个 plane 的 stride / offset / size / fd 逐个存进 planes,外加 modifier 与 supports_zero_copy_webgpu_import。
README 的 "Consuming" 与 "Native Handling" 两节给出的是帧池语义,这部分代码不在 Electron 仓里,但约束是硬的:
GpuMemoryBufferVideoFramePool容量kFramePoolCapacity = 10。消费者不及时release(),最多攒 10 帧就再也不出帧。- 共享纹理不是一块固定纹理,是池;每帧可能给不同的纹理。
release()之后那块纹理会被复用,继续读它就会看到别的帧的内容(画面错乱)。 - Windows 上
DuplicateHandle出来的句柄值不能当作纹理的稳定标识去缓存。正确做法是每个事件都重新OpenSharedResource1打开句柄、拷贝到自己拥有的 staging texture、然后立刻release()。README 说打开一次只需几微秒,并建议结合damaged rect只拷一部分。 textureInfo可以通过 IPC 传给别的进程,但release()只能在主进程调。
19.3.7 release() 与 GC 警告:挂在函数上的弱引用
osr_converter.cc:79-81 把 OffscreenSharedTextureValue 转成 JS 对象,产出的形状是:
{
release: Function,
textureInfo: {
pixelFormat, codedSize, visibleRect, contentRect, timestamp,
colorSpace, widgetType, metadata: {...},
handle: {
ntHandle | ioSurface | nativePixmap: {...}
}
}
}
pixelFormat 的映射有个容易踩的反转(:26-39):
case media::PIXEL_FORMAT_ARGB: return "bgra";
case media::PIXEL_FORMAT_ABGR: return "rgba";
Chromium 的 PIXEL_FORMAT_ARGB 在 JS 里叫 "bgra"。这是因为 media::VideoPixelFormat 描述的是字节序而字符串描述的是通道顺序,两者在两个库里命名相反。做像素解析时以字符串为准。
release() 的实现(:87-103)只是 mon->ReleaseTexture(),即 holder_.ClearAndDelete(),把 OffscreenReleaserHolder 连同 mojo releaser 一起释放。真正的巧劲在后面(:155-193):
// Create a weak persistent that tracks the release function rather than the
// texture object. The release function holds a raw pointer to |monitor| via
// its v8::External data, so |monitor| must outlive it. Since the texture
// keeps |release| alive via its property, this also covers the case where the
// texture itself is leaked without calling release().
auto* tex_persistent = monitor->CreatePersistent(isolate, releaser);
tex_persistent->SetWeak(
monitor,
[](const v8::WeakCallbackInfo<OffscreenReleaseHolderMonitor>& data) {
auto* monitor = data.GetParameter();
if (!monitor->IsTextureReleased()) {
data.SetSecondPassCallback([](const v8::WeakCallbackInfo<...>& data) {
static std::once_flag flag;
std::call_once(flag, [=] {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce([] {
electron::util::EmitWarning(
"Offscreen rendering shared texture was garbage "
"collected before calling `release()`. ...",
"OSRSharedTextureNotReleased");
}));
});
});
}
monitor->ResetPersistent();
delete monitor;
},
v8::WeakCallbackType::kParameter);
四个设计点:
- 弱引用挂在
release函数上,不是挂在纹理对象上。因为release的v8::External里存着monitor的裸指针,必须保证monitor比函数活得久;而纹理对象通过属性持有着release,所以监听到函数被回收就等价于纹理对象也不可达了。 - 只有
!IsTextureReleased()时才警告,即用户没显式调release()。 - 警告放在 second pass callback 里(V8 要求第一遍回调不能分配/执行 JS),并且
PostTask到下一个任务。 static std::once_flag+std::call_once保证整个进程只警告一次,警告码OSRSharedTextureNotReleased。所以如果程序里有 100 次泄漏,控制台只有一行——排查时不要以为只漏了一帧。
还有一点:即使 GC 时没调过 release(),delete monitor 会析构并释放 holder,帧最终会被还回池子。所以泄漏不是永久的,但会拖到 GC 才恢复,表现为不规则卡顿。
19.3.8 帧率、painting 状态与 240 的上限
OffScreenWebContentsView 的默认是 painting_ = true、frame_rate_ = 60(.h:124-125),所以离屏 WebContents 一创建就开始推帧,不需要调 startPainting()。JS 侧暴露的六个方法(electron_api_web_contents.cc:5862-5869):startPainting / stopPainting / isPainting / setFrameRate / getFrameRate / invalidate,外加一个 frameRate 属性(getter/setter 复用同两个函数)。
SetPainting(false) 不是"暂停渲染",是停掉 capturer:
void OffScreenRenderWidgetHostView::SetPainting(bool painting) {
painting_ = painting;
if (popup_host_view_) popup_host_view_->SetPainting(painting);
for (auto* guest_host_view : guest_host_views_)
guest_host_view->SetPainting(painting);
if (video_consumer_) video_consumer_->SetActive(is_painting());
else if (host_display_client_) host_display_client_->SetActive(is_painting());
}
video_capturer_->Stop() / Start() 会停掉捕获,但网页照常渲染、定时器照常跑、音频照常播。is_painting() 还会把父 view 的状态算进去(子 widget 不能比父 view 更活跃)。
SetFrameRate(:893-913)有三条规则:
if (parent_host_view_) {
if (parent_host_view_->frame_rate() == this->frame_rate()) return;
frame_rate_ = parent_host_view_->frame_rate();
} else {
if (frame_rate <= 0) frame_rate = 1;
if (!offscreen_use_shared_texture_ && frame_rate > 240) frame_rate = 240;
frame_rate_ = frame_rate;
}
SetupFrameRate(true);
if (video_consumer_) video_consumer_->SetFrameRate(this->frame_rate());
for (auto* guest_host_view : guest_host_views_)
guest_host_view->SetFrameRate(frame_rate);
- 子 widget 的帧率强制等于父 view,自己传的值被忽略。
<= 0夹到 1(防止 19.3.4 的除零)。- 240 的上限只在非共享纹理模式生效;共享纹理模式下可以设更高(受帧池容量 10 反过来约束)。
- 传给
guest_host_views_递归下发。
SetupFrameRate 还改了合成器的 VSync 参数:
frame_rate_threshold_us_ = 1000000 / frame_rate_;
if (compositor_) {
compositor_->SetDisplayVSyncParameters(
base::TimeTicks::Now(), base::Microseconds(frame_rate_threshold_us_));
}
所以 setFrameRate 不只是限制捕获频率,它同时改了 Chromium 认为的显示器刷新间隔。requestAnimationFrame 的节奏、cc 的调度都会跟着变。SetupFrameRate(false) 的早退条件 frame_rate_threshold_us_ != 0 意味着它只在 ResizeRootLayer 里首次设置一次,之后要靠 SetFrameRate(true) 强制刷新。
invalidate() 在非离屏时是 window->Invalidate(),离屏时是 osr_rwhv->Invalidate() → InvalidateBounds(gfx::Rect(GetRequestedRendererSize())) → CompositeFrame(bounds)——用已有 backing 重新合成一帧并推给 JS,不产生新的捕获帧。这是"画面没变但我需要一帧"的正确做法。
19.3.9 popup / guest / proxy view 是手写 canvas 叠出来的
正常窗口里,下拉菜单、<select> 弹窗、BrowserView 之类的子视图由窗口系统或 Chromium 的 compositor 合成。离屏模式没有窗口系统,于是 CompositeFrame(osr_render_widget_host_view.cc:669-700)手工做:
SkBitmap frame;
// Optimize for the case when there is no popup
if (proxy_views_.empty() && !popup_host_view_) {
frame = GetBacking();
} else {
float sf = GetDeviceScaleFactor();
frame.allocN32Pixels(size_in_pixels.width(), size_in_pixels.height(), false);
if (!GetBacking().drawsNothing()) {
SkCanvas canvas(frame);
canvas.writePixels(GetBacking(), 0, 0);
if (popup_host_view_ && !popup_host_view_->GetBacking().drawsNothing()) {
gfx::Rect rect = popup_host_view_->popup_position_;
gfx::Point origin_in_pixels = gfx::ToFlooredPoint(
gfx::ConvertPointToPixels(rect.origin(), sf));
canvas.writePixels(popup_host_view_->GetBacking(),
origin_in_pixels.x(), origin_in_pixels.y());
}
for (auto* proxy_view : proxy_views_) { ... }
}
}
没有 popup 时走快路径,直接把 GetBacking() 交出去(零拷贝);有 popup 或 proxy view 时新建一张整尺寸位图,用 SkCanvas::writePixels 逐层写入,位置要乘 GetDeviceScaleFactor() 并 ToFlooredPoint。OnPaint 里还有一条 IsPopupWidget() && parent_callback_ 的分支,让 popup 只通知父 view 自己的位置而不独立推帧。
proxy_views_ 对应 OffscreenViewProxy(osr_view_proxy.cc:15-40),它把 views::View 的位图缓存起来,SetBitmap 只在尺寸完全一致时才接受并通知 observer:
void OffscreenViewProxy::SetBitmap(const SkBitmap& bitmap) {
if (view_bounds_.width() == bitmap.width() &&
view_bounds_.height() == bitmap.height() && observer_) {
view_bitmap_ = std::make_unique<SkBitmap>(bitmap);
observer_->OnProxyViewPaint(view_bounds_);
}
}
尺寸对不上就静默丢弃。这条与 19.3.6 的"共享纹理模式不做合成"连起来看,就明白为什么共享纹理模式下 widgetType 会同时出现 "popup" 和 "frame":每一层各自给一份纹理,合成责任完全在 JS/native 侧。
19.3.10 输入注入要自己处理 popup 命中
webContents.sendInputEvent()(electron_api_web_contents.cc:4496-4545)对离屏和非离屏走了不同分支:
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
}
键盘事件不走这个分支——IsKeyboardEventType 那一段无论是否离屏都直接 rwh->ForwardKeyboardEvent。只有鼠标与滚轮被重定向到 OffScreenRenderWidgetHostView,因为只有它们需要做坐标命中:
void OffScreenRenderWidgetHostView::SendMouseEvent(
const blink::WebMouseEvent& event) {
for (auto* proxy_view : proxy_views_) {
gfx::Rect bounds = proxy_view->bounds();
if (bounds.Contains(event.PositionInWidget().x(),
event.PositionInWidget().y())) {
blink::WebMouseEvent proxy_event(event);
proxy_event.SetPositionInWidget(
proxy_event.PositionInWidget().x() - bounds.x(),
proxy_event.PositionInWidget().y() - bounds.y());
ui::MouseEvent ui_event = UiMouseEventFromWebMouseEvent(proxy_event);
proxy_view->OnEvent(&ui_event);
return;
}
}
if (!IsPopupWidget()) {
if (popup_host_view_ &&
popup_host_view_->popup_position_.Contains(
event.PositionInWidget().x(), event.PositionInWidget().y())) {
// ... 坐标减去 popup_position_ 后转给 popup_host_view_
popup_host_view_->ProcessMouseEvent(popup_event, ui::LatencyInfo());
return;
}
}
if (!render_widget_host_) return;
render_widget_host_->ForwardMouseEvent(event);
}
顺序是 proxy view → popup → 主 frame,命中即返回,坐标每次减去该层的原点。19.3.9 里合成时把这些层画在偏移位置,这里注入时做反向变换,两边必须严格对称。
键盘事件那段还留了一条兼容补丁:
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
非离屏模式的滚轮事件还有一处 Chromium quirk 补丁(:4534-4541):必须带 phase 信息否则会 DCHECK,于是发一个 kPhaseBegan 的阻塞事件,再补一个合成的 phaseEnded 结束滚动。离屏模式用 SendMouseWheelEvent 绕开了这段。
19.3.11 screen 信息与 HDR
GetNewScreenInfosForUpdate(osr_render_widget_host_view.cc:945-965)造了一份假的显示器信息:
display::ScreenInfo screen_info;
screen_info.depth = 24;
screen_info.depth_per_component = 8;
screen_info.orientation_angle = 0;
screen_info.orientation_type =
display::mojom::ScreenOrientation::kLandscapePrimary;
screen_info.rect = gfx::Rect(size_);
screen_info.available_rect = gfx::Rect(size_);
screen_info.device_scale_factor = offscreen_device_scale_factor_;
if (offscreen_use_shared_texture_ &&
offscreen_shared_texture_pixel_format_ == "rgbaf16") {
gfx::DisplayColorSpaces hdr_display_color_spaces{
gfx::ColorSpace::CreateSRGBLinear(), viz::SinglePlaneFormat::kRGBA_F16};
// The max luminance value doesn't matter so we set to a large value.
hdr_display_color_spaces.SetHDRMaxLuminanceRelative(100.0f);
screen_info.display_color_spaces = hdr_display_color_spaces;
}
四个后果:
rect和available_rect都等于视图尺寸,所以离屏页面里的window.screen.width/height、screen.availWidth/availHeight报的是虚拟视图大小,不是物理显示器。window.innerWidth与screen.width相等,媒体查询里基于屏幕尺寸的分支会与真实桌面不一致。deviceScaleFactor来自offscreen.deviceScaleFactor,与screen模块(第 18 章)给的真实显示器 DPI 无关,而且CapturePage的注释特别提到它可以小于 1。orientation恒为横向主方向,旋转显示器不会反映到离屏页面。- 只有
rgbaf16+ 共享纹理才注入 HDR color spaces,且HDRMaxLuminanceRelative写死100.0(注释说"值不重要,设大一点")。想拿 HDR 输出必须两个条件同时满足。
19.3.12 子窗口的 paint 归属:先绑 no-op,再重新绑定
window.open() 出来的新 WebContents 会经过 MaybeOverrideCreateParamsForNewWindow(electron_api_web_contents.cc:1592-1610)。这里有一个注释解释得很清楚的两步绑定:
if (is_offscreen) {
// Use a no-op callback here. The real OnPaint callback will be bound
// to the child WebContents in AddNewContents via SetCallback().
auto* view = new OffScreenWebContentsView(
false, offscreen_use_shared_texture_,
offscreen_shared_texture_pixel_format_,
offscreen_device_scale_factor_, base::DoNothing());
create_params->view = view;
create_params->delegate_view = view;
}
创建参数阶段先塞一个 base::DoNothing(),因为这时新的 WebContents 包装对象还不存在,没有 OnPaint 可绑。等 AddNewContents 里 CreateAndTake 造出 api_web_contents 之后再重绑(:1637-1643):
// Rebind the paint callback to the child WebContents. The
// OffScreenWebContentsView was initially created with the parent's OnPaint
// in MaybeOverrideCreateParamsForNewWindow, but the paint data
// belongs to the child.
if (auto* osr_view = api_web_contents->GetOffScreenWebContentsView()) {
osr_view->SetCallback(base::BindRepeating(&WebContents::OnPaint,
api_web_contents->GetWeakPtr()));
}
注释里"initially created with the parent's OnPaint"与代码里的 DoNothing() 略有出入(这是重构后注释没跟上),但意图明确:帧数据必须发到子 WebContents 的 paint 事件,不是父的。实际影响是:监听父 webContents 的 paint 收不到 window.open() 出来的窗口画面,要监听新窗口自己的 webContents。
还有两个构造细节:transparent 这里写死 false(子窗口不继承父的透明设置),offscreen_device_scale_factor_ 也是从父 WebContents 的成员拷贝过来的,子窗口 webPreferences 里若单独设了不同值不会生效。
19.4 capturePage() 与 beginFrameSubscription():同一表面的两种取法
19.4.1 capturePage() 的四个静默分支
WebContents::CapturePage(electron_api_web_contents.cc:4612-4656)是"截一帧"的标准入口,返回 Promise<NativeImage>。它前置了四个判断,其中三个是静默的:
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 || view->GetViewBounds().size().IsEmpty()) {
promise.Resolve(gfx::Image());
return handle;
}
if (!view->IsSurfaceAvailableForCopy()) {
promise.RejectWithErrorMessage(
"Current display surface not available for capture");
return handle;
}
...
}
逐条看:
- options 只在
args->Length() == 2时才被读。写成capturePage(rect, opts, extra)传三个参数,stayHidden/stayAwake会被完全忽略;写成capturePage(opts)(只传选项对象)时,gin::ConvertFromV8到gfx::Rect会失败,rect保持默认空矩形,选项同样读不到。这个 API 的参数个数是硬的。 - 没有 view 或尺寸为空 → resolve 一张空
gfx::Image(),不是 reject。JS 侧拿到一个isEmpty()为 true 的NativeImage,不检查就用会得到一张 0×0 的图。19.3.2里那个"没有宿主窗口尺寸就是 0"的离屏 WebContents 正好命中这条。 IsSurfaceAvailableForCopy()为 false 时 reject,错误串是固定的"Current display surface not available for capture"。窗口被最小化、合成器还没提交第一帧、GPU 进程重启期间都可能命中。rect为空(默认)时按全视图取,而且是gfx::Rect(rect.origin(), view_size)—— origin 仍取rect.origin(),只是尺寸换成视图尺寸。所以传一个{x: 10, y: 10, width: 0, height: 0}的矩形,实际取的是从(10,10)开始、大小为整个视图的区域,右侧和下方会越界。
尺寸换算那两行是 capturePage 与 OSR 唯一真正共享的认知(:4645-4651):
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// Capture at the view's own scale factor. Offscreen views render at
// |offscreen.deviceScaleFactor|, not the display's, and it may be below 1.
const gfx::Size bitmap_size =
gfx::ScaleToCeiledSize(view_size, view->GetDeviceScaleFactor());
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::TimeDelta(),
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
bitmap_size 用的是 view->GetDeviceScaleFactor(),不是 screen 模块报的显示器缩放。离屏模式下这个值是 offscreen.deviceScaleFactor,而且注释特意说 "it may be below 1"——可以小于 1,于是 1000×800 的视图可能产出 500×400 的图。传 rect 时 rect 的单位是 DIP,bitmap_size 是物理像素,两者不在同一坐标系。
19.4.2 stayHidden / stayAwake 到底改了什么
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake, /*is_activity=*/true);
这一句是理解窗口隐藏后截图失败的关键。Chromium 会统计"有多少个捕获得盯着这个 WebContents":计数为 0 时,隐藏窗口可能被降频、停止合成、甚至丢弃表面;计数大于 0 时保持合成。stayHidden 与 stayAwake 传的是这份计数的两个策略位——stayHidden 让窗口在捕获期间继续保持隐藏状态(不为了截图而显示出来),stayAwake 阻止页面进入节流/休眠。is_activity=true 把这次捕获算作用户活动。
返回值是 base::ScopedClosureRunner,被 std::move 进 OnCapturePageDone。它的析构就是 DecrementCapturerCount:只有当整个异步拷贝(含失败分支)走完,捕获计数才被释放。失败路径里还显式调了一次 RunAndReset():
if (!result.has_value()) {
promise.RejectWithErrorMessage(
CopyFromSurfaceErrorToString(result.error()));
capture_handle.RunAndReset();
return;
}
所以这两个选项不是"截图时的开关",而是贯穿整个异步拷贝生命周期的引用计数策略。写循环截图时,如果上一次的 promise 还没 settle 就发起下一次,计数会叠加;这本身不报错,但会让隐藏窗口一直保持合成。
OnCapturePageDone(:762-782)还有一处线程回投:
auto ui_task_runner = content::GetUIThreadTaskRunner({});
if (!ui_task_runner->RunsTasksInCurrentSequence()) {
ui_task_runner->PostTask(
FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle), result));
return;
}
CopyFromSurface 的回调可能来自 GPU 线程,而 gin_helper::Promise 必须在 UI 线程的 V8 isolate 上 resolve,所以整包(promise + capture_handle + result)被重新投递。注意 result 是按值捕获的,含一张 SkBitmap,这次跨线程投递会带一份引用(SkBitmap 内部引用计数,不是深拷贝)。
末尾那行注释有点名不副实:
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(result->bitmap));
capture_handle.RunAndReset();
注释说的是"启用透明度的 hack",但代码里已经只剩一次直接包装——hack 本身在重构中被移走,注释留了下来。实际行为就是 CopyFromSurface 给什么就交什么,透明度由表面的 alpha 决定,不在这里补。
19.4.3 beginFrameSubscription():另一套独立捕获器
electron_api_web_contents.cc:4558-4579 暴露了两个内部方法:
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(); }
frame_subscriber_ 是唯一一个(std::unique_ptr),再调一次 beginFrameSubscription 会直接替换掉旧的订阅,旧的 capturer 随之析构。它不是多播,也没有 isSubscribed()。
frame_subscriber.cc:148-162(197 行)几乎是 19.3.5 那段共享内存逻辑的复制版,连 FramePinner 与三条件越界校验都一模一样。差别在配置:
constexpr static int kMaxFrameRate = 30;
void FrameSubscriber::AttachToHost(content::RenderWidgetHost* host) {
host_ = host;
// The view can be null if the renderer process has crashed.
auto* rwhv = host_->GetView();
if (!rwhv) return;
gfx::Size size = GetRenderViewSize();
DCHECK(!size.IsEmpty());
video_capturer_ = rwhv->CreateVideoCapturer();
video_capturer_->SetResolutionConstraints(size, size, true);
video_capturer_->SetAutoThrottlingEnabled(false);
video_capturer_->SetMinSizeChangePeriod(base::TimeDelta());
video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB);
video_capturer_->SetMinCapturePeriod(base::Seconds(1) / kMaxFrameRate);
video_capturer_->Start(this, viz::mojom::BufferFormatPreference::kDefault);
}
与 OSR 的 OffScreenVideoConsumer 对比,四处关键差异:
FrameSubscriber | OffScreenVideoConsumer | |
|---|---|---|
| 帧率 | 写死 kMaxFrameRate = 30 | 由 setFrameRate() 控制(可到 240+) |
| 分辨率约束 | size, size, true — 锁死在创建时的尺寸 | 1×1 到 kMaxDimension,不约束 |
| 像素格式 | 恒 PIXEL_FORMAT_ARGB | 三种可选 |
| 动画锁 | 未动 | SetAnimationFpsLockIn(false, 1) |
尺寸变化的处理在 OnFrameCaptured 开头(:84-91):
gfx::Size size = GetRenderViewSize();
if (size != content_rect.size()) {
video_capturer_->SetResolutionConstraints(size, size, true);
video_capturer_->RequestRefreshFrame();
return;
}
尺寸不一致的那一帧被直接丢弃,重新设约束并请求刷新。所以窗口 resize 期间回调会短暂停顿,不会出现拉伸的中间帧——这正是 19.3.4 里 OSR 注释批评"会产生模糊输出"的那套做法,这里因为是一次性订阅、尺寸由调用方控制,反而保留了。
FrameSubscriber 还是 content::WebContentsObserver,会在 RenderFrameCreated(host_ 为空时重连)、RenderViewDeleted(匹配 widget 时断开)、PrimaryPageChanged(主帧换了就 DetachFromHost + AttachToHost)时自己重挂。也就是说导航不会让订阅失效,但每次重挂都会重新创建 capturer。
Done()(:168-190)里有一段必须留意的拷贝:
const SkBitmap& bitmap = only_dirty_
? SkBitmapOperations::CreateTiledBitmap(
frame, damage.x(), damage.y(), damage.width(), damage.height())
: frame;
// Copying SkBitmap does not copy the internal pixels, we have to manually
// allocate and write pixels otherwise crash may happen when the original
// frame is modified.
SkBitmap copy;
copy.allocPixels(SkImageInfo::Make(bitmap.width(), bitmap.height(),
kN32_SkColorType, kPremul_SkAlphaType));
SkPixmap pixmap;
bool success = bitmap.peekPixels(&pixmap) && copy.writePixels(pixmap, 0, 0);
CHECK(success);
callback_.Run(gfx::Image::CreateFrom1xBitmap(copy), damage);
SkBitmap 的"拷贝"是浅拷贝,共享像素存储;而底层是 capturer 会回收的共享内存,所以这里手工分配并 writePixels 一次,否则原始帧被改写时就会崩。only_dirty=true 时用 CreateTiledBitmap 把脏矩形那块裁出来,回调的第二个参数 damage 是脏矩形。注意 CHECK(success) ——分配失败会直接终止进程,不是抛 JS 异常。
19.4.4 三条"取合成表面"路径的选择
| 需求 | 用哪个 | 代价 |
|---|---|---|
| 一次截图 | capturePage([rect], opts) | 一次 CopyFromSurface,自带捕获计数生命周期 |
| 持续帧流、要用 JS 处理像素 | OSR 共享内存模式 | 换掉整个 view 实现,paint 事件持续推 NativeImage |
| 持续帧流、要喂给 GPU | OSR useSharedTexture | 需要自己 release()、自己合成 popup、自己导入句柄 |
| 持续帧流但不想改成离屏窗口 | beginFrameSubscription(onlyDirty, cb) | 30fps 上限、恒 ARGB、导航时重挂、只有一个订阅 |
最后一行是最容易被忽略的:beginFrameSubscription 可以在普通可见窗口上用,它不需要 offscreen: true。反过来,OSR 的 paint 事件与 frame_subscriber_ 是两个各自独立的 FrameSinkVideoCapturer,同时开启会创建两个 capturer 抢同一个 frame sink。
19.5 desktopCapturer:枚举操作系统,不是枚举 Chromium
19.5.1 TS 包装层的四件事
desktop-capturer.ts 只有 102 行,却决定了四个可观察行为:
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
let currentlyRunning: { options; getSources }[] = [];
function isValid(options) {
return Array.isArray(options?.types);
}
export async function getSources(args) {
if (!isValid(args)) throw new Error('Invalid options');
const captureWindow = args.types.includes('window');
const captureScreen = args.types.includes('screen');
const { thumbnailSize = { width: 150, height: 150 } } = args;
const { fetchWindowIcons = false } = args;
const options = { captureWindow, captureScreen, thumbnailSize, fetchWindowIcons };
for (const running of currentlyRunning) {
if (deepEqual(running.options, options)) return running.getSources;
}
...
}
isValid只检查types是不是数组。types: []完全合法,两个布尔都是 false,C++ 侧pending_lists_ == 0立刻HandleSuccess(),返回一个空数组。types: ['unknown']也一样——不报错,静默给空结果。- 缩略图默认
150×150。这个尺寸不是"上限",是传给NativeDesktopMediaList::SetThumbnailSize的目标尺寸,会影响枚举耗时。 - 相同参数的并发请求被合并,返回同一个 promise。判等用
JSON.stringify,所以{thumbnailSize:{width:150,height:150}}与{thumbnailSize:{height:150,width:150}}会因为键顺序不同而判为不同请求——deepEqual对键顺序敏感。 stopRunning()里删掉_onerror/_onfinished并把capturer置 null,然后从currentlyRunning里按running.options !== options过滤。注意过滤用的是对象引用,不是deepEqual;因为options是本次调用新建的对象,只有本次登记的那条会被移除。
mac 上还有一段 hack(:24-32):
// Fix for bug in ScreenCaptureKit that modifies a window's styleMask the first time
// it captures a non-resizable window. We record each non-resizable window's styleMask,
// and we restore modified styleMasks later, after the screen capture.
if (process.platform === 'darwin') {
for (const win of BaseWindow.getAllWindows()) {
resizableValues.set(win.id, win.resizable);
}
}
它在枚举之前记录所有窗口的 resizable,在 stopRunning() 里把变过的值改回去。也就是说 macOS 上调用 getSources() 有可能短暂改变本应用窗口的 styleMask,Electron 用一次事后恢复来兜。这条只在 stopRunning 里生效,如果 C++ 侧既不调 _onerror 也不调 _onfinished(见 19.5.7),恢复就不会发生。
19.5.2 两个 DesktopMediaList 与 pending_lists_
DesktopCapturer::StartHandling(electron_api_desktop_capturer.cc:329-428)是 C++ 侧的入口,签名与 TS 传的四个值一一对应。它先清状态:
captured_sources_.clear();
finished_ = false;
pending_lists_ = 0;
deadline_.Stop();
#if BUILDFLAG(IS_MAC)
if (!ui::TryPromptUserForScreenCapture()) {
HandleFailure();
return;
}
#endif
const bool need_thumbnails = !thumbnail_size.IsEmpty();
bool need_screen = capture_screen;
mac 上 TryPromptUserForScreenCapture() 失败会立即走 _onerror,此时 promise reject 的字符串是 "Failed to get sources."(19.5.7)。
窗口捕获那段有个平台特例值得单独看(:346-372):
if (capture_window) {
// Some capturers like PipeWire support a single capturer for both screens
// and windows. Use it if possible, treating both as window capture.
std::unique_ptr<ThumbnailCapturer> capturer;
bool use_generic = false;
if (capture_screen) {
auto desktop_capturer = webrtc::DesktopCapturer::CreateGenericCapturer(
content::desktop_capture::CreateDesktopCaptureOptions());
auto wrapper = desktop_capturer
? std::make_unique<DesktopCapturerWrapper>(
std::move(desktop_capturer))
: nullptr;
if (wrapper && wrapper->GetDelegatedSourceListController()) {
capturer = std::move(wrapper);
use_generic = true;
// Generic capturer handles both types as window capture.
need_screen = false;
}
}
if (!capturer) capturer = MakeWindowCapturer();
...
}
Wayland/PipeWire 上,一个 generic capturer 同时承担窗口和屏幕,于是 need_screen = false,只创建一个 kWindow 类型的 list,却把两类源都放进去。这直接影响 19.5.5 的 display_id 填充:走这条路时所有源都被当作 window source 收集,屏幕源的 display_id 会是空串。
两组 list 各自 StartUpdating(observer) 并 pending_lists_++。如果两个工厂都返回 nullptr:
if (pending_lists_ == 0) {
HandleSuccess();
return;
}
同步 resolve 空数组。TS 侧专门为此加了一条注释(Register in currentlyRunning BEFORE startHandling so that synchronous completion ... can properly clean up),这正是 19.5.1 里 currentlyRunning.push 必须放在 startHandling 之前的原因。
19.5.3 三秒超时与"所有缩略图都到齐才算 ready"
constexpr base::TimeDelta kDesktopCapturerReadyTimeout = base::Seconds(3);
const bool any_delegated =
(window_capturer_ && window_capturer_->IsSourceListDelegated()) ||
(screen_capturer_ && screen_capturer_->IsSourceListDelegated());
if (!any_delegated) {
deadline_.Start(FROM_HERE, kDesktopCapturerReadyTimeout,
base::BindOnce(&DesktopCapturer::OnReadyTimeout, WeakCallbackTarget()));
}
delegated source list(PipeWire 系统选择器)不设超时,因为要等用户在系统 UI 里选,3 秒显然不够。非 delegated 才有 3 秒上限。上面那行常量旁的注释解释了为什么需要给原生 capturer "a few refresh/capture cycles":
// Give native capturers a few refresh/capture cycles to populate the list
// before returning the current snapshot. This preserves the old behavior of
// making progress even when some sources never produce thumbnails (e.g., a
// password manager window that's marked as uncapturable).
ListObserver::IsReady()(:256-270)是超时的直接原因:
[[nodiscard]] bool IsReady() const {
if (!has_sources_) return false;
if (!need_thumbnails_) return true;
// are all the thumbnails ready?
for (int i = 0; i < list_->GetSourceCount(); ++i) {
if (list_->GetSource(i).thumbnail.isNull()) return false;
}
return true;
}
只要有任意一个源的缩略图还是空的,整个 list 就不 ready。注释里点名的"密码管理器窗口被标记为不可捕获"就是典型:它永远不出缩略图,于是 IsReady() 永远 false,只能等 3 秒超时。超时后 OnReadyTimeout 会对两个 list 都调 FinalizeList,把当时已有的源(包括没缩略图的)交出去:
void DesktopCapturer::FinalizeList(std::unique_ptr<ListObserver>& observer,
std::unique_ptr<DesktopMediaList>& list) {
CollectSourcesFrom(list.get());
if (finished_) return;
list.reset();
observer.reset();
if (--pending_lists_ == 0) HandleSuccess();
}
所以 getSources() 的耗时不是固定的:全都能截缩略图时可能几百毫秒就返回;有一个不可捕获窗口时固定 3 秒。need_thumbnails 为 false(thumbnailSize 为空)时不需要等缩略图,IsReady() 只要 has_sources_ 就返回 true,快得多——但 thumbnailSize 默认是 150×150,除非显式传 {width:0,height:0}。
MaybeNotifyReady 用 notified_ 保证只通知一次,并且是 PostTask 而不是直接调用:
if (!IsReady() || notified_) return;
notified_ = true;
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&DesktopCapturer::OnListReady, capturer_, list_type_));
delegated list 的两个事件被特殊处理:OnSourceAdded 里 if (!is_delegated_) has_sources_ = true;(系统选择器不走这个事件),OnDelegatedSourceListSelection 才置位;OnDelegatedSourceListDismissed 直接 PostTask 到 HandleFailure——用户取消系统选择器等于失败,promise reject,而不是返回空数组。
19.5.4 平台后端:四种工厂
MakeWindowCapturer / MakeScreenCapturer(:147-180)的差异:
| 平台 | 窗口 | 屏幕 | 备注 |
|---|---|---|---|
| macOS | ShouldUseThumbnailCapturerMac(kWindow) → CreateThumbnailCapturerMac(ScreenCaptureKit) | 同左,kScreen | 二者都传 web_contents=nullptr |
| 其他 | content::desktop_capture::CreateWindowCapturer | CreateScreenCapturer(..., for_snapshot=false) | 返回 nullptr 则整个 list 不建 |
| Wayland | CreateGenericCapturer + GetDelegatedSourceListController | 被合并进 window list | 见 19.5.2 |
| Windows | 同上 | 同上 | 另查 ScreenCapturerWinDirectx::IsSupported() 决定 using_directx_capturer_ |
Windows 那段(:334-341)还留了一行奇怪的注释:
if (content::desktop_capture::CreateDesktopCaptureOptions()
.allow_directx_capturer()) {
// DxgiDuplicatorController should be alive in this scope according to
// screen_capturer_win.cc.
auto duplicator = webrtc::DxgiDuplicatorController::Instance();
using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported();
}
duplicator 这个局部变量定义完就没再用,它的唯一作用是在这个作用域里保活单例,注释说明了原因。这是那种"删掉看着无害、实际会出问题"的代码。
mac 的系统选择器可用性判断单独在 electron_api_desktop_capturer_mac.mm:10-12:
bool DesktopCapturer::IsDisplayMediaSystemPickerAvailable() {
if (@available(macOS 15.0, *)) return true;
return false;
}
非 mac 的实现只有一行 return false(.cc:574-577)。这个绑定被 TS 层通过 process._linkedBinding('electron_browser_desktop_capturer') 直接导出为 isDisplayMediaSystemPickerAvailable()。
19.5.5 display_id 是三套独立映射拼出来的
CollectSourcesFrom(DesktopMediaList*)(:447-521)对 window source 只填 display_id = "";对 screen source 才做映射,而且三个平台互不相干:
Windows(仅 using_directx_capturer_ 时):
std::vector<std::string> device_names;
// Crucially, this list of device names will be in the same order as
// |screen_sources|.
if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames(
&device_names)) {
HandleFailure();
return;
}
DCHECK_EQ(device_names.size(), screen_sources.size());
先用 EnumDisplayMonitors 收集 HMONITOR,GetMonitorInfo 拿到 szDevice,用 DisplayInfo::DisplayIdFromMonitorInfo 建 device_name → id 表,再按 device_names 的顺序给每个 source 赋值。依赖"两个列表顺序一致"这个隐含契约,DCHECK_EQ 只在 debug 构建里守着。不用 DirectX capturer 时注释说 "the IDs across the APIs already match",所以不映射、display_id 留空(但仍能与 screen API 的 id 对上,因为源头相同)。
macOS:source.display_id = base::NumberToString(source.media_list_source.id.id),"On Mac, the IDs across the APIs match"。
X11:最复杂。文件开头(:58-145)私有复制了 Chromium ui/base/x/x11_display_util.cc 里没导出的 GetMonitors / GetEDIDProperty,然后 MonitorAtomIdToDisplayId() 用 XRandR 的 GetScreenResourcesCurrent → GetOutputInfo → GetCrtcInfo → EdidParser 建一张 monitor name atom → display id 表:
// Note this isn't the atom string, but the numeric atom identifier,
// since this is what the WebRTC system uses as the display identifier
auto output_monitor_iter = output_to_monitor.find(output_id);
if (output_monitor_iter != output_to_monitor.end()) {
x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name;
monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id;
}
若 EDID 解析不出 id,回退成循环下标 i;XRandR 版本低于 1.5 时 GetMonitors 返回空表,所有 display_id 都为空。
Wayland:没有对应分支(#elif BUILDFLAG(SUPPORTS_OZONE_X11) 不成立),display_id 恒为空串。所以依赖 display_id 把 desktopCapturer 的源和 screen.getAllDisplays() 对应起来的代码,在 Wayland 上必然失效——这是第 18 章 screen 模块那条"Wayland 上 getCursorScreenPoint() 恒返回 (0,0)"的同类限制。
19.5.6 源对象的形状由 gin converter 固定
electron_api_desktop_capturer.cc:207-228:
template <>
struct Converter<electron::api::DesktopCapturer::Source> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const Source& source) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
content::DesktopMediaID id = source.media_list_source.id;
dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name));
dict.Set("id", id.ToString());
dict.Set("thumbnail", electron::api::NativeImage::Create(
isolate, gfx::Image(source.media_list_source.thumbnail)));
dict.Set("display_id", source.display_id);
if (source.fetch_icon) {
dict.Set("appIcon", electron::api::NativeImage::Create(
isolate, gfx::Image(GetWindowIcon(source.media_list_source.id))));
} else {
dict.Set("appIcon", nullptr);
}
return ConvertToV8(isolate, dict);
}
};
id是DesktopMediaID::ToString()的结果,形如screen:123:0/window:456:0。这不是数字,直接拿去parseInt会得到NaN。这个字符串正是后面getUserMedia用的chromeMediaSourceId。thumbnail恒存在,即使缩略图还没到(19.5.3 超时路径)也是一张空NativeImage,不是 undefined。用之前要isEmpty()。appIcon恒存在;fetchWindowIcons: false(默认)时是null。而且fetch_icon只在CollectSourcesFrom的 window 分支里被设为fetch_window_icons_,screen source 的构造是screen_sources.emplace_back(list->GetSource(i), std::string()),第三个参数用默认false——所以屏幕源永远没有 appIcon,即使开了fetchWindowIcons。name从 UTF-16 转 UTF-8,窗口标题里的非 BMP 字符按平台转换规则处理。
19.5.7 SelfKeepAlive 与两条终结路径
DesktopCapturer 有一个 gin_helper::SelfKeepAlive<DesktopCapturer> keep_alive_{this}(.h:86),和第 18 章 Tray 是同一个套路:对象创建后自己持有自己,不会被 GC。它只在两条路径里被释放:
void DesktopCapturer::HandleSuccess() {
if (finished_) return;
finished_ = true;
deadline_.Stop();
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
gin_helper::CallMethod(this, "_onfinished", captured_sources_);
screen_capturer_.reset(); window_capturer_.reset();
window_observer_.reset(); screen_observer_.reset();
keep_alive_.Clear();
}
void DesktopCapturer::HandleFailure() {
if (finished_) return;
finished_ = true;
deadline_.Stop();
...
gin_helper::CallMethod(this, "_onerror", "Failed to get sources.");
...
keep_alive_.Clear();
}
顺序是 先调 JS 回调,再 reset 原生资源,最后 keep_alive_.Clear()。如果在 _onfinished 里同步抛异常,keep_alive_.Clear() 就不会执行,这个 DesktopCapturer 会永久存活并一直持有已经 reset 的资源。TS 层的 _onfinished 是 stopRunning() + resolveGetSources(),不会抛;但通过 _linkedBinding 直接调 createDesktopCapturer() 自己挂回调的代码要留意。
finished_ 与 deadline_.Stop() 让三条终结路径(两个 list 都 ready、3 秒超时、mac 权限失败 / 用户取消 delegated 选择器)互斥。错误消息只有一种:"Failed to get sources."——所有失败原因都被折叠成同一句话,包括"没有屏幕录制权限""没有 D-Bus 会话""用户在系统选择器里点了取消""DXGI 拿不到 device names"。排查时只能靠日志和平台判断,不能靠 reject reason。
WeakCallbackTarget() 用的是 cppgc::Persistent<gin::WeakCell<DesktopCapturer>>,所有 PostTask 都绑在 weak cell 上,因此 deadline_ 的回调不会在对象已被回收后触发 UAF(虽然 SelfKeepAlive 正常情况下保证它不被回收)。
19.5.8 与 getUserMedia 的接缝:一个假 id
desktopCapturer 只给源列表,视频流由 renderer 的 getUserMedia 建立。连接两者的通常是 session.setDisplayMediaRequestHandler()。session.ts:45-55:
Session.prototype.setDisplayMediaRequestHandler = function (handler, opts) {
if (!handler) return this._setDisplayMediaRequestHandler(handler, opts);
this._setDisplayMediaRequestHandler(async (req, callback) => {
if (opts && opts.useSystemPicker && isDisplayMediaSystemPickerAvailable()) {
return callback({ video: systemPickerVideoSource });
}
return handler(req, callback);
}, opts);
};
systemPickerVideoSource 是 TS 层凭空造的一个对象(:13-24):
session.ts:12-19
// Fake video window that activates the native system picker
// This is used to get around the need for a screen/window
// id in Chrome's desktopCapturer.
let fakeVideoWindowId = -1;
// See content/public/browser/desktop_media_id.h
const kMacOsNativePickerId = -4;
const systemPickerVideoSource = Object.create(null);
Object.defineProperty(systemPickerVideoSource, 'id', {
get() {
return `window:${kMacOsNativePickerId}:${fakeVideoWindowId--}`;
}
});
systemPickerVideoSource.name = '';
Object.freeze(systemPickerVideoSource);
三层细节:
id是个 getter,每读一次返回不同的字符串(fakeVideoWindowId--从 -1 递减)。这是为了避免 Chromium 缓存同一个 source id。对象本身被Object.freeze,但 getter 每次仍返回新值。- 常量
-4对应DesktopMediaID里的 macOS 原生选择器窗口类型,注释指向content/public/browser/desktop_media_id.h。 Object.create(null)让它没有原型,name是空串。Chromium 只读取id,其余字段只是为了满足形状要求而存在。
也就是说 useSystemPicker: true 在支持的平台(macOS 15+)上完全绕过 desktopCapturer.getSources(),直接把一个"激活系统选择器的假窗口 id"塞给 Chromium。在不支持的平台上 isDisplayMediaSystemPickerAvailable() 返回 false,选项被忽略,仍然走用户 handler——不会报错、不会降级提示。
19.5.9 这条链上的四个静默失败点
把 19.5 全节收拢成排查清单:
| 现象 | 真实原因 | 位置 |
|---|---|---|
| 返回空数组,很快 | types 不含 window/screen,或所有 capturer 工厂返回 nullptr | .ts:17, .cc:415-419 |
| 恰好耗 3 秒 | 某个源的缩略图永远不就绪(不可捕获窗口),走 OnReadyTimeout | .cc:196, .cc:429-444 |
reject "Failed to get sources." | mac 权限被拒 / 用户取消系统选择器 / Win DXGI 取 device names 失败 | .cc:340, .cc:280, .cc:474 |
display_id 为空 | Wayland、X11 旧版 RandR、Win 非 DirectX 路径,或该源是 window | .cc:447-521 |
appIcon 恒为 null | 没开 fetchWindowIcons,或源是 screen | .cc:222-227 |
| 系统选择器没出现 | 平台不支持(非 macOS 15+),选项被静默忽略 | session.ts:49 |
19.5.10 对象模型:SelfKeepAlive 与 WeakCell 同时存在
DesktopCapturer 是这一章里唯一一个完整走 cppgc 对象模型的类,把它和第 18 章的 Tray 放在一起看,能看清 Electron 对"异步任务型对象"的生命周期策略:
class DesktopCapturer final : public gin::Wrappable<DesktopCapturer> {
public:
static DesktopCapturer* Create(v8::Isolate* isolate);
...
void Trace(cppgc::Visitor* visitor) const override;
const gin::WrapperInfo* wrapper_info() const override;
...
private:
cppgc::Persistent<gin::WeakCell<DesktopCapturer>> WeakCallbackTarget();
std::unique_ptr<ListObserver> window_observer_;
std::unique_ptr<ListObserver> screen_observer_;
...
gin_helper::SelfKeepAlive<DesktopCapturer> keep_alive_{this};
gin::WeakCellFactory<DesktopCapturer> weak_factory_{this};
};
创建方式不是 new,是(.cc:566-569):
DesktopCapturer* DesktopCapturer::Create(v8::Isolate* isolate) {
return cppgc::MakeGarbageCollected<DesktopCapturer>(
isolate->GetCppHeap()->GetAllocationHandle());
}
kWrapperInfo 用 MakeWrapperInfo(kElectronDesktopCapturer),GetHumanReadableName() 返回 "Electron / DesktopCapturer"。GetObjectTemplateBuilder 只加了一个方法:
return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate)
.SetMethod("startHandling", &DesktopCapturer::StartHandling);
_onerror / _onfinished 根本不是 C++ 方法,是 desktop-capturer.ts:72-89 直接往包装对象上赋的 JS 属性;C++ 侧用 gin_helper::CallMethod(this, "_onfinished", captured_sources_) 反射调用它们。所以通过 _linkedBinding 直接 createDesktopCapturer() 却忘记挂这两个属性的代码,会走到 CallMethod 找不到方法而什么都不发生——keep_alive_.Clear() 仍会执行,但 promise 永远不 settle。
Trace 只追一件事:
void DesktopCapturer::Trace(cppgc::Visitor* visitor) const {
gin::Wrappable<DesktopCapturer>::Trace(visitor);
visitor->Trace(weak_factory_);
}
WeakCallbackTarget() 返回 gin::WrapPersistent(weak_factory_.GetWeakCell(...)),ListObserver 持有一份 cppgc::Persistent<gin::WeakCell<DesktopCapturer>>,所有 PostTask(MaybeNotifyReady、OnReadyTimeout、HandleFailure)都绑在这个 weak cell 上。于是形成一条看起来循环、实际不阻止回收的引用:DesktopCapturer → unique_ptr<ListObserver> → Persistent<WeakCell<...>> → DesktopCapturer。真正让它活着的是 SelfKeepAlive,weak cell 只负责"如果它已经不在了,回调就别执行"。
与第 18 章 Tray 的对照很清楚:
Tray | DesktopCapturer | |
|---|---|---|
SelfKeepAlive | 有 | 有 |
何时 Clear() | 从不,必须显式 destroy() | HandleSuccess / HandleFailure 里自动 |
| 生命周期 | 与图标同在,直到用户销毁 | 与一次枚举同在,异步结束即释放 |
| 弱引用 | 无 | WeakCellFactory + ListObserver 的 Persistent<WeakCell> |
也就是说,DesktopCapturer 是"自己保活到任务结束、然后自己放手"的模板,而 Tray 是"自己永远保活"的模板。gin_helper::SelfKeepAlive 同一个类,两种用法,区别只在 Clear() 放在哪。识别出这个模式,第 18 章那些"对象为什么没被 GC"的问题和本章"异步枚举期间对象为什么不会消失"的问题就是同一件事。
19.6 对照与常见误解
19.6.1 六条通路逐项对照
把本章全部 API 摊在同一张表上,重点看单位、像素来源、并发模型、失败形态这四列——绝大多数踩坑都出在这四项上:
print() | printToPDF() | capturePage() | OSR paint | beginFrameSubscription | desktopCapturer | |
|---|---|---|---|---|---|---|
| 像素来源 | renderer 重新排版 | renderer 重新排版 | CopyFromSurface | FrameSinkVideoCapturer | 独立 FrameSinkVideoCapturer | 操作系统 / webrtc |
| 取帧时机 | 调用时同步取 rfh | 作业启动时取 rfh | 调用时 | 合成器每帧 | 合成器每帧 | 枚举时 |
| 尺寸单位 | 微米 / 百分比缩放 | 英寸 / 0–2 缩放 | DIP → 乘 view DSF | 视图 DIP → offscreen.deviceScaleFactor | 视图 DIP × DSF | 缩略图 DIP |
| 默认纸张 | A4(297000×210000 µm) | Letter(8.5×11 in) | — | — | — | — |
| 输出 | 无(系统打印作业) | Buffer(拷贝一份) | NativeImage | NativeImage 或纹理句柄 | NativeImage | 源列表 + 缩略图 |
| 并发模型 | 无队列,直接 PrintNow | 按 frame tree 排队 | 每次独立,计数叠加 | 单流,持续 | 单一订阅,后者覆盖前者 | 同参请求合并 |
| 失败形态 | 回调 (false, reason) | rejected promise(或永久 pending) | resolve 空图 / reject 固定串 | 静默丢帧 | 静默丢帧 / CHECK | reject 一句话 |
| 是否受窗口可见性影响 | 否 | 否 | 是 | 是(靠 SetPainting) | 是 | 否 |
| 需要 GPU | 否 | 否 | 是(表面) | 部分(两条路径) | 是 | 视平台 |
"失败形态"那一列最值得记:六个 API 里只有 printToPDF() 全程用 rejected promise 表达失败,而它偏偏还有一个连 promise 都不 settle 的分支;其余五个要么静默、要么回调、要么给一句固定错误串。
19.6.2 十二个不报错的误解
每条都给出一个可验证的源码锚点,避免只列现象:
- "两个打印 API 的
pageSize可以互相抄" —— 不能。一个是微米(kStockMediaSizes,electron_api_web_contents.cc:495),一个是英寸(kPaperFormats,print_to_pdf.cc:52)。抄错的结果分别是"8 微米的纸,静默打不出来"和"8 英寸宽的 A4 变巨幅纸"。 - "
'A4'和'a4'都能用" —— 只有printToPDF()能(ToLowerASCII,print_to_pdf.cc:100);print()是stock.key == name精确比较,只认首字母大写的"A4"。而'Ledger'在print()的表里根本不存在。 - "
print()传{silent:false}与不传参数等价" —— 不等价。不传时走options.IsEmptyObject()短路,把完全空的settings交给 Chromium 补默认值(electron_api_web_contents.cc:4113);传了任何键就走那条把二十多个默认值显式写死的长路径。 - "
printToPDF()打的是调用那一刻的页面" —— 打的是队列轮到它时的帧与 URL。PrintToPDFFrame是Start()里才Run()的回调,GetPrintPagesParams的第一个参数是那时的GetLastCommittedURL()(print_to_pdf.cc:321,335)。头文件把这条列为正式语义。 - "
printToPDF()失败一定会 reject" —— 页面在生成期间被销毁时,Completion析构投递Finish(nullopt),而Finish注释写着// Dropped un-run: leave the promise unsettled, as before.(print_to_pdf.cc:373)。await会永久挂住,必须自己加超时。 - "
printToPDF()期间页面里还能window.print()" ——GetDefaultPrintSettings只要发现pdf_jobs_.size() > 0就返回空PrintParams并打日志"Scripted print is not supported"(print_view_manager_electron.cc:103-112)。页面收不到任何错误,打印对话框也不出现。 - "
useSharedTexture: true时paint的第二个参数还是位图" —— 是空NativeImage。OnFrameCaptured传callback_.Run(content_rect, {}, std::move(texture)),OffScreenRenderWidgetHostView::OnPaint见texture.has_value()直接透传并 return,WebContents::OnPaint仍无条件gfx::Image::CreateFrom1xBitmap(bitmap)包装那个空 bitmap。 - "共享纹理模式下 popup 会自动叠好" —— 不会。共享纹理分支跳过了
CompositeFrame,osr_paint_event.h:60写明// It is user's responsibility to compose popup widget textures.,要靠widgetType自己分层。 - "
sharedTexturePixelFormat写错会有提示" —— 不会。GetTargetPixelFormatFromOption对未识别字符串直接回落PIXEL_FORMAT_ARGB(osr_video_consumer.cc:32-33)。更糟的是开了nv12/rgbaf16却没开useSharedTexture:共享内存分支只接受 ARGB/ABGR,其余整帧丢弃,paint事件直接不再触发。 - "
--disable-gpu只是慢一点,OSR 行为不变" ——video_consumer_只在HardwareAccelerationEnabled()时创建;否则走OffScreenHostDisplayClient,SetPainting的if/else if决定了SetFrameRate对它无效,useSharedTexture也不产生纹理。 - "
capturePage()的选项怎么传都行" ——if (args && args->Length() == 2)(electron_api_web_contents.cc:4619)是硬判据;多传一个参数或只传选项对象,stayHidden/stayAwake都被忽略。而视图尺寸为空时它 resolve 一张空图,不是 reject。 - "
getSources()卡住是权限问题" —— 更常见的是ListObserver::IsReady()要求所有源的缩略图都非空,一个不可捕获窗口就能把整个 list 拖到 3 秒kDesktopCapturerReadyTimeout。而types: []、Wayland 上display_id为空、非 macOS 15+ 上useSystemPicker被忽略,全都是静默的。
19.6.3 三个平面,两种底座
这一章的六个 API 其实只落在三个平面上:
- 打印平面:
PrintViewManagerElectron(WebContentsUserData,一份一个)是唯一枢纽。print()通过它调PrintNow,printToPDF()通过它的pdf_jobs_cookie 集合把生成作业插进同一条 mojo 管线。两者都不是截图。 - 合成表面平面:
capturePage()用一次CopyFromSurface,OSR 与beginFrameSubscription()各自建一个FrameSinkVideoCapturer。后两者的共享内存帧处理代码几乎是逐行复制的(同样的FramePinner、同样的三条件越界校验),但配置不同:OSR 不锁分辨率、可设帧率、可选像素格式;subscriber 锁死创建时尺寸、30fps、恒 ARGB。共享纹理模式则完全跳出这个平面,改成传 GPU 句柄 + 帧池。 - 系统捕获平面:
desktopCapturer用的是 webrtc 的DesktopCapturer与NativeDesktopMediaList,和 Chromium 的渲染合成器没有半点关系。它只做枚举和缩略图,视频流的建立靠一个id字符串接到getUserMedia上;macOS 15+ 的系统选择器甚至用一个每次读取都变值的假window:-4:Nid 绕过了整个枚举过程。
两种底座指的是贯穿全章的两个 Chromium 机制:RenderFrameHost 的选择(GetRenderFrameHostToUse,打印与 PDF 都靠它,优先级是 PDF 子帧 > 有选中的焦点帧 > 主帧)和 FrameSinkVideoCapturer(所有持续取帧的场景都靠它)。Electron 自己写的东西反而不多:一份纸张表、一份参数校验器、一个按 frame tree 排队的调度器、一层 SkBitmap/纹理句柄到 V8 对象的转换,以及若干把 JS 旧语义逐字复刻下来的兼容代码。
19.7 小结
把 19.0 那三条判据再对照一遍,会发现本章所有"奇怪行为"都能归到同一句话:Electron 没有自己的渲染管线,它只是在 Chromium 已有的三条通道上插层,而每条通道都有自己独立的状态与生命周期。
打印通道的状态是 document_cookie 与 pdf_jobs_,所以两类打印会互相挤掉;合成表面通道的状态是 capturer 计数与帧池容量,所以 capturePage() 要用 ScopedClosureRunner 守着计数、共享纹理要显式 release();系统捕获通道的状态是 pending_lists_ 与 3 秒 deadline,所以一个不出缩略图的窗口能拖慢整个枚举。
由此得到三条可以直接用于工程的结论:
- 并发要按"底层状态"排队,不是按 JS 调用顺序。
printToPDF()自己实现了按 frame tree 串行的队列,但print()没有——两类打印撞在一起时,被牺牲的永远是页面的window.print()。capturePage()连发会让捕获计数叠加。需要并发时,用PdfQueue的思路在 JS 侧自己建一个队列。 - 所有"静默"都要显式兜底。
printToPDF()加超时、capturePage()检查isEmpty()、getSources()检查display_id是否为空、OSR 共享纹理检查event.texture并立刻release()、GetWindowIcon拿不到的appIcon判断null。本章至少有九处失败路径不产生任何 JS 异常。 - 平台和构建开关会换掉整条实现路径。
ENABLE_PRINTING关闭时三个打印 API 全部降级;--disable-gpu时 OSR 换后端;Wayland 时display_id与getCursorScreenPoint()同时失效;macOS 15 是系统选择器的分界线;Windows 的打印机驱动必须留在 UI 线程。写跨平台代码时,先确认自己走的是哪条分支,再谈参数怎么用。
下一章转向应用的生命周期后半段:自动更新、崩溃报告与 fuses。那里同样会看到"一个编译期开关换掉整条路径"的模式,只不过开关从 GPU 状态变成了打包时可以翻转的位。
19.8 本章源码落点索引
下列位置全部来自本仓库源码树,按实现层归集;每个
路径:行号指向该文件中与本章论述对应的声明或实现行,可逐条复核。
- 浏览器进程 C++ 层:
osr_web_contents_view_mac.mm:9 electron_api_web_contents_view.cc:38 electron_api_web_contents_view.h:17 print_view_manager_electron.h:21 electron_api_web_contents.h:61 electron_api_web_contents_impl.cc:19 electron_api_web_contents_mac.mm:16 inspectable_web_contents_view.cc:37 -
inspectable_web_contents_view.h:18 inspectable_web_contents_view_delegate.cc:10 inspectable_web_contents_view_delegate.h:15 electron_api_desktop_capturer.h:20 electron_api_web_view_manager.cc:19 osr_host_display_client.h:16 osr_host_display_client_mac.mm:14 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 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 -
inspectable_web_contents.cc:111 inspectable_web_contents.h:28 inspectable_web_contents_delegate.h:12 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 web_view_manager.cc:12 web_view_manager.h:14 - API 文档与类型:
web-contents-view.md:5 desktop-capturer.md:6 desktop-capturer-source.md:3 - JS 门面与运行时:
web-contents.ts:20 guest-view-manager.ts:15 screen.ts:3 - 其他相关位置:
api-web-contents-view.spec.ts:12 - shell 其余实现:
web_contents_utility.mojom:8