ek-ui 0.9.37

ek 生态常驻主界面(egui/eframe):插件即界面——观测页 + 日志页,车头与 UI 同插件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! mount —— 模块挂载表(0.9.34「插件界面 = 一模块一菜单」波)。
//!
//! 规则(用户裁定,2026-11-01):
//! - **一个模块([`ek_core::Plugin::kind`])一个菜单项、一扇窗**;菜单项数**只随模块数变**,
//!   不随实例数变(`ctp_278153` / `ctp_220380` 共用一个「交易网关」项)。
//! - 窗内怎么分(表格 / tab / 分栏)由模块自己决定 —— CTP 用一张账户表,dm/oms/tq 用各自
//!   的 `ui_face`。框架只负责"取到实例、把宿主交进去"。
//! - 关窗**不销毁**实例(= Python `self.widgets` 字典),再点直接复用编辑中的内容。
//! - 装配名单驱动:没装的不出现;`always = true` 的模块(交易网关 / 宿主自有窗)恒在。
//!
//! 与已退役的 `faces.rs`(0.9.10 连根铲)的关系:那条线是"一实例一面",本模块换成
//! "一模块一窗",并把派发收成 [`Body`] 枚举 + `match`(不引 trait、不建新 crate)。

use std::sync::Arc;

use ek_core::cfg_face::CfgHost;
use ek_core::context::PluginContext;
use ek_core::main_engine::MainEngine;
use ek_core::section::SectionMap;

use crate::state::UiShared;

/// 窗内形状(A8)。本期只实现 [`Shape::Single`];`PerInstance` 是留给
/// "确实需要按实例拆二级菜单"的模块的逃生门(字段就位、行为不实现)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Shape {
    /// 一模块一窗,窗内自己分(默认)。
    #[default]
    Single,
    /// 框架按实例拆二级菜单 + 多窗(本期不实现,仅占位)。
    PerInstance,
}

/// 一扇模块窗的体。新增一个插件面 = 加一个变体 + 一个 `match` 分支
/// (`scripts/check_plugin_faces.ps1` 会比对"有面必有体")。
pub enum Body {
    /// ek-dm 自带面。
    Dm(ek_dm::ui_face::DmUiState),
    /// ek-oms 自带面。
    Oms(ek_oms::ui_face::OmsUiState),
    /// ek-tq 自带面。
    Tq(ek_tq::ui_face::TqUiState),
    /// 交易网关(宿主模块:账户表;S4)。
    Gateway(crate::gateway::TableState),
    /// 宿主自有窗(运维 / 查询合约 / K线;S5)。
    Host(crate::hostwin::State),
}

/// 一扇模块窗。
pub struct ModuleWin {
    /// 窗口键(`egui` viewport id / 嵌入窗 id 都吃它,保证多窗互不踩)。
    pub id: String,
    /// 模块名(= [`ek_core::Plugin::kind`])。
    pub kind: String,
    /// 菜单文字 + 窗标题。
    pub title: String,
    /// emoji(菜单前缀)。
    pub icon: &'static str,
    /// 菜单内排序。
    pub order: i32,
    /// 窗内形状。
    pub shape: Shape,
    /// 该模块当前实例名(装配后由 [`Registry::sync`] 维护)。
    pub instances: Vec<String>,
    /// `true` = 未装配也出现(交易网关 / 宿主自有窗)。
    pub always: bool,
    /// 打开即最大化(BD-UI-34:K线窗用户裁定)。
    pub maximized: bool,
    /// 开合(关窗不销毁实例)。
    pub open: bool,
    /// 默认内尺寸。
    pub size: [f32; 2],
    /// 最小内尺寸。
    pub min_size: [f32; 2],
    /// 窗体。
    pub body: Body,
}

impl std::fmt::Debug for ModuleWin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ModuleWin")
            .field("id", &self.id)
            .field("kind", &self.kind)
            .field("instances", &self.instances)
            .field("open", &self.open)
            .finish()
    }
}

