《Electron 45.2.3 内核解剖》第 18 章 原生 UI 集成:菜单、托盘、对话框、通知
第 17 章讲的是"请求怎么出去"。这一章讲相反的方向:操作系统的原生控件怎么被拉进一个 Chromium 窗口里。
18.0 三条铁律与八个模块
Electron 的原生 UI 有三条铁律。理解了这三条,后面所有"为什么这个设置不生效"的问题都能自己推。
铁律一:绑定方向是反的。 一般 GUI 框架里,原生控件是主体,JS 对象是它的包装;Electron 里反过来——JS 对象是主体,原生控件是它的一块附庸资源。构造顺序是"先有 JS 对象,构造时创建原生资源",销毁顺序是"JS 对象被回收 → 析构函数里释放原生资源"。这带来一个后果:你没法靠"把对象置空"来关掉一个原生控件,因为 GC 什么时候跑你不决定。所以 Tray 有 destroy(),Notification 有 close(),Menu 干脆没有销毁接口(它没有需要显式释放的原生资源)。
铁律二:每个模块的生命周期策略都不一样,而且没有统一约定。 同为"会创建原生资源的 JS 包装",Tray 用 SelfKeepAlive<Tray> 让自己永不回收(直到 destroy()),Tray 的 Menu 用 SelfKeepAlive<Menu> keep_alive_{nullptr} 只在菜单打开期间钉住自己,Notification 用一个 gin::PerIsolateData::DisposeObserver 在 isolate 销毁前主动断开平台回调。三种策略,三种"什么时候会泄漏/什么时候会崩"的答案。
铁律三:平台三分,而且分法不统一。 有的模块按 IS_MAC/IS_WIN/IS_LINUX 分三个 .cc(dialog、message box),有的按"Windows vs 其它"分(tray 的 HICON),有的按"macOS 原生 vs views 自绘"分(menu 的 MenuMac / MenuViews)。同一个概念在三个平台上可能是完全不同的实现路径——Menu 在 macOS 上是 NSMenu,在 Windows 和 Linux 上是 Chromium 的 views::MenuRunner 自绘的窗口。
下面这张表是本章要讲的八个模块,以及它们的原生对象是什么、由谁持有。
| 模块 | 原生对象 | JS 对象的生命周期 |
|---|---|---|
Menu | NSMenu(mac)/ views::MenuRunner(Win/Linux) | 应用菜单被 cppgc::Persistent 钉死;弹出菜单只在打开期间钉住 |
MenuItem | 没有原生对象,只是 ElectronMenuModel 里的一行 | 被 Menu 的 Entry 链表持有 |
Tray | StatusIcon(GTK / Windows / mac status item) | SelfKeepAlive,永不回收,直到 destroy() |
Notification | 平台 presenter 里的一条通知 | cppgc + delegate 里的弱引用 |
globalShortcut | ui::GlobalAcceleratorListener | 没有 JS 对象,模块级单例 |
dialog | NSOpenPanel / IFileDialog / GTK dialog | 没有 JS 对象,纯函数 |
clipboard | ui::Clipboard | 没有 JS 对象,纯函数 |
screen | display::Screen | 没有 JS 对象,纯函数 |
注意 MenuItem 那一行:"没有原生对象"。这是理解整个菜单子系统的钥匙——菜单项在原生侧不是对象,只是 model 里的一行数据。所以"改一个菜单项的 label 立刻生效"和"改它的 type 不生效"这两件事可以同时成立。
18.1 buildFromTemplate:一个被藏在菜单 API 里的排序器
打开 Menu.buildFromTemplate 的源码(electron_api_menu_template.cc:349-353,407 行),第一眼看到的不是"遍历数组创建菜单项",而是一个叫 TemplateSorter 的类,里面有 SortTopologically、AttemptToMergeAGroup、SortGroups、RemoveExtraSeparators。这不是过度设计——buildFromTemplate 支持的 before/after/beforeGroupContaining/afterGroupContaining 四个字段,本质上是一个带分组约束的偏序问题。
18.1.1 模板元素必须"有点像菜单项"
electron_api_menu_template.cc:349-353
v8::Local<v8::Value> value;
if (!array->Get(context, i).ToLocal(&value) || !value->IsObject() || value->IsNull()) {
thrower.ThrowTypeError(
"Invalid template for MenuItem: must have at least one of label, role or type");
return {};
}
三个入口条件:
- 元素必须存在。
array->HasOwnProperty(context, i)为假时跳过——所以稀疏数组里的空洞不会报错,直接消失。 - 元素必须是非 null 对象。
[null]和['text']都抛同一个错。 - 如果这个对象不是已经构造好的
MenuItem包装(MenuItem::FromV8失败),它必须带自己的label、role,或者type === 'separator',否则抛错。
第三条是最容易踩的:{ click: () => {} } 这种"只有回调没有标签"的项会被拒。文档没写这条,但错误信息写得很清楚——"must have at least one of label, role or type"。
IsArray 这里有一个细节值得记:
electron_api_menu_template.cc:49-52
bool IsArray(v8::Local<v8::Value> value) {
while (value->IsProxy())
value = value.As<v8::Proxy>()->GetTarget();
return value->IsArray();
}
它穿透 Proxy 找 target。所以 Menu.buildFromTemplate(new Proxy([...], {})) 是能过的。ArrayLength 也不是读真实的数组长度,而是读 length 属性(gin_helper::Dictionary(isolate, array).Get("length", &length))——所以类数组对象也能当模板用。
18.1.2 分隔符的两种身份
TemplateEntry::is_plain_separator() 的定义只有一行:
electron_api_menu_template.cc:35
bool is_plain_separator() const { return separator && !constrained; }
constrained 在 IdList 里被置位,条件是四个约束字段里任何一个在布尔意义上为真:
if (!dict.Get(key, &value)) return out;
if (value->BooleanValue(isolate_)) *constrained = true;
if (!IsArray(value)) return out;
这意味着一个带约束的分隔符不是分隔符。对比:
{ type: 'separator' } // is_plain_separator = true,会切分分组
{ type: 'separator', before: ['paste'] } // constrained = true,不切分,参与排序
{ type: 'separator', before: [] } // 空数组也是真值!constrained = true
第三行是最阴的:[] 是 truthy,所以 before: [] 让分隔符失去切分能力,同时又不提供任何约束。一个"看起来什么都没做"的空数组,改变了整个排序结果。
18.1.3 分组、合并、排序
SortMenuItems 的三步:
electron_api_menu_template.cc:254-261
std::vector<Group> groups(1);
for (EntryIndex i = 0; i < entries_.size(); ++i) {
if (entries_[i].is_plain_separator()) {
separators.push_back(i);
if (!groups.back().empty()) groups.emplace_back();
} else {
groups.back().push_back(i);
}
}
...
while (AttemptToMergeAGroup(groups)) {}
for (Group& group : groups) group = SortItemsInGroup(group);
groups = SortGroups(groups);
第一步按"纯分隔符"切组。第二步 AttemptToMergeAGroup 是个不动点循环:只要某个项的 before/after 指向的 id 落在别的组里,就把两个组合并,然后重新检查。也就是说 before: ['paste'] 这类跨组约束会吃掉它们之间的分隔符。
第三步 SortItemsInGroup 把组内的 before/after 变成有向边,跑拓扑排序:
electron_api_menu_template.cc:208-213
for (ValueIndex to_id : entries_[group[i]].before) {
if (std::optional<size_t> to = index_of(to_id))
edges[*to].push_back(i); // 目标在 i 之前 → 边 to → i
}
for (ValueIndex to_id : entries_[group[i]].after) {
if (std::optional<size_t> to = index_of(to_id))
edges[i].push_back(*to); // i 在目标之前 → 边 i → to
}
index_of 的注释是 "The last item with a given id wins"——它从后往前扫。所以模板里出现两个 id: 'x' 时,before: ['x'] 认的是后面那个。
SortTopologically 是标准 DFS,但它对环的处理不是报错,而是直接断开:
if (!marked[to]) { marked[to] = true; stack.emplace_back(to, 0); }
marked 在入栈时就置位,所以指向已标记节点的边被静默忽略。a: {after: 'b'}, b: {after: 'a'} 不会抛错,会得到某个稳定但无意义的顺序。这是本章第一个"静默失效"。
18.1.4 分隔符会被重排、增补、删除
排完序之后是拼装:
electron_api_menu_template.cc:275-282
for (size_t i = 0; i < groups.size(); ++i) {
if (i > 0 && !groups[i].empty()) {
if (next_separator < separators.size()) {
joined.push_back(separators[next_separator++]);
} else {
TemplateEntry e;
e.value = Push(make_separator());
e.separator = true;
entries_.push_back(std::move(e));
joined.push_back(entries_.size() - 1);
}
}
joined.insert(joined.end(), groups[i].begin(), groups[i].end());
}
模板里写的分隔符不是按原位置插入的,而是按"消费顺序"分配给组与组之间的缝隙。如果分组比模板里的分隔符多(因为合并/切分改变了组数),就凭空造新的分隔符。
接着 RemoveExtraSeparators 做两件事:折叠相邻分隔符,删掉首尾分隔符。
bool keep = e.hidden || !e.separator || i == 0 || !entries_[items[i - 1]].separator;
注意 e.hidden || 这个前缀——visible: false 的项永远不被当作分隔符处理。一个 {type:'separator', visible:false} 会占着位置、阻止相邻分隔符折叠,然后自己在渲染时因为不可见而不画。结果是两个本该折叠的分隔符都留下来,中间夹一个看不见的分隔符。
18.1.5 嵌套深度是 100
electron_api_menu_template.cc:327-332
static int depth = 0;
constexpr int kMaxDepth = 100;
if (depth >= kMaxDepth) {
thrower.ThrowRangeError("Menu template is nested too deeply");
return {};
}
base::AutoReset<int> depth_scope(&depth, depth + 1);
子菜单的模板是靠 MenuItem::Init 里再调一次 BuildFromTemplate 递归处理的(18.2.2),所以循环引用(a.submenu = b; b.submenu = a)会一路递归到 100 层然后抛 RangeError。这个保护是必要的,因为模板是 JS 对象,构造得出环太容易了。
18.2 Menu 与 MenuItem:两套状态,一条链表
Menu 内部有两套并行的数据结构(electron_api_menu.h:171-183):
std::unique_ptr<ElectronMenuModel> model_;
cppgc::Member<Menu> parent_;
cppgc::Member<Entry> first_entry_;
cppgc::Member<Entry> last_entry_;
v8::TracedReference<v8::Array> items_;
model_ 是给原生侧看的(ui::MenuModel 接口),first_entry_ 是一条 cppgc 侵入式链表,唯一作用是持有 MenuItem 的强引用。ItemAt(i) 走的是 model_->item_at(index),链表不参与索引。
为什么要两套?因为原生侧只认 ui::MenuModel*,而 Chromium 不会替你管理 MenuItem 的生命周期;同时 MenuItem 可能同时出现在多个菜单里(头文件注释原话:"an item may be in more than one menu"),所以不能用 unique_ptr。链表是"所有引用者的集合"。
18.2.1 ItemRef:type 和 commandId 被冻在插入那一刻
ElectronMenuModel::InsertItemAt 只有三行:
electron_menu_model.cc:39-42
void ElectronMenuModel::InsertItemAt(size_t index, Item* item) {
CHECK_LE(index, items_.size());
items_.insert(items_.begin() + index,
ItemRef{item, item->GetType(), item->GetCommandId()});
}
ItemRef 存了三个字段:item(指针)、type、command_id。后两个是值拷贝,是插入那一刻的快照。
而 model 的其它访问器全部是"穿透到活对象":
electron_menu_model.cc:130-133
std::u16string ElectronMenuModel::GetLabelAt(size_t index) const {
return ItemAt(index).GetLabel();
}
bool ElectronMenuModel::IsEnabledAt(size_t index) const {
return GetTypeAt(index) != TYPE_SEPARATOR && ItemAt(index).IsEnabled();
}
于是得到一张精确的"改了生效 / 改了不生效"表:
| 改什么 | 生效吗 | 为什么 |
|---|---|---|
item.label | 生效 | GetLabelAt 穿透到活对象 |
item.enabled | 生效 | IsEnabledAt 穿透(但还要看 type 快照) |
item.checked | 生效 | IsItemCheckedAt 用快照 type 判断是不是 CHECK/RADIO,再读活值 |
item.visible | 生效 | IsVisibleAt 穿透 |
item.icon | 生效 | GetIconAt 穿透 |
item.sublabel / toolTip | 生效 | 穿透 |
item.submenu | 生效 | GetSubmenuModelAt 穿透 |
item.type | 不生效 | GetTypeAt 返回快照 |
item.commandId | 不生效 | GetCommandIdAt 返回快照(而且 commandId 是只读属性) |
type 不生效这件事有一个连带后果:IsItemCheckedAt 用快照 type 判断"这个项该不该有勾",所以把一个已插入的 normal 项改成 checkbox 之后,即使把 checked 设成 true,原生菜单也不会画勾——因为 IsItemCheckedAt 看到快照 type 是 TYPE_COMMAND,直接返回 false。
想改类型只有一条路:造一个新的 MenuItem,插到同一位置。但 Menu 没有 remove 方法(FillObjectTemplate 里只有 insert/append/getMenuItemById/popup/closePopup/getItemCount/getIndexOfCommandId),所以"替换某一项"实际上是做不到的——只能重建整个 Menu 再 setApplicationMenu 或 setContextMenu。
18.2.2 MenuItem 的属性是 native data property,不是普通字段
MenuItem::FillInstanceTemplate(electron_api_menu_item.cc:674)用 DefineProperty 注册了十几个属性,全部走 SetNativeDataProperty:
template <MenuItem::Getter getter, MenuItem::Setter setter>
void MenuItem::DefineProperty(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ,
std::string_view name) {
if constexpr (setter == nullptr) {
templ->SetNativeDataProperty(gin::StringToSymbol(isolate, name), &GetterThunk<getter>, nullptr,
v8::Local<v8::Value>(),
static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete),
v8::SideEffectType::kHasNoSideEffect);
} else {
templ->SetNativeDataProperty(gin::StringToSymbol(isolate, name), &GetterThunk<getter>,
&SetterThunk<setter>, v8::Local<v8::Value>(), v8::DontDelete,
v8::SideEffectType::kHasNoSideEffect);
}
}
两个属性值:DontDelete(不可 delete)和 kHasNoSideEffect(优化器可以当它无副作用)。没有 v8::ReadOnly 以外的枚举标记,也就是说这些属性是不可枚举的——它们不出现在 Object.keys(item) 里,也不出现在 JSON.stringify(item) 里。
实际影响:console.log({...item}) 得不到菜单项内容,Object.assign({}, item) 得到空对象。要序列化只能显式取字段。
只读的七个:commandId、type、role、accelerator、submenu、menu、groupId、userAccelerator(userAccelerator 用 SetAccessorProperty,注释说明了原因:"An accessor rather than a data property so that inspecting an item does not evaluate it (on macOS it builds an NSMenu)")。可写的:label/sublabel/toolTip/accessibilityLabel/enabled/visible/checked/icon/click/acceleratorWorksWhenHidden/registerAccelerator,加上 macOS 的 sharingItem/badge。
18.2.3 id 不是字段,是被拷到包装对象上的普通 JS 属性
模板里写 { id: 'save', label: 'Save' },id 去了哪里?MenuItem::Init 开头这段:
electron_api_menu_item.cc:224-231
// Preserve extra fields specified by the app, without shadowing the item's own properties.
v8::Local<v8::Array> keys;
if (options_object->GetPropertyNames(context).ToLocal(&keys)) {
for (uint32_t i = 0, n = keys->Length(); i < n; ++i) {
v8::Local<v8::Value> key, value;
if (!keys->Get(context, i).ToLocal(&key) || !key->IsName() ||
wrapper->Has(context, key.As<v8::Name>()).FromMaybe(true)) {
continue;
}
if (options_object->Get(context, key).ToLocal(&value))
wrapper->Set(context, key, value).Check();
}
}
凡是模板里有、包装对象上还没有的键,都原样拷过去。所以 id、before、after、beforeGroupContaining、afterGroupContaining,以及任何你自己塞的字段({ label:'X', myData: 42 }),全部变成 MenuItem 包装对象上的普通属性。
这解释了三件事:
-
为什么
getMenuItemById用StrictEquals比较。Menu::FindItemById:if (!gin_helper::Dictionary(isolate, wrapper).Get("id", &item_id)) item_id = v8::Undefined(isolate); if (item_id->StrictEquals(id)) return wrapper;它读的是包装对象上的 JS 属性,不是 C++ 字段,所以
1和'1'是不同的 id,menu.getMenuItemById('1')找不到{id: 1}。 -
为什么
id的大小写敏感。它就是普通对象属性,没有任何归一化。 -
为什么
getMenuItemById是 O(n) 且会递归。它先线性扫本层,再对每个子菜单递归:for (size_t i = 0; i < GetItemCount(); ++i) { if (Menu* submenu = ItemAt(i)->submenu()) { v8::Local<v8::Value> found = submenu->FindItemById(isolate, id); if (!found->IsNull()) return found; } }深层菜单里频繁调用是纯浪费,缓存一下包装对象更好。
顺带说:id 的拷贝是浅拷贝。{ label:'X', payload: { a: 1 } } 之后改 payload.a 会反映到包装对象上,因为两个属性指向同一个对象。
18.2.4 click 有三种身份,参数顺序还不一样
MenuItem 里有三个和点击相关的成员(electron_api_menu_item.h:195-199):
// `click` from the options, the bound `item.click`, and a function the app
// assigned to `item.click` afterwards (which replaces the default action).
v8::TracedReference<v8::Value> user_click_;
v8::TracedReference<v8::Function> click_;
v8::TracedReference<v8::Value> replaced_click_;
三种身份对应三条代码路径:
身份一:模板里的 click,存在 user_click_。触发时走 CallClick:
void MenuItem::CallClick(v8::Isolate* isolate, v8::Local<v8::Value> window, v8::Local<v8::Value> event) {
...
v8::Local<v8::Value> argv[] = {wrapper, window, event};
std::ignore = click.As<v8::Function>()->Call(context, wrapper, std::size(argv), argv);
}
参数是 (menuItem, window, event)。
身份二:item.click 的 getter。第一次读 item.click 时,它懒创建一个 JS 函数,这个函数的内部实现是 ClickThunk:
electron_api_menu_item.cc:753-760
if (self->click_.IsEmpty()) {
v8::Local<v8::Object> wrapper;
v8::Local<v8::Function> click;
if (!self->GetWrapper(isolate).ToLocal(&wrapper) ||
!v8::Function::New(isolate->GetCurrentContext(), ClickThunk, wrapper, 3,
v8::ConstructorBehavior::kThrow).ToLocal(&click)) {
return v8::Undefined(isolate);
}
self->click_.Reset(isolate, click);
}
return self->click_.Get(isolate);
身份三:给 item.click 赋值。setter 写的是 replaced_click_,而 getter 第一行就检查它:
if (!self->replaced_click_.IsEmpty()) return self->replaced_click_.Get(isolate);
一旦你赋值,item.click 就变成你的函数,ClickThunk 那条路径彻底失效。
关键在于身份二的参数顺序和身份一不同。ClickThunk:
electron_api_menu_item.cc:576-579
void MenuItem::ClickThunk(const v8::FunctionCallbackInfo<v8::Value>& info) {
...
BaseWindow* window = BaseWindow::FromValue(isolate, info[1]);
...
if (!item->RunBuiltInAction(window, web_contents))
item->CallClick(isolate, info[1], info[0]);
}
它把 info[0] 当 event、info[1] 当 window、info[2] 当 webContents。而 CallClick 又把 info[1] 当 window、info[0] 当 event 传给身份一。所以:
// 模板里的 click:参数是 (menuItem, browserWindow, event)
{ label: 'X', click: (item, win, event) => {} }
// 事后赋值的 click:参数是 (event, focusedWindow, focusedWebContents)
item.click = (event, win, wc) => {};
// 手动调 item.click(...):它是个适配器,把参数转成身份一的形状
item.click(event, win, wc); // → 内部先跑内置动作,再调模板 click(item, win, event)
三种签名,一个属性名。任何"我写的 click 收到的东西不对"的困惑都是这个原因。
18.2.5 内置动作会吞掉你的 click
Activate 的分支是这样的:
electron_api_menu_item.cc:523-526
if (replaced_click_.IsEmpty()) {
if (!RunBuiltInAction(window, web_contents))
CallClick(isolate, window_value, CreateEventFromFlags(flags));
return;
}
而 RunBuiltInAction 的最后:
electron_api_menu_item.cc:544-551
bool MenuItem::RunBuiltInAction(BaseWindow* window, WebContents* web_contents) {
const bool computes_checked = role_ && role_->computes_checked();
if (!computes_checked && (type_ == Type::kCheckbox || type_ == Type::kRadio)) {
SetChecked(!checked_);
}
if (role_ && menu_roles::Execute(*role_, window, web_contents))
return true; // ← 内置动作执行了,返回 true
if (!user_click_.IsEmpty())
return false; // ← 有模板 click,交给它
#if BUILDFLAG(IS_MAC)
if (!selector_.empty())
Menu::SendActionToFirstResponder(selector_);
#endif
return true;
}
所以 { role: 'quit', click: fn } 的行为取决于平台:
- Windows / Linux:
Execute真的执行了Quit(),返回true,fn永远不会被调用。 - macOS:
Execute第一行就把非non_native_mac的 role 挡回去了(18.3.4),返回false,于是fn会被调用——同时原生菜单已经通过 NSResponder 链自己执行完退出了。
同一个菜单模板,同一个回调,两个平台一个调一个不调。想保证回调一定跑,就别给 role 配 click;想自己在 macOS 上接管,就干脆不写 role。
18.2.6 radio group 是自动分的,group id 是全局自增的
InsertItem 里这一段决定了单选组:
electron_api_menu.cc:218-221
int group_id = 0;
if (item->type() == MenuItem::Type::kRadio)
group_id = item->group_id() ? item->group_id() : GenerateGroupId(pos);
item->AttachToMenu(this, group_id);
GenerateGroupId(pos) 的规则是"跨过分隔符找邻居":
electron_api_menu.cc:149-156
int Menu::GenerateGroupId(int pos) {
static int next_group_id = 0;
if (pos > 0) {
for (int i = pos - 1; i >= 0; --i) {
if (ItemAt(i)->type() == MenuItem::Type::kRadio) return ItemAt(i)->group_id();
if (ItemAt(i)->type() == MenuItem::Type::kSeparator) break;
}
} else {
for (size_t i = 0; i < GetItemCount(); ++i) {
if (ItemAt(i)->type() == MenuItem::Type::kRadio) return ItemAt(i)->group_id();
if (ItemAt(i)->type() == MenuItem::Type::kSeparator) break;
}
}
return ++next_group_id;
}
三个后果:
- 两个 radio 之间没有分隔符,就属于同一组。想让两组 radio 独立,中间必须放分隔符——而且是"纯分隔符"(带
before/after的那种在 model 里仍然是TYPE_SEPARATOR,所以这里也能切断;这条判据和 18.1.2 的is_plain_separator不是一回事)。 - 插在组中间的 radio 会加入前面那组,因为它向前扫到的第一个 radio 是同组。
static int next_group_id是函数级静态变量,进程级、永不重置。组的 id 会一直涨。这本身无害(id 只是比较用的),但意味着你不能用 group id 做跨菜单重建的稳定标识——重建一次菜单,同一组 radio 拿到的是新 id。
MenuWillShow 里还有一段自动补勾:
if (!any_checked) item->SetCheckedForRadioGroup();
所以一个从来没设过 checked 的单选组,在菜单第一次弹出时会被自动勾上第一项。这解释了"我没设 checked,它怎么自己勾了一个"。
18.2.7 menu.items 是一份缓存,只在插入时失效
electron_api_menu.cc:245-249
v8::Local<v8::Value> Menu::Items(v8::Isolate* isolate) {
if (items_.IsEmpty()) {
... 重建数组 ...
items_.Reset(isolate, items);
}
return items_.Get(isolate);
}
只有 InsertItem 末尾会 items_.Reset()。因为 Menu 没有 remove 方法、也没有修改项的方法,所以这份缓存除了插入之外不会过期——但数组里的 MenuItem 包装对象是活的,改动它们会立刻反映。
items 在实例模板里被定义成只读、不可删的访问器(Menu::FillInstanceTemplate),注释写着 "An own, enumerable property so that a serialised menu includes it"。所以 JSON.stringify(menu) 能拿到 {"items": [null, null, ...]}——注意元素是 null,因为 MenuItem 的属性不可枚举,JSON.stringify 把它们当空对象处理不了就写 null。序列化菜单得自己写映射。
18.3 role 表:42 项,四个维度
electron_api_menu_roles.h:48-55 里的 Role 结构只有五个字段:
struct Role {
std::u16string Label() const;
bool computes_checked() const { return action == Action::kToggleSpellChecker; }
const char* id; // lower-case
const char* label; // nullptr when the label depends on the app name
const char* accelerator; // may be empty
Action action = Action::kNone;
bool register_accelerator = true;
// macOS handles all roles natively except for these.
bool non_native_mac = false;
};
kRoles 表里 42 个条目,全部靠位置初始化。举三行看它的含义:
electron_api_menu_roles.cc:57-59
{"copy", "Copy", "CommandOrControl+C", Action::kCopy, false},
{"reload", "Reload", "CmdOrCtrl+R", Action::kReload, true, true},
{"help", "Help", ""},
- 第一行第五个参数
false→register_accelerator = false。 - 第二行第五、第六个都是
true→ 注册加速键,并且 macOS 上不走原生。 - 第三行只有前三个 → action 是
kNone,register_accelerator是默认true。
数一下:42 项里 20 项有真实动作(about 只在 Win/Linux 有动作),4 项 register_accelerator = false(copy/cut/paste/pasteandmatchstyle),7 项 non_native_mac = true(reload/forcereload/resetzoom/zoomin/zoomout/toggledevtools/togglespellchecker)。剩下 22 项是纯占位(子菜单角色和 front/help/services 这类交给系统处理的)。
18.3.1 computes_checked() 只有一个成员返回 true
看结构体定义:computes_checked() 是 action == Action::kToggleSpellChecker。整个表里只有 togglespellchecker 一项。
为什么它特殊?因为它对应的勾选状态存在 session 的 prefs 里,不在 MenuItem 上:
electron_api_menu_roles.cc:272-276
bool IsChecked(const Role& role) {
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
if (role.action == Action::kToggleSpellChecker) {
return SpellcheckPrefs(WebContents::GetFocusedWebContents())
->GetBoolean(spellcheck::prefs::kSpellCheckEnable);
}
#endif
return false;
}
SpellcheckPrefs 优先取当前聚焦 webContents 所属 session 的 prefs,没有就退到默认 session。所以多 session 应用里,两个窗口可以有不同的勾选状态。
18.3.2 未知 role 静默降级成普通项
MenuItem::Init:
electron_api_menu_item.cc:237-240
if (options.Get("role", &role_name_)) {
role_name_ = base::ToLowerASCII(role_name_);
role_ = menu_roles::Find(role_name_);
has_role_ = true;
}
Find 是线性扫 42 项,找不到返回 nullptr。没有错误,没有警告。而 has_role_ = true 又让 item.role 属性返回你写的那个字符串(即使它不存在)。
后果链:role_ 为空 → ApplyRoleDefaults 里所有 if (role_ && ...) 全不成立 → type_ 保持 kNormal、label_ 为空、accelerator_ 为空 → 得到一个没有标签、没有快捷键、点了什么也不发生的空菜单项。在原生菜单里它表现为一条空白行。
role 的大小写是宽容的(ToLowerASCII),所以 role: 'ToggleDevTools' 能用;但拼写不容错,role: 'togglDevTools' 就是空行。
18.3.3 四个 register_accelerator: false 的 role
copy/cut/paste/pasteandmatchstyle 这四项的 registerAccelerator 是 false。意思是:菜单上显示 Cmd+C,但不把 Cmd+C 注册成菜单加速键。
为什么?因为 Cmd+C 在页面里必须由 Chromium 的编辑命令链处理(WebContents::Copy() 走的是 Blink 的 selection 复制路径),如果注册成菜单加速键,按键会被菜单吃掉,光标在 <input> 里的复制行为就变了。
这条设置体现在 GenerateAcceleratorTable:
accelerator_util.cc:81-84
if (model->ShouldRegisterAcceleratorAt(i)) {
if (model->GetAcceleratorAtWithParams(i, true, &accelerator)) {
MenuItem item = {i, model};
(*table)[accelerator] = item;
}
}
没注册的项不进这张表,所以窗口的 TriggerAcceleratorTableCommand 找不到它。但用户点菜单项时它照样工作——ActivatedAt 是另一条路。
反过来说:如果你自己写 { label:'Copy', accelerator:'CmdOrCtrl+C', click: fn },默认 registerAccelerator 是 true,Cmd+C 就真的被菜单抢走了。这是一个非常常见的"我加了个自定义复制菜单项,结果页面里的复制坏了"。
18.3.4 macOS:只有 7 个 role 走 C++
Execute 的第一行是整张表最反直觉的地方:
bool Execute(const Role& role, BaseWindow* focused_window, WebContents* focused_web_contents) {
if (role.action == Action::kNone || (kIsMac && !role.non_native_mac))
return false;
在 macOS 上,除那 7 个以外的所有 role 都在这里直接返回 false,一行动作都不做。它们靠的是 NSMenuItem 自己的 action 沿着 NSResponder 链往上走——quit 找到 NSApplication,copy 找到第一响应者的 copy:,close 找到 NSWindow。
那 7 个必须走 C++,因为它们要操作的是 Chromium 侧的 WebContents:reload、强制 reload、toggle devtools、reset zoom、zoom in/out、toggle spellchecker。NSResponder 链上没有人认识这些。
顺带解释了一个行为差异:role: 'reload' 在 macOS 上会调 DevToolsOwnerOr(wc)->Reload()——如果你焦点在 devtools 里,它刷新的是被调试的页面,不是 devtools。DevToolsOwnerOr 的实现就是遍历所有 WebContents,看谁的 GetOpenDevToolsWebContents() 等于传进来的这个:
electron_api_menu_roles.cc:138-142
WebContents* DevToolsOwnerOr(WebContents* web_contents) {
for (WebContents* candidate : WebContents::GetWebContentsList()) {
if (candidate->GetOpenDevToolsWebContents() == web_contents->web_contents())
return candidate;
}
return web_contents;
}
18.3.5 动态 label 与动态 enabled
Role::Label() 有四个 role 的标签是运行时拼的:
if (role == "about") return kIsLinux ? u"About" : base::UTF8ToUTF16("About " + name);
if (role == "hide") return base::UTF8ToUTF16("Hide " + name);
if (role == "quit") { if (kIsMac) return base::UTF8ToUTF16("Quit " + name);
return kIsWin ? u"Exit" : u"Quit"; }
if (role == "appmenu") return base::UTF8ToUTF16(name);
name 来自 Browser::Get()->GetName(),也就是 app.getName()。所以 app.setName('Foo') 之后重建菜单,"Quit" 变 "Quit Foo"(mac)/"Exit"(win)/"Quit"(linux)。注意 Linux 的 about 不带应用名,Windows 的 quit 是 "Exit"——这些差异全在这四行里。
IsEnabled 只有三个 role 会返回非空:
case Action::kMinimize: if (auto* w = FocusedNativeWindow()) return w->IsMinimizable();
case Action::kToggleFullScreen: if (auto* w = FocusedNativeWindow()) return w->IsFullScreenable();
case Action::kClose: if (auto* w = FocusedNativeWindow()) return w->IsClosable();
其余返回 nullopt,MenuItem::IsEnabled 再退回 enabled_ 字段:
electron_api_menu_item.cc:461-464
bool MenuItem::IsEnabled() const {
if (role_) {
if (std::optional<bool> enabled = menu_roles::IsEnabled(*role_)) return *enabled;
}
return enabled_;
}
所以 {role:'close'} 的菜单项在窗口不可关闭时(setClosable(false))会自动变灰,即使你写了 enabled: true——role 的判断优先。
18.4 加速键字符串的五个坑
accelerator_util::StringToAccelerator 只有 53 行,但它定义了所有加速键的行为。
18.4.1 只接受 ASCII
accelerator_util.cc:19-21
if (!base::IsStringASCII(shortcut)) {
LOG(ERROR) << "The accelerator string can only contain ASCII characters, invalid string: \"" << shortcut << "\"";
return false;
}
非 ASCII 直接失败,且只打日志、不抛异常。所以 accelerator: 'Ctrl+中' 静默无效——菜单项没有快捷键,也没有报错。
18.4.2 按 + 切分,空 token 被丢弃
accelerator_util.cc:27-28
const std::vector<std::string_view> tokens = base::SplitStringPiece(
shortcut, "+", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
SPLIT_WANT_NONEMPTY 意味着 "Ctrl++" 切成 ["Ctrl"],+ 键本身没了。所以键名叫 + 的键必须写成 Plus——这就是为什么 role 表里写的是 "CommandOrControl+Plus" 而不是 "CommandOrControl++"。
18.4.3 后一个非修饰键覆盖前一个
accelerator_util.cc:34-41
for (const std::string_view token : tokens) {
ui::KeyboardCode code = electron::KeyboardCodeFromStr(token, &shifted_char);
if (shifted_char) modifiers |= ui::EF_SHIFT_DOWN;
switch (code) {
case ui::VKEY_SHIFT: modifiers |= ui::EF_SHIFT_DOWN; break;
case ui::VKEY_CONTROL: modifiers |= ui::EF_CONTROL_DOWN; break;
case ui::VKEY_MENU: modifiers |= ui::EF_ALT_DOWN; break;
case ui::VKEY_COMMAND: modifiers |= ui::EF_COMMAND_DOWN; break;
case ui::VKEY_ALTGR: modifiers |= ui::EF_ALTGR_DOWN; break;
default: key = code;
}
}
default: key = code; 是覆盖不是"取第一个"。所以 'A+B' 的结果是 B,'F1+F2' 的结果是 F2。没有校验,没有警告。
18.4.4 需要 Shift 才能打出的字符会自动加 Shift
KeyboardCodeFromStr 对单字符走 KeyboardCodeFromCharCode,返回 (code, shifted_char) 二元组。比如 '!' 返回 (VKEY_1, '!'),'@' 返回 (VKEY_2, '@')。外层:
if (shifted_char) modifiers |= ui::EF_SHIFT_DOWN;
...
accelerator->shifted_char = shifted_char;
于是 'CmdOrCtrl+!' 等价于 'CmdOrCtrl+Shift+1',并且显示成后者的样子。这条规则让"用户按了什么"和"显示什么"保持一致,不用手写 Shift。
18.4.5 CmdOrCtrl 是解析期决定的,不是运行期
keyboard_util.cc:21-22 里:
#if BUILDFLAG(IS_MAC)
constexpr auto CommandOrControl = ui::VKEY_COMMAND;
#else
constexpr auto CommandOrControl = ui::VKEY_CONTROL;
#endif
编译期定的是"映射到哪个 VKEY",解析期把这个 VKEY 转成 EF_COMMAND_DOWN 或 EF_CONTROL_DOWN。ui::Accelerator 里存的是具体的修饰键,不是"CmdOrCtrl"这个抽象概念。所以:
- 同一个字符串
'CmdOrCtrl+S'在不同平台上解析成不同的ui::Accelerator,比较相等时不会互通。 accelerator_util::GenerateAcceleratorTable用的是std::map<ui::Accelerator, MenuItem>,键是具体修饰键,所以'Ctrl+S'和'CmdOrCtrl+S'在 macOS 上是两个不同的键(后者是 Command,前者是 Control)。- 想让某个键在三个平台都生效,必须写
'CmdOrCtrl+X',不能只写'Ctrl+X'——后者在 macOS 上真的就是 Control 键。
18.5 应用菜单与弹出菜单:两条完全不同的路
同一个 Menu 对象,用在两个地方:Menu.setApplicationMenu(menu) 和 menu.popup(options)。这两件事在原生侧几乎没有共同点。
18.5.1 setApplicationMenu 只有一个开关,但平台各走各的
electron_api_menu.cc:451-458
void Menu::ChangeApplicationMenu(Menu* menu) {
g_application_menu_was_set = true;
if (menu)
ApplicationMenu() = cppgc::Persistent<Menu>(menu);
else
ApplicationMenu().Clear();
#if BUILDFLAG(IS_MAC)
if (!menu)
return;
SetApplicationMenu(menu);
#else
std::vector<BaseWindow*> windows = BaseWindow::GetAllNative();
for (BaseWindow* window : windows) {
if (!BaseWindow::IsLive(window)) continue;
if (menu)
window->SetMenuNatively(menu);
else
window->RemoveMenu();
}
#endif
}
四个要点:
-
g_application_menu_was_set = true在判断 menu 是否为空之前就设了。所以Menu.setApplicationMenu(null)也会把"用户设置过"这个标记点亮——之后默认菜单就再也不会被装上了。 -
ApplicationMenu()是base::NoDestructor<cppgc::Persistent<Menu>>,进程级不析构。被设成应用菜单的Menu因此永不回收。 -
macOS 上
setApplicationMenu(null)不会移除主菜单。if (!menu) return;只是把Persistent清掉,NSApp.mainMenu还是原来那个。想在 mac 上换掉主菜单只能设一个新的,没有"取消"这条路径。 -
Win/Linux 上是逐窗口设置,而且注释写了原因:
// Setting a menu can run app JS (e.g. 'resize'), which can open or close // windows; iterate a copy.GetAllNative()返回副本,循环里再用IsLive挡一次,因为SetMenuNatively可能触发 JS,JS 可能关窗口。
SetMenuNatively 还藏着一条:
electron_api_base_window.cc:855-860
void BaseWindow::SetMenuNatively(Menu* menu) {
// We only want to update the menu if the menu has a non-zero item count,
// or we risk crashes.
if (menu->model()->GetItemCount() == 0) {
RemoveMenu();
} else {
window_->SetMenu(menu->model());
}
menu_ = menu;
}
空 Menu 等于没有菜单。win.setMenu(new Menu()) 不会得到一个空菜单栏,而是把菜单栏整个去掉。注释里的 "risk crashes" 说明这是防崩溃的补丁,不是设计。
18.5.2 macOS:真正安装被推迟到下一个 runloop
Menu::SetApplicationMenu 在 mac 上的实现不是直接 [NSApp setMainMenu:]:
electron_api_menu_mac.mm:327-334
void Menu::SetApplicationMenu(Menu* menu) {
ElectronApplicationMenuHolder* holder =
[[ElectronApplicationMenuHolder alloc] initWithMenu:menu];
// Install in the default run loop mode so the main menu is not swapped
// while a menu is open; the installed holder keeps its Menu alive till then.
NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];
if (g_pending_application_menu) {
[currentRunLoop cancelPerformSelectorsWithTarget:g_pending_application_menu];
}
g_pending_application_menu = holder;
[currentRunLoop performSelector:@selector(install) target:holder argument:nil
order:0 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
}
三个细节:
- 延迟安装。
performSelector:...modes:@[NSDefaultRunLoopMode]把安装排到当前 runloop 的下一次迭代。为什么?因为如果在菜单打开期间换主菜单,AppKit 会在菜单跟踪循环里拿到一个被换掉的NSMenu,行为未定义。 - 后一次取消前一次。连续调两次
setApplicationMenu,只有最后一次生效;前一次的 holder 被cancelPerformSelectorsWithTarget取消,然后被 ARC 释放。 ElectronApplicationMenuHolder存在的唯一理由是持有cppgc::Persistent<Menu>。注释写得很直白:"ElectronMenuController only holds a weak reference to the model"。也就是说:NSMenu的 delegate 持有的是ElectronMenuModel*的弱引用,而Menu对象(及其model_)靠 Objective-C 侧的 holder 钉住。如果 holder 被释放而NSMenu还活着,就会拿到一个悬空的 model 指针。
这条链解释了 mac 上一个容易困惑的现象:Menu.getApplicationMenu() 在新进程里可能返回 null,但屏幕上明明有菜单栏——因为默认菜单是在 will-finish-launching 之前由 InstallDefaultApplicationMenu 装的,而它走的是同一个 ChangeApplicationMenu,所以 GetApplicationMenu 应该能拿到。真正返回 null 的情况是:菜单已经 setApplicationMenu(null) 清掉了 Persistent,但 NSApp.mainMenu 还在(18.5.1 第 3 点)。
18.5.3 默认菜单的安装时机:will-finish-launching 之前
调用链是这样的:
electron_browser_main_parts.cc:648
#if !BUILDFLAG(IS_MAC)
// The corresponding call in macOS is in ElectronApplicationDelegate.
Browser::Get()->WillFinishLaunching();
Browser::Get()->DidFinishLaunching(base::DictValue());
#endif
Browser::WillFinishLaunching() → 通知所有 BrowserObserver → App::OnWillFinishLaunching(electron_api_app.cc:627):
void App::OnWillFinishLaunching() {
Menu::InstallDefaultApplicationMenu(JavascriptEnvironment::GetIsolate());
Emit("will-finish-launching");
}
所以时间线是:主消息循环启动前 → 装默认菜单 → 发 will-finish-launching → 发 ready。你在 app.whenReady() 里设置菜单时,默认菜单已经存在了,你在覆盖它。
InstallDefaultApplicationMenu 本身有三个防呆:
electron_api_menu.cc:491-498
void Menu::InstallDefaultApplicationMenu(v8::Isolate* isolate) {
if (g_application_menu_was_set) return;
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
// Nothing need have touched electron.Menu yet; the wrappers created below
// get their templates from the constructors.
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
if (data->GetObjectTemplate(&kWrapperInfo).IsEmpty())
GetConstructor(isolate, context, &kWrapperInfo);
if (data->GetObjectTemplate(&MenuItem::kWrapperInfo).IsEmpty())
MenuItem::GetConstructor(isolate, context, &MenuItem::kWrapperInfo);
...
}
g_application_menu_was_set为真就跳过——这是"用户设过就别插手"。- 手动确保对象模板已创建。如果用户在 ready 之前根本没
require('electron').Menu,gin::PerIsolateData里没有Menu的ObjectTemplate,直接cppgc::MakeGarbageCollected<Menu>会拿到一个造不出包装的对象。所以这里先GetConstructor补一次。 v8::Context::Scope context_scope(context)是在建完模板之后、ChangeApplicationMenu之前才进的作用域。前面那些GetConstructor调用不要求带作用域,最后装菜单时要求。
模板内容是五个(macOS 六个)role:
electron_api_menu.cc:504-509
for (std::string_view role : {
#if BUILDFLAG(IS_MAC)
"appMenu",
#endif
"fileMenu", "editMenu", "viewMenu", "windowMenu"}) {
gin_helper::Dictionary entry = gin::Dictionary::CreateEmpty(isolate);
entry.Set("role", role);
entries.push_back(entry.GetHandle());
}
每个 role 的子菜单由 DefaultSubmenu 现搭(18.3)。注意 macOS 上 appMenu 在第一位,其它平台没有——这就是"mac 有应用菜单、Win/Linux 没有"的实现位置,不是靠原生侧判断的。
18.5.4 popup 的坐标:内容区坐标,mac 的 y 还要翻
两个平台的 PopupAt 第一段几乎一样:
electron_api_menu_views.cc:44-49
// views
gfx::Point location;
if (x == -1 || y == -1) {
location = display::Screen::Get()->GetCursorScreenPoint();
} else {
gfx::Point origin = native_window->GetContentBounds().origin();
location = gfx::Point(origin.x() + x, origin.y() + y);
}
electron_api_menu_mac.mm:179-183
// mac
NSPoint position;
if (x == -1 || y == -1) {
position = [view convertPoint:[nswindow mouseLocationOutsideOfEventStream] fromView:nil];
} else {
position = NSMakePoint(x, [view frame].size.height - y);
}
三件事:
- 坐标原点是内容区左上角,不是窗口左上角,不是屏幕。
GetContentBounds().origin()加偏移得到屏幕坐标。所以有标题栏的窗口,popup({x:0, y:0})出现在网页左上角,不是标题栏左上角。 x === -1 || y === -1是"或"不是"与"。只写x: -1会让y也被忽略,直接弹在鼠标位置。想让它在某个 y 上贴着鼠标 x 弹,做不到。- mac 的 y 要翻转:
[view frame].size.height - y。因为 AppKit 的视图坐标原点在左下。这个转换在 Electron 里做了,所以 JS 层两个平台的y语义一致(都从顶往下)。
mac 还多了两段溢出修正,只在没指定 positioningItem 时生效:
electron_api_menu_mac.mm:188-195
// If no preferred item is specified, try to show all of the menu items.
if (!item) {
CGFloat windowBottom = CGRectGetMinY([view window].frame);
CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height;
CGFloat screenBottom = CGRectGetMinY([view window].screen.visibleFrame);
CGFloat distanceFromBottom = lowestMenuPoint - screenBottom;
if (distanceFromBottom < 0) position.y = position.y - distanceFromBottom + 4;
}
// Place the menu left of cursor if it is overflowing off right of screen.
CGFloat windowLeft = CGRectGetMinX([view window].frame);
CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width;
CGFloat screenRight = CGRectGetMaxX([view window].screen.visibleFrame);
if (rightmostMenuPoint > screenRight) position.x = position.x - [menu size].width;
也就是说 mac 上右键菜单靠近屏幕底部时会被自动上推,靠近右边缘时会自动左翻,而 Windows/Linux 交给 views::MenuRunner 自己处理。这解释了"mac 上菜单位置和我算的不一样"——它不是 bug,是这段代码在挪。
18.5.5 mac 的 popup 是异步的,frame 会切换整条路径
void MenuMac::PopupAt(...) {
...
auto popup = base::BindOnce(&MenuMac::PopupOnUI, ..., native_window->GetWeakPtr(),
std::move(weak_frame), window->weak_map_id(),
x, y, positioning_item, std::move(callback_with_ref));
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE, std::move(popup));
}
整个弹出被 PostTask 到下一轮任务。对比 MenuViews::PopupAt,它是同步调 runner_ptr->RunMenuAt(...)(虽然 views 的 RunMenuAt 内部会进嵌套循环)。
后果很实际:
menu.popup(); // 排队,还没弹
menu.closePopup(); // 也排队,但它 PostTask 在 popup 之后 → 先关后弹 = 关不掉
在 mac 上,同一个 tick 里 popup 再 closePopup 是无效的。要关得等它真的弹出来之后。
PopupOnUI 里还有一处分支:
electron_api_menu_mac.mm:207-214
if (WebFrameMain* frame_ptr = frame.Get();
frame_ptr && frame_ptr->render_frame_host()) {
auto* rfh = frame_ptr->render_frame_host()->GetOutermostMainFrameOrEmbedder();
auto* rwhv = rfh && rfh->IsRenderFrameLive() ? rfh->GetView() : nullptr;
NSView* frame_view = rwhv ? rwhv->GetNativeView().GetNativeNSView() : nil;
if (frame_view) {
NSEvent* dummy_event = [NSEvent mouseEventWithType:NSEventTypeRightMouseDown ...];
ui::ShowContextMenu(menu, dummy_event, frame_view, true);
return;
}
}
那两行 NSEvent 的构造被源码里的一条开发者注记解释着:ui::ShowContextMenu 在找不到 frame 时不能正确派发事件,所以要手工造一个 event 绕过。也就是说这个 if/else 是一处已知缺陷的绕法,不是设计。
传了 frame 就换一条实现:走 ui::ShowContextMenu + 一个手工构造的 NSEvent,而不是 [menu popUpMenuPositioningItem:...]。这条路径是为了让右键事件正确地进 Blink(菜单关闭时要通知页面"contextmenu 结束了")。不传 frame 走的是普通 popUpMenuPositioningItem,事件不会派发到页面。
所以在 renderer 里 ipcRenderer.invoke('show-menu') 让主进程弹菜单时,必须把 frame 传回去,否则页面收不到 contextmenu 的收尾。Menu::Popup 的 frame 是从 options 里 dict.Get("frame", &frame_ptr) 拿的,类型是 WebFrameMain。
最后那段:
electron_api_menu_mac.mm:232-234
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
base::mac::ScopedSendingEvent sendingEventScoper;
[menu popUpMenuPositioningItem:item atLocation:position inView:view];
popUpMenuPositioningItem 会开一个嵌套 runloop,阻塞当前调用栈。所以必须显式允许应用任务在这个嵌套循环里跑(否则主进程的 JS 全卡住,菜单里的异步逻辑不响应),还要用 ScopedSendingEvent 保护,否则嵌套循环里跑出来的 window.close() 会把程序搞崩。
18.5.6 Windows/Linux:MenuRunner 会静默拒绝第二个菜单
electron_api_menu_views.cc:70-77
auto runner = std::make_unique<MenuRunner>(model(), flags, close_callback);
auto* const runner_ptr = runner.get();
menu_runners_[window_id] = std::move(runner);
runner_ptr->RunMenuAt(native_window->widget(), nullptr, gfx::Rect{location, gfx::Size{}},
views::MenuAnchorPosition::kTopLeft, source_type);
// MenuRunner silently no-ops if another menu is active and never runs the
// close callback; treat that as an immediate close so nothing leaks.
if (auto iter = menu_runners_.find(window_id);
iter != menu_runners_.end() && iter->second.get() == runner_ptr &&
!runner_ptr->IsRunning()) {
close_callback.Run();
}
MenuRunner 在已有一个菜单在跑时不报错、不弹、也不调 close callback。Electron 用 !IsRunning() 检测这个情况,然后手工补一次 close_callback——否则 BindSelfToClosure 钉住的 Menu 永远不放,泄漏。
ClosePopupAt 用 weak_map_id 做 key,-1 表示"关掉这个 Menu 的所有 runner":
electron_api_menu_views.cc:86-92
void MenuViews::ClosePopupAt(int32_t window_id) {
if (auto iter = menu_runners_.find(window_id); iter != menu_runners_.end()) {
iter->second->Cancel();
return;
}
if (window_id == -1) {
// Note: `Cancel()` invalidaes iters, so move() to a temp before looping
auto tmp = std::move(menu_runners_);
for (auto& [id, runner] : tmp) runner->Cancel();
}
}
注意 menu_runners_ 是 std::map<int32_t, std::unique_ptr<MenuRunner>>,每个窗口最多一个活动 runner。在同一个窗口连弹两个菜单,第二个会覆盖第一个的 map 条目(menu_runners_[window_id] = std::move(runner) 直接替换),第一个 runner 被析构——而它可能正在运行。这是"别在同一个窗口同时弹两个菜单"的实现层原因。
18.5.7 keep_alive_ 只管菜单打开的那一小段时间
electron_api_menu.cc:555-560
void Menu::OnMenuWillClose() {
Emit("menu-will-close");
keep_alive_.Clear();
}
void Menu::OnMenuWillShow() {
keep_alive_ = this;
Emit("menu-will-show");
}
一个 SelfKeepAlive<Menu> 在 menu-will-show 时钉住自己,在 menu-will-close 时松开。这是唯一防止"弹出菜单的 Menu 对象在菜单还开着的时候被 GC"的机制——因为 ElectronMenuModel 里存的是 MenuItem* 裸指针,MenuItem 又通过 menu_ 反向指回 Menu,如果 Menu 被回收,原生菜单就有悬空指针。
另一层保护是 BindSelfToClosure:
electron_api_menu.cc:537-541
base::OnceClosure Menu::BindSelfToClosure(base::OnceClosure callback) {
return base::BindOnce(
[](base::OnceClosure callback, cppgc::Persistent<Menu> prevent_gc) {
std::move(callback).Run();
},
std::move(callback), cppgc::Persistent<Menu>(this));
}
这个闭包在 popup 时被创建,在关闭回调里执行,所以它的生命周期覆盖了"菜单开着"的整段时间。两层加起来:keep_alive_ 覆盖 show→close,Persistent 覆盖 popup→callback。即使 Emit('menu-will-close') 里的 JS 抛异常导致 keep_alive_.Clear() 之后又被重新钉住(Show 重入),Persistent 那份也还在。
一个反直觉的推论:应用菜单不需要 keep_alive_,因为它被 ApplicationMenu() 那个 NoDestructor 里的 Persistent 永久钉住了。所以 Menu.getApplicationMenu() 永远拿得到,直到你 setApplicationMenu(null)。
18.6 Tray:一个永生的对象
Tray 是本章生命周期最特殊的模块,头文件最后一行:
gin_helper::SelfKeepAlive<Tray> keep_alive_{this};
{this} 而不是 {nullptr}。对比 Menu 的 keep_alive_{nullptr}(需要显式赋值才生效),Tray 的 SelfKeepAlive 在构造完成时就立刻钉住自己。这意味着:
Tray 对象永远不会被 GC,直到你调用 tray.destroy()。
electron_api_tray.cc:194-198
void Tray::Destroy() {
menu_.Clear();
tray_icon_.reset();
keep_alive_.Clear();
}
bool Tray::IsDestroyed() { return !tray_icon_; }
这和"JS 对象被回收 → 原生资源释放"的直觉完全相反。它的实际影响:
function createTray() {
const tray = new Tray(icon); // 局部变量,函数返回后本该被回收
tray.setToolTip('Hi');
}
createTray();
// 托盘图标还在。永远在。进程退出才消失。
很多人以为"把 tray 赋给一个模块级变量"才能保住图标,其实不需要——图标保住了,是你自己需要 destroy() 才能去掉它。反过来,如果应用里有"创建/销毁托盘"的开关,忘了 destroy() 就会每点一次多一个图标,而且旧图标的 Tray 对象还在监听事件、还持有菜单。
18.6.1 构造:三个前置检查,一个补救
Tray* Tray::New(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> image,
std::optional<base::Uuid> guid, gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create Tray before app is ready");
return {};
}
if (!guid.has_value() && args->Length() > 1) {
thrower.ThrowError("Invalid GUID format - GUID must be a string");
return {};
}
v8::Isolate* isolate = args->isolate();
v8::TryCatch try_catch{isolate};
Tray* tray = cppgc::MakeGarbageCollected<Tray>(
isolate->GetCppHeap()->GetAllocationHandle(), isolate, image, guid);
if (try_catch.HasCaught()) {
// Remove the already-created OS icon now, not at eventual collection.
tray->Destroy();
try_catch.ReThrow();
return {};
}
return tray;
}
- 必须
app.isReady()。new Tray()在 ready 之前抛错,不是静默失败。 - GUID 传入但解析失败时报错。
args->Length() > 1说明用户传了第二个参数,但guid没解析出来 → 类型不对。注意这条判据是"传了两个以上参数且 guid 为空",所以new Tray(icon, undefined)也会报错。 TryCatch是为了补救。构造函数里SetImage可能抛错(图标不是NativeImage也不是合法路径)。C++ 抛出的异常在跨越 V8 边界时会被丢弃(注释引了 V8 的一次改动),所以这里手动捕获、立刻Destroy()掉已经创建的 OS 图标,再ReThrow。
第 3 点的意义在于:如果不 Destroy(),那个 Tray 对象会因为 keep_alive_{this} 永远不回收,OS 图标永远留在托盘里,而 JS 侧又拿不到这个对象(构造抛异常了)。这是一个"必须立刻清理"的强制路径,不是优化。
18.6.2 CheckAlive():每个方法的第一行
electron_api_tray.cc:423-429
bool Tray::CheckAlive() {
if (!tray_icon_) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
gin_helper::ErrorThrower(isolate).ThrowError("Tray is destroyed");
return false;
}
return true;
}
SetImage/SetToolTip/SetTitle/DisplayBalloon/Focus/PopUpContextMenu/SetContextMenu/GetBounds/GetGUID 全部以它开头。destroy() 之后再调任何方法都是抛异常,不是静默无操作。
有两处 CheckAlive 被调了两次:
void Tray::DisplayBalloon(gin_helper::ErrorThrower thrower, const gin_helper::Dictionary& options) {
if (!CheckAlive()) return;
...
if (icon) {
...
balloon_options.icon = icon->GetHICON(...); // ← 可能跑 JS(转换 NativeImage)
}
if (!CheckAlive()) return; // ← 再查一次
tray_icon_->DisplayBalloon(balloon_options);
}
// Converting the arguments can run JS that destroys the tray.
if (!CheckAlive()) return;
原因写得很清楚:参数转换会跑 JS(icon 可能是 NativeImage,读取它的像素可能触发 getter),JS 里可能 tray.destroy()。所以**"检查 → 转换参数 → 再检查 → 用原生对象"**是这个模块的标准防御模式。
18.6.3 setContextMenu 与 popUpContextMenu 的区别
void Tray::SetContextMenu(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> arg) {
if (!CheckAlive()) return;
if (arg->IsNull()) {
menu_.Clear();
tray_icon_->SetContextMenu(nullptr);
} else if (Menu* menu = nullptr; gin::ConvertFromV8(thrower.isolate(), arg, &menu)) {
menu_ = menu;
tray_icon_->SetContextMenu(menu->model());
} else {
thrower.ThrowTypeError("Must pass Menu or null");
}
}
setContextMenu 把 menu->model() 的裸指针交给 TrayIcon。TrayIcon 不认识 Menu 对象,只认识 ElectronMenuModel*。所以 Tray 必须用 cppgc::Member<Menu> menu_ 把 Menu 钉住——否则 Menu 一旦被 GC,model_ 跟着死,TrayIcon 手里就是一个悬空指针。
对比 popUpContextMenu,它不存 menu_,而是用一个只在弹出期间有效的 ScopedClosureRunner:
electron_api_tray.cc:375-380
// Root |menu| until the platform is done with its model; JS may not hold it.
base::ScopedClosureRunner retain_menu;
if (menu) {
retain_menu.ReplaceClosure(base::BindOnce([](cppgc::Persistent<Menu>) {},
cppgc::Persistent<Menu>(menu)));
}
tray_icon_->PopUpContextMenu(pos, menu ? menu->model()->GetWeakPtr() : nullptr,
std::move(retain_menu));
两个要点:
popUpContextMenu的 menu 可以不被 JS 持有。base::BindOnce([](cppgc::Persistent<Menu>) {}, ...)这个空 lambda 的唯一作用是让Persistent活到闭包被销毁——也就是"平台用完这个 model 之后"。- 传的是
GetWeakPtr()。ElectronMenuModel是base::WeakPtrFactory支持的,所以平台侧能检测到 model 已经死了。setContextMenu传的却是裸指针,靠menu_成员保活。两条路径的健壮性不一样。
18.6.4 setTitle 在非 mac 上是空函数
void Tray::SetTitle(const std::string& title, const std::optional<gin_helper::Dictionary>& options,
gin::Arguments* args) {
if (!CheckAlive()) return;
#if BUILDFLAG(IS_MAC)
...
tray_icon_->SetTitle(title, title_options);
#endif
}
std::string Tray::GetTitle() {
if (!CheckAlive()) return {};
#if BUILDFLAG(IS_MAC)
return tray_icon_->GetTitle();
#else
return "";
#endif
}
整个函数体在 #if 里面,非 mac 编译出来是一个只有 CheckAlive 的空函数。不报错、不警告,setTitle('99+') 在 Windows 上什么也不做。setIgnoreDoubleClickEvents/getIgnoreDoubleClickEvents 同理(后者直接返回 false)。
setTitle 的 fontType 校验有两层,第二层容易被忽略:
electron_api_tray.cc:249-255
if (options->Get("fontType", &title_options.font_type)) {
if (title_options.font_type != "monospaced" && title_options.font_type != "monospacedDigit") {
args->ThrowTypeError("fontType must be one of 'monospaced' or 'monospacedDigit'");
return;
}
} else if (options->Has("fontType")) {
args->ThrowTypeError("fontType must be one of 'monospaced' or 'monospacedDigit'");
return;
}
Get 失败但 Has 为真 → 说明 fontType 存在但类型不是 string(比如 fontType: 1),也报同一个错。这是 gin 的 Get 语义逼出来的补丁:Get 一个类型不匹配的值返回 false,和"字段不存在"无法区分。
18.6.5 Linux 的托盘是 GtkStatusIcon,不是 StatusNotifier
TrayIcon::Create 在 Linux 上返回 StatusIconGtk,构造是:
status_icon_gtk.cc:19-21
StatusIconGtk::StatusIconGtk() : icon_(TakeGObject(gtk_status_icon_new())) {
...
connect(icon_.get(), "activate", &StatusIconGtk::OnClick);
connect(icon_.get(), "popup_menu", &StatusIconGtk::OnContextMenuRequested);
}
GtkStatusIcon 是 XEmbed 时代的遗留 API(GTK 里已标记 deprecated),走的是 X11 系统托盘协议,不是现代的 StatusNotifierItem/AppIndicator over D-Bus。后果:
- 纯 Wayland 会话(没有 XWayland 兼容层)里图标不显示。
- 一些只支持 SNI 的桌面环境(GNOME 默认)需要装扩展才看得到。
- 左键点击走
activate信号,右键走popup_menu,所以tray.on('click')和'right-click'在不同桌面上触发时机不一致。 displayBalloon在 Linux 上是空实现(TrayIcon::DisplayBalloon基类就是{},只有 Windows 覆盖),所以tray.displayBalloon()在 mac/Linux 上静默无操作。
这就是"托盘在 Linux 上行为怪异"的全部原因——它不是 Electron 的实现问题,是一个 20 年前的协议在现代桌面上的兼容问题。
18.7 dialog:没有 JS 对象,只有一道道检查和一堆平台分支
dialog 模块是本章最"朴素"的一个:它没有 class、没有 cppgc 对象、没有生命周期问题。整个 electron_api_dialog.cc:94-101 只有 110 行,全是把 C++ 函数挂到 binding 上:
dict.SetMethod<&ShowMessageBoxSync>("showMessageBoxSync");
dict.SetMethod<&ShowMessageBox>("showMessageBox");
dict.SetMethod<&electron::CloseMessageBox>("_closeMessageBox");
dict.SetMethod<&electron::ShowErrorBox>("showErrorBox");
dict.SetMethod<&ShowOpenDialogSync>("showOpenDialogSync");
dict.SetMethod<&ShowOpenDialog>("showOpenDialog");
dict.SetMethod<&ShowSaveDialogSync>("showSaveDialogSync");
dict.SetMethod<&ShowSaveDialog>("showSaveDialog");
但这一层之上有一层 TypeScript(dialog.ts:62-64,320 行),而所有有意思的逻辑都在 TS 层。这是本章唯一一个"逻辑在 JS 不在 C++"的模块,原因是它要做的全是对 options 的归一化和对结果的拼装。
18.7.1 所有入口都先查 app.isReady()
dialog.ts:62-64
const checkAppInitialized = function () {
if (!app.isReady()) {
throw new Error('dialog module can only be used after app is ready');
}
};
showOpenDialog/showOpenDialogSync/showSaveDialog/showSaveDialogSync/showMessageBox/showMessageBoxSync 六个函数的第一行都是它。注意是同步抛错,不是返回 rejected promise——所以 await dialog.showOpenDialog() 在 ready 之前是抛异常而不是 reject,try/catch 能抓到但 .catch() 抓不到。
唯一不受限制的是 dialog.showErrorBox():它不走 dialog.ts:207-213 的包装(直接 _linkedBinding),因为 C++ 侧的注释写着 "safe to call at very early stage of application"。启动失败时你只有这一个能用的对话框——这也是为什么所有 Electron 崩溃兜底代码都用 showErrorBox 而不是 showMessageBox。
18.7.2 cancelId 是猜出来的
dialog.ts:207-213
// Choose a default button to get selected when dialog is cancelled.
if (cancelId == null) {
// If the defaultId is set to 0, ensure the cancel button is a different index (1)
cancelId = defaultId === 0 && buttons.length > 1 ? 1 : 0;
for (const [i, button] of buttons.entries()) {
const text = button.toLowerCase();
if (text === 'cancel' || text === 'no') {
cancelId = i;
break;
}
}
}
三层逻辑:
- 初值:如果
defaultId是 0 且按钮多于一个,cancelId取 1;否则取 0。目的是不要让"取消"和"默认"落在同一个按钮上——否则用户按 Esc 和按回车是同一边,等于没有取消。 - 然后线性扫,找小写之后等于
'cancel'或'no'的按钮。 - 取第一个匹配(
break)。所以['OK', 'No', 'Cancel']的cancelId是 1("No"),不是 2。
这带来两个实际影响:
- 文案是英文硬编码判据。中文界面
['确定', '取消']匹配不到任何项,cancelId保持初值 0——按 Esc 会触发"确定"。要正确必须显式传cancelId: 1。 'No'会被当成取消按钮。确认框['Yes', 'No']里 Esc 返回 1,这通常正是想要的;但['No', 'Yes']里 Esc 返回 0,语义就反了。
18.7.3 checkboxChecked 的依赖,和 AbortSignal 的一个形状不一致
dialog.ts:201-203
checkboxChecked = !!checkboxChecked;
if (checkboxChecked && !checkboxLabel) {
throw new Error('checkboxChecked requires that checkboxLabel also be passed');
}
这个检查在同步阶段抛,不是 resolve 时。然后:
dialog.ts:220-225
let id: number | undefined;
if (signal) {
id = getNextId();
if (signal.aborted) {
return Promise.resolve({ cancelId, checkboxChecked });
}
signal.addEventListener('abort', () => dialogBinding._closeMessageBox(id));
}
getNextId() 是 TS 层的一个单调计数器(++nextId),和菜单的 commandId、Notification 的 id 完全无关——它是专门给"关掉某个消息框"用的句柄。
关键在于 signal.aborted 的早退路径:
return Promise.resolve({ cancelId, checkboxChecked });
正常路径 resolve 的是 { response, checkboxChecked }(18.7.5 的 C++ 侧 ResolvePromiseObject)。早退路径 resolve 的是 { cancelId, checkboxChecked }——字段名都不一样。所以:
const controller = new AbortController();
controller.abort(); // 先 abort
const { response } = await dialog.showMessageBox({ signal: controller.signal, buttons: ['A'] });
// response === undefined,多出来一个 cancelId
这是一个只在"signal 已经 abort 之后才调用"时出现的形状差异。写通用封装时必须两个字段都兜:
const response = result.response ?? result.cancelId ?? 0;
还有一点:signal.addEventListener('abort', ...) 从不移除。传一个长生命周期的 AbortSignal(比如应用级的"退出时取消所有对话框")给很多次 showMessageBox,监听器会一直累积。
18.7.4 properties 的位掩码在两边各写一遍
TS 侧有一份枚举:
dialog.ts:22-29
enum OpenFileDialogProperties {
openFile = 1 << 0,
openDirectory = 1 << 1,
multiSelections = 1 << 2,
createDirectory = 1 << 3, // macOS
showHiddenFiles = 1 << 4,
promptToCreate = 1 << 5, // Windows
noResolveAliases = 1 << 6, // macOS
treatPackageAsDirectory = 1 << 7, // macOS
dontAddToRecent = 1 << 8 // Windows
}
C++ 侧(file_dialog.h:39-46)也有一份:
enum OpenFileDialogProperty {
OPEN_DIALOG_OPEN_FILE = 1 << 0,
OPEN_DIALOG_OPEN_DIRECTORY = 1 << 1,
OPEN_DIALOG_MULTI_SELECTIONS = 1 << 2,
OPEN_DIALOG_CREATE_DIRECTORY = 1 << 3, // macOS
OPEN_DIALOG_SHOW_HIDDEN_FILES = 1 << 4,
OPEN_DIALOG_PROMPT_TO_CREATE = 1 << 5, // Windows
OPEN_DIALOG_NO_RESOLVE_ALIASES = 1 << 6, // macOS
OPEN_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY = 1 << 7, // macOS
FILE_DIALOG_DONT_ADD_TO_RECENT = 1 << 8, // Windows
};
两份手写的位值,靠人保证同步。这不是可以随便改的地方——加一个 property 必须同时改两个文件、两个位置,且位值不能冲突,否则某个平台的行为会静默错位。
TS 侧的转换是宽容的:
const setupOpenDialogProperties = (properties) => {
let dialogProperties = 0;
for (const property of properties) {
if (Object.hasOwn(OpenFileDialogProperties, property)) {
dialogProperties |= OpenFileDialogProperties[property];
}
}
return dialogProperties;
};
用 Object.hasOwn 而不是 in,所以 'toString' 这类原型链上的名字不会被当成 property,也不会因为读到函数而算出 NaN。未知字符串静默忽略——properties: ['openFile', 'openFiles'](多了个 s)不会报错,'openFiles' 直接消失。
另一个坑:openFile 和 openDirectory 是两个独立的位,同时给会得到 1|2 = 3,各平台对"既要文件又要目录"的支持不一致(Windows 的 IFileOpenDialog 根本不支持),实际行为是看平台实现怎么处理这个组合。
18.7.5 结果字典:filePath 只属于 save,filePaths 只属于 open
三个平台各写一遍结果拼装,把它们放在一起就能看出规律。
Linux(file_dialog_linux.cc:195-202,ui::SelectFileDialog::Listener):
void FileSelected(const ui::SelectedFileInfo& file, int index) override {
dict.Set("canceled", false);
if (type_ == DialogType::SAVE) {
dict.Set("filePath", file.file_path);
} else {
dict.Set("filePaths", std::vector<base::FilePath>{file.file_path});
}
...
}
void FileSelectionCanceled() override {
dict.Set("canceled", true);
if (type_ == DialogType::SAVE) dict.Set("filePath", base::FilePath());
else dict.Set("filePaths", std::vector<base::FilePath>());
}
Windows(file_dialog_win.cc:223-226):
// open
dict.Set("canceled", !success);
dict.Set("filePaths", result);
// save
dict.Set("canceled", !result.has_value());
dict.Set("filePath", result.value_or(base::FilePath{}));
macOS(file_dialog_mac.mm):
gin_helper::Dictionary OpenDialogResult(...) {
dict.Set("canceled", canceled);
dict.Set("filePaths", paths);
#if IS_MAS_BUILD()
dict.Set("bookmarks", bookmarks);
#endif
}
gin_helper::Dictionary SaveDialogResult(...) {
dict.Set("canceled", canceled);
dict.Set("filePath", path);
}
汇总:
| 调用 | 结果字段 |
|---|---|
showOpenDialog(三平台) | { canceled, filePaths } |
showSaveDialog(三平台) | { canceled, filePath } |
showOpenDialog(仅 MAS 构建) | 多一个 { bookmarks: string[] } |
open 对话框从来不给 filePath,即使是单选。Linux 的 FileSelected 在单选时也要包成 filePaths: [path]。所以 const { filePath } = await dialog.showOpenDialog(...) 在任何平台都是 undefined——必须用 filePaths[0]。
反过来 save 从来不给 filePaths。想写一个两个都能用的封装,只能判 canceled:
const result = await (isSave ? dialog.showSaveDialog(o) : dialog.showOpenDialog(o));
if (result.canceled) return null;
return result.filePath ?? result.filePaths?.[0] ?? null;
bookmarks 只在 IS_MAS_BUILD() 时才有——这是 Mac App Store 沙盒版本的专用字段,用来在重启后重新获得文件访问权限(security-scoped bookmark 的 base64 编码)。非 MAS 的 mac 版没有这个字段,即使你传了 securityScopedBookmarks: true。
18.7.6 filters 静默失败的两种方式
filters 的转换器(file_dialog_converter.cc:14-21)要求两个字段都存在:
bool Converter<file_dialog::Filter>::FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
file_dialog::Filter* out) {
gin::Dictionary dict(nullptr);
if (!ConvertFromV8(isolate, val, &dict)) return false;
if (!dict.Get("name", &(out->first))) return false;
if (!dict.Get("extensions", &(out->second))) return false;
return true;
}
name 或 extensions 缺一个就返回 false。vector 的转换有一条失败就整体失败,而外层是:
dict.Get("filters", &(out->filters));
返回值没人看。所以:
dialog.showOpenDialog({ filters: [{ name: 'Images', extensions: ['png'] }] }) // 正常
dialog.showOpenDialog({ filters: [{ extensions: ['png'] }] }) // 没有 name → 整个 filters 变空
dialog.showOpenDialog({ filters: [{ name: 'Images', extensions: 'png' }] }) // extensions 不是数组 → 整个 filters 变空
三种情况下对话框都会打开,只是"文件类型"下拉框里什么筛选都没有——用户能看到所有文件。这是最典型的一类静默失败:参数不全不会报错,只会降级。
还有一个平台差异:extensions: ['*'] 在 Windows 上表示"所有文件",在 mac/Linux 上要写 ['*'] 也能被识别,但把通配符和具体扩展名混写(['*.png', 'jpg'])在 Linux 的 GTK 实现里行为不确定。安全写法是永远写纯扩展名(不带点、不带星号),要"所有文件"就单独加一个 { name: 'All Files', extensions: ['*'] }。
18.7.7 macOS 的 sheet 与 modal 是两条路径
if (settings.parent_window) { ... chosen = [dialog runModal]; }
...
[dialog beginSheetModalForWindow:window ...]; // 有父窗口
...
[NSApp runModalForWindow:window]; // 没有父窗口,自己开一个
macOS 上"模态"有两种完全不同的做法:sheet(贴着父窗口滑下来的那张)和 app-modal(挡住整个应用)。Electron 的选择是:
- 传了
window→beginSheetModalForWindow,出 sheet,只阻塞那个窗口。 - 没传 →
runModal或runModalForWindow,阻塞整个应用。
这解释了一个常见困惑:"mac 上不传 window 时对话框会挡住所有窗口,Windows 上不会"。Windows 的 IFileDialog 没有 sheet 概念,GetParentWindowHandle(settings) 拿不到父窗口时就以桌面为父,模态范围只到"没有父"的那个层级。
file_dialog.h:100 里还有两个只在 mac 上存在的 ShowOpenDialogForNSWindow / ShowSaveDialogForNSWindow,注释写着 "for a parent that is not a NativeWindow of this process: the panel is a sheet of window" ——这是给 app shim(macOS 上把 Chromium 拆成 app bundle + helper 的那种构建)用的,让 helper 进程里的面板能贴在主进程的窗口上。
18.7.8 同步版是嵌套消息循环,异步版是 Promise
electron_api_dialog.cc:27-34
int ShowMessageBoxSync(const electron::MessageBoxSettings& settings) {
return electron::ShowMessageBoxSync(settings);
}
v8::Local<v8::Promise> ShowMessageBox(v8::Isolate* const isolate,
const electron::MessageBoxSettings& settings) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
electron::ShowMessageBox(settings, base::BindOnce(&ResolvePromiseObject, std::move(promise)));
return handle;
}
showMessageBoxSync 返回的是 int(按钮索引),不是对象;showMessageBox 返回 Promise<{response, checkboxChecked}>。两个形状不同,不能互相替换。
同步版在内部开一个嵌套 runloop 等用户点按钮。这意味着:
- 同步版期间主进程的 JS 会继续跑(微任务、定时器都会触发),因为嵌套 runloop 会 pump 消息。所以"同步"不等于"冻结"——你在
showMessageBoxSync之后立刻假设状态没变是错的。 - 同步版不能在渲染进程调用(
dialog只有主进程有)。 - 异步版在 Linux 上有个额外行为:
electron_api_dialog.cc:96里挂了一个_closeMessageBox,是给AbortSignal用的。C++ 侧的CloseMessageBox(int id)靠MessageBoxSettings::id找到那个正在显示的框。
18.8 Notification:一个 snapshot,不是活对象
Notification 的模型和 Tray 完全相反:Tray 是"JS 对象活着,原生图标跟着活";Notification 是"Show 的那一刻把字段拷成一份 NotificationOptions 交出去,之后平台侧那个通知和 JS 对象就没关系了"。
electron_api_notification.cc:369-376
if (presenter_) {
notification_ = presenter_->CreateNotification(delegate_.get(), id_);
if (notification_) {
electron::NotificationOptions options;
options.title = title_;
options.subtitle = subtitle_;
options.msg = body_;
options.icon_url = GURL();
options.icon = icon_.AsBitmap();
options.silent = silent_;
options.has_reply = has_reply_;
options.timeout_type = timeout_type_;
options.reply_placeholder = reply_placeholder_;
options.actions = actions_;
options.sound = sound_;
options.close_button_text = close_button_text_;
options.urgency = urgency_;
options.toast_xml = toast_xml_;
options.group_id = group_id_;
options.group_title = group_title_;
notification_->Show(options);
}
}
所以 notification.title = 'new' 在一个已经 show 过的通知上没有任何效果——title_ 变了,平台侧那份 options 没变。只有 close() 再 show() 才会带新值。
18.8.1 构造:三个前置条件
Notification* Notification::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create Notification before app is ready");
return nullptr;
}
auto* notification = cppgc::MakeGarbageCollected<Notification>(...);
#if BUILDFLAG(IS_WIN)
constexpr size_t kMaxTagLength = 64;
if (!notification->id_.empty() && base::UTF8ToWide(notification->id_).length() > kMaxTagLength) {
thrower.ThrowError("Notification id exceeds Windows limit of 64 UTF-16 characters");
return nullptr;
}
if (!notification->group_id_.empty() && base::UTF8ToWide(notification->group_id_).length() > kMaxTagLength) {
thrower.ThrowError("Notification groupId exceeds Windows limit of 64 UTF-16 characters");
return nullptr;
}
if (!notification->group_title_.empty() && notification->group_id_.empty()) {
thrower.ThrowError("Notification groupTitle requires groupId to be set");
return nullptr;
}
#endif
return notification;
}
Windows 的三条硬限制都是抛错,不是降级——因为它们最终会变成 toast XML 的 tag/group 属性,超长会被系统静默丢弃,所以 Electron 选择在 JS 侧就拦住。
id 的默认值是随机 UUID:
electron_api_notification.cc:167-168
if (id_.empty())
id_ = base::Uuid::GenerateRandomV4().AsLowercaseString();
每条通知的 id 都不一样。这意味着同名更新("同一个通知,改内容再弹一次")必须显式传 id。Windows 上 id 对应 toast 的 tag,同一个 tag 会替换旧 toast;mac/Linux 上 id 的作用小得多,基本只用于内部去重。
注意 Notification 的构造函数里还有一句:
presenter_ = static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
presenter_ 在构造时就固定了。IsSupported() 也是查这个:
electron_api_notification.cc:394-396
bool Notification::IsSupported() {
return !!static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
}
在没有通知服务的 Linux 容器里,presenter_ 为空,show() 静默什么都不做——不报错。所以 Notification.isSupported() 必须显式查,不能靠 show() 失败来发现。
18.8.2 Show() 先 Close(),然后查一次重入
electron_api_notification.cc:359-363
void Notification::Show() {
// Restored notifications are read-only snapshots from Notification Center.
if (is_restored_) return;
Close();
// A 'close' listener may have re-entered Show() and already created one.
if (notification_) return;
if (presenter_) { ... }
}
三步:
is_restored_直接返回。restored 通知是从通知中心恢复的只读快照,重新 show 会删掉原通知再建一个重复的。Close()掉上一条。- 再查一次
notification_。因为Close()里会Dismiss(),而Dismiss()可能在某些平台上同步触发NotificationClosed→Emit('close')→ 你的 JS 监听器里又调了notification.show()。这时候notification_已经被新的Show()填上了,直接返回,避免无限递归。
Close() 本身的顺序也是被这个重入逼出来的:
electron_api_notification.cc:340-347
void Notification::Close() {
auto notification = notification_;
notification_.reset(); // ← 先清指针
if (!notification) return;
if (notification->is_dismissed()) {
notification->Remove();
} else {
notification->Dismiss();
}
// Dismiss() may run JS ('close' is emitted synchronously on some platforms).
if (notification) notification->set_delegate(nullptr);
}
先 reset() 再 Dismiss()。如果反过来,Dismiss() 同步触发 'close',监听器里再调 close() 会看到非空的 notification_,于是对同一个对象再 dismiss 一次。set_delegate(nullptr) 放在最后,也是为了让 Dismiss() 期间的回调还能正常派发。
18.8.3 delegate 是一个 isolate 销毁的观察者
electron_api_notification.cc:81-87
class NotificationDelegateProxy final
: public electron::NotificationDelegate,
public gin::PerIsolateData::DisposeObserver {
...
void OnBeforeMicrotasksRunnerDispose(v8::Isolate* isolate) override {
notification_.Clear();
gin::PerIsolateData::From(isolate_)->RemoveDisposeObserver(this);
is_observing_ = false;
}
NotificationDelegateProxy 同时是两个东西的实现者:给平台侧的 NotificationDelegate(回调入口),和 isolate 的 DisposeObserver(销毁通知)。
notification_ 是 cppgc::WeakPersistent<Notification>,所以平台回调进来时:
electron_api_notification.cc:110-112
void NotificationClick() override {
if (auto* notification = notification_.Get())
notification->NotificationClick();
}
每个回调都要先 Get() 判空。因为通知可以在 JS 对象被 GC 之后才被用户点掉——比如 new Notification({...}).show() 之后不保留引用,GC 回收了 Notification,平台侧那条通知还在屏幕上,两小时后用户点了它,回调进来时 WeakPersistent 已经是空的。
OnBeforeMicrotasksRunnerDispose 里的 notification_.Clear() 是主动断开:isolate 要销毁了,之后任何回调都不该再碰 V8。
18.8.4 事件形状不统一
四个事件里有两个带自定义 event 对象,两个不带:
void NotificationClick() { Emit("click"); }
void NotificationDisplayed() { Emit("show"); }
void NotificationFailed(const std::string& error) { Emit("failed", error); }
void NotificationAction(int action_index, int selection_index) {
gin_helper::internal::Event* event = gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("selectionIndex", selection_index);
dict.Set("actionIndex", action_index);
EmitWithoutEvent("action", event_object, action_index, selection_index);
}
void NotificationClosed(const std::string& reason) {
if (reason.empty()) {
Emit("close");
} else {
... dict.Set("reason", reason);
EmitWithoutEvent("close", event_object);
}
}
'click'/'show':没有参数。'failed':一个Error对象(Emit会把std::string转成Error)。'action':四个参数 ——(event, actionIndex, selectionIndex),因为EmitWithoutEvent的第一个参数就是 event 对象本身。所以监听器签名是(event, index, selectionIndex)。'close':有reason时是两个参数(event),没有reason时零个参数。同一个事件两种形状,这是最容易写出event?.reason之外还崩的地方:
n.on('close', (event) => {
console.log(event?.reason); // 大多数平台是 undefined
});
reason 只在部分平台的部分收起方式上有值(mac 的 "userCanceled"、"applicationHidden" 之类)。想区分"用户点掉"和"被 close() 掉",不能靠这个。
18.8.5 action 的索引是双层含义
'action' 事件的 (actionIndex, selectionIndex) 两个数字来自 actions 数组:
electron_api_notification.cc:44-51
struct Converter<electron::NotificationAction> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::NotificationAction* out) {
gin::Dictionary dict(isolate);
if (!ConvertFromV8(isolate, val, &dict)) return false;
if (!dict.Get("type", &(out->type))) return false; // ← type 必填
dict.Get("text", &(out->text));
std::vector<std::u16string> items;
if (dict.Get("items", &items)) out->items = std::move(items);
return true;
}
type 必填且没有校验值域——'button'、'button'、'button' 三个一样的也能过,错字也能过('buton')。平台的解析在各自实现里,不认识的 type 会被忽略。
items 是给"下拉选择型 action"用的(mac 的 NSUserNotificationAction 支持不了,Windows toast 的 selection 可以)。selectionIndex 就是用户在下拉里选的第几项,-1 表示不是这类 action。
18.8.6 restored 通知是只读快照
electron_api_notification.cc:171-175
Notification::Notification(v8::Isolate* isolate, const NotificationInfo& info)
: id_(info.id), group_id_(info.group_id), title_(base::UTF8ToUTF16(info.title)),
subtitle_(base::UTF8ToUTF16(info.subtitle)), body_(base::UTF8ToUTF16(info.body)),
is_restored_(true), presenter_(nullptr),
delegate_(std::make_unique<NotificationDelegateProxy>(isolate, this)) {}
注意 presenter_ 是 nullptr。这个构造函数只被 Notification.getHistory() 用到——它向 presenter 要一份"已投递但还在通知中心里"的列表,为每一条造一个只读的 Notification 包装:
electron_api_notification.cc:516-518
auto* notif = cppgc::MakeGarbageCollected<Notification>(
isolate->GetCppHeap()->GetAllocationHandle(), isolate, info);
notif->notification_ = presenter->CreateNotification(notif->delegate_.get(), notif->id_);
注释把这条链讲得很清楚:"A WeakPtr links API to platform; the platform points to a proxy whose WeakPersistent target is cleared when cppgc finds the API object unreachable." 得到的对象:
show()无效(is_restored_早退)。close()会走另一条路——析构函数里:
electron_api_notification.cc:181-184
Notification::~Notification() {
if (notification_) {
notification_->set_delegate(nullptr);
// For restored notifications, destroy the platform notification to remove
// it from the presenter's set. The platform-level is_restored_ flag ensures
// this won't remove the notification from Notification Center.
if (is_restored_) notification_->Destroy();
}
}
Destroy() 而不是 Dismiss():把它从 presenter 的集合里移除,但不从通知中心删掉。这个区分很细——Dismiss 会让用户看到通知消失,Destroy 只是"我们不再管它了"。
18.8.7 Linux 上通知可能整个不存在
NotificationPresenter::Create() 是每个平台各写一份的静态函数,Linux 那份在 notification_presenter_linux.cc:13-16 里:
// static
std::unique_ptr<NotificationPresenter> NotificationPresenter::Create() {
if (LibnotifyNotification::Initialize())
return std::make_unique<NotificationPresenterLinux>();
return {};
}
return {} 就是一个空的 unique_ptr,ElectronBrowserClient::GetNotificationPresenter() 把它缓存下来:
electron_browser_client.cc:1282-1285
NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() {
if (!notification_presenter_)
notification_presenter_ = NotificationPresenter::Create();
return notification_presenter_.get();
}
所以 Linux 上有两种失败方式,对应两条不同的日志:
libnotify_notification.cc:81-88
for (const char* soname : kLibnotifySonames) {
if (GetLibNotifyLoader().Load(soname)) { loaded_soname = soname; break; }
}
if (!loaded_soname) {
LOG(WARNING) << "Unable to find libnotify; notifications disabled";
return false;
}
if (!GetLibNotifyLoader().notify_is_initted() &&
!GetLibNotifyLoader().notify_init(GetApplicationName().c_str())) {
LOG(WARNING) << "Unable to initialize libnotify; notifications disabled";
return false;
}
- 找不到
libnotify.so(依次试.so.4、.so.5、.so.1、.so)——精简镜像里没装这个包。 notify_init()失败——库在,但它连不上 D-Bus 会话总线上的org.freedesktop.Notifications。
两种都返回 false,于是 presenter_ 为空、show() 什么都不做、isSupported() 返回 false。这就是为什么"通知在 Docker 里不工作"——不是权限问题,是既没有库也没有接受方。写自动化测试时应该先 Notification.isSupported() 再决定是否跑通知相关的断言。
顺带一个副作用:GetNotificationPresenter() 是懒创建 + 记忆化的。第一次调 Notification.isSupported() 或构造第一个 Notification 时才真正去连 D-Bus,之后即使 D-Bus 服务起来了,presenter_ 也还是那个空指针。反过来说,isSupported() 调用本身会把这个连接永久建起来。
presenter 的基类里还有一处值得记的写法:
void NotificationPresenter::CloseNotificationWithId(const std::string& notification_id) {
auto it = std::ranges::find_if(notifications_, [¬ification_id](const Notification* n) {
return n->notification_id() == notification_id;
});
if (it != notifications_.end()) {
Notification* notification = (*it);
notification->Dismiss();
// Dismiss() may already have destroyed |notification|. Look it up by
// address rather than erasing by key, which would construct a raw_ptr
// from a possibly-freed pointer.
if (auto found = notifications_.find(notification); found != notifications_.end()) {
notifications_.erase(found);
}
}
}
Dismiss() 可能直接把 Notification 删掉(platform 实现里 RemoveNotification() 会 delete)。所以后面不能再用 notification 指针做任何事——连 erase(notification) 都不行,因为 notifications_ 是 std::set<raw_ptr<Notification>>,构造一个 raw_ptr 参数就要读那个已释放的地址。注释里的"look it up by address"意思是:拿这个数值去 set 里找,不构造新的 raw_ptr。这类"删除可能发生在回调里"的顺序问题,是本章所有模块的共同主题。
18.9 globalShortcut:两套后端,一套 API
globalShortcut 是本章唯一一个"在 Wayland 上必须换实现"的模块。它的代码里有两套完全不同的注册路径,靠一个运行时判断切换:
electron_api_global_shortcut.cc:170-177
auto* instance = ui::GlobalAcceleratorListener::GetInstance();
if (!instance) return false;
if (instance->IsRegistrationHandledExternally()) {
... // 走 portal
} else {
if (instance->RegisterAccelerator(accelerator, this)) {
accelerator_callback_map_[accelerator] = callback;
return true;
}
}
return false;
IsRegistrationHandledExternally() 是 Chromium 侧的判断:在 Wayland 会话里,全局快捷键不能由应用自己抢(compositor 不给你这个权限),必须通过 xdg-desktop-portal 的 GlobalShortcuts 接口向桌面环境"申请"。
18.9.1 内部后端:一张 map<Accelerator, closure>
std::map<ui::Accelerator, base::RepeatingClosure> accelerator_callback_map_;
...
void GlobalShortcut::OnKeyPressed(const ui::Accelerator& accelerator) {
if (auto* cb = base::FindOrNull(accelerator_callback_map_, accelerator)) {
cb->Run();
} else {
// This should never occur, because if it does,
// ui::GlobalAcceleratorListener notifies us with wrong accelerator.
if (!is_disposed_) NOTREACHED();
}
}
ui::Accelerator 直接当 map 的键,说明加速键是全等比较。Ctrl+Shift+a 和 Ctrl+Shift+A 解析出的 ui::Accelerator 相同(KeyboardCodeFromStr 里做了 ToLowerASCII),但 Ctrl+A 和 CmdOrCtrl+A 在 macOS 上是两个不同的键(18.4.5)。
NOTREACHED() 那两行是防御:平台告诉我们"某个键被按了",但 map 里没有对应回调——说明状态不同步。用 is_disposed_ 挡一下,是因为对象析构之后可能还有在途通知。
18.9.2 外部后端:每个快捷键伪装成一个独立的"扩展命令"
portal 后端的逻辑比内部后端复杂得多,因为它要适配 Chromium 的 extensions 命令模型:
electron_api_global_shortcut.cc:175-182
if (instance->IsRegistrationHandledExternally()) {
const std::string profile_id = GetPortalProfileId();
// There is no way to get command id for the accelerator as it's extensions'
// thing. Instead, we can convert it to string in a following example form
// - std::string("Alt+Shift+K").
const std::string command_str = extensions::Command::AcceleratorToString(accelerator);
ui::CommandMap commands;
extensions::Command command(
command_str,
base::UTF8ToUTF16(electron::Browser::Get()->GetName() + " shortcut: " + command_str),
/*accelerator=*/std::string(), /*global=*/true);
command.set_accelerator(accelerator);
commands[command_str] = command;
...
instance->OnCommandsChanged(
GetPortalExtensionId(command_str, profile_id), profile_id, commands,
gfx::kNullAcceleratedWidget,
base::BindRepeating(&GlobalShortcut::ExecuteCommand,
gin::WrapPersistent(weak_factory_.GetWeakCell(
isolate->GetCppHeap()->GetAllocationHandle()))));
command_callback_map_[command_str] = callback;
return true;
}
四层适配,每层都是被 portal 的模型逼出来的:
-
命令 id 用字符串化后的加速键。
extensions::Command::AcceleratorToString(accelerator)得到"Alt+Shift+K",拿它当 command id。因为 portal 那套接口是给浏览器扩展设计的,它没有"Electron 的快捷键"这种概念。 -
每个快捷键占一个伪扩展 id。
GetPortalExtensionId(command_str, profile_id)拼成"Alt+Shift+K+<uuid>"。源码注释把原因写得很清楚:In order to distinguish the shortcuts, we must register multiple commands as different extensions. Otherwise, each shortcut will be an alternative for the very first registered and we'll not be able to distinguish them. For example, if Alt+Shift+K is registered first, registering and pressing Alt+Shift+M will trigger global shortcuts, but the command id that is received by GlobalShortcut will correspond to Alt+Shift+K as our command id is basically a stringified accelerator.
翻译一下:同一个扩展下的多条命令,在 portal 眼里是"同一功能的多个备选键"。注册第二条不会新增一个快捷键,而是给第一条加了个备选。结果就是回调里拿到的 command id 永远是最先注册的那条。
-
profile_id持久化在 prefs 里:std::string GetPortalProfileId() { auto* context = electron::ElectronBrowserContext::GetDefaultBrowserContext(); PrefService* prefs = context->prefs(); std::string profile_id = prefs->GetString(electron::kElectronGlobalShortcutsUuid); if (profile_id.empty()) { profile_id = base::Uuid::GenerateRandomV4().AsLowercaseString(); prefs->SetString(electron::kElectronGlobalShortcutsUuid, profile_id); } return profile_id; }为什么不能每次随机?因为 portal 记住某个 profile 注册过的快捷键,用户在系统设置里也能看到并修改绑定。如果每次启动换一个新 profile id,应用就会被当成新客户端,之前的绑定全部作废。这个 UUID 写进 prefs 就是为了"重启后还是同一个身份"。
-
注销要单独发一次空命令:
void ClearPortalCommand(ui::GlobalAcceleratorListener* instance, const std::string& command_str, const std::string& profile_id) { instance->OnCommandsChanged(GetPortalExtensionId(command_str, profile_id), profile_id, ui::CommandMap(), gfx::kNullAcceleratedWidget, base::DoNothing()); }传一个空
CommandMap,表示"这个伪扩展不再有任何命令"。portal 据此释放绑定。
因为两套后端用两个不同的 map(accelerator_callback_map_ 和 command_callback_map_),IsRegistered 要查两遍:
electron_api_global_shortcut.cc:261-264
bool GlobalShortcut::IsRegistered(const ui::Accelerator& accelerator) {
if (accelerator_callback_map_.contains(accelerator)) return true;
const std::string command_str = extensions::Command::AcceleratorToString(accelerator);
return command_callback_map_.contains(command_str);
}
ExecuteCommand 那边还有一条注释:"May arrive after the command was unregistered; ignore it then." —— portal 的回调可能在你注销之后才到,base::FindOrNull 找不到就静默忽略,不会崩。
18.9.3 registerAll 是全有或全无
bool GlobalShortcut::RegisterAll(const std::vector<ui::Accelerator>& accelerators,
const base::RepeatingClosure& callback) {
...
std::vector<ui::Accelerator> registered;
for (auto& accelerator : accelerators) {
if (!Register(accelerator, callback)) {
// Unregister all shortcuts if any failed.
UnregisterSome(registered);
return false;
}
registered.push_back(accelerator);
}
return true;
}
registerAll(['CmdOrCtrl+A', 'CmdOrCtrl+B']) 里第二个失败时,第一个会被回滚注销并返回 false。不会留下"一半注册上、一半没注册"的中间状态。
而 register 失败的原因在内部后端只有一条:instance->RegisterAccelerator(...) 返回 false——系统里已经有别的应用占了这个键(X11 的 XGrabKey 失败、Windows 的 RegisterHotKey 失败)。这个过程不抛异常,只返回 false:
if (!globalShortcut.register('CommandOrControl+Shift+I', fn)) {
// 必须显式检查,否则静默失败
}
18.9.4 macOS 的媒体键要辅助功能权限
electron_api_global_shortcut.cc:41-43
#if BUILDFLAG(IS_MAC)
bool RegisteringMediaKeyForUntrustedClient(const ui::Accelerator& accelerator) {
return accelerator.IsMediaKey() &&
!electron::api::SystemPreferences::IsTrustedAccessibilityClient(false);
}
注册媒体键(播放/暂停、上一曲、下一曲)要求应用被授予"辅助功能"权限。没授权时 Register 直接返回 false——又是返回 false 而不是抛错。IsTrustedAccessibilityClient(false) 传 false 表示"只查询,不弹授权提示"。
配套两行:
ui::GlobalAcceleratorListener::SetShouldUseInternalMediaKeyHandling(false);
// Unregister 里
if (accelerator.IsMediaKey() && !MapHasMediaKeys(accelerator_callback_map_)) {
ui::GlobalAcceleratorListener::SetShouldUseInternalMediaKeyHandling(true);
}
第一个媒体键注册时关掉 Chromium 自己的媒体键处理(否则两边抢),最后一个媒体键注销时再打开。MapHasMediaKeys 扫一遍 map 看还有没有媒体键——手工实现的引用计数。
18.9.5 所有入口都查 app.isReady()
Register、RegisterAll、Unregister、UnregisterAll、SetSuspended 五个函数的开头都是同一段:
if (!electron::Browser::Get()->is_ready()) {
gin_helper::ErrorThrower(JavascriptEnvironment::GetIsolate())
.ThrowError("globalShortcut cannot be used before the app is ready");
return false;
}
注意 ErrorThrower 的临时对象:它的析构函数会把异常真正抛出去,所以这段代码靠 RAII 生效,不需要显式 throw。
SetSuspended 没有暴露给 JS(不在 FillObjectTemplate 里),是内部用的——Electron 在弹出菜单、显示模态对话框时会挂起全局快捷键,避免"菜单开着的时候按快捷键还触发了后台动作"。
Unregister 的顺序也值得记:
if (instance) instance->UnregisterAccelerator(accelerator, this);
// Remove from local callback map after unregistering from UI listener to
// avoid reentrancy races where in-flight key notifications arrive while the
// platform listener is stopping.
accelerator_callback_map_.erase(accelerator);
先让平台停止监听,再删本地回调。反过来的话中间会有一个窗口期:平台还在发通知、本地 map 已经空了,OnKeyPressed 走进 NOTREACHED()。
18.10 clipboard:一个 W3C 化的实现
这个版本的 clipboard 不是"一堆同步 getter/setter",而是一个按 W3C Async Clipboard 规范做的实现,外面再包一层 TS 适配层。理解这一点,才能解释它的返回值为什么是 Promise。
18.10.1 readText() 返回的是 Promise
electron_api_clipboard.cc:254-261
v8::Local<v8::Promise> Clipboard::ReadText(ui::ClipboardBuffer buffer,
v8::Isolate* const isolate) {
gin_helper::Promise<std::u16string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ui::Clipboard::GetForCurrentThread()->ReadText(
buffer, /* data_dst = */ std::nullopt,
base::BindOnce(
[](gin_helper::Promise<std::u16string> promise, ui::ClipboardBuffer buf,
std::u16string result) {
#if BUILDFLAG(IS_WIN)
if (result.empty()) {
ui::Clipboard::GetForCurrentThread()->ReadAsciiText(
buf, /* data_dst = */ std::nullopt,
base::BindOnce([](gin_helper::Promise<std::u16string> p, std::string ascii) {
p.Resolve(base::ASCIIToUTF16(ascii));
}, std::move(promise)));
return;
}
#endif
promise.Resolve(result);
},
std::move(promise), buffer));
return handle;
}
三件事:
- 返回值是
Promise<string>。不是string。所以const text = clipboard.readText()拿到的是一个 Promise 对象,text.toUpperCase()会抛TypeError。必须await。 - Windows 有一条 ASCII 兜底。
ReadText返回空时,再试ReadAsciiText,然后用ASCIIToUTF16转回 UTF-16。这条路径是为"写剪贴板的应用只放了 ANSI 文本"的老程序准备的——它的代价是:如果那段字节不是 ASCII(比如 GBK 编码的中文),ASCIIToUTF16会把它变成一堆?。 - 整个读是异步回调风格的,因为
ui::Clipboard在 ozone/Wayland 上真的是异步的(要跟 compositor 通信)。
配套的 writeText 也是 Promise:
electron_api_clipboard.cc:375-380
v8::Local<v8::Promise> Clipboard::WriteText(ui::ClipboardBuffer buffer,
const std::u16string& text, v8::Isolate* const isolate) {
...
{
ui::ScopedClipboardWriter writer{buffer};
writer.WriteText(text);
}
promise.Resolve();
return handle;
}
ScopedClipboardWriter 的作用域结束时才真正提交。所以「写」在同步阶段完成了实际工作,只是在 API 形状上包了个 Promise。
18.10.2 has() 和 read() 共用一份类型列表
has 不是"试试能不能读出来",而是"看看类型列表里有没有这个字符串":
electron_api_clipboard.cc:236-243
// Resolves `true` iff `format_string` appears in the same aggregated MIME
// list `clipboard.read()` exposes. This means `has` is consistent with
// `read` for every MIME the API surfaces: standard types, `web `-prefixed
// W3C custom formats, `electron application/osclipboard;format="..."`
// raw formats, `electron application/bookmark`, and the macOS find
// pasteboard pseudo-MIME.
v8::Local<v8::Promise> Clipboard::Has(ui::ClipboardBuffer buffer,
const std::string& format_string,
v8::Isolate* const isolate) {
...
EnumerateAvailableTypes(
buffer, base::BindOnce([](gin_helper::Promise<bool> promise, std::string needle,
std::vector<std::string> types) {
promise.Resolve(std::find(types.begin(), types.end(), needle) != types.end());
}, std::move(promise), format_string));
has 返回 Promise<boolean>,且用的是同一个 EnumerateAvailableTypes。这保证了一致性:has(x) 为真 ⟺ (await read())[0].types 里包含 x。
这份列表是四段拼起来的,EnumerateAvailableTypes 里是一条 Promise 链:
-
ReadAvailableStandardAndCustomFormatNames→ 标准 MIME(text/plain、text/html、text/rtf、image/png等)+web前缀的 W3C 自定义格式。Chromium 给的是vector<u16string>,这里一次性转成 UTF-8。 -
GetAllAvailableFormats→ 原始平台格式,但要过滤掉标准格式,否则同一个内容会出现两次:for (const auto& fmt : formats) { // Skip standards — already emitted as MIMEs above. if (IsStandardClipboardFormat(fmt)) continue; const std::string name = ResolvePlatformFormatName(fmt); if (name.empty()) continue; std::string mime = name.starts_with(ui::kWebClipboardFormatPrefix) ? name : BuildOSClipboardFormat(name); if (std::find(types.begin(), types.end(), mime) == types.end()) types.push_back(std::move(mime)); }IsStandardClipboardFormat那张表覆盖三个平台的实现细节(mac 的public.utf8-plain-text、Windows 的CF_DIB、Linux 的 MIME 列表),注释里逐平台列了出来。没有这张表,你就会看到text/plain和一个electron application/osclipboard;format="public.utf8-plain-text"同时存在,指的还是同一份内容。 -
加
electron application/bookmark(如果有书签)。 -
加
electron application/findtext(macOS 的查找粘贴板)。
18.10.3 MIME 的命名规则
三种前缀,各有各的用途:
| 前缀 | 例子 | 含义 |
|---|---|---|
| 标准 MIME | text/plain、text/html、image/png | Chromium 认识的标准格式 |
web 前缀 | web text/uri-list | W3C 自定义格式(Chromium 的约定) |
electron application/osclipboard;format="…" | electron application/osclipboard;format="com.apple.flat-rtfd" | 原始 OS 格式,Electron 自定义 |
第三种格式的解析在 ParseOSClipboardFormat:
electron_api_clipboard.cc:203-210
std::optional<std::string> ParseOSClipboardFormat(const std::string& mime) {
// Expecting `<kOSClipboardMimePrefix>;format="<name>"`. Peel the prefix
// and the trailing quote with `base::Remove{Prefix,Suffix}`; if anything
// doesn't line up, return nullopt.
auto after_prefix = base::RemovePrefix(mime, kOSClipboardMimePrefix);
if (!after_prefix) return std::nullopt;
auto after_eq = base::RemovePrefix(*after_prefix, ";format=\"");
if (!after_eq) return std::nullopt;
auto name = base::RemoveSuffix(*after_eq, "\"");
if (!name) return std::nullopt;
return std::string{*name};
}
严格三段匹配,任何一段不对就 nullopt——所以自己拼一个不完全一样的 MIME 是读不出来的(多个空格、少了引号都不行)。
Windows 上还有一个坑:ClipboardFormatType::GetName() 返回的是数字 id(形如 "49472"),不是名字。所以 ResolvePlatformFormatName 在 Windows 上要反查:
// ClipboardFormatType::GetName() returns the numeric registered-format id
// (e.g. "49472"); this resolves it back to the registered string name
// (e.g. "public/utf8-plain-text") via GetClipboardFormatName so a raw
// format round-trips through the same MIME on write and read.
"round-trips" 是重点:read() 给你的 MIME 拿去 write() 必须能对应回同一个系统格式。如果直接用数字 id,用户看到的是一串无意义的数字;如果只存名字,写入时又找不到对应的注册格式。
18.10.4 write() 是原子的,且拒绝读出来的 item
electron_api_clipboard.cc:333-340
v8::Local<v8::Promise> Clipboard::Write(ui::ClipboardBuffer buffer,
const v8::LocalVector<v8::Value>& items,
v8::Isolate* const isolate) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
{
ui::ScopedClipboardWriter writer{buffer};
for (const auto& val : items) {
ClipboardItem* item = nullptr;
if (!gin::ConvertFromV8(isolate, val, &item) || !item) {
writer.Reset();
promise.Reject(v8::Exception::TypeError(gin::StringToV8(
isolate, "clipboard.write expects an array of ClipboardItem")));
return handle;
}
if (item->is_read_side()) {
// ClipboardItems returned by `clipboard.read()` don't carry the user's
// payload object — they're lightweight readers bound to a buffer and
// can't be passed back to `write()`.
writer.Reset();
promise.Reject(v8::Exception::TypeError(gin::StringToV8(
isolate, "clipboard.write cannot accept a ClipboardItem returned from "
"clipboard.read() — construct a new ClipboardItem to write.")));
return handle;
}
item->WriteTo(writer);
}
// ScopedClipboardWriter's destructor runs here, committing every
// accumulated entry to the system clipboard atomically.
}
promise.Resolve();
return handle;
}
三个设计点:
- 一个
ScopedClipboardWriter覆盖所有 item,所以"写text/plain+text/html+ 一张图"是一次原子提交。系统剪贴板不会出现"只有一半内容"的中间态。这也是 W3C 规范要求的:一次write()对应一次系统级写入。 - 失败时
writer.Reset()。不 Reset 直接返回的话,析构函数会把已经积累的那几条提交上去——变成一次部分写入。 - 读出来的
ClipboardItem不能写回去。read()返回的是"绑定到 buffer 的懒读取器",它内部没有 payload 对象。源码选择显式拒绝并给出一条能看懂的报错,而不是让它写出空内容。
18.10.5 TS 层:Blob 适配
clipboard.ts 是一个纯适配层,把"Buffer 世界"翻译成"Blob 世界":
const wrapClipboard = (native) => {
const api = {
clear: () => native.clear(),
has: (format) => native.has(format),
readText: () => native.readText(),
writeText: (text) => native.writeText(text),
read: async () => {
const items = await native.read();
return items.map((item) => ClipboardItem[kFromNative](item));
},
write: async (items) => {
if (!Array.isArray(items)) throw new TypeError('clipboard.write expects an array of ClipboardItem');
// Resolve every item's Blob payloads to Buffers first, then commit
// them all through a single synchronous native write so the entries
// still land on the system clipboard atomically.
const nativeItems = [];
for (const item of items) {
if (!(item instanceof ClipboardItem)) throw new TypeError('clipboard.write expects an array of ClipboardItem');
nativeItems.push(await item[kToNative]());
}
return native.write(nativeItems);
}
};
return api;
};
关键在 write 的两阶段:先把所有 Blob 读成 Buffer(异步),再一次同步提交。注释说明了原因:Blob.arrayBuffer() 是异步的,如果在提交过程中间 await,ScopedClipboardWriter 就被拆成多次提交,原子性丢了。所以必须"先全部解析完,再一次性写"。
kToNative / kFromNative 是两个 Symbol,作为 clipboard.ts:1-19 和 clipboard-item.ts:21-25 之间的内部接口。用 Symbol 而不是普通方法名,是为了不让它们出现在公开 API 上(Object.keys(item) 看不到)。
clipboard-item.ts 顶部的注释交代了构造函数的校验责任:
The native binding is typed as the public
Electron.ClipboardItem, but its constructor is the real validator: per the W3C spec it accepts aBufferor a string for any MIME type (a string is UTF-8 encoded into the payload bytes), and a{ title, url }object for the bookmark format, throwingTypeErrorfor anything else.
所以 new ClipboardItem({ 'text/plain': 'hello' }) 里的字符串会被 UTF-8 编码,而 { 'electron application/bookmark': { title, url } } 是唯一接受对象的 MIME。
18.10.6 Linux 的 selection 剪贴板是第二个对象
Initialize 里有一段只在 Linux 上编进去的代码:
PopulateClipboardObject(isolate, context, exports, ui::ClipboardBuffer::kCopyPaste);
#if BUILDFLAG(IS_LINUX)
auto selection = v8::Object::New(isolate);
PopulateClipboardObject(isolate, context, selection, ui::ClipboardBuffer::kSelection);
exports->Set(context, gin::StringToV8(isolate, "selection"), selection).Check();
#endif
PopulateClipboardObject 的做法是把 buffer 参数烘进一个 bind:
electron_api_clipboard.cc:417-422
auto set = [&](std::string_view name, auto callback) {
auto tmpl = gin::CreateFunctionTemplate(isolate, std::move(callback));
target->Set(context, gin::StringToV8(isolate, name), tmpl->GetFunction(context).ToLocalChecked()).Check();
};
set("clear", base::BindRepeating(&Clipboard::Clear, buffer));
set("has", base::BindRepeating(&Clipboard::Has, buffer));
set("read", base::BindRepeating(&Clipboard::Read, buffer));
...
所以 JS 层看到的 clipboard.readText 和 clipboard.selection.readText 是两个不同的函数,各自绑定了不同的 ClipboardBuffer。这就是为什么 clipboard.selection 只在 Linux 上存在——只有 X11/Wayland 有"选中即复制"这个独立剪贴板。
macOS 的查找粘贴板是第三个:
#if !BUILDFLAG(IS_MAC)
// Mac impls live in `electron_api_clipboard_mac.mm`.
void Clipboard::WriteFindText(const std::u16string& text) {}
std::u16string Clipboard::ReadFindText() { return {}; }
#endif
非 mac 上是空实现,返回空串。mac 上它操作的是 NSPasteboard 的 find 类型(NSFindPboard),而且保持同步——头文件注释给了理由:"The macOS find pasteboard is a separate pasteboard and the backing Cocoa API is synchronous, so these stay synchronous as well."
18.11 nativeImage:一个多分辨率的容器
NativeImage 不是"一张图",而是 gfx::ImageSkia,一个"同一张图在不同缩放比下的多个位图"的集合。这个模型是所有困惑的源头。
electron_api_native_image.cc:359-364
std::vector<float> NativeImage::GetScaleFactors() {
gfx::ImageSkia image_skia = image_.AsImageSkia();
std::vector<float> scale_factors;
for (const auto& rep : image_skia.image_reps())
scale_factors.push_back(rep.scale());
return scale_factors;
}
一个 NativeImage 里可能只有 [1.0],也可能有 [1.0, 2.0, 3.0]。getScaleFactors() 就是把实际存在的那些列出来。
18.11.1 getSize() 是 DIP,toBitmap() 是像素
gfx::Size NativeImage::GetSize(const std::optional<float> scale_factor) {
float sf = scale_factor.value_or(1.0f);
gfx::ImageSkiaRep image_rep = image_.AsImageSkia().GetRepresentation(sf);
return {image_rep.GetWidth(), image_rep.GetHeight()};
}
GetRepresentation(sf) 会返回"以 sf 为缩放比"的表示——如果那个比例不存在,Skia 会从别的表示缩放出一份。所以:
- 一张只有 2x 表示的图(比如 32×32 像素代表 16×16 DIP),
getSize()默认sf=1.0,返回{16, 16}。 - 同一张图
getSize(2.0)返回{32, 32}。
而 toBitmap() 返回的是像素:
const auto src = image_.AsImageSkia().GetRepresentation(scale).GetBitmap();
const auto dst_info = SkImageInfo::MakeN32Premul(src.dimensions(), color_space.ToSkColorSpace());
const size_t dst_n_bytes = dst_info.computeMinByteSize();
v8::Local<v8::Object> dst_buf;
if (!node::Buffer::New(isolate, dst_n_bytes).ToLocal(&dst_buf)) return {};
if (!src.readPixels(dst_info, node::Buffer::Data(dst_buf), ...
MakeN32Premul 在 little-endian 上是 BGRA 预乘 alpha,不是 RGBA。把它当 RGBA 处理会得到颜色错乱的图(红蓝互换)。readPixels 到 Node Buffer 是一份拷贝,所以后续修改 Buffer 不影响 NativeImage。
colorSpace 是可选的,默认 sRGB。这个参数只在要跟别的色彩空间对齐时才有意义。
18.11.2 createFromBuffer 吃的是裸像素,不是 PNG
NativeImage* NativeImage::CreateFromBuffer(gin_helper::ErrorThrower thrower,
v8::Local<v8::Value> buffer, gin::Arguments* args) {
if (!node::Buffer::HasInstance(buffer)) {
thrower.ThrowError("buffer must be a node Buffer");
return nullptr;
}
int width = 0, height = 0;
double scale_factor = 1.;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("width", &width);
options.Get("height", &height);
options.Get("scaleFactor", &scale_factor);
}
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromBuffer(&image_skia, electron::Buffer::as_byte_span(buffer),
width, height, scale_factor);
return Create(args->isolate(), gfx::Image(image_skia));
}
它要求 width 和 height,因为数据是裸像素。传一张 PNG 的字节进去不会报错——它会被按 width×height×4 解释成一张噪点图(或者因为长度不匹配而得到一张空图)。
想从编码后的字节创建,用 nativeImage.createFromPath / createFromDataURL,或者自己解码后走 createFromBitmap(那个会校验长度):
const auto buffer_data = electron::Buffer::as_byte_span(buffer);
if (size_bytes != buffer_data.size()) {
thrower.ThrowError("invalid buffer size");
return nullptr;
}
createFromDataURL 只认两种 mime:
if (mime_type == "image/png") return CreateFromPNG(isolate, base::as_byte_span(data));
if (mime_type == "image/jpeg") return CreateFromJPEG(isolate, base::as_byte_span(data));
return CreateEmpty(isolate);
image/gif、image/webp、image/svg+xml 的 data URL 全部得到空图,不报错。
18.11.3 空图是静默的
isEmpty() 就是 image_.IsEmpty()。而"空图"出现在很多地方:
createFromPath路径不存在或格式不支持。createFromDataURL遇到非 png/jpeg。createFromBuffer长度不匹配。resize/crop传了非法尺寸。
空图被设成窗口图标、托盘图标、菜单项图标时,不会报错,只是什么都不显示。托盘那个尤其难查:new Tray(emptyImage) 会成功创建一个托盘项,但图标区域是空的,你在系统托盘里找不到它(或者只看到一块透明占位)。
所以所有图标路径都应该加一行断言:
const icon = nativeImage.createFromPath(p);
if (icon.isEmpty()) throw new Error(`icon not loaded: ${p}`);
getAspectRatio() 对空图返回 1(if (size.IsEmpty()) return 1.f;),而不是 0 或 NaN——这也是个"看起来正常"的静默降级。
顺带说 setTemplateImage(true):它让图标在 macOS 上作为模板图渲染——系统只取 alpha 通道,按当前明暗自动涂黑或涂白。所以模板图必须是纯黑 + 透明的单色图,彩色图设了模板会被压成一坨。这个标志在别的平台上没有渲染效果。
18.12 screen:一个懒到极致的 Proxy
screen 模块有一个很特殊的约束:它的内容必须 app.ready 之后才能读。但用户可能在模块顶层就 import { screen } from 'electron'。两者的折中办法是一个 Proxy:
const createScreenIfNeeded = () => {
if (_screen === undefined) _screen = createScreen();
};
export default new Proxy({}, {
get: (target, property) => {
createScreenIfNeeded();
const value = _screen[property];
if (typeof value === 'function') return value.bind(_screen);
return value;
},
set: (target, property, value) => {
createScreenIfNeeded();
return Reflect.set(_screen, property, value);
},
ownKeys: () => { createScreenIfNeeded(); return Reflect.ownKeys(_screen); },
has: (target, property) => { createScreenIfNeeded(); return property in _screen; },
getOwnPropertyDescriptor: (target, property) => {
createScreenIfNeeded();
return Reflect.getOwnPropertyDescriptor(_screen, property);
},
getPrototypeOf: () => {
// This is necessary as a result of weirdness with EventEmitterMixin
// and FunctionTemplate - we need to explicitly ensure it's returned
// in the prototype.
return EventEmitter.prototype;
}
});
源码注释交代了动机:
We can't call createScreen until after app.on('ready'), but this module exposes an instance created by createScreen. In order to avoid side-effecting and calling createScreen upon import of this module, instead we export a proxy which lazily calls createScreen on first access.
三个后果:
import { screen }本身安全,碰任何属性都会抛。screen.getAllDisplays()在 ready 之前抛 "The 'screen' module can't be used before the app 'ready' event"。而console.log(screen)也会触发(ownKeys)——调试时在 ready 之前打印screen会抛异常。- 每次取方法都新建一个绑定函数。
value.bind(_screen)每次调用get都产生新函数,所以screen.getAllDisplays === screen.getAllDisplays是false。想拿它当removeListener的参数时要注意:必须保存同一个引用。 getPrototypeOf硬返回EventEmitter.prototype。注释说是为了绕EventEmitterMixin+FunctionTemplate的怪问题。实际效果是screen instanceof EventEmitter为真。
18.12.1 Wayland 上 getCursorScreenPoint() 恒返回 (0,0)
electron_api_screen.cc:93-96
gfx::Point Screen::GetCursorScreenPoint(v8::Isolate* isolate) {
#if BUILDFLAG(IS_LINUX)
if (x11_util::IsWayland()) return {};
#endif
auto* screen = GetDisplayScreen();
return screen ? screen->GetCursorScreenPoint() : gfx::Point{};
}
Wayland 协议不给客户端读全局鼠标位置(隐私设计),所以这里直接返回原点。这意味着:
screen.getCursorScreenPoint()在 Wayland 上永远是{x: 0, y: 0}。- 依赖它算弹出位置的代码(
menu.popup({x, y})传鼠标坐标)在 Wayland 上会弹到屏幕左上角。 - 判据是
x11_util::IsWayland(),即运行时会话类型,不是编译期平台。
正确的替代方案是让 menu.popup() 不传坐标(x/y 为 -1 时两个平台都会用系统给的鼠标位置,18.5.4),或者从 webContents 的 context-menu 事件里拿 params.x/params.y——那是 renderer 侧算出来的,不受限制。
18.12.2 所有方法都先 GetDisplayScreen(),因为它可能是空
// Calls the one-liner `display::Screen::Get()` to get ui's global screen.
// NOTE: during shutdown, that screen can be destroyed before us. This means:
// 1. Call this instead of keeping a possibly-dangling raw_ptr in api::Screen.
// 2. Always check this function's return value for nullptr before use.
[[nodiscard]] auto* GetDisplayScreen() {
return display::Screen::Get();
}
Screen 对象自己不缓存 display::Screen*,每次用都现场取。因为关机时 display::Screen 可能比 api::Screen 先销毁,缓存下来就是一个悬空指针。
每个方法都写了空值兜底:
display::Display Screen::GetPrimaryDisplay() const {
const auto* screen = GetDisplayScreen();
return screen ? screen->GetPrimaryDisplay() : GetFallbackDisplay();
}
std::vector<display::Display> Screen::GetAllDisplays() const {
if (const auto* screen = GetDisplayScreen()) return screen->GetAllDisplays();
// Even though this is only reached during shutdown by Screen::Get() failing,
// display::Screen::GetAllDisplays() is guaranteed to return >= 1 display.
// For consistency with that API, let's return a nonempty vector here.
return {GetFallbackDisplay()};
}
GetAllDisplays() 的空值路径返回一个单元素数组而不是空数组,注释明确说是为了跟 Chromium 的契约保持一致。所以 screen.getAllDisplays().length 永远 ≥ 1,你不能靠它判断"有没有显示器"。
18.12.3 DIP 换算只有两个平台有
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
.SetMethod("screenToDipPoint", &Screen::ScreenToDIPPoint)
.SetMethod("dipToScreenPoint", &Screen::DIPToScreenPoint)
#endif
#if BUILDFLAG(IS_WIN)
.SetMethod("screenToDipRect", &ScreenToDIPRect)
.SetMethod("dipToScreenRect", &DIPToScreenRect)
#endif
screenToDipPoint / dipToScreenPoint 在 Windows 和 Linux 上有,macOS 上没有;screenToDipRect / dipToScreenRect 只有 Windows 有。
原因:macOS 的坐标系本来就是 DIP(点),不存在"物理像素坐标"这个概念需要换算;Windows 有 per-monitor DPI,窗口坐标在"物理像素"和"DIP"之间要转;Linux 在混合 DPI 多显示器下也要转。所以 API 只在需要转的平台上存在——跨平台代码里调它们会得到 undefined is not a function。
display-metrics-changed 事件的 metrics 数组也只有四种可能:
std::vector<std::string> MetricsToArray(uint32_t metrics) {
if (metrics & display::DisplayObserver::DISPLAY_METRIC_BOUNDS) array.emplace_back("bounds");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_WORK_AREA) array.emplace_back("workArea");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR) array.emplace_back("scaleFactor");
if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION) array.emplace_back("rotation");
return array;
}
bounds / workArea / scaleFactor / rotation。一次显示器变化可能同时带多个(比如分辨率变了,bounds 和 scaleFactor 一起变),所以这个数组是要遍历的,不能只取 [0]。
18.13 小结
这一章讲的八个模块,表面上是八个 API,实际上是三种资源归属模式的样本。
第一种:无状态函数。 dialog 和 screen 都在这一类。它们没有 JS 对象、没有原生资源、没有生命周期。dialog 甚至把一半逻辑放在了 TypeScript 里,因为它要做的全是对 options 的归一化。这类模块的问题永远在"参数校验"和"平台差异"上——filePath vs filePaths、properties 位掩码的两份手写副本、mac 的 sheet vs modal。
第二种:JS 对象持有原生资源,生命周期由 JS 决定。 Tray、Notification、Menu 在弹窗时都属于这一类,但三者的策略完全不同:
Tray用SelfKeepAlive{this}把自己永久钉住,必须显式destroy()。代价是忘记销毁就泄漏。Menu用SelfKeepAlive{nullptr}只在自己被"打开"的期间钉住(menu-will-show→menu-will-close),另外用cppgc::Persistent覆盖 popup 的整个回调周期。代价是关闭瞬间到回收之间有一个窗口,靠两层保护叠起来才安全。Notification谁都不钉,改用WeakPersistent+IsolateDisposeObserver。平台回调进来时先Get()判空,对象没了就静默返回。
第三种:原生侧持有 model 指针,JS 侧必须反向保活。 这是最容易出悬空指针的一类。TrayIcon 拿着 ElectronMenuModel*,ElectronMenuController 拿着弱引用的 model,ElectronMenuModel 里存的是 MenuItem* 裸指针。三条链都需要 JS 侧主动钉住上游对象:Tray::menu_、ElectronApplicationMenuHolder::_menu、Menu::first_entry_ 那条侵入式链表。
第 7 章讲 gin 绑定层时反复出现的一个主题是:一个 C++ 对象的生命周期归谁管,是一份必须显式签订的契约——gin::Wrappable 只负责"V8 那一半",剩下那一半要么靠 Managed 式的 ownership,要么靠 cppgc 的 Trace,要么靠手写 SelfKeepAlive。这一章是那份契约在原生 UI 上的完整展开——每一个 Persistent、每一个 WeakPersistent、每一个 SelfKeepAlive,对应的都是"如果不这么写,会在什么时机崩"。
还有一条贯穿全章的规律:原生 UI 的失败几乎都是静默的。未知 role 变成空行、type 改了不生效、setTitle 在非 mac 上是空函数、空图不显示、showMessageBox 的 early-abort 返回另一个形状、globalShortcut.register 返回 false 而不是抛错、Linux 上没有通知服务就什么都不做。这一章之所以要逐个字段读源码,就是因为这些失败都不会出现在日志里——它们表现为"界面看起来不太对"。
下一章换一个方向:从"屏幕上的东西"转向"离开屏幕的东西"——打印、PDF 生成、离屏渲染和桌面捕获。它们共同的技术底座是同一件事:把一段渲染结果从 GPU 的合成器里取出来。
18.14 本章源码落点索引
下列位置全部来自本仓库源码树,按实现层归集;每个
路径:行号指向该文件中与本章论述对应的声明或实现行,可逐条复核。
- 浏览器进程 C++ 层:
electron_api_menu_views.h:17 electron_api_notification.h:22 electron_api_global_shortcut.h:21 electron_browser_client.h:26 electron_api_clipboard.h:19 electron_api_clipboard_item.cc:51 electron_api_clipboard_item.h:20 electron_api_clipboard_win.cc:18 -
electron_api_menu_mac.h:17 electron_api_push_notifications.cc:19 electron_api_push_notifications.h:19 electron_api_push_notifications_mac.mm:17 libnotify_notification.h:15 notification_presenter_linux.h:13 windows_toast_notification.cc:49 windows_toast_notification.h:30 -
accelerator_util.h:17 accelerator_util_unittests.cc:11 electron_extensions_browser_client.cc:58 electron_extensions_browser_client.h:20 electron_api_screen.h:16 load_url_promises.cc:27 load_url_promises.h:32 cocoa_notification.h:17 -
cocoa_notification.mm:29 - shell 其余实现:
file_dialog_converter.h:14 accelerator_converter.cc:14 accelerator_converter.h:11 - JS 门面与运行时:
global-shortcut.ts:1 menu-item.ts:1 push-notifications.ts:1 screen.ts:3