1use std::collections::{BTreeMap, VecDeque};
7use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
8use std::sync::{Arc, Mutex};
9
10use ek_data::bar::BarData;
11use ek_dm::wire::BarsFrame;
12use ek_station::wire::PlugRow;
13
14pub const RING_CAP: usize = 512;
16
17pub(crate) fn beijing_tz() -> chrono::FixedOffset {
22 chrono::FixedOffset::east_opt(8 * 3600).expect("+08 offset is always valid")
23}
24
25#[derive(Debug, Clone)]
29pub struct LogEntry {
30 pub at: String,
32 pub text: String,
34}
35
36#[derive(Debug)]
38pub struct LogRing {
39 lines: VecDeque<LogEntry>,
40 cap: usize,
41 spilled: u64,
42}
43
44impl Default for LogRing {
45 fn default() -> Self {
46 Self::new(RING_CAP)
47 }
48}
49
50impl LogRing {
51 pub fn new(cap: usize) -> Self {
53 Self {
54 lines: VecDeque::with_capacity(cap),
55 cap,
56 spilled: 0,
57 }
58 }
59
60 pub fn push(&mut self, line: impl Into<String>) {
62 if self.cap == 0 {
63 self.spilled += 1;
64 return;
65 }
66 if self.lines.len() == self.cap {
67 self.lines.pop_front();
68 self.spilled += 1;
69 }
70 let at = chrono::Utc::now()
71 .with_timezone(&beijing_tz())
72 .format("%H:%M:%S")
73 .to_string();
74 self.lines.push_back(LogEntry {
75 at,
76 text: line.into(),
77 });
78 }
79
80 pub fn len(&self) -> usize {
82 self.lines.len()
83 }
84
85 pub fn is_empty(&self) -> bool {
87 self.lines.is_empty()
88 }
89
90 pub fn spilled(&self) -> u64 {
92 self.spilled
93 }
94
95 pub fn snapshot(&self) -> Vec<String> {
97 self.lines.iter().map(|e| e.text.clone()).collect()
98 }
99
100 pub fn entries(&self) -> Vec<LogEntry> {
102 self.lines.iter().cloned().collect()
103 }
104
105 pub fn clear(&mut self) {
107 self.lines.clear();
108 }
109}
110
111#[derive(Debug, Clone, Default)]
113pub struct BusSnap {
114 pub rows: Vec<PlugRow>,
116 pub services: Vec<(String, Vec<String>)>,
118}
119
120#[derive(Debug, Clone, PartialEq)]
122pub enum UiCmd {
123 Start { factory: String, name: String },
126 Remove { name: String },
128 Reload {
130 interval: i64,
131 symbol: String,
132 bars: Vec<BarData>,
133 },
134 SendOrder {
140 req: ek_data::order_request::OrderRequest,
141 gateway: String,
142 mode: ek_oms::LockMode,
143 },
144 CancelOrder { orderid: String, gateway: String },
148 CtpConfigure { gateway: String, form: CtpForm },
152 Connect { gateway: String, form: CtpForm },
157 CtpSubscribe {
160 gateway: String,
161 symbols: Vec<String>,
162 },
163 Disconnect { gateway: String },
167}
168
169pub const KLINE_CELL_CAP: usize = 4096;
171
172pub const MAX_ACCOUNTS: usize = 8;
175
176pub const QUERY_REJECT_STREAK_LIMIT: u32 = 3;
181
182pub const ACCOUNT_STALE_SECS: i64 = 30;
187
188pub const STATUS_POLL_TICKS: u32 = 2;
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum ConfirmStep {
197 Armed,
198 Fired,
199 Switched,
200}
201
202#[must_use]
205pub fn is_quarantined(state: &str) -> bool {
206 state.contains("Quarantin")
207}
208
209#[derive(Debug, Default)]
213pub struct MarketStore {
214 cells: Mutex<BTreeMap<(String, i64), Vec<BarData>>>,
215 frames: AtomicU64,
217 updates: AtomicU64,
219 reloads: AtomicU64,
221}
222
223#[derive(Debug, Clone, PartialEq)]
225pub struct CellView {
226 pub symbol: String,
227 pub interval: i64,
228 pub bars: Vec<BarData>,
229}
230
231impl MarketStore {
232 pub fn on_frame(&self, frame: &BarsFrame) {
234 let mut cells = self.cells.lock().unwrap();
235 for b in &frame.bars {
236 let key = (b.symbol.clone(), frame.interval);
237 let cell = cells.entry(key).or_default();
238 match cell.last() {
239 Some(last) if b.datetime < last.datetime => continue,
240 Some(last) if b.datetime == last.datetime => {
241 let slot = cell.last_mut().expect("len>1");
242 *slot = b.clone();
243 }
244 _ => {
245 cell.push(b.clone());
246 if cell.len() > KLINE_CELL_CAP {
247 cell.remove(0);
248 }
249 }
250 }
251 }
252 self.frames.fetch_add(1, Ordering::AcqRel);
253 }
254
255 pub fn on_update(&self, b: &BarData) {
257 let mut cells = self.cells.lock().unwrap();
258 let iv = b
259 .interval
260 .unwrap_or(ek_data::constant::Interval::MINUTE)
261 .seconds();
262 let key = (b.symbol.clone(), iv);
263 let cell = cells.entry(key).or_default();
264 match cell.last() {
265 Some(last) if b.datetime == last.datetime => {
266 let slot = cell.last_mut().expect("len>1");
267 *slot = b.clone();
268 }
269 Some(last) if b.datetime < last.datetime => {}
270 _ => {
271 cell.push(b.clone());
272 if cell.len() > KLINE_CELL_CAP {
273 cell.remove(0);
274 }
275 }
276 }
277 self.updates.fetch_add(1, Ordering::AcqRel);
278 }
279
280 pub fn note_reload(&self) {
282 self.reloads.fetch_add(1, Ordering::AcqRel);
283 }
284
285 pub fn cells(&self) -> Vec<CellView> {
287 self.cells
288 .lock()
289 .unwrap()
290 .iter()
291 .map(|((sym, iv), bars)| CellView {
292 symbol: sym.clone(),
293 interval: *iv,
294 bars: bars.clone(),
295 })
296 .collect()
297 }
298
299 pub fn counts(&self) -> (u64, u64, u64) {
301 (
302 self.frames.load(Ordering::Acquire),
303 self.updates.load(Ordering::Acquire),
304 self.reloads.load(Ordering::Acquire),
305 )
306 }
307}
308
309#[derive(Debug, Default, Clone, PartialEq)]
312pub struct ReloadForm {
313 pub interval: String,
314 pub symbol: String,
315 pub csv: String,
316}
317
318pub fn parse_gateway(raw: &str, fallback: Option<&str>) -> Result<String, String> {
325 let g = raw.trim();
326 if !g.is_empty() {
327 if g.chars().any(|c| c.is_whitespace()) {
328 return Err(format!("网关解析: 含空白:{raw:?}"));
329 }
330 return Ok(g.to_string());
331 }
332 match fallback.map(|f| f.trim()).filter(|f| !f.is_empty()) {
333 Some(f) => Ok(f.to_string()),
334 None => Err("网关解析: 未选择账户(先在账户面板添加账户)".to_string()),
335 }
336}
337
338#[derive(Debug, Clone, PartialEq)]
341pub struct CtpForm {
342 pub broker_id: String,
343 pub td_addr: String,
344 pub td_user: String,
345 pub td_password: String,
346 pub td_auth_code: String,
347 pub td_app_id: String,
348 pub md_addr: String,
349 pub md_user: String,
350 pub md_password: String,
351 pub symbols: String,
353 pub accept_futures: bool,
356 pub accept_options: bool,
357}
358
359impl Default for CtpForm {
362 fn default() -> Self {
363 Self {
364 broker_id: String::new(),
365 td_addr: String::new(),
366 td_user: String::new(),
367 td_password: String::new(),
368 td_auth_code: String::new(),
369 td_app_id: String::new(),
370 md_addr: String::new(),
371 md_user: String::new(),
372 md_password: String::new(),
373 symbols: String::new(),
374 accept_futures: true,
375 accept_options: false,
376 }
377 }
378}
379
380impl CtpForm {
381 #[must_use]
385 pub fn product_classes(&self) -> Vec<String> {
386 let mut codes = Vec::new();
387 if self.accept_futures {
388 codes.push("1".to_string());
389 }
390 if self.accept_options {
391 codes.push("2".to_string());
392 }
393 codes
394 }
395
396 pub fn to_configure_req(&self) -> ek_ctp::plugin::ConfigureReq {
398 ek_ctp::plugin::ConfigureReq {
399 broker_id: self.broker_id.trim().to_string(),
400 td_addr: self.td_addr.trim().to_string(),
401 td_user: self.td_user.trim().to_string(),
402 td_password: self.td_password.clone(),
403 td_auth_code: self.td_auth_code.trim().to_string(),
404 td_app_id: self.td_app_id.trim().to_string(),
405 md_addr: self.md_addr.trim().to_string(),
406 md_user: self.md_user.trim().to_string(),
407 md_password: self.md_password.clone(),
408 product_classes: self.product_classes(),
409 }
410 }
411
412 pub fn parse_symbols(&self) -> Result<Vec<String>, String> {
414 let list: Vec<String> = self
415 .symbols
416 .split([',', ',', ' '])
417 .map(|s| s.trim().to_string())
418 .filter(|s| !s.is_empty())
419 .collect();
420 if list.is_empty() {
421 return Err("订阅解析: 标的位空".to_string());
422 }
423 Ok(list)
424 }
425
426 pub fn validate(&self) -> Result<(), String> {
435 fn front(name: &str, v: &str) -> Result<(), String> {
436 let v = v.trim();
437 let Some(rest) = v.strip_prefix("tcp://") else {
438 return Err(format!("{name} 形制应为 tcp://host:port(当前 {:?})", v));
439 };
440 let Some((host, port)) = rest.rsplit_once(':') else {
441 return Err(format!("{name} 缺端口:{name} {:?}", v));
442 };
443 if host.trim().is_empty() {
444 return Err(format!("{name} 主机位空:{}", v));
445 }
446 let port: u32 = port
447 .parse()
448 .map_err(|_| format!("{name} 端口不是数字:{}", v))?;
449 if port == 0 || port > 65535 {
450 return Err(format!("{name} 端口越界(1..=65535):{}", v));
451 }
452 Ok(())
453 }
454 if self.broker_id.trim().is_empty() {
455 return Err("broker 位空".to_string());
456 }
457 if self.td_user.trim().is_empty() {
458 return Err("交易账号位空".to_string());
459 }
460 front("td 前置", &self.td_addr)?;
461 if !self.md_addr.trim().is_empty() {
462 front("md 前置", &self.md_addr)?;
463 }
464 if self.td_app_id.trim().is_empty() {
465 return Err("AppID 位空(CTP 登录必需)".to_string());
466 }
467 if self.td_auth_code.trim().is_empty() {
468 return Err("AuthCode 位空(CTP 登录必需)".to_string());
469 }
470 Ok(())
471 }
472}
473
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
481pub enum AccountStage {
482 #[default]
484 NotAssembled,
485 Assembling,
487 Assembled,
489 AssembleFailed,
491}
492
493impl AccountStage {
494 #[must_use]
496 pub fn label(self) -> &'static str {
497 match self {
498 AccountStage::NotAssembled => "未装配",
499 AccountStage::Assembling => "装配中…",
500 AccountStage::Assembled => "已装配·登录态未知",
503 AccountStage::AssembleFailed => "装配失败",
504 }
505 }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
513pub enum LoginState {
514 #[default]
519 Unknown,
520 Online,
522 LoginFailed,
524 FrontDown,
526 QueryStarved,
528 Stopped,
530}
531
532impl LoginState {
533 #[must_use]
535 pub fn label(self) -> &'static str {
536 match self {
537 LoginState::Unknown => "登录态未知",
538 LoginState::Online => "在线",
539 LoginState::LoginFailed => "登录失败",
540 LoginState::FrontDown => "掉线",
541 LoginState::QueryStarved => "查询断供",
542 LoginState::Stopped => "已断开",
543 }
544 }
545
546 #[must_use]
548 pub fn is_alarm(self) -> bool {
549 matches!(self, LoginState::LoginFailed | LoginState::FrontDown)
550 }
551}
552
553fn count_note(label: &str, n: u32) -> Option<String> {
555 (n > 0).then(|| format!("{label} {n} 次"))
556}
557
558#[derive(Debug, Clone, PartialEq, Default)]
564pub struct AccountRow {
565 pub gateway: String,
567 pub alias: String,
569 pub broker_id: String,
570 pub account: String,
571 pub md_source: bool,
573 pub form: CtpForm,
575 pub stage: AccountStage,
577 pub fail_note: Option<String>,
579 pub effective_classes: Vec<String>,
584 pub connected: bool,
587 pub login: LoginState,
591 pub status_note: Option<String>,
594}
595
596impl AccountRow {
597 pub fn derive(form: &CtpForm) -> Result<Self, String> {
602 let broker = form.broker_id.trim();
603 let account = form.td_user.trim();
604 let gateway = ek_ctp::derived_gateway_name(broker, account).ok_or_else(|| {
605 "账户: broker/账号 不能为空且只能含字母数字(且派生名 ≤32)".to_string()
606 })?;
607 Ok(Self {
608 gateway,
609 alias: String::new(),
610 broker_id: broker.to_string(),
611 account: account.to_string(),
612 md_source: false,
613 form: form.clone(),
614 stage: AccountStage::NotAssembled,
615 fail_note: None,
616 effective_classes: Vec::new(),
617 connected: false,
618 login: LoginState::Unknown,
619 status_note: None,
620 })
621 }
622
623 #[must_use]
629 pub fn status_label(&self) -> String {
630 if self.stage == AccountStage::Assembled {
631 match self.login {
632 LoginState::Unknown => "已装配·登录态未知".to_string(),
633 other => format!("已装配·{}", other.label()),
634 }
635 } else {
636 self.stage.label().to_string()
637 }
638 }
639
640 pub fn apply_status(
653 &mut self,
654 st: &ek_ctp::plugin::GatewayStatus,
655 now_ms: i64,
656 reject_limit: u32,
657 stale_secs: i64,
658 ) {
659 let td_side = !self.form.td_addr.trim().is_empty();
660 let (login, note) = if td_side {
661 if st.td_login_failed && !st.td_logged_in {
662 (
663 LoginState::LoginFailed,
664 st.td_last_error
665 .clone()
666 .or_else(|| Some("登录失败(网关未回带原因)".to_string())),
667 )
668 } else if st.td_logged_in {
669 if st.td_query_reject_streak >= reject_limit {
670 (
671 LoginState::QueryStarved,
672 Some(format!("查询连续被拒 {} 次", st.td_query_reject_streak)),
673 )
674 } else if let Some(last) = st.td_last_account_ms {
675 let idle_ms = now_ms.saturating_sub(last);
676 if idle_ms > stale_secs.saturating_mul(1_000) {
677 (
678 LoginState::QueryStarved,
679 Some(format!("资金回报已 {}s 未更新", idle_ms / 1_000)),
680 )
681 } else {
682 (LoginState::Online, count_note("掉线", st.td_disconnects))
683 }
684 } else {
685 let since_login_ms = st.td_last_login_ok_ms.map(|ok| now_ms.saturating_sub(ok));
692 match since_login_ms {
693 Some(ms) if ms > stale_secs.saturating_mul(1_000) => (
694 LoginState::QueryStarved,
695 Some(format!("资金回报从未到手(登录已 {}s)", ms / 1_000)),
696 ),
697 _ => (LoginState::Online, Some("资金回报尚未到手".to_string())),
698 }
699 }
700 } else if self.login == LoginState::Stopped {
701 let extra = if st.td_disconnects > 0 {
702 format!("(此前掉线 {} 次)", st.td_disconnects)
703 } else {
704 String::new()
705 };
706 (
707 LoginState::Stopped,
708 Some(format!("会话已停{extra};『连接』可恢复")),
709 )
710 } else if st.td_disconnects > 0 {
711 (
712 LoginState::FrontDown,
713 Some(format!("掉线 {} 次", st.td_disconnects)),
714 )
715 } else {
716 (LoginState::Unknown, st.td_last_error.clone())
717 }
718 } else if st.md_logged_in {
719 (
720 LoginState::Online,
721 count_note("掉线", st.md_disconnects)
722 .or_else(|| Some("纯行情账户(无 TD 会话)".to_string())),
723 )
724 } else if self.login == LoginState::Stopped {
725 (
726 LoginState::Stopped,
727 Some("会话已停;『连接』可恢复".to_string()),
728 )
729 } else if st.md_disconnects > 0 {
730 (
731 LoginState::FrontDown,
732 Some(format!("掉线 {} 次", st.md_disconnects)),
733 )
734 } else {
735 (LoginState::Unknown, st.md_last_error.clone())
736 };
737 let note = if td_side && st.td_instrument_rejects > 0 {
742 let add = format!("合约查询被拒 {} 次", st.td_instrument_rejects);
743 match note {
744 Some(base) if base.contains("合约查询被拒") => Some(base),
746 Some(base) => Some(format!("{base};{add}")),
747 None => Some(add),
748 }
749 } else {
750 note
751 };
752 self.login = login;
753 self.status_note = note;
754 }
755
756 #[must_use]
758 pub fn display_name(&self) -> String {
759 let a = self.alias.trim();
760 if a.is_empty() {
761 self.account.clone()
762 } else {
763 a.to_string()
764 }
765 }
766}
767
768#[derive(Debug, Clone, PartialEq, Default)]
770pub struct TradeSnap {
771 pub orders: Vec<ek_data::order::OrderData>,
772 pub trades: Vec<ek_data::trade::TradeData>,
773 pub positions: Vec<ek_data::position::PositionData>,
774 pub accounts: Vec<ek_data::account::AccountData>,
776}
777
778pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
781 let interval: i64 = form
782 .interval
783 .trim()
784 .parse()
785 .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
786 let symbol = form.symbol.trim().to_string();
787 if symbol.is_empty() {
788 return Err("回灌解析: symbol 空".to_string());
789 }
790 if form.csv.trim().is_empty() {
791 return Err("回灌解析: csv 空".to_string());
792 }
793 let mut bars = Vec::new();
794 for (i, raw) in form.csv.lines().enumerate() {
795 let line = raw.trim();
796 if line.is_empty() || line.starts_with('#') {
797 continue;
798 }
799 let parts: Vec<&str> = line.split(',').map(str::trim).collect();
800 if parts.len() != 6 {
801 return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
802 }
803 let num = |s: &str| -> Result<f64, String> {
804 s.parse::<f64>()
805 .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
806 };
807 let dt_s: i64 = parts[0]
808 .parse()
809 .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
810 bars.push(BarData {
811 symbol: symbol.clone(),
812 datetime: dt_s * 1_000_000_000,
813 interval: Some(
814 ek_dm::wire::interval_of_seconds(interval)
815 .unwrap_or(ek_data::constant::Interval::MINUTE),
816 ),
817 open_price: num(parts[1])?,
818 high_price: num(parts[2])?,
819 low_price: num(parts[3])?,
820 close_price: num(parts[4])?,
821 volume: num(parts[5])?,
822 ..BarData::default()
823 });
824 }
825 if bars.is_empty() {
826 return Err("回灌解析: 无有效行".to_string());
827 }
828 Ok((interval, symbol, bars))
829}
830
831#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
836pub enum TopLeftTab {
837 #[default]
838 Orders,
839 Active,
840}
841
842impl TopLeftTab {
843 pub fn label(self) -> &'static str {
844 match self {
845 Self::Orders => "委托",
846 Self::Active => "未成交",
847 }
848 }
849}
850
851#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
853pub enum BottomRightTab {
854 #[default]
855 Account,
856 Logs,
857}
858
859impl BottomRightTab {
860 pub fn label(self) -> &'static str {
861 match self {
862 Self::Account => "资金",
863 Self::Logs => "日志",
864 }
865 }
866}
867
868#[derive(Debug, Default)]
877pub struct TickStore {
878 ticks: BTreeMap<String, ek_data::tick::TickData>,
879}
880
881impl TickStore {
882 pub fn put(&mut self, t: &ek_data::tick::TickData) {
885 self.ticks
886 .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
887 }
888
889 pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
891 let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
892 v.sort_by(|a, b| {
893 (a.exchange.as_str().to_string(), a.symbol.clone())
894 .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
895 });
896 v
897 }
898
899 pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
901 let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
902 for t in self.rows() {
903 let ex = t.exchange.as_str().to_string();
904 match out.last_mut() {
905 Some((e, v)) if *e == ex => v.push(t),
906 _ => out.push((ex, vec![t])),
907 }
908 }
909 out
910 }
911
912 pub fn len(&self) -> usize {
913 self.ticks.len()
914 }
915
916 pub fn is_empty(&self) -> bool {
917 self.ticks.is_empty()
918 }
919}
920
921#[derive(Debug, Clone, PartialEq)]
923pub struct OrderForm {
924 pub exchange: String,
926 pub symbol: String,
928 pub direction: ek_data::constant::Direction,
929 pub offset: ek_data::constant::Offset,
930 pub order_type: ek_data::constant::OrderType,
931 pub price: String,
933 pub volume: String,
934 pub gateway: String,
936 pub follow_price: bool,
938 pub auto_split: bool,
941}
942
943impl Default for OrderForm {
944 fn default() -> Self {
945 Self {
946 exchange: "SHFE".to_string(),
947 symbol: String::new(),
948 direction: ek_data::constant::Direction::LONG,
949 offset: ek_data::constant::Offset::OPEN,
950 order_type: ek_data::constant::OrderType::LIMIT,
951 price: String::new(),
952 volume: "1".to_string(),
953 gateway: String::new(),
954 follow_price: true,
955 auto_split: true,
956 }
957 }
958}
959
960impl OrderForm {
961 pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
963 use std::str::FromStr;
964 let symbol = self.symbol.trim();
965 if symbol.is_empty() {
966 return Err("下单: 代码为空".to_string());
967 }
968 if symbol.contains('.') {
969 return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
970 }
971 let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
972 .map_err(|e| format!("下单: {e}"))?;
973 let price: f64 = self
974 .price
975 .trim()
976 .parse()
977 .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
978 let volume: f64 = self
979 .volume
980 .trim()
981 .parse()
982 .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
983 if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
984 return Err("下单: 限价单价格须为正".to_string());
985 }
986 if volume <= 0.0 {
987 return Err("下单: 数量须为正".to_string());
988 }
989 Ok(ek_data::order_request::OrderRequest {
990 symbol: symbol.to_string(),
991 exchange,
992 direction: self.direction,
993 order_type: self.order_type,
994 volume,
995 price,
996 offset: self.offset,
997 ..ek_data::order_request::OrderRequest::default()
998 })
999 }
1000}
1001
1002#[derive(Debug, Default)]
1008pub struct ContractStore {
1009 contracts: BTreeMap<String, ek_data::contract::ContractData>,
1010}
1011
1012impl ContractStore {
1013 pub fn put(&mut self, c: &ek_data::contract::ContractData) {
1014 self.contracts
1015 .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
1016 }
1017
1018 pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1020 let p = pattern.trim();
1021 self.contracts
1022 .values()
1023 .filter(|c| {
1024 p.is_empty()
1025 || c.symbol.contains(p)
1026 || c.exchange.as_str().eq_ignore_ascii_case(p)
1027 || c.name.contains(p)
1028 })
1029 .cloned()
1030 .collect()
1031 }
1032
1033 pub fn len(&self) -> usize {
1034 self.contracts.len()
1035 }
1036
1037 pub fn is_empty(&self) -> bool {
1038 self.contracts.is_empty()
1039 }
1040}
1041
1042#[derive(Debug, Default)]
1044pub struct UiShared {
1045 logs: Mutex<LogRing>,
1046 snap: Mutex<Arc<BusSnap>>,
1047 market: MarketStore,
1048 ctp_form: Mutex<CtpForm>,
1049 trade_snap: Mutex<Arc<TradeSnap>>,
1050 tick_store: Mutex<TickStore>,
1051 order_form: Mutex<OrderForm>,
1052 selected_exchange: Mutex<String>,
1053 topleft_tab: Mutex<TopLeftTab>,
1054 monitor_dock: Mutex<Option<egui_dock::DockState<crate::dock::DataGroup>>>,
1058 bottomright_tab: Mutex<BottomRightTab>,
1059 ops_window: AtomicBool,
1060 accounts_window: AtomicBool,
1063 contracts_window: AtomicBool,
1064 contract_store: Mutex<ContractStore>,
1065 contract_query: Mutex<String>,
1066 contract_selected: Mutex<Vec<String>>,
1067 kline_windows: Mutex<Vec<String>>,
1068 rev: AtomicU64,
1069 stop: AtomicBool,
1071 cmds: Mutex<VecDeque<UiCmd>>,
1073 pending_confirm: Mutex<Option<String>>,
1075 accounts: Mutex<Vec<AccountRow>>,
1077 account_edit_window: AtomicBool,
1079 editing_account: Mutex<Option<String>>,
1081 edit_alias: Mutex<String>,
1083 edit_error: Mutex<Option<String>>,
1085 md_source: Mutex<String>,
1087 subscriptions: Mutex<Vec<String>>,
1089 row_sel: Mutex<BTreeMap<String, String>>,
1092 table_sorts: Mutex<BTreeMap<String, Option<(usize, bool)>>>,
1096 table_resize: Mutex<BTreeMap<String, bool>>,
1098 status_tick: AtomicU32,
1100 status_thresholds: Mutex<Option<(u32, i64)>>,
1103 pending_alerts: Mutex<Vec<(crate::toast::AlertLevel, String)>>,
1105 toasts: crate::toast::ToastsCell,
1108 alerted: Mutex<std::collections::BTreeSet<String>>,
1110 exit_confirm_open: AtomicBool,
1112 exit_confirmed: AtomicBool,
1114}
1115
1116impl UiShared {
1117 pub fn new() -> Self {
1119 Self::default()
1120 }
1121
1122 pub fn update_tick(&self, t: &ek_data::tick::TickData) {
1126 self.tick_store.lock().unwrap().put(t);
1127 self.bump();
1128 }
1129
1130 pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
1132 self.tick_store.lock().unwrap().rows()
1133 }
1134
1135 pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1137 self.tick_store.lock().unwrap().groups()
1138 }
1139
1140 pub fn tick_count(&self) -> usize {
1142 self.tick_store.lock().unwrap().len()
1143 }
1144
1145 pub fn order_form(&self) -> OrderForm {
1147 self.order_form.lock().unwrap().clone()
1148 }
1149
1150 pub fn set_order_form(&self, f: OrderForm) {
1152 *self.order_form.lock().unwrap() = f;
1153 self.bump();
1154 }
1155
1156 pub fn selected_exchange(&self) -> String {
1158 self.selected_exchange.lock().unwrap().clone()
1159 }
1160
1161 pub fn set_selected_exchange(&self, s: impl Into<String>) {
1163 *self.selected_exchange.lock().unwrap() = s.into();
1164 self.bump();
1165 }
1166
1167 pub fn topleft_tab(&self) -> TopLeftTab {
1169 *self.topleft_tab.lock().unwrap()
1170 }
1171
1172 pub fn set_topleft_tab(&self, t: TopLeftTab) {
1174 *self.topleft_tab.lock().unwrap() = t;
1175 self.bump();
1176 }
1177
1178 pub fn bottomright_tab(&self) -> BottomRightTab {
1180 *self.bottomright_tab.lock().unwrap()
1181 }
1182
1183 pub fn set_bottomright_tab(&self, t: BottomRightTab) {
1185 *self.bottomright_tab.lock().unwrap() = t;
1186 self.bump();
1187 }
1188
1189 pub fn ops_window_open(&self) -> bool {
1193 self.ops_window.load(Ordering::Acquire)
1194 }
1195
1196 pub fn table_sort(&self, table: &str) -> Option<(usize, bool)> {
1200 self.table_sorts
1201 .lock()
1202 .unwrap()
1203 .get(table)
1204 .copied()
1205 .flatten()
1206 }
1207
1208 pub fn toggle_table_sort(&self, table: &str, col: usize) {
1210 let mut m = self.table_sorts.lock().unwrap();
1211 let asc = match m.get(table).copied().flatten() {
1212 Some((c, a)) if c == col => !a,
1213 _ => true,
1214 };
1215 m.insert(table.to_string(), Some((col, asc)));
1216 }
1217
1218 pub fn table_resize_on(&self, table: &str) -> bool {
1220 *self
1221 .table_resize
1222 .lock()
1223 .unwrap()
1224 .get(table)
1225 .unwrap_or(&false)
1226 }
1227
1228 pub fn toggle_table_resize(&self, table: &str) {
1229 let mut m = self.table_resize.lock().unwrap();
1230 let cur = *m.get(table).unwrap_or(&false);
1231 m.insert(table.to_string(), !cur);
1232 }
1233
1234 pub fn dock_tree(
1235 &self,
1236 ) -> std::sync::MutexGuard<'_, Option<egui_dock::DockState<crate::dock::DataGroup>>> {
1237 self.monitor_dock.lock().unwrap()
1238 }
1239
1240 pub fn set_ops_window_open(&self, v: bool) {
1241 self.ops_window.store(v, Ordering::Release);
1242 self.bump();
1243 }
1244
1245 pub fn accounts_window_open(&self) -> bool {
1249 self.accounts_window.load(Ordering::Acquire)
1250 }
1251
1252 pub fn set_accounts_window_open(&self, v: bool) {
1254 self.accounts_window.store(v, Ordering::Release);
1255 self.bump();
1256 }
1257
1258 pub fn account_edit_open(&self) -> bool {
1260 self.account_edit_window.load(Ordering::Acquire)
1261 }
1262
1263 pub fn editing_account(&self) -> Option<String> {
1265 self.editing_account.lock().unwrap().clone()
1266 }
1267
1268 pub fn begin_account_edit(&self, gateway: Option<&str>) -> bool {
1272 match gateway {
1273 Some(gw) => {
1274 let Some(row) = self.account(gw) else {
1275 return false;
1276 };
1277 *self.editing_account.lock().unwrap() = Some(gw.to_string());
1278 *self.edit_alias.lock().unwrap() = row.alias.clone();
1279 self.set_ctp_form(row.form.clone());
1280 }
1281 None => {
1282 *self.editing_account.lock().unwrap() = None;
1283 *self.edit_alias.lock().unwrap() = String::new();
1284 let draft = self.draft_from_existing();
1285 self.set_ctp_form(draft);
1286 }
1287 }
1288 *self.edit_error.lock().unwrap() = None;
1289 self.account_edit_window.store(true, Ordering::Release);
1290 self.bump();
1291 true
1292 }
1293
1294 pub fn end_account_edit(&self) {
1296 *self.editing_account.lock().unwrap() = None;
1297 *self.edit_alias.lock().unwrap() = String::new();
1298 *self.edit_error.lock().unwrap() = None;
1299 self.account_edit_window.store(false, Ordering::Release);
1300 let draft = self.draft_from_existing();
1301 self.set_ctp_form(draft);
1302 self.bump();
1303 }
1304
1305 pub fn end_account_edit_if_editing(&self, gateway: &str) {
1311 if self.editing_account().as_deref() == Some(gateway) {
1312 self.end_account_edit();
1313 }
1314 }
1315
1316 pub fn edit_alias(&self) -> String {
1318 self.edit_alias.lock().unwrap().clone()
1319 }
1320
1321 pub fn set_edit_alias(&self, v: impl Into<String>) {
1323 *self.edit_alias.lock().unwrap() = v.into();
1324 self.bump();
1325 }
1326
1327 pub fn edit_error(&self) -> Option<String> {
1329 self.edit_error.lock().unwrap().clone()
1330 }
1331
1332 pub fn set_edit_error(&self, e: Option<String>) {
1334 *self.edit_error.lock().unwrap() = e;
1335 self.bump();
1336 }
1337
1338 pub fn account_edit_dirty(&self) -> bool {
1340 let editing = self.editing_account();
1341 let draft = self.ctp_form();
1342 match editing {
1343 Some(gw) => self.account(&gw).map(|a| a.form != draft).unwrap_or(false),
1344 None => draft != CtpForm::default() && !draft.td_user.trim().is_empty(),
1345 }
1346 }
1347
1348 pub fn accounts(&self) -> Vec<AccountRow> {
1350 self.accounts.lock().unwrap().clone()
1351 }
1352
1353 pub fn account(&self, gateway: &str) -> Option<AccountRow> {
1355 self.accounts
1356 .lock()
1357 .unwrap()
1358 .iter()
1359 .find(|a| a.gateway == gateway)
1360 .cloned()
1361 }
1362
1363 pub fn add_account(&self, row: AccountRow) -> Result<(), String> {
1369 let mut acc = self.accounts.lock().unwrap();
1370 if acc.iter().any(|a| a.gateway == row.gateway) {
1371 return Err(format!("账户 {} 已存在(同 broker + 账号)", row.gateway));
1372 }
1373 let alias = row.alias.trim();
1374 if !alias.is_empty()
1375 && acc
1376 .iter()
1377 .any(|a| a.alias.trim().eq_ignore_ascii_case(alias))
1378 {
1379 return Err(format!("别名 {alias:?} 已被其他账户占用(别名须唯一)"));
1380 }
1381 if acc.len() >= MAX_ACCOUNTS {
1382 return Err(format!(
1383 "账户已达软上限 {MAX_ACCOUNTS} 个(先移除一个再添加)"
1384 ));
1385 }
1386 acc.push(row);
1387 drop(acc);
1388 self.bump();
1389 Ok(())
1390 }
1391
1392 #[must_use]
1394 pub fn can_add_account(&self) -> bool {
1395 self.accounts.lock().unwrap().len() < MAX_ACCOUNTS
1396 }
1397
1398 pub fn set_account_alias(&self, gateway: &str, alias: &str) -> bool {
1404 let alias = alias.trim().to_string();
1405 let mut acc = self.accounts.lock().unwrap();
1406 if !alias.is_empty()
1407 && acc
1408 .iter()
1409 .any(|a| a.gateway != gateway && a.alias.eq_ignore_ascii_case(&alias))
1410 {
1411 return false;
1412 }
1413 match acc.iter_mut().find(|a| a.gateway == gateway) {
1414 Some(a) => {
1415 a.alias = alias;
1416 drop(acc);
1417 self.bump();
1418 true
1419 }
1420 None => false,
1421 }
1422 }
1423
1424 pub fn note_connect_sent(&self, gateway: &str) {
1429 let mut acc = self.accounts.lock().unwrap();
1430 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1431 a.stage = AccountStage::Assembling;
1432 a.fail_note = None;
1433 a.login = LoginState::Unknown;
1434 a.status_note = None;
1435 drop(acc);
1436 self.bump();
1437 }
1438 }
1439
1440 pub fn note_connect_result(&self, gateway: &str, result: Result<(), String>) {
1444 let mut acc = self.accounts.lock().unwrap();
1445 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1446 match result {
1447 Ok(()) => {
1448 a.stage = AccountStage::Assembled;
1449 a.fail_note = None;
1450 }
1451 Err(e) => {
1452 a.stage = AccountStage::AssembleFailed;
1453 a.fail_note = Some(e);
1454 }
1455 }
1456 drop(acc);
1457 self.bump();
1458 }
1459 }
1460
1461 pub fn note_effective_product_classes(&self, gateway: &str, classes: &[String]) {
1465 let mut acc = self.accounts.lock().unwrap();
1466 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1467 a.effective_classes = classes.to_vec();
1468 drop(acc);
1469 self.bump();
1470 }
1471 }
1472
1473 #[must_use]
1477 pub fn status_thresholds(&self) -> (u32, i64) {
1478 self.status_thresholds
1479 .lock()
1480 .unwrap()
1481 .unwrap_or((QUERY_REJECT_STREAK_LIMIT, ACCOUNT_STALE_SECS))
1482 }
1483
1484 pub fn set_status_thresholds(&self, reject_limit: u32, stale_secs: i64) {
1486 *self.status_thresholds.lock().unwrap() = Some((reject_limit, stale_secs));
1487 self.bump();
1488 }
1489
1490 pub fn status_poll_due(&self) -> bool {
1492 let n = self.status_tick.fetch_add(1, Ordering::Relaxed) + 1;
1493 n % STATUS_POLL_TICKS == 0
1494 }
1495
1496 pub fn note_gateway_status(&self, gateway: &str, st: &ek_ctp::plugin::GatewayStatus) {
1504 let (limit, stale) = self.status_thresholds();
1505 let now = ek_ctp::map::now_epoch_ms();
1506 let mut alarm: Option<(LoginState, String)> = None;
1509 let mut found = false;
1510 {
1511 let mut acc = self.accounts.lock().unwrap();
1512 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1513 found = true;
1514 a.apply_status(st, now, limit, stale);
1515 if a.login.is_alarm() || a.login == LoginState::QueryStarved {
1516 alarm = Some((
1517 a.login,
1518 a.status_note
1519 .clone()
1520 .unwrap_or_else(|| a.login.label().to_string()),
1521 ));
1522 }
1523 }
1524 }
1525 if found {
1526 self.bump();
1527 }
1528 if let Some((login, note)) = alarm {
1529 if self.alert_once(format!("{gateway}|{}", login.label())) {
1530 self.push_alert(
1531 crate::toast::AlertLevel::Error,
1532 format!("账户 {gateway}:{note}"),
1533 );
1534 }
1535 }
1536 }
1537
1538 pub fn note_status_unreachable(&self, gateway: &str, why: &str) {
1542 let mut acc = self.accounts.lock().unwrap();
1543 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1544 a.login = LoginState::Unknown;
1545 a.status_note = Some(format!("状态口问不到:{why}"));
1546 drop(acc);
1547 self.bump();
1548 }
1549 }
1550
1551 pub fn mark_account_stopped(&self, gateway: &str) {
1553 let mut acc = self.accounts.lock().unwrap();
1554 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1555 a.login = LoginState::Stopped;
1556 a.status_note = Some("会话已停;『连接』可恢复".to_string());
1557 drop(acc);
1558 self.bump();
1559 }
1560 }
1561
1562 pub fn prepare_connect_form(&self, gateway: &str, form: CtpForm) -> CtpForm {
1565 let source = self.md_source();
1566 let mut f = form;
1567 if source.as_str() != gateway {
1568 f.md_addr.clear();
1569 f.md_user.clear();
1570 f.md_password.clear();
1571 }
1572 self.update_account_form(gateway, f.clone());
1573 f
1574 }
1575
1576 #[must_use]
1580 pub fn draft_from_existing(&self) -> CtpForm {
1581 let acc = self.accounts.lock().unwrap();
1582 let mut draft = CtpForm::default();
1583 if let Some(a) = acc.last() {
1584 draft.broker_id = a.form.broker_id.clone();
1585 draft.td_auth_code = a.form.td_auth_code.clone();
1586 draft.td_app_id = a.form.td_app_id.clone();
1587 draft.accept_futures = a.form.accept_futures;
1588 draft.accept_options = a.form.accept_options;
1589 }
1590 draft
1591 }
1592
1593 pub fn update_account_form(&self, gateway: &str, form: CtpForm) -> bool {
1595 let mut acc = self.accounts.lock().unwrap();
1596 match acc.iter_mut().find(|a| a.gateway == gateway) {
1597 Some(a) => {
1598 a.form = form;
1599 drop(acc);
1600 self.bump();
1601 true
1602 }
1603 None => false,
1604 }
1605 }
1606
1607 pub fn remove_account(&self, gateway: &str) -> bool {
1609 let mut acc = self.accounts.lock().unwrap();
1610 let before = acc.len();
1611 acc.retain(|a| a.gateway != gateway);
1612 let removed = acc.len() != before;
1613 if removed {
1614 let mut md = self.md_source.lock().unwrap();
1616 if md.as_str() == gateway {
1617 md.clear();
1618 }
1619 drop(acc);
1620 self.bump();
1621 }
1622 removed
1623 }
1624
1625 pub fn sync_accounts_connected(&self, rows: &[PlugRow]) -> Vec<String> {
1634 let mut newly = Vec::new();
1635 {
1636 let mut acc = self.accounts.lock().unwrap();
1637 for a in acc.iter_mut() {
1638 let up = rows.iter().any(|r| r.name == a.gateway);
1639 if up && !a.connected {
1640 newly.push(a.gateway.clone());
1641 }
1642 a.connected = up;
1643 if up {
1644 a.stage = AccountStage::Assembled;
1645 a.fail_note = None;
1646 } else if a.stage == AccountStage::Assembled {
1647 a.stage = AccountStage::NotAssembled;
1648 a.login = LoginState::Unknown;
1649 a.status_note = None;
1650 }
1651 }
1652 }
1653 if !newly.is_empty() {
1654 self.bump();
1655 }
1656 newly
1657 }
1658
1659 pub fn md_source(&self) -> String {
1661 self.md_source.lock().unwrap().clone()
1662 }
1663
1664 pub fn accounts_locked(&self) -> bool {
1666 self.accounts.lock().unwrap().iter().any(|a| a.connected)
1667 }
1668
1669 pub fn set_md_source(&self, gateway: &str) -> Result<(), String> {
1671 {
1672 let acc = self.accounts.lock().unwrap();
1673 if acc.iter().any(|a| a.connected) {
1674 return Err("元账号已锁定:有账户在线,切换行情源需先断开该账户".to_string());
1675 }
1676 if !acc.iter().any(|a| a.gateway == gateway) {
1677 return Err(format!("账户 {gateway} 不在清册"));
1678 }
1679 }
1680 let mut acc = self.accounts.lock().unwrap();
1681 for a in acc.iter_mut() {
1682 a.md_source = a.gateway == gateway;
1683 }
1684 drop(acc);
1685 let mut md = self.md_source.lock().unwrap();
1686 *md = gateway.to_string();
1687 self.bump();
1688 Ok(())
1689 }
1690
1691 pub fn subscriptions(&self) -> Vec<String> {
1693 self.subscriptions.lock().unwrap().clone()
1694 }
1695
1696 pub fn note_subscriptions(&self, symbols: &[String]) {
1698 {
1699 let mut subs = self.subscriptions.lock().unwrap();
1700 for s in symbols {
1701 let s = s.trim();
1702 if !s.is_empty() && !subs.iter().any(|x| x == s) {
1703 subs.push(s.to_string());
1704 }
1705 }
1706 }
1707 self.bump();
1708 }
1709
1710 pub fn default_gateway(&self) -> Option<String> {
1717 let chosen = {
1718 let f = self.order_form.lock().unwrap();
1719 f.gateway.trim().to_string()
1720 };
1721 if !chosen.is_empty() && self.account(&chosen).is_some_and(|a| a.connected) {
1722 return Some(chosen);
1723 }
1724 let acc = self.accounts.lock().unwrap();
1725 acc.iter().find(|a| a.connected).map(|a| a.gateway.clone())
1726 }
1727
1728 pub fn kline_symbols(&self) -> Vec<String> {
1730 self.kline_windows.lock().unwrap().clone()
1731 }
1732
1733 pub fn open_kline(&self, symbol: impl Into<String>) {
1735 let s = symbol.into();
1736 let mut v = self.kline_windows.lock().unwrap();
1737 if !v.contains(&s) {
1738 v.push(s.clone());
1739 }
1740 drop(v);
1741 self.log_line(format!("[kline] 打开 K线窗 {s}"));
1742 }
1743
1744 pub fn close_kline(&self, symbol: &str) {
1746 self.kline_windows.lock().unwrap().retain(|s| s != symbol);
1747 self.bump();
1748 }
1749
1750 pub fn contracts_window_open(&self) -> bool {
1754 self.contracts_window.load(Ordering::Acquire)
1755 }
1756
1757 pub fn set_contracts_window_open(&self, v: bool) {
1759 self.contracts_window.store(v, Ordering::Release);
1760 self.bump();
1761 }
1762
1763 pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
1765 self.contract_store.lock().unwrap().put(c);
1766 self.bump();
1767 }
1768
1769 pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1771 self.contract_store.lock().unwrap().query(pattern)
1772 }
1773
1774 pub fn contract_count(&self) -> usize {
1776 self.contract_store.lock().unwrap().len()
1777 }
1778
1779 pub fn contract_query(&self) -> String {
1781 self.contract_query.lock().unwrap().clone()
1782 }
1783
1784 pub fn set_contract_query(&self, q: impl Into<String>) {
1786 *self.contract_query.lock().unwrap() = q.into();
1787 self.bump();
1788 }
1789
1790 pub fn toggle_contract_selection(&self, en_symbol: &str) {
1792 let mut v = self.contract_selected.lock().unwrap();
1793 match v.iter().position(|s| s == en_symbol) {
1794 Some(i) => {
1795 v.remove(i);
1796 }
1797 None => v.push(en_symbol.to_string()),
1798 }
1799 self.bump();
1800 }
1801
1802 pub fn selected_contracts(&self) -> Vec<String> {
1804 self.contract_selected.lock().unwrap().clone()
1805 }
1806
1807 pub fn log_line(&self, line: impl Into<String>) {
1809 self.logs.lock().unwrap().push(line);
1810 self.bump();
1811 }
1812
1813 pub fn clear_logs(&self) {
1815 self.logs.lock().unwrap().clear();
1816 self.bump();
1817 }
1818
1819 pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
1821 let r = self.logs.lock().unwrap();
1822 (r.snapshot(), r.spilled())
1823 }
1824
1825 pub fn logs_entries(&self) -> (Vec<LogEntry>, u64) {
1827 let r = self.logs.lock().unwrap();
1828 (r.entries(), r.spilled())
1829 }
1830
1831 pub fn logs_len(&self) -> usize {
1833 self.logs.lock().unwrap().len()
1834 }
1835
1836 pub fn set_snapshot(&self, snap: BusSnap) {
1838 *self.snap.lock().unwrap() = Arc::new(snap);
1839 self.bump();
1840 }
1841
1842 pub fn snapshot(&self) -> Arc<BusSnap> {
1844 Arc::clone(&self.snap.lock().unwrap())
1845 }
1846
1847 pub fn rev(&self) -> u64 {
1849 self.rev.load(Ordering::Acquire)
1850 }
1851
1852 pub fn bump(&self) {
1854 self.rev.fetch_add(1, Ordering::AcqRel);
1855 }
1856
1857 pub fn request_stop(&self) {
1859 self.stop.store(true, Ordering::Release);
1860 }
1861
1862 pub fn push_alert(&self, level: crate::toast::AlertLevel, text: impl Into<String>) {
1865 self.pending_alerts
1866 .lock()
1867 .unwrap_or_else(std::sync::PoisonError::into_inner)
1868 .push((level, text.into()));
1869 }
1870
1871 pub(crate) fn take_alerts(&self) -> Vec<(crate::toast::AlertLevel, String)> {
1873 let mut q = self
1874 .pending_alerts
1875 .lock()
1876 .unwrap_or_else(std::sync::PoisonError::into_inner);
1877 std::mem::take(&mut *q)
1878 }
1879
1880 pub(crate) fn toasts(&self) -> std::sync::MutexGuard<'_, Option<egui_notify::Toasts>> {
1882 self.toasts.lock()
1883 }
1884
1885 pub fn alert_once(&self, key: impl Into<String>) -> bool {
1887 let key = key.into();
1888 self.alerted
1889 .lock()
1890 .unwrap_or_else(std::sync::PoisonError::into_inner)
1891 .insert(key)
1892 }
1893
1894 #[must_use]
1896 pub fn pending_alert_count(&self) -> usize {
1897 self.pending_alerts
1898 .lock()
1899 .unwrap_or_else(std::sync::PoisonError::into_inner)
1900 .len()
1901 }
1902
1903 #[must_use]
1905 pub fn alerted_count(&self) -> usize {
1906 self.alerted
1907 .lock()
1908 .unwrap_or_else(std::sync::PoisonError::into_inner)
1909 .len()
1910 }
1911
1912 pub fn exit_confirm_open(&self) -> bool {
1914 self.exit_confirm_open
1915 .load(std::sync::atomic::Ordering::Relaxed)
1916 }
1917
1918 pub fn open_exit_confirm(&self) {
1919 self.exit_confirm_open
1920 .store(true, std::sync::atomic::Ordering::Relaxed);
1921 }
1922
1923 pub fn close_exit_confirm(&self) {
1924 self.exit_confirm_open
1925 .store(false, std::sync::atomic::Ordering::Relaxed);
1926 }
1927
1928 pub fn exit_confirmed(&self) -> bool {
1929 self.exit_confirmed
1930 .load(std::sync::atomic::Ordering::Relaxed)
1931 }
1932
1933 pub fn confirm_exit(&self) {
1934 self.exit_confirmed
1935 .store(true, std::sync::atomic::Ordering::Relaxed);
1936 }
1937
1938 pub fn is_stop(&self) -> bool {
1939 self.stop.load(Ordering::Acquire)
1940 }
1941
1942 pub fn push_cmd(&self, cmd: UiCmd) {
1946 self.cmds.lock().unwrap().push_back(cmd);
1947 self.bump();
1948 }
1949
1950 pub fn drain_cmds(&self) -> Vec<UiCmd> {
1952 self.cmds.lock().unwrap().drain(..).collect()
1953 }
1954
1955 pub fn pending_confirm(&self) -> Option<String> {
1957 self.pending_confirm.lock().unwrap().clone()
1958 }
1959
1960 pub fn confirm_step(&self, name: &str) -> ConfirmStep {
1962 let mut g = self.pending_confirm.lock().unwrap();
1963 match g.take() {
1964 Some(p) if p == name => ConfirmStep::Fired,
1965 Some(_) => {
1966 *g = Some(name.to_string());
1967 ConfirmStep::Switched
1968 }
1969 None => {
1970 *g = Some(name.to_string());
1971 ConfirmStep::Armed
1972 }
1973 }
1974 }
1975
1976 pub fn confirm_cancel(&self) {
1978 *self.pending_confirm.lock().unwrap() = None;
1979 self.bump();
1980 }
1981
1982 pub fn market(&self) -> &MarketStore {
1986 &self.market
1987 }
1988
1989 pub fn set_trade_snap(&self, ts: TradeSnap) {
1993 *self.trade_snap.lock().unwrap() = Arc::new(ts);
1994 self.bump();
1995 }
1996
1997 pub fn trade_snap(&self) -> Arc<TradeSnap> {
1999 self.trade_snap.lock().unwrap().clone()
2000 }
2001
2002 pub fn ctp_form(&self) -> CtpForm {
2006 self.ctp_form.lock().unwrap().clone()
2007 }
2008
2009 pub fn set_ctp_form(&self, f: CtpForm) {
2011 *self.ctp_form.lock().unwrap() = f;
2012 self.bump();
2013 }
2014
2015 pub fn row_selected(&self, table: &str, key: &str) -> bool {
2019 self.row_sel
2020 .lock()
2021 .unwrap()
2022 .get(table)
2023 .is_some_and(|k| k == key)
2024 }
2025
2026 pub fn select_row(&self, table: &str, key: &str) {
2028 self.row_sel
2029 .lock()
2030 .unwrap()
2031 .insert(table.to_string(), key.to_string());
2032 }
2033}