impl ModuleWin {
    /// 本窗要渲染的实例名(`Single` 取第一个;无实例 = 空串)。
    #[must_use]
    fn primary_instance(&self) -> &str {
        self.instances.first().map(String::as_str).unwrap_or("")
    }
}

/// 挂载表。
pub struct Registry {
    /// 模块窗(按 `order` 排序后使用)。
    pub list: Vec<ModuleWin>,
}

impl Default for Registry {
    /// 空表也是"合法表":`always` 模块在 [`Registry::with_always`] 里补齐,
    /// `Default` 只给 `#[derive(Default)] UiShared` 用(测试无引擎时也不炸)。
    fn default() -> Self {
        Self { list: Vec::new() }
    }
}

impl std::fmt::Debug for Registry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(self.list.iter().map(|m| (&m.id, &m.instances)))
            .finish()
    }
}

// ================ 模块描述(一模块一行;新增模块只改这张表)================

/// 模块描述(静态元数据)。
pub struct ModDesc {
    pub kind: &'static str,
    pub title: &'static str,
    pub icon: &'static str,
    pub order: i32,
    pub size: [f32; 2],
    pub min_size: [f32; 2],
    pub always: bool,
    /// 打开即最大化(BD-UI-34:K线窗用户裁定)。
    pub maximized: bool,
}

/// 已知模块表。**顺序无关**(渲染按 `order`)。
pub const MODULES: &[ModDesc] = &[
    ModDesc {
        kind: "ctp",
        title: "交易网关",
        icon: "🔗",
        order: 10,
        size: [1100.0, 560.0],
        min_size: [720.0, 360.0],
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "dm",
        title: "数据管理",
        icon: "📊",
        order: 20,
        size: [560.0, 420.0],
        min_size: [380.0, 260.0],
        // 0.9.37(用户裁定):**有界面的插件常驻菜单**,不等装配 —— 窗口本体在插件
        // 缺席时显示「未装配」提示,菜单项本身不许消失(消失 = 用户找不到入口)。
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "oms",
        title: "交易中枢",
        icon: "⚙",
        order: 30,
        size: [560.0, 460.0],
        min_size: [380.0, 280.0],
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "tq",
        title: "天勤桥",
        icon: "🌉",
        order: 40,
        size: [520.0, 400.0],
        min_size: [360.0, 260.0],
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "ops",
        title: "运维",
        icon: "🛠",
        order: 50,
        size: [680.0, 420.0],
        min_size: [420.0, 260.0],
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "contracts",
        title: "查询合约",
        icon: "🔍",
        order: 60,
        size: [620.0, 460.0],
        min_size: [420.0, 260.0],
        always: true,
        maximized: false,
    },
    ModDesc {
        kind: "kline",
        title: "K线",
        icon: "📈",
        order: 70,
        size: [560.0, 360.0],
        min_size: [360.0, 220.0],
        always: true,
        maximized: true,
    },
];

fn desc_of(kind: &str) -> Option<&'static ModDesc> {
    MODULES.iter().find(|d| d.kind == kind)
}

/// 由模块名建窗体。**本函数就是"新插件面"的唯一登记点**:
/// 插件有 `ui_face` 却没在这里登记 = `scripts/check_plugin_faces.ps1` 红。
fn body_of(kind: &str) -> Option<Body> {
    match kind {
        "dm" => Some(Body::Dm(ek_dm::ui_face::DmUiState::new())),
        "oms" => Some(Body::Oms(ek_oms::ui_face::OmsUiState::new())),
        "tq" => Some(Body::Tq(ek_tq::ui_face::TqUiState::new())),
        "ctp" => Some(Body::Gateway(crate::gateway::TableState::new())),
        "ops" => Some(Body::Host(crate::hostwin::State::new(
            crate::hostwin::HostKind::Ops,
        ))),
        "contracts" => Some(Body::Host(crate::hostwin::State::new(
            crate::hostwin::HostKind::Contracts,
        ))),
        // 菜单里那一项「K线」只是入口(点了按当前合约开一扇真窗);真窗体在
        // `sync_hosts` 里按 `kline_symbols()` 逐合约建。
        "kline" => Some(Body::Host(crate::hostwin::State::new(
            crate::hostwin::HostKind::Kline {
                symbol: String::new(),
            },
        ))),
        _ => None,
    }
}

