Skip to content

Commit e9d6e43

Browse files
committed
feat(extension): 扩展新增 presence / lifecycle 状态事件
扩展此前只能看到按键、模式、上屏,无从知道输入法整体状态。新增两类不含输入内容、 不受授权档位管的事件: - presence:终端数与是否有输入焦点,变化时发,握手后补发当前值; - lifecycle:started(握手后)、stopping(宿主收到 shutdown 时先告知再收走)、 config_reloaded(配置热重载)。服务重启在扩展看来即新握手 + started。
1 parent 1d1ac84 commit e9d6e43

9 files changed

Lines changed: 380 additions & 18 deletions

File tree

‎docs/design/extension-hook-channel.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,22 @@ key 事件带具体按键,敏感度等同键盘记录器。以下全部是**
162162
产出随中英、Shift、标点设置变化,按键位配音效要的是物理键。只有 `key.class` 档时,`key` 字段省略。
163163
- 键名由 VK 推导:三平台前端送到核心的 `keyCode` 都已统一换算为 Windows VK,`scanCode`
164164
在 macOS/Linux 恒为 0,不可用。
165+
- 状态类事件(不含输入内容,不受授权档位管,任何已启用的扩展都能收):
166+
167+
```jsonc
168+
{"t":"presence","seq":6,"ts":140,"terminals":0,"focused":false}
169+
{"t":"lifecycle","seq":7,"ts":150,"event":"started"} // started / stopping / config_reloaded
170+
```
171+
172+
- `presence`:`terminals` 为连着核心的终端数(push 客户端),`focused` 为 `ime_active && has_edit_context`。
173+
服务进程的扩展监护线程约每 200ms 调协调器的 `hook_presence`,只在「有无终端 / 有无焦点」变化时发;
174+
不在每个焦点处理函数里埋点,免得漏掉连接断开这类没有处理函数的变化。宿主缓存最近一条,握手后补发。
175+
- `lifecycle.started`:宿主在握手、补发状态、选项之后发给每个扩展;服务重启时旧宿主连同扩展一起结束,
176+
新服务拉起全新的一批,所以「重启」对扩展就是新握手 + `started`,不需要单独的事件。
177+
- `lifecycle.stopping`:宿主收到 `shutdown`(服务重启/退出,或扩展全部停用)时先广播再收走扩展;
178+
队列关闭时会写完已入队消息,扩展有宽限期收尾。崩溃或被强杀时发不出。
179+
- `lifecycle.config_reloaded`:核心配置热重载后发(与 `[extensions]` 是否变化无关)。
180+
- 不加新档位:位图已用 7/8 位,且这些事件不含输入内容。代价是用户无法单独关掉它们,可接受。
165181
- `key` 只表示**按下**,没有抬起事件(理由见 §8.2)。
166182
- `key.handled`:输入法是否吃掉了这个键。
167183
- `key.observed`:该键输入法本不处理,是前端为扩展额外上报的旁路通知(见 §8.1)。

‎wind_input/apps/extension_host/src/lib.rs‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,10 @@ use wind_hook::PROTOCOL_VERSION;
2323
use wind_hook::backoff::{Backoff, Decision};
2424
use wind_hook::frame::{Frame, read_frame, write_frame};
2525
use wind_hook::manifest::{self, Manifest};
26-
use wind_hook::msg::{ExtensionGrant, ExtensionStatus, Msg};
26+
use wind_hook::msg::{ExtensionGrant, ExtensionStatus, LifecycleEvent, Msg, lifecycle};
2727
use wind_hook::options;
2828
use wind_hook::queue::{DropOldest, Pop};
29+
use wind_hook::tap::now_ms;
2930
use wind_hook::tier::{Grants, trim};
3031

