优化:更新配置文件中的重置动作和点击等待时间;调整映射表生成逻辑,提升代码可读性

This commit is contained in:
Your Name committed 2026-01-20 12:16:19 +08:00
1 parent 3b4293365d
commit b9b21d472f
9 files changed
+1062 -528

No files matched your search

+660
View File
@@ -0,0 +1,660 @@
import json
import os
import time
import tkinter as tk
from tkinter import ttk
from typing import Any, List
from datetime import datetime
try:
from . import mapping_utils
except Exception:
try:
import gui.components.mapping_utils as mapping_utils
except Exception:
mapping_utils = None
try:
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
ScrolledText = TBSrolledText
except Exception:
try:
from tkinter.scrolledtext import ScrolledText
except Exception:
ScrolledText = None
def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Frame:
"""创建并返回映射表 Tab(文本样式,类似预约队列)"""
mapping_tab = ttk.Frame(notebook)
map_box = ttk.LabelFrame(mapping_tab, text="运行时映射表(文本样式)")
map_box.pack(fill=tk.BOTH, expand=True, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=tk.X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=tk.LEFT)
refresh_btn = ttk.Button(map_ctrl, text="刷新映射表", width=12)
refresh_btn.pack(side=tk.LEFT, padx=(8, 6))
mapping_source_var = tk.StringVar(value="未加载")
ttk.Label(map_ctrl, textvariable=mapping_source_var).pack(side=tk.LEFT, padx=(8, 0))
show_title_raw_var = tk.BooleanVar(value=False)
show_title_raw_chk = ttk.Checkbutton(
map_ctrl, text="显示原始标题", variable=show_title_raw_var
)
show_title_raw_chk.pack(side=tk.LEFT, padx=(8, 6))
mapping_text_box = ttk.Frame(map_box)
mapping_text_box.pack(fill=tk.BOTH, expand=True, padx=10, pady=(6, 10))
# 使用 Canvas + Frame 的卡片式布局以获得更高档的样式和更好的可读性
canvas = tk.Canvas(mapping_text_box, borderwidth=0, highlightthickness=0)
vscroll = ttk.Scrollbar(mapping_text_box, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vscroll.set)
vscroll.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
inner_frame = ttk.Frame(canvas)
window_id = canvas.create_window((0, 0), window=inner_frame, anchor="nw")
def _on_inner_configure(event: object | None = None) -> None:
try:
canvas.configure(scrollregion=canvas.bbox("all"))
except Exception:
pass
def _on_canvas_configure(event: object | None = None) -> None:
try:
canvas.itemconfigure(window_id, width=event.width)
except Exception:
pass
inner_frame.bind("<Configure>", _on_inner_configure)
canvas.bind("<Configure>", _on_canvas_configure)
# 鼠标滚轮支持(进入时绑定,离开时解绑),兼容 Windows/macOS/Linux
def _on_mousewheel(event: object | None = None) -> None:
try:
# Windows / Mac / X11 事件差异处理
if hasattr(event, "delta") and event.delta:
# Windows 和 macOS 返回 delta(macOS 可能需要不同符号)
# 在 Windows 上,event.delta 为 120 的倍数/方向
delta = int(-1 * (event.delta / 120))
if delta == 0:
# fallback for small deltas
delta = -1 if event.delta < 0 else 1
canvas.yview_scroll(delta, "units")
else:
# X11 可能使用 Button-4/Button-5
if getattr(event, "num", None) == 4:
canvas.yview_scroll(-1, "units")
elif getattr(event, "num", None) == 5:
canvas.yview_scroll(1, "units")
except Exception:
pass
def _bind_mousewheel(_: object | None = None) -> None:
try:
# 绑定到 canvas 的所有滚轮事件,以保证在 card 上也能滚动
canvas.bind_all("<MouseWheel>", _on_mousewheel)
canvas.bind_all("<Button-4>", _on_mousewheel)
canvas.bind_all("<Button-5>", _on_mousewheel)
except Exception:
pass
def _unbind_mousewheel(_: object | None = None) -> None:
try:
canvas.unbind_all("<MouseWheel>")
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
except Exception:
pass
try:
canvas.bind("<Enter>", _bind_mousewheel)
canvas.bind("<Leave>", _unbind_mousewheel)
except Exception:
pass
# 字体与样式(调小以适配用户需求)
try:
import tkinter.font as tkfont
base_font = tkfont.Font(family="Consolas", size=10)
title_font = tkfont.Font(family="Consolas", size=12, weight="bold")
meta_font = tkfont.Font(family="Consolas", size=9, slant="italic")
body_font = tkfont.Font(family="Consolas", size=10)
except Exception:
base_font = title_font = meta_font = body_font = None
# 记录每个卡片的 widget 以便选中与复制
mapping_entries_widgets: List[tk.Widget] = []
# 视觉样式变量
normal_bg = "#ffffff"
hover_bg = "#f6fbff"
selected_bg = "#eaf2ff"
# 状态/搜索/复制 控件
mapping_status_var = tk.StringVar(value="")
ttk.Label(map_ctrl, textvariable=mapping_status_var, foreground="#666666").pack(
side=tk.LEFT, padx=(8, 6)
)
search_var = tk.StringVar(value="")
search_entry = ttk.Entry(map_ctrl, textvariable=search_var, width=26)
search_entry.pack(side=tk.LEFT, padx=(8, 6))
ttk.Button(
map_ctrl,
text="清除",
width=6,
command=lambda: (search_var.set(""), _load_mapping_to_view()),
).pack(side=tk.LEFT, padx=(0, 6))
copy_btn = ttk.Button(map_ctrl, text="复制条目", width=10)
copy_btn.pack(side=tk.LEFT, padx=(4, 6))
# 记录最后一次单击选中的条目索引
last_selected_entry = {"idx": None}
# 存储文本块以便双击查看详情
mapping_entries_text: List[str] = []
mapping_entries_start_lines: List[int] = []
def _load_mapping_to_view():
nonlocal mapping_entries_text, mapping_entries_start_lines
# entries_pool 存放解析得到的所有条目文本;mapping_entries_text 用于显示(会在渲染时按过滤更新)
entries_pool: List[str] = []
mapping_entries_text = []
mapping_entries_start_lines = []
all_lines: List[str] = []
# 读取预约队列与映射表(使用 mapping_utils 模块以实现模块化)
try:
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
except Exception:
base_dir = os.getcwd()
# 尝试通过工具模块加载 reservations 信息
reservations_data = {}
try:
if mapping_utils:
reservations_data = mapping_utils.load_reservations(base_dir)
except Exception:
reservations_data = {}
possible_paths = [
os.path.join(base_dir, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
found = False
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
raw = f.read()
try:
parsed = json.loads(raw)
except Exception:
parsed = None
mapping_source_var.set(p)
if not parsed:
all_lines = ["(非JSON,查看原始文件)", raw]
entries_pool = []
else:
try:
if mapping_utils:
entries_pool = mapping_utils.parse_entries(
parsed, show_title_raw_var.get(), reservations_data
)
else:
# fallback to simple parsing: convert dict/list to strings
if isinstance(parsed, dict):
entries_pool = [
"\n".join([f"[{k}] {v}"])
for k, v in parsed.items()
]
else:
entries_pool = [str(parsed)]
# build all_lines for raw view
all_lines = []
for entry in entries_pool:
all_lines.extend(entry.split("\n"))
all_lines.append("")
except Exception:
entries_pool = []
all_lines = []
found = True
break
except Exception:
pass
# 保存当前可见位置(避免刷新后回到顶部)
try:
prev_top = None
try:
v = canvas.yview()
if isinstance(v, (tuple, list)) and len(v) >= 1:
prev_top = float(v[0])
except Exception:
prev_top = None
except Exception:
prev_top = None
# 清空旧卡片
try:
for w in inner_frame.winfo_children():
try:
w.destroy()
except Exception:
pass
mapping_entries_widgets.clear()
except Exception:
pass
# 渲染卡片式条目(每个字段单独一行)
mapping_entries_start_lines = []
mapping_entries_text = []
if found and entries_pool:
filter_key = (search_var.get() or "").strip().lower()
try:
canvas.update_idletasks()
wraplen = max(220, canvas.winfo_width() - 60)
except Exception:
wraplen = 800
# 计算列数以合理分配右边空白区域
try:
canvas.update_idletasks()
canvas_w = canvas.winfo_width() or 800
except Exception:
canvas_w = 800
min_card_w = 300
h_gap = 12
try:
columns = max(1, int((canvas_w + h_gap) / (min_card_w + h_gap)))
except Exception:
columns = 1
# 限制最大列数以避免过窄(可根据实际需求调整)
columns = min(columns, 3)
# 配置列权重
try:
for ci in range(columns):
inner_frame.grid_columnconfigure(ci, weight=1, uniform="col")
except Exception:
pass
placed = 0
for idx, entry in enumerate(entries_pool):
if filter_key and filter_key not in entry.lower():
continue
# 存储用于复制/详情的纯文本
mapping_entries_text.append(entry)
lines = entry.split("\n")
# 卡片容器(更紧凑的间距与更清晰的边界)
try:
card = tk.Frame(
inner_frame,
bg=normal_bg,
bd=0,
highlightthickness=1,
highlightbackground="#e6e6e6",
relief="flat",
)
except Exception:
card = tk.Frame(inner_frame, bg=normal_bg)
# 计算网格位置
row = placed // columns
col = placed % columns
try:
card.grid(row=row, column=col, sticky="nwe", padx=6, pady=4)
except Exception:
try:
card.pack(fill="x", padx=6, pady=4, anchor="n")
except Exception:
pass
# 计算每列可用宽度用于 wraplength
try:
col_total_gap = columns * 12
col_width = max(220, int((canvas_w - col_total_gap) / columns))
card_wraplen = max(160, col_width - 40)
except Exception:
card_wraplen = wraplen
# 标题行(紧凑)
try:
lbl_title = tk.Label(
card,
text=lines[0],
font=title_font,
bg=normal_bg,
fg="#0b3d91",
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
except Exception:
lbl_title = tk.Label(card, text=lines[0], bg=normal_bg)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
# 其余行逐行显示(meta/body 区分),行间距更小
for li, ln in enumerate(lines[1:], start=1):
try:
if show_title_raw_var.get():
if li in (1, 2, 3):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
if li in (1, 2):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl.pack(fill="x", padx=10, pady=(0, 1))
except Exception:
try:
tk.Label(card, text=ln, bg=normal_bg).pack(
fill="x", padx=10, pady=(0, 1)
)
except Exception:
pass
# 分隔线
try:
ttk.Separator(card, orient="horizontal").pack(
fill="x", padx=8, pady=(6, 4)
)
except Exception:
pass
mapping_entries_widgets.append(card)
# 绑定点击/双击以及 hover 事件
def _make_bind_handlers(ci: int, cframe: tk.Widget):
def _on_click(e: object | None = None) -> None:
try:
# 取消其他选中并高亮当前
for i, w in enumerate(mapping_entries_widgets):
bg = normal_bg if i != ci else selected_bg
try:
try:
w.configure(**{"bg": bg})
except Exception:
w.configure(**{"background": bg})
except Exception:
pass
for ch in w.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
last_selected_entry["idx"] = ci
except Exception:
pass
def _on_dbl(e: object | None = None) -> None:
try:
content = mapping_entries_text[ci]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
def _on_enter(e: object | None = None) -> None:
try:
# 悬停时改变背景(若已选中则保持选中色)
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else hover_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
def _on_leave(e: object | None = None) -> None:
try:
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else normal_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
return _on_click, _on_dbl, _on_enter, _on_leave
on_click, on_dbl, on_enter, on_leave = _make_bind_handlers(
len(mapping_entries_widgets) - 1, card
)
try:
card.bind("<Button-1>", on_click)
card.bind("<Double-1>", on_dbl)
card.bind("<Enter>", on_enter)
card.bind("<Leave>", on_leave)
for child in card.winfo_children():
try:
child.bind("<Button-1>", on_click)
child.bind("<Double-1>", on_dbl)
child.bind("<Enter>", on_enter)
child.bind("<Leave>", on_leave)
except Exception:
pass
except Exception:
pass
placed += 1
else:
mapping_source_var.set("未找到 room_pos_map.json")
try:
tk.Label(
inner_frame, text="未找到映射表文件或无数据", fg="#666666"
).pack(padx=8, pady=8)
except Exception:
pass
# 恢复之前的滚动位置(若可用)
try:
canvas.update_idletasks()
except Exception:
pass
try:
if prev_top is not None:
canvas.yview_moveto(prev_top)
except Exception:
pass
# 刷新后清除选中索引
try:
last_selected_entry["idx"] = None
except Exception:
pass
# 绑定刷新按钮与自动刷新
refresh_btn.config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询
root.after(5000, _maybe_auto_refresh)
# 点击/双击的回退处理:如果用户在卡片外双击或点击,使用最后一次选中项展示详情
def _open_selected_entry_detail(event: object | None = None) -> None:
try:
idx = last_selected_entry.get("idx")
if idx is None:
if mapping_entries_text:
idx = 0
else:
return
try:
content = mapping_entries_text[idx]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
pass
try:
# 在 canvas 上双击会打开当前选中条目的详情(作为卡片双击的补偿)
canvas.bind("<Double-1>", _open_selected_entry_detail)
except Exception:
pass
# 复制选中条目到剪贴板
def _copy_selected_entry() -> None:
try:
idx = last_selected_entry.get("idx")
if idx is None or idx < 0 or idx >= len(mapping_entries_text):
if mapping_entries_text:
content = mapping_entries_text[0]
else:
content = ""
else:
content = mapping_entries_text[idx]
if content:
try:
root.clipboard_clear()
root.clipboard_append(content)
mapping_status_var.set("已复制到剪贴板")
root.after(1800, lambda: mapping_status_var.set(""))
except Exception:
pass
except Exception:
pass
try:
copy_btn.config(command=_copy_selected_entry)
except Exception:
pass
try:
search_entry.bind("<Return>", lambda e: _load_mapping_to_view())
except Exception:
pass
try:
show_title_raw_chk.config(command=_load_mapping_to_view)
_load_mapping_to_view()
except Exception:
pass
return mapping_tab
+216
View File
@@ -0,0 +1,216 @@
import json
import os
from datetime import datetime
from typing import Any, Dict, List, Tuple
def load_reservations(base_dir: str | None = None) -> Dict[int, Any]:
"""加载 reservations.json 并返回以 pos_seen 为键的映射字典。"""
if not base_dir:
try:
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
except Exception:
base_dir = os.getcwd()
reservations_data: Dict[int, Any] = {}
reservations_paths = [
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "reservations.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "reservations.json"),
]
for res_path in reservations_paths:
try:
if os.path.exists(res_path):
with open(res_path, "r", encoding="utf-8") as f:
raw = f.read()
parsed = json.loads(raw)
if isinstance(parsed, dict) and "queue" in parsed:
for item in parsed["queue"]:
pos = item.get("pos_seen", 0)
try:
if pos:
reservations_data[int(pos)] = item
except Exception:
# pos 可能不可转为 int,跳过
pass
break
except Exception:
# ignore malformed reservation files
pass
return reservations_data
def _format_timestamp(ts: Any) -> str:
try:
return datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
try:
return str(ts)
except Exception:
return "-"
def parse_entries(
parsed: Any,
show_title_raw: bool = False,
reservations_data: Dict[int, Any] | None = None,
) -> List[str]:
"""从解析后的 JSON 数据中生成 entries_pool(每项为多行文本)。
返回值:entries_pool(List[str]),每个字符串为一个条目的多行表示。
"""
if reservations_data is None:
reservations_data = {}
entries_pool: List[str] = []
if not parsed:
return entries_pool
# 如果是字典,按 key 排序(尽可能把纯数字当作数字排序)
if isinstance(parsed, dict):
try:
if "_meta" in parsed:
parsed = dict(parsed)
parsed.pop("_meta", None)
except Exception:
pass
try:
keys = sorted(
parsed.keys(), key=lambda x: int(x) if str(x).isdigit() else x
)
except Exception:
keys = list(parsed.keys())
for k in keys:
try:
v = parsed.get(k, {})
# prepare defaults
title = title_raw = "-"
has_fudai = ""
fudai_content = "-"
task_list = button_text = countdown_text = fudai_value = (
participants
) = copies = "-"
if isinstance(v, dict):
title = (v.get("title", "") or "").strip() or "-"
title_raw = (v.get("title_raw", "") or "").strip() or "-"
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (v.get("fudai_content", "") or "").strip() or "-"
fudai_detail = v.get("fudai_detail")
if isinstance(fudai_detail, dict):
task_list = (
str(fudai_detail.get("task_list") or "").strip() or "-"
)
button_text = (
str(fudai_detail.get("button_text") or "").strip() or "-"
)
fudai_time = (
str(fudai_detail.get("time_text") or "").strip() or "-"
)
fudai_value = (
f"{float(fudai_detail.get('prize_value_yuan') or 0):.2f}"
if fudai_detail.get("prize_value_yuan")
else "-"
)
participants = (
str(fudai_detail.get("participants") or 0)
if fudai_detail.get("participants")
else "-"
)
copies = (
str(fudai_detail.get("copies") or 0)
if fudai_detail.get("copies")
else "-"
)
mm = str(fudai_detail.get("countdown_mm") or "").strip()
ss = str(fudai_detail.get("countdown_ss") or "").strip()
if fudai_time and fudai_time != "-":
countdown_text = fudai_time
elif mm or ss:
if mm.isdigit() and len(mm) == 1:
mm = f"0{mm}"
if ss.isdigit() and len(ss) == 1:
ss = f"0{ss}"
if mm and ss:
countdown_text = f"{mm}:{ss}"
else:
countdown_text = mm or ss
elif (
fudai_detail
and isinstance(fudai_detail, (tuple, list))
and len(fudai_detail) >= 5
):
fudai_time = fudai_detail[1] or "-"
fudai_value = (
f"{fudai_detail[4] or 0:.2f}" if fudai_detail[4] else "-"
)
participants = (
str(fudai_detail[2] or 0) if fudai_detail[2] else "-"
)
copies = str(fudai_detail[3] or 0) if fudai_detail[3] else "-"
countdown_text = fudai_time or "-"
else:
fudai_time = "-"
try:
is_reserved = "✓" if int(k) in reservations_data else ""
except Exception:
is_reserved = ""
else:
# v is likely a list/tuple
try:
title = (v[0] or "").strip() or "-"
except Exception:
title = "-"
try:
title_raw = (v[1] or "").strip() or "-"
except Exception:
title_raw = "-"
is_reserved = ""
except Exception:
title = title_raw = "-"
has_fudai = ""
fudai_content = task_list = countdown_text = fudai_value = (
participants
) = copies = button_text = is_reserved = "-"
# timestamp
try:
ts = v.get("timestamp") if isinstance(v, dict) else None
if not ts and isinstance(v, dict):
fd = v.get("fudai_detail")
if isinstance(fd, dict):
ts = fd.get("timestamp")
updated_text = _format_timestamp(ts) if ts else "-"
except Exception:
updated_text = "-"
entry_lines: List[str] = []
entry_lines.append(f"[位置 {k}] {title}")
if show_title_raw:
entry_lines.append(f"原始标题: {title_raw}")
entry_lines.append(f"更新时间: {updated_text}")
entry_lines.append(f"已预约: {is_reserved}")
entry_lines.append(f"有福袋: {has_fudai}")
entry_lines.append(f"价值(元): {fudai_value}")
entry_lines.append(f"参与人数: {participants}")
entry_lines.append(f"份数: {copies}")
entry_lines.append(f"倒计时: {countdown_text}")
entry_lines.append(f"按钮: {button_text}")
entry_lines.append(f"任务列表: {task_list}")
entry_lines.append(f"福袋内容: {fudai_content}")
entries_pool.append("\n".join(entry_lines))
elif isinstance(parsed, (list, tuple)):
for i, v in enumerate(parsed):
entries_pool.append(str(v))
return entries_pool