impl Registry {
    /// 只要 [`MODULES`] 里标了 `always` 的模块(交易网关 / 宿主自有窗)。
    ///
    /// `UiShared::new()` 用它 —— 保证"没引擎、没装配"时这几扇窗也在菜单里
    /// (先建账户档案再连接,是 CTP 的正常用法)。
    #[must_use]
    pub fn with_always() -> Self {
        let mut reg = Self::default();
        reg.ensure_always();
        reg
    }

    fn ensure_always(&mut self) {
        for d in MODULES.iter().filter(|d| d.always) {
            if self.list.iter().any(|w| w.kind == d.kind) {
                continue;
            }
            if let Some(body) = body_of(d.kind) {
                self.list.push(ModuleWin {
                    id: d.kind.to_string(),
                    kind: d.kind.to_string(),
                    title: d.title.to_string(),
                    icon: d.icon,
                    order: d.order,
                    shape: Shape::Single,
                    instances: Vec::new(),
                    always: true,
                    maximized: d.maximized,
                    open: false,
                    size: d.size,
                    min_size: d.min_size,
                    body,
                });
            }
        }
        self.list.sort_by_key(|w| (w.order, w.id.clone()));
    }

    /// 模块窗开合读。
    #[must_use]
    pub fn is_open(&self, kind: &str) -> bool {
        self.list
            .iter()
            .find(|w| w.kind == kind)
            .is_some_and(|w| w.open)
    }

    /// 模块窗开合写(`always` 模块不在册时先补建 —— 测试/启动器阶段无引擎也通)。
    pub fn set_open(&mut self, kind: &str, open: bool) {
        if self.list.iter().all(|w| w.kind != kind) {
            self.ensure_always();
        }
        if let Some(w) = self.list.iter_mut().find(|w| w.kind == kind) {
            w.open = open;
        }
    }

    /// 按引擎当前在册插件建挂载表(开机装配完成后调一次)。
    #[must_use]
    pub fn mount(shared: &UiShared) -> Self {
        let mut reg = Self::with_always();
        reg.sync(shared);
        reg
    }

    /// 同步实例列表:插件增删后调(`svctl.start/remove` 回执处)。
    ///
    /// 语义:
    /// - 已有模块窗**保留**(开合、窗内编辑态都不丢),只更新 `instances`;
    /// - 新模块(首次出现)建窗并挂上;
    /// - 模块的实例全部摘掉 → 非 `always` 的窗下架。
    pub fn sync(&mut self, shared: &UiShared) {
        let mut groups: std::collections::BTreeMap<String, Vec<String>> =
            std::collections::BTreeMap::new();
        if let Some(engine) = shared.engine_arc() {
            for name in engine.plugin_names() {
                if let Some(p) = engine.plugin_arc(&name) {
                    groups.entry(p.kind().to_string()).or_default().push(name);
                }
            }
        }
        // 1) 更新/新增
        for (kind, insts) in &groups {
            if let Some(w) = self.list.iter_mut().find(|w| &w.kind == kind) {
                w.instances = insts.clone();
                continue;
            }
            let Some(d) = desc_of(kind) else { continue };
            let Some(body) = body_of(kind) else { continue };
            self.list.push(ModuleWin {
                id: d.kind.to_string(),
                kind: d.kind.to_string(),
                title: d.title.to_string(),
                icon: d.icon,
                order: d.order,
                shape: Shape::Single,
                instances: insts.clone(),
                always: d.always,
                maximized: d.maximized,
                open: false,
                size: d.size,
                min_size: d.min_size,
                body,
            });
        }
        // 2) always 模块恒在(未装配也建窗)
        self.ensure_always();
        // 2.5) 实例全摘的模块要把实例表清零(否则摘光了还挂着旧名单)
        for w in &mut self.list {
            if !groups.contains_key(&w.kind) {
                w.instances.clear();
            }
        }
        // 3) 非 always 且没实例 → 下架
        self.list
            .retain(|w| w.always || groups.contains_key(&w.kind));
        // 4) 稳定排序(菜单顺序只由 order 决定,与装配先后无关)
        self.list.sort_by_key(|w| (w.order, w.id.clone()));
    }