3132
/// 每个扩展的待写队列长度。按键再快每秒也就几十条,几百条够扛住一两秒的卡顿。
@@ -212,11 +213,20 @@ pub struct Host {
212213
/// 核心最近发来的模式事件。模式不常变,后连上(或重启后)的扩展握手完立即补发一份,
213214
/// 否则它要等到用户下次切中英才知道当前状态。
214215
last_mode: Arc<Mutex<Option<Msg>>>,
216+
/// 核心最近发来的终端在线/焦点状态,补发理由同 `last_mode`。
217+
last_presence: Arc<Mutex<Option<Msg>>>,
215218
stop: AtomicBool,
216219
#[cfg(windows)]
217220
job: Option<job::Job>,
218221
}
219222

223+
fn lifecycle_msg(event: &str) -> Msg {
224+
Msg::Lifecycle(LifecycleEvent {
225+
ts: now_ms(),
226+
event: event.into(),
227+
})
228+
}
229+
220230
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
221231
m.lock().unwrap_or_else(|e| e.into_inner())
222232
}
@@ -228,6 +238,7 @@ impl Host {
228238
out: Mutex::new(out),
229239
slots: Mutex::new(BTreeMap::new()),
230240
last_mode: Arc::new(Mutex::new(None)),
241+
last_presence: Arc::new(Mutex::new(None)),
231242
stop: AtomicBool::new(false),
232243
#[cfg(windows)]
233244
job: job::Job::kill_on_close()
@@ -240,20 +251,28 @@ impl Host {
240251
fn on_core(&self, msg: Msg) -> bool {
241252
match msg {
242253
Msg::Config { extensions } => self.apply_config(extensions),
243-
Msg::Shutdown => return false,
254+
Msg::Shutdown => {
255+
// 先告知再收走:队列关闭时会把已入队的消息写完,扩展有机会收尾。
256+
self.broadcast_keep(lifecycle_msg(lifecycle::STOPPING));
257+
return false;
258+
}
244259
Msg::Key(_)
245260
| Msg::Mode(_)
246261
| Msg::Composition(_)
247262
| Msg::Candidates(_)
248-
| Msg::Commit(_) => self.dispatch(&msg),
263+
| Msg::Commit(_)
264+
| Msg::Presence(_)
265+
| Msg::Lifecycle(_) => self.dispatch(&msg),
249266
_ => {}
250267
}
251268
true
252269
}
253270

254271
fn dispatch(&self, msg: &Msg) {
255-
if matches!(msg, Msg::Mode(_)) {
256-
*lock(&self.last_mode) = Some(msg.clone());
272+
match msg {
273+
Msg::Mode(_) => *lock(&self.last_mode) = Some(msg.clone()),
274+
Msg::Presence(_) => *lock(&self.last_presence) = Some(msg.clone()),
275+
_ => {}
257276
}
258277
for slot in lock(&self.slots).values() {
259278
if let Some(run) = &slot.run
@@ -264,6 +283,15 @@ impl Host {
264283
}
265284
}
266285

286+
/// 给全部运行中的扩展发一条不可淘汰的状态消息(经写线程按授权/订阅过滤)。
287+
fn broadcast_keep(&self, msg: Msg) {
288+
for slot in lock(&self.slots).values() {
289+
if let Some(run) = &slot.run {
290+
run.link.queue.push_keep(msg.clone());
291+
}
292+
}
293+
}
294+
267295
fn apply_config(&self, extensions: Vec<ExtensionGrant>) {
268296
let mut slots = lock(&self.slots);
269297
let wanted: BTreeMap<String, (Grants, Options)> = extensions
@@ -455,6 +483,7 @@ impl Host {
455483
self.opts.core_version.clone(),
456484
m.protocol.clone(),
457485
self.last_mode.clone(),
486+
self.last_presence.clone(),
458487
);
459488
Ok(Running { child, link })
460489
}
@@ -590,6 +619,7 @@ fn spawn_reader(
590619
core_version: String,
591620
manifest_protocol: Vec<u32>,
592621
last_mode: Arc<Mutex<Option<Msg>>>,
622+
last_presence: Arc<Mutex<Option<Msg>>>,
593623
) {
594624
let id = id.to_string();
595625
let _ = std::thread::Builder::new()
@@ -626,7 +656,12 @@ fn spawn_reader(
626656
if let Some(m) = lock(&last_mode).clone() {
627657
link.queue.push_keep(m);
628658
}
659+
if let Some(m) = lock(&last_presence).clone() {
660+
link.queue.push_keep(m);
661+
}
629662
link.send_options();
663+
// 最后发 started:此时扩展已拿到授权、当前状态与选项,可以开始工作。
664+
link.queue.push_keep(lifecycle_msg(lifecycle::STARTED));
630665
}
631666
Msg::Subscribe { events } => {
632667
*lock(&link.subscribed) = Some(events.into_iter().collect());

‎wind_input/apps/extension_host/tests/host.rs‎

Lines changed: 95 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ use std::time::{Duration, Instant};
88

99
use serde_json::Value;
1010
use wind_hook::frame::{Frame, read_frame, write_frame};
11-
use wind_hook::msg::{CommitEvent, ExtensionGrant, ExtensionStatus, KeyEvent, ModeEvent, Msg};
11+
use wind_hook::msg::{
12+
CommitEvent, ExtensionGrant, ExtensionStatus, KeyEvent, LifecycleEvent, ModeEvent, Msg,
13+
PresenceEvent,
14+
};
1215

1316
fn fake_extension_exe() -> PathBuf {
1417
let host = Path::new(env!("CARGO_BIN_EXE_wind_input_ext"));
@@ -218,16 +221,20 @@ fn events_are_trimmed_to_granted_and_wanted_tiers() {
218221
});
219222
let got = msgs(&lines);
220223
let kinds: Vec<&str> = got.iter().map(|m| m["t"].as_str().unwrap()).collect();
221-
assert_eq!(kinds, ["welcome", "key", "commit"], "mode 未授权不应送达");
224+
assert_eq!(
225+
kinds,
226+
["welcome", "lifecycle", "key", "commit"],
227+
"mode 未授权不应送达"
228+
);
222229
assert_eq!(
223230
got[0]["granted"],
224231
serde_json::json!(["key.class", "commit"])
225232
);
226233
assert!(
227-
got[1].get("key").is_none() && got[1].get("mods").is_none(),
234+
got[2].get("key").is_none() && got[2].get("mods").is_none(),
228235
"只有 key.class 时抹掉具体键"
229236
);
230-
assert_eq!(got[2]["text"], "你好");
237+
assert_eq!(got[3]["text"], "你好");
231238
}
232239

233240
#[test]
@@ -306,10 +313,91 @@ fn late_extension_receives_current_mode_after_handshake() {
306313
});
307314
let got = msgs(&lines);
308315
let kinds: Vec<&str> = got.iter().map(|m| m["t"].as_str().unwrap()).collect();
309-
assert_eq!(kinds, ["welcome", "mode"]);
316+
assert_eq!(kinds, ["welcome", "mode", "lifecycle"]);
310317
assert_eq!(got[1]["full_width"], true);
311318
}
312319

320+
#[test]
321+
fn state_events_reach_extensions_without_any_tier() {
322+
let mut core = Core::start();
323+
let out = core._tmp.path().join("echo.log");
324+
// 不申请任何档位:状态类事件不含输入内容,照样能收到。
325+
core.install("echo", &["echo", out.to_str().unwrap()]);
326+
// presence 先于扩展启动到达:握手后应补收当前值,且随后收到 started。
327+
core.config(&[("echo", &[])]);
328+
core.send(Msg::Presence(PresenceEvent {
329+
ts: 1,
330+
terminals: 0,
331+
focused: false,
332+
}));
333+
read_lines(&out, Duration::from_secs(5), |l| {
334+
msgs(l).iter().any(|m| m["event"] == "started")
335+
});
336+
core.send(Msg::Lifecycle(LifecycleEvent {
337+
ts: 2,
338+
event: "config_reloaded".into(),
339+
}));
340+
let lines = read_lines(&out, Duration::from_secs(5), |l| {
341+
msgs(l).iter().any(|m| m["event"] == "config_reloaded")
342+
});
343+
let got = msgs(&lines);
344+
let kinds: Vec<(&str, &str)> = got
345+
.iter()
346+
.map(|m| (m["t"].as_str().unwrap(), m["event"].as_str().unwrap_or("")))
347+
.collect();
348+
assert_eq!(
349+
kinds,
350+
[
351+
("welcome", ""),
352+
("presence", ""),
353+
("lifecycle", "started"),
354+
("lifecycle", "config_reloaded")
355+
]
356+
);
357+
assert_eq!(got[1]["terminals"], 0);
358+
}
359+
360+
#[test]
361+
fn subscribe_can_narrow_state_events() {
362+
let mut core = Core::start();
363+
let out = core._tmp.path().join("echo.log");
364+
core.install("echo", &["echo", out.to_str().unwrap(), "mode"]);
365+
core.config(&[("echo", &["mode"])]);
366+
core.wait_for("echo", Duration::from_secs(5), |s| s.state == "running");
367+
read_lines(&out, Duration::from_secs(5), |l| {
368+
msgs(l).iter().any(|m| m["event"] == "started")
369+
});
370+
// 默认订阅全部;这里只验证没收窄时 presence 能到(收窄由写线程的既有订阅逻辑负责)。
371+
core.send(Msg::Presence(PresenceEvent {
372+
ts: 3,
373+
terminals: 2,
374+
focused: true,
375+
}));
376+
let lines = read_lines(&out, Duration::from_secs(5), |l| {
377+
msgs(l).iter().any(|m| m["t"] == "presence")
378+
});
379+
assert!(msgs(&lines).iter().any(|m| m["focused"] == true));
380+
}
381+
382+
#[test]
383+
fn shutdown_tells_extensions_before_they_are_stopped() {
384+
let mut core = Core::start();
385+
let out = core._tmp.path().join("echo.log");
386+
core.install("echo", &["echo", out.to_str().unwrap()]);
387+
core.config(&[("echo", &[])]);
388+
read_lines(&out, Duration::from_secs(5), |l| {
389+
msgs(l).iter().any(|m| m["event"] == "started")
390+
});
391+
core.send(Msg::Shutdown);
392+
let lines = read_lines(&out, Duration::from_secs(5), |l| {
393+
msgs(l).iter().any(|m| m["event"] == "stopping")
394+
});
395+
assert!(
396+
msgs(&lines).iter().any(|m| m["event"] == "stopping"),
397+
"宿主收到 shutdown 应先通知扩展 stopping"
398+
);
399+
}
400+
313401
#[test]
314402
fn invalid_extension_is_retried_on_next_config() {
315403
let mut core = Core::start();
@@ -357,7 +445,7 @@ fn options_are_validated_sent_after_handshake_and_updated_without_restart() {
357445
});
358446
let got = msgs(&lines);
359447
let kinds: Vec<&str> = got.iter().map(|m| m["t"].as_str().unwrap()).collect();
360-
assert_eq!(kinds, ["welcome", "options"]);
448+
assert_eq!(kinds, ["welcome", "options", "lifecycle"]);
361449
assert_eq!(
362450
got[1]["values"],
363451
serde_json::json!({"volume": 1.0, "theme": "click"})
@@ -420,5 +508,5 @@ fn extension_without_options_gets_no_options_message() {
420508
.iter()
421509
.map(|m| m["t"].as_str().unwrap().to_string())
422510
.collect();
423-
assert_eq!(kinds, ["welcome", "mode"]);
511+
assert_eq!(kinds, ["welcome", "mode", "lifecycle"]);
424512
}

‎wind_input/apps/service/src/extensions.rs‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,11 @@ fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
7575
}
7676

7777
impl Extensions {
78-
pub fn start(tap: Arc<Tap>, on_hook_changed: Box<dyn Fn() + Send + Sync>) -> Arc<Extensions> {
78+
pub fn start(
79+
tap: Arc<Tap>,
80+
on_hook_changed: Box<dyn Fn() + Send + Sync>,
81+
on_poll: Box<dyn Fn() + Send + Sync>,
82+
) -> Arc<Extensions> {
7983
let rx = tap.connect(Grants::NONE, TAP_CAP);
8084
let p = Arc::new(Extensions {
8185
tap,
@@ -111,13 +115,40 @@ impl Extensions {
111115
.spawn(move || {
112116
loop {
113117
p.tick(Instant::now());
118+
on_poll();
114119
std::thread::sleep(TICK);
115120
}
116121
});
117122
}
118123
p
119124
}
120125

126+
/// 服务即将重启或退出:关宿主,扩展会先收到 `lifecycle: stopping`(宿主发),有机会收尾。
127+
/// 最多等 `STOP_GRACE`,宿主退出即返回;没有宿主时立即返回。
128+
pub fn stop(&self) {
129+
let host = {
130+
let mut st = lock(&self.state);
131+
st.want.clear();
132+
st.next_start = None;
133+
st.host.take()
134+
};
135+
let Some(mut h) = host else {
136+
return;
137+
};
138+
// 宿主收到 shutdown 会先向各扩展发 `lifecycle: stopping`,再收走它们。
139+
h.queue.push_keep(Msg::Shutdown);
140+
h.queue.close();
141+
let deadline = Instant::now() + STOP_GRACE;
142+
while Instant::now() < deadline {
143+
if matches!(h.child.try_wait(), Ok(Some(_))) {
144+
return;
145+
}
146+
std::thread::sleep(Duration::from_millis(20));
147+
}
148+
let _ = h.child.kill();
149+
let _ = h.child.wait();
150+
}
151+
121152
/// 配置变化(含启动时的初值)。授权有变时通知协调器(放锁之后)。
122153
pub fn apply_config(&self, cfg: &ExtensionsConfig) {
123154
if self.apply_config_locked(cfg) {

‎wind_input/apps/service/src/main.rs‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -440,11 +440,19 @@ fn main() {
440440
let coord_for_exit = coordinator.clone();
441441
coordinator.install_exit_flush();
442442
// 扩展程序:按 `[extensions]` 配置拉起扩展宿主,配置热重载时增量调整(注册即按当前值生效)。
443-
let extensions = extensions::Extensions::start(coordinator.hook_tap(), {
444-
let c = coordinator.clone();
445-
Box::new(move || c.hook_changed())
446-
});
443+
let extensions = extensions::Extensions::start(
444+
coordinator.hook_tap(),
445+
{
446+
let c = coordinator.clone();
447+
Box::new(move || c.hook_changed())
448+
},
449+
{
450+
let c = coordinator.clone();
451+
Box::new(move || c.hook_presence())
452+
},
453+
);
447454
let extensions_for_rpc = extensions.clone();
455+
let extensions_for_exit = extensions.clone();
448456
coordinator.set_extensions_config_hook(Box::new(move |c| extensions.apply_config(c)));
449457
deferred.set_ready(coordinator);
450458

@@ -588,6 +596,7 @@ fn main() {
588596

589597
if RESTART.load(Ordering::SeqCst) {
590598
info!("Restart requested, relaunching service...");
599+
extensions_for_exit.stop();
591600
coord_for_exit.flush_user_data_before_exit();
592601
drop(_singleton_guard);
593602
relaunch_self();
@@ -602,6 +611,7 @@ fn main() {
602611
match restart_rx.recv() {
603612
Ok(()) => {
604613
info!("Restart requested, relaunching service...");
614+
extensions_for_exit.stop();
605615
coord_for_exit.flush_user_data_before_exit();
606616
// 先释放单例 Named Mutex(关闭句柄),让新实例可获取所有权,避免竞争
607617
drop(_singleton_guard);

‎wind_input/crates/wind-bridge/src/push.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,11 @@ impl PushServer {
301301
self.gained_token.load(Ordering::Relaxed)
302302
}
303303

304+
/// 已连接的客户端(宿主应用进程)数。
305+
pub fn client_count(&self) -> usize {
306+
self.clients.lock().unwrap().len()
307+
}
308+
304309
/// 是否有已连接的 TSF 客户端(用于决定是否经 IPC 让宿主执行前台操作)
305310
pub fn has_clients(&self) -> bool {
306311
!self.clients.lock().unwrap().is_empty()

0 commit comments

Comments
 (0)