Skip to main content

ek_ui/
state.rs

1//! 共享观测状态:`UiPlugin`(总线面)写、`render_body`(窗口面)读。
2//!
3//! 线程形貌:总线侧在**插件 worker 线程**写;窗口侧在 **eframe 主线程**读;
4//! 锁粒度 = 每次 `lock().clone()/snapshot()`,不跨帧持锁。
5
6use std::collections::{BTreeMap, VecDeque};
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, Mutex};
9
10use ek_data::bar::BarData;
11use ek_dm::wire::BarsFrame;
12use ek_station::wire::PlugRow;
13
14/// 日志环形容量(S1b 门面;溢出不丢累计计数,见 [`LogRing::spilled`])。
15pub const RING_CAP: usize = 512;
16
17/// 环形日志:push 满则挤掉最旧一条,溢出计数单调(页面显示"已丢弃 N 条")。
18#[derive(Debug)]
19pub struct LogRing {
20    lines: VecDeque<String>,
21    cap: usize,
22    spilled: u64,
23}
24
25impl Default for LogRing {
26    fn default() -> Self {
27        Self::new(RING_CAP)
28    }
29}
30
31impl LogRing {
32    /// 定容环形(测试可传小容量逼溢出)。
33    pub fn new(cap: usize) -> Self {
34        Self {
35            lines: VecDeque::with_capacity(cap),
36            cap,
37            spilled: 0,
38        }
39    }
40
41    /// 追加一行;满则挤旧 + spilled+1。
42    pub fn push(&mut self, line: impl Into<String>) {
43        if self.cap == 0 {
44            self.spilled += 1;
45            return;
46        }
47        if self.lines.len() == self.cap {
48            self.lines.pop_front();
49            self.spilled += 1;
50        }
51        self.lines.push_back(line.into());
52    }
53
54    /// 当前长度。
55    pub fn len(&self) -> usize {
56        self.lines.len()
57    }
58
59    /// 是否空行。
60    pub fn is_empty(&self) -> bool {
61        self.lines.is_empty()
62    }
63
64    /// 累计已丢弃条数(只有溢出才涨)。
65    pub fn spilled(&self) -> u64 {
66        self.spilled
67    }
68
69    /// 只读快照(渲染用;不消费)。
70    pub fn snapshot(&self) -> Vec<String> {
71        self.lines.iter().cloned().collect()
72    }
73
74    /// 全清;spilled 保留(历史溢出事实不抹)。
75    pub fn clear(&mut self) {
76        self.lines.clear();
77    }
78}
79
80/// 一次 eTimer 拉取的服务/插件快照(渲染直接可用)。
81#[derive(Debug, Clone, Default)]
82pub struct BusSnap {
83    /// svctl.list 全行(svctl 独裁班;状态原文)。
84    pub rows: Vec<PlugRow>,
85    /// 逐插件服务目录(id 清单;无服务为空)。
86    pub services: Vec<(String, Vec<String>)>,
87}
88
89/// UI 操作指令(窗口面 → 总线面;eTimer 节拍被 ui 插件请辞)。
90#[derive(Debug, Clone, PartialEq)]
91pub enum UiCmd {
92    /// svctl.start(工厂名;v1 与插件注册名同,BD-U5)。
93    Start { factory: String },
94    /// svctl.remove(插件名)。
95    Remove { name: String },
96    /// dm.reload 回灌(S4;push=true 逐条广播,行情面板实时见 Rows)。
97    Reload {
98        interval: i64,
99        symbol: String,
100        bars: Vec<BarData>,
101    },
102    /// sim.send_order 下单(S5;纸面网关受理即 SUBMITTING 单上总线)。
103    /// S6 起网关可选(`gateway.send_order`,空 = sim)。
104    /// 0.1.1(BD-UI-30):改走 `oms.submit_order` 五段管线(拆单/风控/逐腿
105    /// 发送/记账,parent 聚合);`mode` = 拆单四态(勾选「自动开平」= Auto,
106    /// 取消勾选 = None 原样旁路)。
107    SendOrder {
108        req: ek_data::order_request::OrderRequest,
109        gateway: String,
110        mode: ek_oms::LockMode,
111    },
112    /// sim.cancel_order 撤单(S5;携三段号所需的 orderid;S6 起网关同选)。
113    /// 0.1.1(BD-UI-30):改走 `oms.cancel_order`(守卫 4000 不可绕过;
114    /// symbol/exchange 由 oms 订单缓存解,不再随令携带)。
115    CancelOrder { orderid: String, gateway: String },
116    /// sim.query_rate 流控查询(S5;回执进日志)。
117    QueryRate,
118    /// ctp.configure 网关配置(S6 测试面;界面手工输入表单直映,插件侧校验;
119    /// 出队时 `to_configure_req` 抬成线上契约)。
120    CtpConfigure(CtpForm),
121    /// ctp.subscribe 订阅行情(S6 测试面;逗号分隔标的)。
122    CtpSubscribe { symbols: Vec<String> },
123}
124
125/// 行情缓存单格容量(防涨;丢头保尾,bar 流单调)。
126pub const KLINE_CELL_CAP: usize = 4096;
127
128/// 二次确认步进:Armed = 首点待确认;Fired = 同名二点已发令;Switched = 目标迁移。
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum ConfirmStep {
131    Armed,
132    Fired,
133    Switched,
134}
135
136/// 隔离态判定(svctl.list 状态原文含 Quarantin → 红;ePlugQDown.<名> 是定向
137/// 广播,未知名无法预订阅 —— 快照行扫描是唯一闭环面,BD-UI-17)。
138#[must_use]
139pub fn is_quarantined(state: &str) -> bool {
140    state.contains("Quarantin")
141}
142
143// ================= S4:行情库(eBar./eBarUpdate. 上屏地面) =================
144
145/// 单格 = (symbol, interval) → bar 升序序列(丢头保尾;datetime 单调)。
146#[derive(Debug, Default)]
147pub struct MarketStore {
148    cells: Mutex<BTreeMap<(String, i64), Vec<BarData>>>,
149    /// eBar. 帧接收计数(帧统计,刷新不丢帧观感面)。
150    frames: AtomicU64,
151    /// eBarUpdate. 接收计数。
152    updates: AtomicU64,
153    /// dm.reload 成功计数(回灌确认面)。
154    reloads: AtomicU64,
155}
156
157/// 一格的可读视图(渲染/测试用)。
158#[derive(Debug, Clone, PartialEq)]
159pub struct CellView {
160    pub symbol: String,
161    pub interval: i64,
162    pub bars: Vec<BarData>,
163}
164
165impl MarketStore {
166    /// eBar. 收帧:逐 bar 并格(同 dt 替尾;更旧丢弃;更晚追加,溢出丢头)。
167    pub fn on_frame(&self, frame: &BarsFrame) {
168        let mut cells = self.cells.lock().unwrap();
169        for b in &frame.bars {
170            let key = (b.symbol.clone(), frame.interval);
171            let cell = cells.entry(key).or_default();
172            match cell.last() {
173                Some(last) if b.datetime < last.datetime => continue,
174                Some(last) if b.datetime == last.datetime => {
175                    let slot = cell.last_mut().expect("len>1");
176                    *slot = b.clone();
177                }
178                _ => {
179                    cell.push(b.clone());
180                    if cell.len() > KLINE_CELL_CAP {
181                        cell.remove(0);
182                    }
183                }
184            }
185        }
186        self.frames.fetch_add(1, Ordering::AcqRel);
187    }
188
189    /// eBarUpdate. 收单 bar 快照(实时门;同 dt 替尾,新 dt 追加 = in-flight bar)。
190    pub fn on_update(&self, b: &BarData) {
191        let mut cells = self.cells.lock().unwrap();
192        let iv = b
193            .interval
194            .unwrap_or(ek_data::constant::Interval::MINUTE)
195            .seconds();
196        let key = (b.symbol.clone(), iv);
197        let cell = cells.entry(key).or_default();
198        match cell.last() {
199            Some(last) if b.datetime == last.datetime => {
200                let slot = cell.last_mut().expect("len>1");
201                *slot = b.clone();
202            }
203            Some(last) if b.datetime < last.datetime => {}
204            _ => {
205                cell.push(b.clone());
206                if cell.len() > KLINE_CELL_CAP {
207                    cell.remove(0);
208                }
209            }
210        }
211        self.updates.fetch_add(1, Ordering::AcqRel);
212    }
213
214    /// dm.reload 回灌登记(RELOAD OK 计数;dm 侧行为独立)。
215    pub fn note_reload(&self) {
216        self.reloads.fetch_add(1, Ordering::AcqRel);
217    }
218
219    /// 全格只读快照(键序 = BTreeMap 序,symbol/interval 稳定)。
220    pub fn cells(&self) -> Vec<CellView> {
221        self.cells
222            .lock()
223            .unwrap()
224            .iter()
225            .map(|((sym, iv), bars)| CellView {
226                symbol: sym.clone(),
227                interval: *iv,
228                bars: bars.clone(),
229            })
230            .collect()
231    }
232
233    /// 计算(Ai) 帧统计。
234    pub fn counts(&self) -> (u64, u64, u64) {
235        (
236            self.frames.load(Ordering::Acquire),
237            self.updates.load(Ordering::Acquire),
238            self.reloads.load(Ordering::Acquire),
239        )
240    }
241}
242
243/// 回灌表单(v4:界面面已退役,总线口 `UiCmd::Reload` 保留;解析器留作
244/// 测试与脚本面)。
245#[derive(Debug, Default, Clone, PartialEq)]
246pub struct ReloadForm {
247    pub interval: String,
248    pub symbol: String,
249    pub csv: String,
250}
251
252/// 票据网关选择子解析(空 → "sim";含空白 = 错)。
253pub fn parse_gateway(raw: &str) -> Result<String, String> {
254    let g = raw.trim();
255    if g.is_empty() {
256        return Ok("sim".to_string());
257    }
258    if g.chars().any(|c| c.is_whitespace()) {
259        return Err(format!("网关解析: 含空白:{raw:?}"));
260    }
261    Ok(g.to_string())
262}
263
264/// CTP 网关配置表单(S6 测试面;界面手工输入源 → UiCmd::CtpConfigure →
265/// ask `ctp.configure`。零配置口径:界面不读文件,值全部人敲;密码位掩码)。
266#[derive(Debug, Default, Clone, PartialEq)]
267pub struct CtpForm {
268    pub broker_id: String,
269    pub td_addr: String,
270    pub td_user: String,
271    pub td_password: String,
272    pub td_auth_code: String,
273    pub td_app_id: String,
274    pub md_addr: String,
275    pub md_user: String,
276    pub md_password: String,
277    /// 订阅标的(逗号分隔;`订阅行情` 钮解析)。
278    pub symbols: String,
279}
280
281impl CtpForm {
282    /// 表单 → 线上契约(字段直映;md 回落由插件侧裁决,表单不预处理)。
283    pub fn to_configure_req(&self) -> ek_ctp::plugin::ConfigureReq {
284        ek_ctp::plugin::ConfigureReq {
285            broker_id: self.broker_id.trim().to_string(),
286            td_addr: self.td_addr.trim().to_string(),
287            td_user: self.td_user.trim().to_string(),
288            td_password: self.td_password.clone(),
289            td_auth_code: self.td_auth_code.trim().to_string(),
290            td_app_id: self.td_app_id.trim().to_string(),
291            md_addr: self.md_addr.trim().to_string(),
292            md_user: self.md_user.trim().to_string(),
293            md_password: self.md_password.clone(),
294        }
295    }
296
297    /// 订阅位解析(逗号/空白分隔;空表 = Err)。
298    pub fn parse_symbols(&self) -> Result<Vec<String>, String> {
299        let list: Vec<String> = self
300            .symbols
301            .split([',', ',', ' '])
302            .map(|s| s.trim().to_string())
303            .filter(|s| !s.is_empty())
304            .collect();
305        if list.is_empty() {
306            return Err("订阅解析: 标的位空".to_string());
307        }
308        Ok(list)
309    }
310}
311
312/// 交易监控快照(S5;ui 插件 eTimer 拍 ask oms 全量查询组帧)。
313#[derive(Debug, Clone, PartialEq, Default)]
314pub struct TradeSnap {
315    pub orders: Vec<ek_data::order::OrderData>,
316    pub trades: Vec<ek_data::trade::TradeData>,
317    pub positions: Vec<ek_data::position::PositionData>,
318    /// 资金帧(oms.get_all_accounts;CTP configure 登录后有数)。
319    pub accounts: Vec<ek_data::account::AccountData>,
320}
321
322/// CSV(每行 `dt,open,high,low,close,volume`;dt 为 epoch 秒)→ BarData 批。
323/// 错行报行号;空 csv = Err;升序不强制(dm.reload 自会逐行入窗)。
324pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
325    let interval: i64 = form
326        .interval
327        .trim()
328        .parse()
329        .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
330    let symbol = form.symbol.trim().to_string();
331    if symbol.is_empty() {
332        return Err("回灌解析: symbol 空".to_string());
333    }
334    if form.csv.trim().is_empty() {
335        return Err("回灌解析: csv 空".to_string());
336    }
337    let mut bars = Vec::new();
338    for (i, raw) in form.csv.lines().enumerate() {
339        let line = raw.trim();
340        if line.is_empty() || line.starts_with('#') {
341            continue;
342        }
343        let parts: Vec<&str> = line.split(',').map(str::trim).collect();
344        if parts.len() != 6 {
345            return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
346        }
347        let num = |s: &str| -> Result<f64, String> {
348            s.parse::<f64>()
349                .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
350        };
351        let dt_s: i64 = parts[0]
352            .parse()
353            .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
354        bars.push(BarData {
355            symbol: symbol.clone(),
356            datetime: dt_s * 1_000_000_000,
357            interval: Some(
358                ek_dm::wire::interval_of_seconds(interval)
359                    .unwrap_or(ek_data::constant::Interval::MINUTE),
360            ),
361            open_price: num(parts[1])?,
362            high_price: num(parts[2])?,
363            low_price: num(parts[3])?,
364            close_price: num(parts[4])?,
365            volume: num(parts[5])?,
366            ..BarData::default()
367        });
368    }
369    if bars.is_empty() {
370        return Err("回灌解析: 无有效行".to_string());
371    }
372    Ok((interval, symbol, bars))
373}
374
375// ================= v4 布局面(带/组 tab / tick 库 / 下单表单;docs/ek-ui-layout-v2-plan.md) =================
376
377/// 左上组 tab(Python [委托|未成交];审计修正:行情是带不是 tab,K线/运维/CTP
378/// 是弹窗不是 tab,故不设全局 10 值 UiTab——那是 v2 残影)。
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
380pub enum TopLeftTab {
381    #[default]
382    Orders,
383    Active,
384}
385
386impl TopLeftTab {
387    pub fn label(self) -> &'static str {
388        match self {
389            Self::Orders => "委托",
390            Self::Active => "未成交",
391        }
392    }
393}
394
395/// 右下组 tab(Python [资金|日志])。
396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
397pub enum BottomRightTab {
398    #[default]
399    Account,
400    Logs,
401}
402
403impl BottomRightTab {
404    pub fn label(self) -> &'static str {
405        match self {
406            Self::Account => "资金",
407            Self::Logs => "日志",
408        }
409    }
410}
411
412/// tick 库(v2 行情 tab 唯一数据源):symbol → 最新 tick,逐 symbol 覆盖,
413/// 有界 = 订阅面(ek-ctp 只发已订阅合约;无 bar 回落,用户裁定)。
414#[derive(Debug, Default)]
415pub struct TickStore {
416    ticks: BTreeMap<String, ek_data::tick::TickData>,
417}
418
419impl TickStore {
420    /// 逐合约覆盖(审计修正:键 = en_symbol「交易所.合约」,防跨所同码相撞;
421    /// 交易所分组取 tick 自带 exchange)。
422    pub fn put(&mut self, t: &ek_data::tick::TickData) {
423        self.ticks
424            .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
425    }
426
427    /// 只读视图(交易所 → 合约排序,tab 分组顺序稳定)。
428    pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
429        let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
430        v.sort_by(|a, b| {
431            (a.exchange.as_str().to_string(), a.symbol.clone())
432                .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
433        });
434        v
435    }
436
437    /// 按交易所分组(tab 键只列有 tick 的所,不预置全枚举)。
438    pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
439        let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
440        for t in self.rows() {
441            let ex = t.exchange.as_str().to_string();
442            match out.last_mut() {
443                Some((e, v)) if *e == ex => v.push(t),
444                _ => out.push((ex, vec![t])),
445            }
446        }
447        out
448    }
449
450    pub fn len(&self) -> usize {
451        self.ticks.len()
452    }
453
454    pub fn is_empty(&self) -> bool {
455        self.ticks.is_empty()
456    }
457}
458
459/// 下单面板表单(v2 常驻右侧;Python TradingWidget 字段面等价;操作面非配置面)。
460#[derive(Debug, Clone, PartialEq)]
461pub struct OrderForm {
462    /// 交易所代码(下拉;from_str 抬成枚举)
463    pub exchange: String,
464    /// 合约代码(纯 symbol,不带前缀)
465    pub symbol: String,
466    pub direction: ek_data::constant::Direction,
467    pub offset: ek_data::constant::Offset,
468    pub order_type: ek_data::constant::OrderType,
469    /// 输入面保持字符串(同 Python QLineEdit),委托时解析
470    pub price: String,
471    pub volume: String,
472    /// 网关(下拉源 = trade_snap gateway 去重集 ∪ CTP 表单现值)
473    pub gateway: String,
474    /// 价格随行情勾选(勾选时价格框随选中合约最新 tick)
475    pub follow_price: bool,
476    /// 「自动开平」勾选(0.1.1 BD-UI-30;默认开 = LockMode::Auto 走拆单器,
477    /// 关 = LockMode::None 原样旁路——守卫不可绕,拆单可逐请求旁路)
478    pub auto_split: bool,
479}
480
481impl Default for OrderForm {
482    fn default() -> Self {
483        Self {
484            exchange: "SHFE".to_string(),
485            symbol: String::new(),
486            direction: ek_data::constant::Direction::LONG,
487            offset: ek_data::constant::Offset::OPEN,
488            order_type: ek_data::constant::OrderType::LIMIT,
489            price: String::new(),
490            volume: "1".to_string(),
491            gateway: String::new(),
492            follow_price: true,
493            auto_split: true,
494        }
495    }
496}
497
498impl OrderForm {
499    /// 表单 → OrderRequest(与票据解析同一出口;错误红字就地,不进总线)。
500    pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
501        use std::str::FromStr;
502        let symbol = self.symbol.trim();
503        if symbol.is_empty() {
504            return Err("下单: 代码为空".to_string());
505        }
506        if symbol.contains('.') {
507            return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
508        }
509        let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
510            .map_err(|e| format!("下单: {e}"))?;
511        let price: f64 = self
512            .price
513            .trim()
514            .parse()
515            .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
516        let volume: f64 = self
517            .volume
518            .trim()
519            .parse()
520            .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
521        if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
522            return Err("下单: 限价单价格须为正".to_string());
523        }
524        if volume <= 0.0 {
525            return Err("下单: 数量须为正".to_string());
526        }
527        Ok(ek_data::order_request::OrderRequest {
528            symbol: symbol.to_string(),
529            exchange,
530            direction: self.direction,
531            order_type: self.order_type,
532            volume,
533            price,
534            offset: self.offset,
535            ..ek_data::order_request::OrderRequest::default()
536        })
537    }
538}
539
540/// 合约库(v4 查询合约窗数据源):en_symbol → ContractData。
541///
542/// 数据面 = ek-ctp 登录后自动 reqQryInstrument 回流(`eContract.` 裸键逐条 +
543/// `eContractFinish` 完成线,driver.rs:779)——**无 ask 口,UI 只收不催**
544/// (用户裁定:订阅不在网关配置定死,查询窗勾选订阅 / 下单代码回车)。
545#[derive(Debug, Default)]
546pub struct ContractStore {
547    contracts: BTreeMap<String, ek_data::contract::ContractData>,
548}
549
550impl ContractStore {
551    pub fn put(&mut self, c: &ek_data::contract::ContractData) {
552        self.contracts
553            .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
554    }
555
556    /// Python ContractManager 查询口径:代码/交易所/名称模糊,留空 = 全部。
557    pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
558        let p = pattern.trim();
559        self.contracts
560            .values()
561            .filter(|c| {
562                p.is_empty()
563                    || c.symbol.contains(p)
564                    || c.exchange.as_str().eq_ignore_ascii_case(p)
565                    || c.name.contains(p)
566            })
567            .cloned()
568            .collect()
569    }
570
571    pub fn len(&self) -> usize {
572        self.contracts.len()
573    }
574
575    pub fn is_empty(&self) -> bool {
576        self.contracts.is_empty()
577    }
578}
579
580/// 插件面板与宿主观察线程共用的观测状态。
581#[derive(Debug, Default)]
582pub struct UiShared {
583    logs: Mutex<LogRing>,
584    snap: Mutex<Arc<BusSnap>>,
585    market: MarketStore,
586    ctp_form: Mutex<CtpForm>,
587    trade_snap: Mutex<Arc<TradeSnap>>,
588    tick_store: Mutex<TickStore>,
589    order_form: Mutex<OrderForm>,
590    selected_exchange: Mutex<String>,
591    topleft_tab: Mutex<TopLeftTab>,
592    bottomright_tab: Mutex<BottomRightTab>,
593    ops_window: AtomicBool,
594    ctp_window: AtomicBool,
595    contracts_window: AtomicBool,
596    contract_store: Mutex<ContractStore>,
597    contract_query: Mutex<String>,
598    contract_selected: Mutex<Vec<String>>,
599    kline_windows: Mutex<Vec<String>>,
600    rev: AtomicU64,
601    /// 关窗/测试结束信号(窗口面置位,宿主观察线程消费)。
602    stop: AtomicBool,
603    /// svctl 操作指令队列(窗口面入,ui 插件 eTimer 出)。
604    cmds: Mutex<VecDeque<UiCmd>>,
605    /// 待二次确认的移除目标(单槽;再次同名点 = 发令)。
606    pending_confirm: Mutex<Option<String>>,
607    /// 表格行选中(BD-UI-31):表 id → 选中行键(每表一行;键由渲染侧构造,
608    /// 纯界面态,不发指令;悬停跳色是渲染侧即时判断,不入状态)。
609    row_sel: Mutex<BTreeMap<String, String>>,
610}
611
612impl UiShared {
613    /// 空状态(快照空、日志空、rev 0)。
614    pub fn new() -> Self {
615        Self::default()
616    }
617
618    // ---- v2 布局面访问器(tick 库 / 表单 / 选中 / tab) ----
619
620    /// 落一条 tick(eTick. 裸键上屏;逐 symbol 覆盖)。
621    pub fn update_tick(&self, t: &ek_data::tick::TickData) {
622        self.tick_store.lock().unwrap().put(t);
623        self.bump();
624    }
625
626    /// tick 只读视图(排序后)。
627    pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
628        self.tick_store.lock().unwrap().rows()
629    }
630
631    /// tick 按交易所分组(行情 tab 二级 tab 键表)。
632    pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
633        self.tick_store.lock().unwrap().groups()
634    }
635
636    /// tick 库格数。
637    pub fn tick_count(&self) -> usize {
638        self.tick_store.lock().unwrap().len()
639    }
640
641    /// 下单表单只读快照。
642    pub fn order_form(&self) -> OrderForm {
643        self.order_form.lock().unwrap().clone()
644    }
645
646    /// 下单表单写(渲染侧每控件改动即写)。
647    pub fn set_order_form(&self, f: OrderForm) {
648        *self.order_form.lock().unwrap() = f;
649        self.bump();
650    }
651
652    /// 选中交易所(行情二级 tab 态;行情行单击 = 带入下单面板见 render 侧)。
653    pub fn selected_exchange(&self) -> String {
654        self.selected_exchange.lock().unwrap().clone()
655    }
656
657    /// 选中交易所写。
658    pub fn set_selected_exchange(&self, s: impl Into<String>) {
659        *self.selected_exchange.lock().unwrap() = s.into();
660        self.bump();
661    }
662
663    /// 左上组当前 tab。
664    pub fn topleft_tab(&self) -> TopLeftTab {
665        *self.topleft_tab.lock().unwrap()
666    }
667
668    /// 左上组 tab 写。
669    pub fn set_topleft_tab(&self, t: TopLeftTab) {
670        *self.topleft_tab.lock().unwrap() = t;
671        self.bump();
672    }
673
674    /// 右下组当前 tab。
675    pub fn bottomright_tab(&self) -> BottomRightTab {
676        *self.bottomright_tab.lock().unwrap()
677    }
678
679    /// 右下组 tab 写。
680    pub fn set_bottomright_tab(&self, t: BottomRightTab) {
681        *self.bottomright_tab.lock().unwrap() = t;
682        self.bump();
683    }
684
685    // ---- v4 弹窗面(egui::Window 开关;kittest 可断言) ----
686
687    /// 运维窗开合。
688    pub fn ops_window_open(&self) -> bool {
689        self.ops_window.load(Ordering::Acquire)
690    }
691
692    /// 运维窗开合写。
693    pub fn set_ops_window_open(&self, v: bool) {
694        self.ops_window.store(v, Ordering::Release);
695        self.bump();
696    }
697
698    /// CTP 配置窗开合。
699    pub fn ctp_window_open(&self) -> bool {
700        self.ctp_window.load(Ordering::Acquire)
701    }
702
703    /// CTP 配置窗开合写。
704    pub fn set_ctp_window_open(&self, v: bool) {
705        self.ctp_window.store(v, Ordering::Release);
706        self.bump();
707    }
708
709    /// 已开 K线窗合约表(多开,去重)。
710    pub fn kline_symbols(&self) -> Vec<String> {
711        self.kline_windows.lock().unwrap().clone()
712    }
713
714    /// 开 K线窗(去重;日志留痕可断言)。
715    pub fn open_kline(&self, symbol: impl Into<String>) {
716        let s = symbol.into();
717        let mut v = self.kline_windows.lock().unwrap();
718        if !v.contains(&s) {
719            v.push(s.clone());
720        }
721        drop(v);
722        self.log_line(format!("[kline] 打开 K线窗 {s}"));
723    }
724
725    /// 关 K线窗(窗关闭钮 → 出表)。
726    pub fn close_kline(&self, symbol: &str) {
727        self.kline_windows.lock().unwrap().retain(|s| s != symbol);
728        self.bump();
729    }
730
731    // ---- v4 查询合约窗面(合约库 / 查询串 / 勾选集) ----
732
733    /// 查询合约窗开合。
734    pub fn contracts_window_open(&self) -> bool {
735        self.contracts_window.load(Ordering::Acquire)
736    }
737
738    /// 查询合约窗开合写。
739    pub fn set_contracts_window_open(&self, v: bool) {
740        self.contracts_window.store(v, Ordering::Release);
741        self.bump();
742    }
743
744    /// 落一条合约(`eContract.` 裸键上屏)。
745    pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
746        self.contract_store.lock().unwrap().put(c);
747        self.bump();
748    }
749
750    /// 合约查询(Python ContractManager 口径:留空 = 全部)。
751    pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
752        self.contract_store.lock().unwrap().query(pattern)
753    }
754
755    /// 合约库格数。
756    pub fn contract_count(&self) -> usize {
757        self.contract_store.lock().unwrap().len()
758    }
759
760    /// 查询串读写。
761    pub fn contract_query(&self) -> String {
762        self.contract_query.lock().unwrap().clone()
763    }
764
765    /// 查询串写。
766    pub fn set_contract_query(&self, q: impl Into<String>) {
767        *self.contract_query.lock().unwrap() = q.into();
768        self.bump();
769    }
770
771    /// 勾选翻转(en_symbol)。
772    pub fn toggle_contract_selection(&self, en_symbol: &str) {
773        let mut v = self.contract_selected.lock().unwrap();
774        match v.iter().position(|s| s == en_symbol) {
775            Some(i) => {
776                v.remove(i);
777            }
778            None => v.push(en_symbol.to_string()),
779        }
780        self.bump();
781    }
782
783    /// 当前勾选集。
784    pub fn selected_contracts(&self) -> Vec<String> {
785        self.contract_selected.lock().unwrap().clone()
786    }
787
788    /// 追加一行日志(总线面/宿主观察线程写)。
789    pub fn log_line(&self, line: impl Into<String>) {
790        self.logs.lock().unwrap().push(line);
791        self.bump();
792    }
793
794    /// 清空日志(渲染"清空日志"按钮 / 测试)。
795    pub fn clear_logs(&self) {
796        self.logs.lock().unwrap().clear();
797        self.bump();
798    }
799
800    /// 日志只读快照 + 溢出计数。
801    pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
802        let r = self.logs.lock().unwrap();
803        (r.snapshot(), r.spilled())
804    }
805
806    /// 日志当前长度(kittest 断言用)。
807    pub fn logs_len(&self) -> usize {
808        self.logs.lock().unwrap().len()
809    }
810
811    /// 落一次服务快照(eTimer 节流回调)。
812    pub fn set_snapshot(&self, snap: BusSnap) {
813        *self.snap.lock().unwrap() = Arc::new(snap);
814        self.bump();
815    }
816
817    /// 当前快照(Arc 克隆,零拷贝走锁)。
818    pub fn snapshot(&self) -> Arc<BusSnap> {
819        Arc::clone(&self.snap.lock().unwrap())
820    }
821
822    /// revision:任何写入 +1(插件面 ePlug 事件也用;测试判定"有事件进来过")。
823    pub fn rev(&self) -> u64 {
824        self.rev.load(Ordering::Acquire)
825    }
826
827    /// 手动推一次 revision(总线面 ePlugUp/Down 记账用)。
828    pub fn bump(&self) {
829        self.rev.fetch_add(1, Ordering::AcqRel);
830    }
831
832    /// 置关窗信号(eframe App 关窗钩子调用)。
833    pub fn request_stop(&self) {
834        self.stop.store(true, Ordering::Release);
835    }
836
837    /// 观察线程轮询用。
838    pub fn is_stop(&self) -> bool {
839        self.stop.load(Ordering::Acquire)
840    }
841
842    // ---- svctl 操作面(S2) ----
843
844    /// 入一条操作指令(窗口面离场动作唯一通道;左位不直调)。
845    pub fn push_cmd(&self, cmd: UiCmd) {
846        self.cmds.lock().unwrap().push_back(cmd);
847        self.bump();
848    }
849
850    /// 取走全部指令(eTimer 节拍辞行)。
851    pub fn drain_cmds(&self) -> Vec<UiCmd> {
852        self.cmds.lock().unwrap().drain(..).collect()
853    }
854
855    /// 当前待二次确认目标(Some = 二次确认中)。
856    pub fn pending_confirm(&self) -> Option<String> {
857        self.pending_confirm.lock().unwrap().clone()
858    }
859
860    /// 确认步进:同名二点 = 发令(Fired),异名 = 迁移(Switched),首点 = 进入待确认。
861    pub fn confirm_step(&self, name: &str) -> ConfirmStep {
862        let mut g = self.pending_confirm.lock().unwrap();
863        match g.take() {
864            Some(p) if p == name => ConfirmStep::Fired,
865            Some(_) => {
866                *g = Some(name.to_string());
867                ConfirmStep::Switched
868            }
869            None => {
870                *g = Some(name.to_string());
871                ConfirmStep::Armed
872            }
873        }
874    }
875
876    /// 清除待确认(取消钮)。
877    pub fn confirm_cancel(&self) {
878        *self.pending_confirm.lock().unwrap() = None;
879        self.bump();
880    }
881
882    // ---- S4 行情面 ----
883
884    /// 行情库直读(读写两用:worker 写,渲染读)。
885    pub fn market(&self) -> &MarketStore {
886        &self.market
887    }
888
889    // ---- S5 交易面 ----
890
891    /// 交易监控快照写(ui 插件 eTimer 拍)。
892    pub fn set_trade_snap(&self, ts: TradeSnap) {
893        *self.trade_snap.lock().unwrap() = Arc::new(ts);
894        self.bump();
895    }
896
897    /// 交易监控快照读(渲染)。
898    pub fn trade_snap(&self) -> Arc<TradeSnap> {
899        self.trade_snap.lock().unwrap().clone()
900    }
901
902    // ---- S6 CTP 配置面 ----
903
904    /// CTP 配置表单读(渲染克隆面)。
905    pub fn ctp_form(&self) -> CtpForm {
906        self.ctp_form.lock().unwrap().clone()
907    }
908
909    /// CTP 配置表单写。
910    pub fn set_ctp_form(&self, f: CtpForm) {
911        *self.ctp_form.lock().unwrap() = f;
912        self.bump();
913    }
914
915    // ---- BD-UI-31 表格行选中面 ----
916
917    /// 该行是否为所属表的选中行(渲染判断;无键 = 未选)。
918    pub fn row_selected(&self, table: &str, key: &str) -> bool {
919        self.row_sel
920            .lock()
921            .unwrap()
922            .get(table)
923            .is_some_and(|k| k == key)
924    }
925
926    /// 设所属表的选中行(每表一行;同键重复点 = 保持)。
927    pub fn select_row(&self, table: &str, key: &str) {
928        self.row_sel
929            .lock()
930            .unwrap()
931            .insert(table.to_string(), key.to_string());
932    }
933}