    /// 菜单区渲染:**一项 = 一个模块**(点谁开谁;再点置真,幂等)。
    ///
    /// 文字 = 模块标题本身(不带 emoji 前缀):菜单的可检索文本与模块名一一对应,
    /// 图标只进 tooltip —— 判据(含 kittest 按 label 取件)只认标题,不认装饰。
    pub fn menu(&mut self, ui: &mut egui::Ui, shared: &UiShared) {
        for w in &mut self.list {
            // 动态窗(`kline:{合约}`)不进菜单:菜单只有一项「K线」,
            // 真窗由 `sync_hosts` 按 `kline_symbols()` 建。
            if w.id.starts_with("kline:") {
                continue;
            }
            if !ui
                .button(w.title.as_str())
                .on_hover_text(format!(
                    "{} {}:{} 个实例(点开看它自己的窗)",
                    w.icon,
                    w.title,
                    w.instances.len()
                ))
                .clicked()
            {
                continue;
            }
            // 宿主自有窗:开合事实源仍是 UiShared 老旗子(挂载表只是视图)。
            match w.id.as_str() {
                "ops" => shared.set_ops_window_open(true),
                "contracts" => shared.set_contracts_window_open(true),
                _ => w.open = true,
            }
        }
    }

    /// 窗口区渲染:开着的逐个开(都在独立 OS 窗;不支持多窗的后端走主窗内嵌)。
    ///
    /// ⚠ 重入纪律:本方法持着挂载表锁渲染整扇窗 —— **窗体内不许再调**
    /// [`UiShared::modules`](`Mutex` 非重入,会自锁)。窗体内的开合要么走
    /// `UiShared` 的老旗子(`set_ops_window_open` 等,纯原子位),要么等下一拍由
    /// 调用方处理。
    pub fn windows(&mut self, ctx: &egui::Context, shared: &UiShared) {
        self.sync_hosts(shared);
        for w in &mut self.list {
            // 菜单入口「K线」不是真窗:点了按当前合约开一扇(`sync_hosts` 下一拍建窗)。
            if w.id == "kline" {
                if w.open {
                    w.open = false;
                    let sym = shared.order_form().symbol.trim().to_string();
                    if sym.is_empty() {
                        shared.log_line("[kline] 先在行情表选一个合约再点「K线」".to_string());
                    } else {
                        shared.open_kline(sym);
                    }
                }
                continue;
            }
            if !w.open {
                continue;
            }
            if show_module_window(ctx, w, shared) {
                w.open = false;
                match w.id.as_str() {
                    "ops" => shared.set_ops_window_open(false),
                    "contracts" => shared.set_contracts_window_open(false),
                    id if id.starts_with("kline:") => shared.close_kline(&id[6..]),
                    _ => {}
                }
            }
        }
    }

