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, AtomicU8, 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/// 界面主题(BD-UI-34,用户问「有没有 PySide6 那种可换的金融向主题」):
413/// 菜单钮一键循环切换(运行期态,无配置文件——ek-ui 零配置口径)。
414/// 语义色(多红/空绿/隔离红/选中蓝)跨主题恒定——金融语义不随主题漂移。
415#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
416pub enum Theme {
417    /// 金融深色(默认):egui dark 骨架 + 深海军蓝面板/窗底(交易终端观感)。
418    #[default]
419    FinanceDark,
420    /// egui 原生深色。
421    EguiDark,
422    /// egui 原生浅色。
423    EguiLight,
424    /// Qt Fusion 灰白近似(Python/PySide6 版观感迁移用)。
425    QtClassic,
426}
427
428impl Theme {
429    pub fn label(self) -> &'static str {
430        match self {
431            Self::FinanceDark => "金融深色",
432            Self::EguiDark => "egui深色",
433            Self::EguiLight => "egui浅色",
434            Self::QtClassic => "Qt灰白",
435        }
436    }
437
438    /// 循环下一主题(菜单钮一键循环口径,单层无下拉)。
439    pub fn next(self) -> Self {
440        match self {
441            Self::FinanceDark => Self::EguiDark,
442            Self::EguiDark => Self::EguiLight,
443            Self::EguiLight => Self::QtClassic,
444            Self::QtClassic => Self::FinanceDark,
445        }
446    }
447}
448
449/// tick 库(v2 行情 tab 唯一数据源):symbol → 最新 tick,逐 symbol 覆盖,
450/// 有界 = 订阅面(ek-ctp 只发已订阅合约;无 bar 回落,用户裁定)。
451#[derive(Debug, Default)]
452pub struct TickStore {
453    ticks: BTreeMap<String, ek_data::tick::TickData>,
454}
455
456impl TickStore {
457    /// 逐合约覆盖(审计修正:键 = en_symbol「交易所.合约」,防跨所同码相撞;
458    /// 交易所分组取 tick 自带 exchange)。
459    pub fn put(&mut self, t: &ek_data::tick::TickData) {
460        self.ticks
461            .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
462    }
463
464    /// 只读视图(交易所 → 合约排序,tab 分组顺序稳定)。
465    pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
466        let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
467        v.sort_by(|a, b| {
468            (a.exchange.as_str().to_string(), a.symbol.clone())
469                .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
470        });
471        v
472    }
473
474    /// 按交易所分组(tab 键只列有 tick 的所,不预置全枚举)。
475    pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
476        let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
477        for t in self.rows() {
478            let ex = t.exchange.as_str().to_string();
479            match out.last_mut() {
480                Some((e, v)) if *e == ex => v.push(t),
481                _ => out.push((ex, vec![t])),
482            }
483        }
484        out
485    }
486
487    pub fn len(&self) -> usize {
488        self.ticks.len()
489    }
490
491    pub fn is_empty(&self) -> bool {
492        self.ticks.is_empty()
493    }
494}
495
496/// 下单面板表单(v2 常驻右侧;Python TradingWidget 字段面等价;操作面非配置面)。
497#[derive(Debug, Clone, PartialEq)]
498pub struct OrderForm {
499    /// 交易所代码(下拉;from_str 抬成枚举)
500    pub exchange: String,
501    /// 合约代码(纯 symbol,不带前缀)
502    pub symbol: String,
503    pub direction: ek_data::constant::Direction,
504    pub offset: ek_data::constant::Offset,
505    pub order_type: ek_data::constant::OrderType,
506    /// 输入面保持字符串(同 Python QLineEdit),委托时解析
507    pub price: String,
508    pub volume: String,
509    /// 网关(下拉源 = trade_snap gateway 去重集 ∪ CTP 表单现值)
510    pub gateway: String,
511    /// 价格随行情勾选(勾选时价格框随选中合约最新 tick)
512    pub follow_price: bool,
513    /// 「自动开平」勾选(0.1.1 BD-UI-30;默认开 = LockMode::Auto 走拆单器,
514    /// 关 = LockMode::None 原样旁路——守卫不可绕,拆单可逐请求旁路)
515    pub auto_split: bool,
516}
517
518impl Default for OrderForm {
519    fn default() -> Self {
520        Self {
521            exchange: "SHFE".to_string(),
522            symbol: String::new(),
523            direction: ek_data::constant::Direction::LONG,
524            offset: ek_data::constant::Offset::OPEN,
525            order_type: ek_data::constant::OrderType::LIMIT,
526            price: String::new(),
527            volume: "1".to_string(),
528            gateway: String::new(),
529            follow_price: true,
530            auto_split: true,
531        }
532    }
533}
534
535impl OrderForm {
536    /// 表单 → OrderRequest(与票据解析同一出口;错误红字就地,不进总线)。
537    pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
538        use std::str::FromStr;
539        let symbol = self.symbol.trim();
540        if symbol.is_empty() {
541            return Err("下单: 代码为空".to_string());
542        }
543        if symbol.contains('.') {
544            return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
545        }
546        let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
547            .map_err(|e| format!("下单: {e}"))?;
548        let price: f64 = self
549            .price
550            .trim()
551            .parse()
552            .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
553        let volume: f64 = self
554            .volume
555            .trim()
556            .parse()
557            .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
558        if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
559            return Err("下单: 限价单价格须为正".to_string());
560        }
561        if volume <= 0.0 {
562            return Err("下单: 数量须为正".to_string());
563        }
564        Ok(ek_data::order_request::OrderRequest {
565            symbol: symbol.to_string(),
566            exchange,
567            direction: self.direction,
568            order_type: self.order_type,
569            volume,
570            price,
571            offset: self.offset,
572            ..ek_data::order_request::OrderRequest::default()
573        })
574    }
575}
576
577/// 合约库(v4 查询合约窗数据源):en_symbol → ContractData。
578///
579/// 数据面 = ek-ctp 登录后自动 reqQryInstrument 回流(`eContract.` 裸键逐条 +
580/// `eContractFinish` 完成线,driver.rs:779)——**无 ask 口,UI 只收不催**
581/// (用户裁定:订阅不在网关配置定死,查询窗勾选订阅 / 下单代码回车)。
582#[derive(Debug, Default)]
583pub struct ContractStore {
584    contracts: BTreeMap<String, ek_data::contract::ContractData>,
585}
586
587impl ContractStore {
588    pub fn put(&mut self, c: &ek_data::contract::ContractData) {
589        self.contracts
590            .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
591    }
592
593    /// Python ContractManager 查询口径:代码/交易所/名称模糊,留空 = 全部。
594    pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
595        let p = pattern.trim();
596        self.contracts
597            .values()
598            .filter(|c| {
599                p.is_empty()
600                    || c.symbol.contains(p)
601                    || c.exchange.as_str().eq_ignore_ascii_case(p)
602                    || c.name.contains(p)
603            })
604            .cloned()
605            .collect()
606    }
607
608    pub fn len(&self) -> usize {
609        self.contracts.len()
610    }
611
612    pub fn is_empty(&self) -> bool {
613        self.contracts.is_empty()
614    }
615}
616
617/// 插件面板与宿主观察线程共用的观测状态。
618#[derive(Debug, Default)]
619pub struct UiShared {
620    logs: Mutex<LogRing>,
621    snap: Mutex<Arc<BusSnap>>,
622    market: MarketStore,
623    ctp_form: Mutex<CtpForm>,
624    trade_snap: Mutex<Arc<TradeSnap>>,
625    tick_store: Mutex<TickStore>,
626    order_form: Mutex<OrderForm>,
627    selected_exchange: Mutex<String>,
628    topleft_tab: Mutex<TopLeftTab>,
629    bottomright_tab: Mutex<BottomRightTab>,
630    ops_window: AtomicBool,
631    ctp_window: AtomicBool,
632    contracts_window: AtomicBool,
633    /// 界面主题(BD-UI-34;AtomicU8 = Theme 判别值,菜单钮循环)。
634    theme: AtomicU8,
635    contract_store: Mutex<ContractStore>,
636    contract_query: Mutex<String>,
637    contract_selected: Mutex<Vec<String>>,
638    kline_windows: Mutex<Vec<String>>,
639    rev: AtomicU64,
640    /// 关窗/测试结束信号(窗口面置位,宿主观察线程消费)。
641    stop: AtomicBool,
642    /// svctl 操作指令队列(窗口面入,ui 插件 eTimer 出)。
643    cmds: Mutex<VecDeque<UiCmd>>,
644    /// 待二次确认的移除目标(单槽;再次同名点 = 发令)。
645    pending_confirm: Mutex<Option<String>>,
646    /// 表格行选中(BD-UI-31):表 id → 选中行键(每表一行;键由渲染侧构造,
647    /// 纯界面态,不发指令;悬停跳色是渲染侧即时判断,不入状态)。
648    row_sel: Mutex<BTreeMap<String, String>>,
649}
650
651impl UiShared {
652    /// 空状态(快照空、日志空、rev 0)。
653    pub fn new() -> Self {
654        Self::default()
655    }
656
657    // ---- v2 布局面访问器(tick 库 / 表单 / 选中 / tab) ----
658
659    /// 落一条 tick(eTick. 裸键上屏;逐 symbol 覆盖)。
660    pub fn update_tick(&self, t: &ek_data::tick::TickData) {
661        self.tick_store.lock().unwrap().put(t);
662        self.bump();
663    }
664
665    /// tick 只读视图(排序后)。
666    pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
667        self.tick_store.lock().unwrap().rows()
668    }
669
670    /// tick 按交易所分组(行情 tab 二级 tab 键表)。
671    pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
672        self.tick_store.lock().unwrap().groups()
673    }
674
675    /// tick 库格数。
676    pub fn tick_count(&self) -> usize {
677        self.tick_store.lock().unwrap().len()
678    }
679
680    /// 下单表单只读快照。
681    pub fn order_form(&self) -> OrderForm {
682        self.order_form.lock().unwrap().clone()
683    }
684
685    /// 下单表单写(渲染侧每控件改动即写)。
686    pub fn set_order_form(&self, f: OrderForm) {
687        *self.order_form.lock().unwrap() = f;
688        self.bump();
689    }
690
691    /// 选中交易所(行情二级 tab 态;行情行单击 = 带入下单面板见 render 侧)。
692    pub fn selected_exchange(&self) -> String {
693        self.selected_exchange.lock().unwrap().clone()
694    }
695
696    /// 选中交易所写。
697    pub fn set_selected_exchange(&self, s: impl Into<String>) {
698        *self.selected_exchange.lock().unwrap() = s.into();
699        self.bump();
700    }
701
702    /// 左上组当前 tab。
703    pub fn topleft_tab(&self) -> TopLeftTab {
704        *self.topleft_tab.lock().unwrap()
705    }
706
707    /// 左上组 tab 写。
708    pub fn set_topleft_tab(&self, t: TopLeftTab) {
709        *self.topleft_tab.lock().unwrap() = t;
710        self.bump();
711    }
712
713    /// 右下组当前 tab。
714    pub fn bottomright_tab(&self) -> BottomRightTab {
715        *self.bottomright_tab.lock().unwrap()
716    }
717
718    /// 右下组 tab 写。
719    pub fn set_bottomright_tab(&self, t: BottomRightTab) {
720        *self.bottomright_tab.lock().unwrap() = t;
721        self.bump();
722    }
723
724    // ---- v4 弹窗面(egui::Window 开关;kittest 可断言) ----
725
726    /// 当前主题(BD-UI-34)。
727    pub fn theme(&self) -> Theme {
728        match self.theme.load(Ordering::Acquire) {
729            1 => Theme::EguiDark,
730            2 => Theme::EguiLight,
731            3 => Theme::QtClassic,
732            _ => Theme::FinanceDark,
733        }
734    }
735
736    /// 主题写。
737    pub fn set_theme(&self, t: Theme) {
738        self.theme.store(t as u8, Ordering::Release);
739        self.bump();
740    }
741
742    /// 菜单钮一键循环:切到下一主题并返回。
743    pub fn cycle_theme(&self) -> Theme {
744        let t = self.theme().next();
745        self.set_theme(t);
746        t
747    }
748
749    /// 运维窗开合。
750    pub fn ops_window_open(&self) -> bool {
751        self.ops_window.load(Ordering::Acquire)
752    }
753
754    /// 运维窗开合写。
755    pub fn set_ops_window_open(&self, v: bool) {
756        self.ops_window.store(v, Ordering::Release);
757        self.bump();
758    }
759
760    /// CTP 配置窗开合。
761    pub fn ctp_window_open(&self) -> bool {
762        self.ctp_window.load(Ordering::Acquire)
763    }
764
765    /// CTP 配置窗开合写。
766    pub fn set_ctp_window_open(&self, v: bool) {
767        self.ctp_window.store(v, Ordering::Release);
768        self.bump();
769    }
770
771    /// 已开 K线窗合约表(多开,去重)。
772    pub fn kline_symbols(&self) -> Vec<String> {
773        self.kline_windows.lock().unwrap().clone()
774    }
775
776    /// 开 K线窗(去重;日志留痕可断言)。
777    pub fn open_kline(&self, symbol: impl Into<String>) {
778        let s = symbol.into();
779        let mut v = self.kline_windows.lock().unwrap();
780        if !v.contains(&s) {
781            v.push(s.clone());
782        }
783        drop(v);
784        self.log_line(format!("[kline] 打开 K线窗 {s}"));
785    }
786
787    /// 关 K线窗(窗关闭钮 → 出表)。
788    pub fn close_kline(&self, symbol: &str) {
789        self.kline_windows.lock().unwrap().retain(|s| s != symbol);
790        self.bump();
791    }
792
793    // ---- v4 查询合约窗面(合约库 / 查询串 / 勾选集) ----
794
795    /// 查询合约窗开合。
796    pub fn contracts_window_open(&self) -> bool {
797        self.contracts_window.load(Ordering::Acquire)
798    }
799
800    /// 查询合约窗开合写。
801    pub fn set_contracts_window_open(&self, v: bool) {
802        self.contracts_window.store(v, Ordering::Release);
803        self.bump();
804    }
805
806    /// 落一条合约(`eContract.` 裸键上屏)。
807    pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
808        self.contract_store.lock().unwrap().put(c);
809        self.bump();
810    }
811
812    /// 合约查询(Python ContractManager 口径:留空 = 全部)。
813    pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
814        self.contract_store.lock().unwrap().query(pattern)
815    }
816
817    /// 合约库格数。
818    pub fn contract_count(&self) -> usize {
819        self.contract_store.lock().unwrap().len()
820    }
821
822    /// 查询串读写。
823    pub fn contract_query(&self) -> String {
824        self.contract_query.lock().unwrap().clone()
825    }
826
827    /// 查询串写。
828    pub fn set_contract_query(&self, q: impl Into<String>) {
829        *self.contract_query.lock().unwrap() = q.into();
830        self.bump();
831    }
832
833    /// 勾选翻转(en_symbol)。
834    pub fn toggle_contract_selection(&self, en_symbol: &str) {
835        let mut v = self.contract_selected.lock().unwrap();
836        match v.iter().position(|s| s == en_symbol) {
837            Some(i) => {
838                v.remove(i);
839            }
840            None => v.push(en_symbol.to_string()),
841        }
842        self.bump();
843    }
844
845    /// 当前勾选集。
846    pub fn selected_contracts(&self) -> Vec<String> {
847        self.contract_selected.lock().unwrap().clone()
848    }
849
850    /// 追加一行日志(总线面/宿主观察线程写)。
851    pub fn log_line(&self, line: impl Into<String>) {
852        self.logs.lock().unwrap().push(line);
853        self.bump();
854    }
855
856    /// 清空日志(渲染"清空日志"按钮 / 测试)。
857    pub fn clear_logs(&self) {
858        self.logs.lock().unwrap().clear();
859        self.bump();
860    }
861
862    /// 日志只读快照 + 溢出计数。
863    pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
864        let r = self.logs.lock().unwrap();
865        (r.snapshot(), r.spilled())
866    }
867
868    /// 日志当前长度(kittest 断言用)。
869    pub fn logs_len(&self) -> usize {
870        self.logs.lock().unwrap().len()
871    }
872
873    /// 落一次服务快照(eTimer 节流回调)。
874    pub fn set_snapshot(&self, snap: BusSnap) {
875        *self.snap.lock().unwrap() = Arc::new(snap);
876        self.bump();
877    }
878
879    /// 当前快照(Arc 克隆,零拷贝走锁)。
880    pub fn snapshot(&self) -> Arc<BusSnap> {
881        Arc::clone(&self.snap.lock().unwrap())
882    }
883
884    /// revision:任何写入 +1(插件面 ePlug 事件也用;测试判定"有事件进来过")。
885    pub fn rev(&self) -> u64 {
886        self.rev.load(Ordering::Acquire)
887    }
888
889    /// 手动推一次 revision(总线面 ePlugUp/Down 记账用)。
890    pub fn bump(&self) {
891        self.rev.fetch_add(1, Ordering::AcqRel);
892    }
893
894    /// 置关窗信号(eframe App 关窗钩子调用)。
895    pub fn request_stop(&self) {
896        self.stop.store(true, Ordering::Release);
897    }
898
899    /// 观察线程轮询用。
900    pub fn is_stop(&self) -> bool {
901        self.stop.load(Ordering::Acquire)
902    }
903
904    // ---- svctl 操作面(S2) ----
905
906    /// 入一条操作指令(窗口面离场动作唯一通道;左位不直调)。
907    pub fn push_cmd(&self, cmd: UiCmd) {
908        self.cmds.lock().unwrap().push_back(cmd);
909        self.bump();
910    }
911
912    /// 取走全部指令(eTimer 节拍辞行)。
913    pub fn drain_cmds(&self) -> Vec<UiCmd> {
914        self.cmds.lock().unwrap().drain(..).collect()
915    }
916
917    /// 当前待二次确认目标(Some = 二次确认中)。
918    pub fn pending_confirm(&self) -> Option<String> {
919        self.pending_confirm.lock().unwrap().clone()
920    }
921
922    /// 确认步进:同名二点 = 发令(Fired),异名 = 迁移(Switched),首点 = 进入待确认。
923    pub fn confirm_step(&self, name: &str) -> ConfirmStep {
924        let mut g = self.pending_confirm.lock().unwrap();
925        match g.take() {
926            Some(p) if p == name => ConfirmStep::Fired,
927            Some(_) => {
928                *g = Some(name.to_string());
929                ConfirmStep::Switched
930            }
931            None => {
932                *g = Some(name.to_string());
933                ConfirmStep::Armed
934            }
935        }
936    }
937
938    /// 清除待确认(取消钮)。
939    pub fn confirm_cancel(&self) {
940        *self.pending_confirm.lock().unwrap() = None;
941        self.bump();
942    }
943
944    // ---- S4 行情面 ----
945
946    /// 行情库直读(读写两用:worker 写,渲染读)。
947    pub fn market(&self) -> &MarketStore {
948        &self.market
949    }
950
951    // ---- S5 交易面 ----
952
953    /// 交易监控快照写(ui 插件 eTimer 拍)。
954    pub fn set_trade_snap(&self, ts: TradeSnap) {
955        *self.trade_snap.lock().unwrap() = Arc::new(ts);
956        self.bump();
957    }
958
959    /// 交易监控快照读(渲染)。
960    pub fn trade_snap(&self) -> Arc<TradeSnap> {
961        self.trade_snap.lock().unwrap().clone()
962    }
963
964    // ---- S6 CTP 配置面 ----
965
966    /// CTP 配置表单读(渲染克隆面)。
967    pub fn ctp_form(&self) -> CtpForm {
968        self.ctp_form.lock().unwrap().clone()
969    }
970
971    /// CTP 配置表单写。
972    pub fn set_ctp_form(&self, f: CtpForm) {
973        *self.ctp_form.lock().unwrap() = f;
974        self.bump();
975    }
976
977    // ---- BD-UI-31 表格行选中面 ----
978
979    /// 该行是否为所属表的选中行(渲染判断;无键 = 未选)。
980    pub fn row_selected(&self, table: &str, key: &str) -> bool {
981        self.row_sel
982            .lock()
983            .unwrap()
984            .get(table)
985            .is_some_and(|k| k == key)
986    }
987
988    /// 设所属表的选中行(每表一行;同键重复点 = 保持)。
989    pub fn select_row(&self, table: &str, key: &str) {
990        self.row_sel
991            .lock()
992            .unwrap()
993            .insert(table.to_string(), key.to_string());
994    }
995}