    /// 宿主自有窗:开合从 UiShared 读回;K线按 `kline_symbols()` 逐合约建/收。
    fn sync_hosts(&mut self, shared: &UiShared) {
        for w in &mut self.list {
            match w.id.as_str() {
                "ops" => w.open = shared.ops_window_open(),
                "contracts" => w.open = shared.contracts_window_open(),
                _ => {}
            }
        }
        let syms = shared.kline_symbols();
        self.list.retain(|w| {
            !w.id.starts_with("kline:") || syms.iter().any(|s| w.id == format!("kline:{s}"))
        });
        for s in syms {
            let id = format!("kline:{s}");
            if self.list.iter().any(|w| w.id == id) {
                continue;
            }
            self.list.push(ModuleWin {
                id,
                kind: "kline".to_string(),
                title: format!("K线 — {s}"),
                icon: "📈",
                order: 71,
                shape: Shape::Single,
                instances: Vec::new(),
                always: true,
                maximized: true,
                // 打开即显示(K线出现=窗就在);BD-UI-34 的"打开即最大化"改由
                // 窗口尺寸给足 + 用户自己最大化(统一窗框不按 kind 特判 maximized)。
                open: true,
                size: [900.0, 620.0],
                min_size: [360.0, 220.0],
                body: Body::Host(crate::hostwin::State::new(
                    crate::hostwin::HostKind::Kline { symbol: s.clone() },
                )),
            });
        }
        self.list.sort_by_key(|w| (w.order, w.id.clone()));
    }
}

// ================ 宿主桥(插件窗不碰文件/密库/线程)================

/// [`CfgHost`] 的 ek-ui 实现:写档走 `cfg.save` 总线,`cfg` 缺席 = 直写托底
/// (与 `plugin.rs::cfg_bus_save` 同口径,不另造一条写路)。
pub struct CfgBridge<'a> {
    shared: &'a UiShared,
    ctx: Option<PluginContext>,
    /// 显式存储根(判据/装配者注入;`None` = 走 `ui_cfg_store()` 缺省根)。
    store: Option<ek_cfg::Store>,
}

impl<'a> CfgBridge<'a> {
    /// 用当前共享面 + 引擎里的 ui 插件句柄建桥。
    #[must_use]
    pub fn new(shared: &'a UiShared) -> Self {
        let ctx = shared.engine_arc().and_then(|engine| {
            engine
                .get_typed::<crate::plugin::UiPlugin>(crate::plugin::UI_NAME)
                .and_then(|p| p.ctx_handle())
        });
        Self {
            shared,
            ctx,
            store: None,
        }
    }

    /// 钉死存储根(判据专用:写/读都落这一次给的根,不碰缺省根)。
    #[must_use]
    pub fn with_store(shared: &'a UiShared, store: ek_cfg::Store) -> Self {
        Self {
            shared,
            ctx: None,
            store: Some(store),
        }
    }

    fn store(&self) -> ek_cfg::Store {
        match &self.store {
            Some(s) => s.clone(),
            None => crate::plugin::ui_cfg_store(),
        }
    }
}

impl CfgHost for CfgBridge<'_> {
    fn cfg_save(&self, ns: &str, map: &SectionMap) -> Result<(), String> {
        if let Some(ctx) = &self.ctx {
            match ctx.ask_service::<ek_cfg::wire::SaveReq, ek_cfg::wire::SaveRes>(
                "cfg.save",
                ek_cfg::wire::SaveReq {
                    ns: ns.to_string(),
                    map: map.clone(),
                },
                std::time::Duration::from_millis(1500),
            ) {
                Ok(r) if r.ok => return Ok(()),
                Ok(r) => return Err(r.msg),
                Err(ek_core::error::AskError::UnknownService { .. }) => {
                    self.shared
                        .log_line(format!("[cfg] cfg 缺席,{ns} 直写托底(软集中负形)"));
                }
                Err(e) => return Err(format!("{e:?}")),
            }
        }
        self.store().save(ns, map).map_err(|e| e.to_string())
    }

    fn cfg_load(&self, ns: &str) -> Result<Option<SectionMap>, String> {
        match self.store().load(ns) {
            Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => Ok(Some(map)),
            Ok(ek_cfg::LoadOutcome::Fresh) => Ok(None),
            Err(e) => Err(e.to_string()),
        }
    }

    fn log(&self, line: &str) {
        self.shared.log_line(line.to_string());
    }
}

// ================ 窗口开法 ================

/// 独立 OS 窗(不支持多窗的后端回退成主窗内嵌窗)。
///
/// 与 `render::show_independent_window` 的差别:本函数**按 `id`** 做 viewport/窗键
/// (旧函数按 title 做键,带参数的窗会互踩),且用一个闭包跑两路(嵌入回退与 OS 窗
/// 共用同一个 `&mut Body`,不需要两份可变借用)。
///
/// 返回 `true` = 本拍该窗被关。
fn show_module_window(ctx: &egui::Context, w: &mut ModuleWin, shared: &UiShared) -> bool {
    let id = w.id.clone();
    // 宿主自有窗的窗标题带「窗」后缀:菜单项 = 标题,窗标题 = 标题+窗 ——
    // 两者是不同的可检索文本(kittest 按 label 取件时不会互撞)。
    let title = match w.kind.as_str() {
        "ops" | "contracts" => format!("{}窗", w.title),
        _ => w.title.clone(),
    };
    let size = w.size;
    let min = w.min_size;
    let inst = w.primary_instance().to_string();
    let mut open = w.open;
    let mut closed = false;
    let body = &mut w.body;

    let mut builder = egui::ViewportBuilder::default()
        .with_title(&title)
        .with_inner_size(size)
        .with_min_inner_size(min)
        .with_minimize_button(true)
        .with_maximize_button(true)
        .with_close_button(true);
    if w.maximized {
        builder = builder.with_maximized(true);
    }
    ctx.show_viewport_immediate(
        egui::ViewportId::from_hash_of(("module_win", &id)),
        builder,
        |ctx2, class| {
            if class == egui::ViewportClass::Embedded {
                egui::Window::new(&title)
                    .id(egui::Id::new(("module_win", &id)))
                    .open(&mut open)
                    .default_size(size)
                    .show(ctx2, |ui| {
                        render_body(body, shared, &inst, ui);
                    });
                if !open {
                    closed = true;
                }
                return;
            }
            if ctx2.input(|i| i.viewport().close_requested()) {
                closed = true;
                return;
            }
            egui::CentralPanel::default().show(ctx2, |ui| {
                render_body(body, shared, &inst, ui);
            });
        },
    );
    closed
}

/// 窗体派发(**不用 trait,用 `match`**:编译期穷举,删一个分支 = 编译/门禁双红)。
fn render_body(body: &mut Body, shared: &UiShared, inst: &str, ui: &mut egui::Ui) {
    match body {
        Body::Dm(st) => {
            let Some(engine) = shared.engine_arc() else {
                ui.label("引擎未就绪");
                return;
            };
            let Some(p) = engine.get_typed::<ek_dm::plugin::DmPlugin>(inst) else {
                ui.label(format!("数据管理器未装配({inst})"));
                return;
            };
            let host = CfgBridge::new(shared);
            if ek_dm::ui_face::render(ui, &p, &host, st) {
                ui.ctx().request_repaint();
            }
        }
        Body::Oms(st) => {
            let Some(engine) = shared.engine_arc() else {
                ui.label("引擎未就绪");
                return;
            };
            let Some(p) = engine.get_typed::<ek_oms::plugin::OmsPlugin>(inst) else {
                ui.label(format!("交易中枢未装配({inst})"));
                return;
            };
            let host = CfgBridge::new(shared);
            if ek_oms::ui_face::render(ui, &p, &host, st) {
                ui.ctx().request_repaint();
            }
        }
        Body::Tq(st) => {
            let Some(engine) = shared.engine_arc() else {
                ui.label("引擎未就绪");
                return;
            };
            let Some(p) = engine.get_typed::<ek_tq::plugin::TqPlugin>(inst) else {
                ui.label(format!("天勤桥未装配({inst})"));
                return;
            };
            let host = CfgBridge::new(shared);
            if ek_tq::ui_face::render(ui, &p, &host, st) {
                ui.ctx().request_repaint();
            }
        }
        Body::Gateway(st) => crate::gateway::render(ui, st, shared),
        Body::Host(st) => crate::hostwin::render(ui, st, shared),
    }
}

/// 便利:引擎句柄(窗口体里取插件实例用)。
#[must_use]
pub fn engine_of(shared: &UiShared) -> Option<Arc<MainEngine>> {
    shared.engine_arc()
}