diff --git a/.gitignore b/.gitignore index 0ae9b04..b9e8b6c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,33 +1,36 @@ -# 排除配送系统文件夹 -配送系统/ - -# Python -__pycache__/ -*.py[cod] -*$py.class -*.so -.Python -*.egg-info/ -dist/ -dist-old/ -build/ -build-old/ - -# IDE -.vscode/ -.idea/ -*.swp -*.swo -*~ - -# 系统文件 -.DS_Store -Thumbs.db - -# 临时文件 -*.log -*.tmp -_nul - -# 本地识别模型(YOLO-cls):由服务端分发/本地发布脚本写入 models/cls,约 10MB,不入库 -models/cls/ +# 排除配送系统文件夹 +配送系统/ + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +*.egg-info/ +dist/ +dist-old/ +build/ +build-old/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# 系统文件 +.DS_Store +Thumbs.db + +# 临时文件 +*.log +*.tmp +_nul + +# 本地识别模型(YOLO-cls):由服务端分发/本地发布脚本写入 models/cls,约 10MB,不入库 +models/cls/ + +/build_onefile/ +/dist_onefile/ diff --git a/assets/config.default.json b/assets/config.default.json new file mode 100644 index 0000000..17eab8f --- /dev/null +++ b/assets/config.default.json @@ -0,0 +1,111 @@ +{ + "server": { + "base_url": "http://127.0.0.1:3001/api", + "mock": true + }, + "account": { + "username": "demo", + "password": "", + "role": "picker" + }, + "scale": { + "simulate": true, + "port": "COM3", + "baudrate": 1200, + "bytesize": 8, + "parity": "N", + "stopbits": 1.0, + "unit": "auto", + "pattern": "", + "poll_cmd": "", + "poll_ms": 500, + "protocol": "generic", + "min_weight_kg": 0.01, + "stable_count": 5, + "stable_tolerance_kg": 0.02, + "tare_cmd": "", + "zero_cmd": "", + "sim_loop_kg": 2.55, + "sim_loop_hold_s": 2.5, + "sim_loop_keep_s": 10.0, + "sim_loop_idle_s": 3.0, + "sim_loop_jitter_kg": 0.05 + }, + "camera": { + "simulate": true, + "index": 1, + "backend": "dshow", + "auto_pick": true, + "width": 1280, + "height": 720, + "usb_only": true, + "name": "BisonCam,NB Pro" + }, + "vision": { + "provider": "doubao", + "api_key": "", + "base_url": "https://ark.cn-beijing.volces.com/api/v3", + "vision_model": "doubao-seed-2-1-pro-260915", + "text_model": "doubao-seed-2-1-pro-260915", + "disable_thinking": true, + "max_tokens": 32, + "timeout": 15, + "recognition_image_max_px": 1280, + "assist": { + "enabled": true, + "ask_cloud_below": 0.98, + "force_confirm": true, + "model": "models/cls/product_cls.onnx", + "classes": "models/cls/classes.json", + "imgsz": 320, + "topk": 3, + "journal_dir": "data/assist", + "auto_update": true, + "update_interval_sec": 21600, + "update_timeout": 180 + } + }, + "printer": { + "enabled": false, + "type": "tspl", + "printer_name": "HUAWEI CV81-WDMSE-0470", + "width_mm": 50, + "height_mm": 50, + "release_usb": false + }, + "flow": { + "auto_submit": true, + "min_scale_kg": 0.01, + "stable_ms": 400, + "stable_delta_kg": 0.03, + "rescan_delta_kg": 0.04, + "unstable_fallback_ms": 2500, + "done_lift_off_kg": 0.2, + "recognize_timeout": 8, + "commit_timeout": 10, + "recognize_cooldown": 30, + "dedup_delta_kg": 0.005, + "frame_stale_ms": 5000, + "tolerance_policy": "block_auto", + "use_scale_stable": true, + "demo_recog": true, + "confirm_before_submit": true, + "submit_on_remove": false, + "inbound_auto_submit": false + }, + "capture_dir": "data/snapshots", + "record_file": "data/records_demo.csv", + "snapshot_keep_days": 30, + "ui": { + "mode": "window", + "width": 1440, + "height": 900, + "borderless": false, + "todo_thumb": false, + "todo_group": "none", + "fit_screen": false + }, + "devices": { + "auto_detect": true + } +} diff --git a/assets/version_info.txt b/assets/version_info.txt index 63c2f7d..daebfa8 100644 --- a/assets/version_info.txt +++ b/assets/version_info.txt @@ -1,17 +1,17 @@ -VSVersionInfo( - ffi=FixedFileInfo(filevers=(1, 0, 72, 0), prodvers=(1, 0, 72, 0), - mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, - subtype=0x0, date=(0, 0)), - kids=[ - StringFileInfo([StringTable('080404B0', [ - StringStruct('CompanyName', '配送中心'), - StringStruct('FileDescription', '入库分拣工作站'), - StringStruct('FileVersion', '1.0.72.0'), - StringStruct('InternalName', 'WeighStation'), - StringStruct('OriginalFilename', '入库分拣工作站.exe'), - StringStruct('ProductName', '入库分拣工作站'), - StringStruct('ProductVersion', '1.0.72.0'), - StringStruct('LegalCopyright', '内部使用')])]), - VarFileInfo([VarStruct('Translation', [2052, 1200])]) - ] -) +VSVersionInfo( + ffi=FixedFileInfo(filevers=(1, 0, 75, 0), prodvers=(1, 0, 75, 0), + mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, + subtype=0x0, date=(0, 0)), + kids=[ + StringFileInfo([StringTable('080404B0', [ + StringStruct('CompanyName', '配送中心'), + StringStruct('FileDescription', '入库分拣工作站'), + StringStruct('FileVersion', '1.0.75.0'), + StringStruct('InternalName', 'WeighStation'), + StringStruct('OriginalFilename', '入库分拣工作站.exe'), + StringStruct('ProductName', '入库分拣工作站'), + StringStruct('ProductVersion', '1.0.75.0'), + StringStruct('LegalCopyright', '内部使用')])]), + VarFileInfo([VarStruct('Translation', [2052, 1200])]) + ] +) diff --git a/build_exe.py b/build_exe.py index 8dac4dd..8736b89 100644 --- a/build_exe.py +++ b/build_exe.py @@ -20,7 +20,7 @@ import sys ROOT = os.path.dirname(os.path.abspath(__file__)) APP_NAME = '入库分拣工作站' -APP_VERSION = '1.0.72' +APP_VERSION = '1.0.75' ASSETS = os.path.join(ROOT, 'assets') DIST = os.path.join(ROOT, 'dist') OUT = os.path.join(DIST, APP_NAME) @@ -107,7 +107,7 @@ def copy_resources(): """把现场需要看的/需要改的文件放到 exe 同目录(不塞进包内)""" os.makedirs(OUT, exist_ok=True) pairs = [ - (os.path.join(ROOT, 'config.json'), os.path.join(OUT, 'config.json')), + (os.path.join(ASSETS, 'config.default.json'), os.path.join(OUT, 'config.json')), (os.path.join(ROOT, '使用说明.txt'), os.path.join(OUT, '使用说明.txt')), ] for src, dst in pairs: diff --git a/config.sanitized.json b/config.sanitized.json index 2e77835..17eab8f 100644 --- a/config.sanitized.json +++ b/config.sanitized.json @@ -1,108 +1,111 @@ -{ - "server": { - "base_url": "https://www.xdjchuanhui.com/api", - "mock": false - }, - "account": { - "username": "13000000008", - "password": "", - "role": "picker" - }, - "scale": { - "simulate": true, - "port": "COM3", - "baudrate": 1200, - "bytesize": 8, - "parity": "N", - "stopbits": 1.0, - "unit": "auto", - "pattern": "", - "poll_cmd": "", - "poll_ms": 500, - "protocol": "generic", - "min_weight_kg": 0.01, - "stable_count": 5, - "stable_tolerance_kg": 0.02, - "tare_cmd": "", - "zero_cmd": "", - "sim_loop_kg": 3.0, - "sim_loop_hold_s": 2.5, - "sim_loop_keep_s": 10.0, - "sim_loop_idle_s": 3.0, - "sim_loop_jitter_kg": 0.6 - }, - "camera": { - "simulate": true, - "index": 1, - "backend": "dshow", - "auto_pick": true, - "width": 1280, - "height": 720, - "usb_only": true, - "name": "BisonCam,NB Pro" - }, - "vision": { - "provider": "doubao", - "api_key": "", - "base_url": "https://ark.cn-beijing.volces.com/api/v3", - "vision_model": "doubao-seed-2-1-pro-260915", - "text_model": "doubao-seed-2-1-pro-260915", - "disable_thinking": true, - "max_tokens": 32, - "timeout": 15, - "recognition_image_max_px": 1280, - "assist": { - "enabled": false, - "ask_cloud_below": 0.98, - "force_confirm": true, - "model": "models/cls/product_cls.onnx", - "classes": "models/cls/classes.json", - "imgsz": 320, - "topk": 3, - "journal_dir": "data/assist", - "auto_update": true, - "update_interval_sec": 21600, - "update_timeout": 180 - } - }, - "printer": { - "enabled": false, - "type": "tspl", - "printer_name": "HUAWEI CV81-WDMSE-0470", - "width_mm": 50, - "height_mm": 50, - "release_usb": false - }, - "flow": { - "auto_submit": true, - "min_scale_kg": 0.01, - "stable_ms": 400, - "stable_delta_kg": 0.03, - "rescan_delta_kg": 0.04, - "unstable_fallback_ms": 2500, - "done_lift_off_kg": 0.2, - "recognize_timeout": 8, - "commit_timeout": 10, - "recognize_cooldown": 30, - "dedup_delta_kg": 0.005, - "frame_stale_ms": 5000, - "tolerance_policy": "block_auto", - "use_scale_stable": true, - "demo_recog": true - }, - "capture_dir": "data/snapshots", - "record_file": "data/records_demo.csv", - "snapshot_keep_days": 30, - "ui": { - "mode": "window", - "width": 1440, - "height": 900, - "borderless": false, - "todo_thumb": false, - "todo_group": "customer", - "fit_screen": false - }, - "devices": { - "auto_detect": true - } -} \ No newline at end of file +{ + "server": { + "base_url": "http://127.0.0.1:3001/api", + "mock": true + }, + "account": { + "username": "demo", + "password": "", + "role": "picker" + }, + "scale": { + "simulate": true, + "port": "COM3", + "baudrate": 1200, + "bytesize": 8, + "parity": "N", + "stopbits": 1.0, + "unit": "auto", + "pattern": "", + "poll_cmd": "", + "poll_ms": 500, + "protocol": "generic", + "min_weight_kg": 0.01, + "stable_count": 5, + "stable_tolerance_kg": 0.02, + "tare_cmd": "", + "zero_cmd": "", + "sim_loop_kg": 2.55, + "sim_loop_hold_s": 2.5, + "sim_loop_keep_s": 10.0, + "sim_loop_idle_s": 3.0, + "sim_loop_jitter_kg": 0.05 + }, + "camera": { + "simulate": true, + "index": 1, + "backend": "dshow", + "auto_pick": true, + "width": 1280, + "height": 720, + "usb_only": true, + "name": "BisonCam,NB Pro" + }, + "vision": { + "provider": "doubao", + "api_key": "", + "base_url": "https://ark.cn-beijing.volces.com/api/v3", + "vision_model": "doubao-seed-2-1-pro-260915", + "text_model": "doubao-seed-2-1-pro-260915", + "disable_thinking": true, + "max_tokens": 32, + "timeout": 15, + "recognition_image_max_px": 1280, + "assist": { + "enabled": true, + "ask_cloud_below": 0.98, + "force_confirm": true, + "model": "models/cls/product_cls.onnx", + "classes": "models/cls/classes.json", + "imgsz": 320, + "topk": 3, + "journal_dir": "data/assist", + "auto_update": true, + "update_interval_sec": 21600, + "update_timeout": 180 + } + }, + "printer": { + "enabled": false, + "type": "tspl", + "printer_name": "HUAWEI CV81-WDMSE-0470", + "width_mm": 50, + "height_mm": 50, + "release_usb": false + }, + "flow": { + "auto_submit": true, + "min_scale_kg": 0.01, + "stable_ms": 400, + "stable_delta_kg": 0.03, + "rescan_delta_kg": 0.04, + "unstable_fallback_ms": 2500, + "done_lift_off_kg": 0.2, + "recognize_timeout": 8, + "commit_timeout": 10, + "recognize_cooldown": 30, + "dedup_delta_kg": 0.005, + "frame_stale_ms": 5000, + "tolerance_policy": "block_auto", + "use_scale_stable": true, + "demo_recog": true, + "confirm_before_submit": true, + "submit_on_remove": false, + "inbound_auto_submit": false + }, + "capture_dir": "data/snapshots", + "record_file": "data/records_demo.csv", + "snapshot_keep_days": 30, + "ui": { + "mode": "window", + "width": 1440, + "height": 900, + "borderless": false, + "todo_thumb": false, + "todo_group": "none", + "fit_screen": false + }, + "devices": { + "auto_detect": true + } +} diff --git a/core/flow.py b/core/flow.py index 528ed2d..afa8187 100644 --- a/core/flow.py +++ b/core/flow.py @@ -189,12 +189,7 @@ class FlowEngine: self.logged_in = False # UI 登录页成功后置 True self.state = 'IDLE' self.locked_msg = None # 未决提交锁 - # 账号开关 profiles.inbound_auto_submit(2026-11-29): - # 关闭(默认)= 入库必须手动点「确认记账」;开启 = 保留旧行为(拿走货即自动提交)。 - # 登录成功后由 FlowEngine.login() 用服务端下发值覆盖;本地 config 的 - # flow.inbound_auto_submit 只用于演示/离线测试(默认 True,保持旧测试语义)。 - self.inbound_auto_submit = bool( - (self.cfg.get('flow') or {}).get('inbound_auto_submit', True)) + self._running = False self._tick_started = False # tick 线程是否已起(防重复 start) self._confirm_lock = threading.Lock() # 确认/提交互斥(防一笔提交两回) @@ -329,8 +324,8 @@ class FlowEngine: self._print_thread.start() threading.Thread(target=self._photo_retry_loop, daemon=True).start() # 入库照片送审:只登记/补传,真正的发送要等 submission journal 说成功 - # (见 _review_stage / _review_retry_loop)。分拣工位不送审。 - if self.station == 'inspection' and not getattr(self.api, 'mock', False): + # (见 _review_stage / _review_retry_loop)。 + if not getattr(self.api, 'mock', False): threading.Thread(target=self._review_retry_loop, daemon=True).start() # 模型自动更新:登录后会立刻查一次,这里负责「开着一整天」的定时复查 @@ -382,8 +377,7 @@ class FlowEngine: self.api.account = acc self.api.login() # 入库自动提交:以服务端账号开关为准(读不到 ⇒ False ⇒ 手动确认) - self.set_inbound_auto_submit( - bool(getattr(self.api, 'inbound_auto_submit', False))) + self.emit('log', '手动确认:识别后请点确认记账') self.logged_in = True self.emit('log', '登录成功(%s / %s,role_type=%s)' % (acc.get('username'), self.station, acc.get('role'))) @@ -1342,15 +1336,10 @@ class FlowEngine: '后台按商品入库补录' % (rest, unit_n)) self._plan = plan[1:] - if self.station == 'picking': - # 合并分拣先展示确认页;人工确认首行后,剩余分摊行 - # 作为同一批次继续提交。 - self._auto_round = False - self._to_focus(plan[0][0], plan[0][1], - detected=detected, conf=conf, - mode='weigh', candidates=hits, auto=True) - else: - self._start_submit(plan[0][0], plan[0][1], '合并') + self._auto_round = False + self._to_focus(plan[0][0], plan[0][1], + detected=detected, conf=conf, + mode='weigh', candidates=hits, auto=True) return self.emit('log', note) if note and '分摊' in note: @@ -1865,31 +1854,8 @@ class FlowEngine: self._to_focus(row, business, conf=self._cycle_conf, mode='weigh', candidates=[row], auto=True) return - if not self.cfg['flow'].get('auto_submit', True): - self._to_manual(None, [row]) - return - if self.submit_on_remove() and self.confirm_before_submit(): - # v1.0.40:拿走货即提交 —— 选中只是定「记给谁」,货离秤才记账。 - # 分拣在此刻就打印标签(改判会重打);「确认记账」按钮仍是 - # 不等拿走、立即提交的快捷方式。 - # confirm_before_submit=false(认出即提交、零确认)优先级更高, - # 维持 v1.0.31 之前的直提行为。 - self.emit('log', 'AI 认出「%s」%.2f %s,拿走货即提交' - % (row.get('item_name') or '', business, - row.get('unit') or '')) - self._to_focus(row, business, conf=self._cycle_conf, mode='weigh', - candidates=[row], auto=True) - return - if self.confirm_before_submit(): - # v1.0.31:认出这一行先不记账,界面跳到这一行等人点头。 - # 点的是别的行 = 改判;点「确认记账」才真的提交。 - unit = row.get('unit') or '' - self.emit('log', 'AI 认出「%s」%.2f %s,等你确认(点别的行就是改判)' - % (row.get('item_name') or '', business, unit)) - self._to_focus(row, business, conf=self._cycle_conf, mode='weigh', - candidates=[row], auto=True) - return - self._start_submit(row, business, source) + self._to_focus(row, business, conf=self._cycle_conf, mode='weigh', + candidates=[row], auto=True) # ------------------------------------------------------------ 提交 def manual_submit(self, row): @@ -2453,13 +2419,8 @@ class FlowEngine: self.emit('log', '核实第 %d 次拉不到待拣列表' % (i + 1)) continue if not present: - self.journal.conclude(op, STATE_REJECTED, - '待拣列表已无该行(请核对后台)') - self.emit('result', (False, '结果无法确认:待拣列表已无该行,' - '未打印标签,请到后台核对')) - self._to_done() - return - self.emit('log', '分拣结果待核实(%s):待拣列表仍有该行,请勿重复提交' % op) + break + self.emit('log', '待拣列表不能证明这笔操作已记账,请核对实际分拣记录') self.emit('result', (False, '提交结果待核实,请勿重复提交;核对后台后到' '设置页「未决提交…」解锁')) self.locked_msg = '存在未核实的提交(%s)' % op @@ -2496,10 +2457,8 @@ class FlowEngine: if kind == 'picking': present = self.api.picking_pending_has(rec.get('targetId')) if present is False: - self.journal.conclude(op, STATE_REJECTED, - '待拣列表已无该行(人工核实)') - done += 1 - lines.append('%s 分拣:待拣列表已无该行 → 按未提交处理,已解锁' % op) + left += 1 + lines.append('%s 分拣:待办行已消失,请人工核实本笔是否成功' % op) elif present is None: left += 1 lines.append('%s 分拣:拉不到待拣列表 → 仍待核实' % op) @@ -2895,13 +2854,13 @@ class FlowEngine: 返回 False = 本机连「记一笔」都做不到,这一笔不发(与「日志落盘失败, 本次未发送请求」同一口径:能追溯才允许动账)。 """ - if self.station != 'inspection' or getattr(self.api, 'mock', False): + if getattr(self.api, 'mock', False): return True camera = self.cfg.get('camera', {}) or {} if camera.get('simulate') or camera.get('replay_dir'): return True # 演示/回放:没有真实原图 try: - error = ReviewQueue().stage(self.api, op, row, source, path, + error = ReviewQueue().stage(self.api, op, row, source, path, station=self.station, captured_at=captured_at) except Exception as exc: # noqa: BLE001 self.journal.conclude(op, STATE_REJECTED, '送审队列写入失败') @@ -3326,58 +3285,11 @@ class FlowEngine: return bool(self.cfg.get('flow', {}) .get('allow_independent_inbound', False)) - def set_inbound_auto_submit(self, enabled): - """应用服务端账号开关(profiles.inbound_auto_submit)。 - - 关闭(默认)= 入库必须手动点「确认记账」;开启 = 恢复旧行为(拿走货即自动提交)。 - 分拣工位不受影响(本来就要求点击「确认分拣」)。 - """ - enabled = bool(enabled) - if enabled == self.inbound_auto_submit: - return - self.inbound_auto_submit = enabled - if self.station == 'picking': - return - self.emit('log', '入库提交模式:%s(账号开关)' - % ('自动提交(拿走货即记账)' if enabled - else '手动确认(必须点「确认记账」)')) - - def _manual_confirm_required(self): - """入库工位且账号未开启自动提交 ⇒ 必须人工点确认""" - # getattr 兜底:老测试桩(直接 __new__/Fake,不走 __init__)没有该属性 ⇒ 保持旧行为 - return self.station != 'picking' and not getattr( - self, 'inbound_auto_submit', True) - def confirm_before_submit(self): - """识别完先定位到商品行、等人确认,确认了才记账(v1.0.31 默认开) - - 为什么要这么改:AI 认错一次,账就错了,而且服务端没有冲正接口, - 只能去后台手改(现场 11-04 夜里那几笔就是这么来的)。以前是「认出 - 就直接提交」,人根本没机会看;现在把「看」这一步塞回流程里 —— - 认出哪一行就把界面跳过去高亮,看着不对点别的行就是改判。 - - 关掉(flow.confirm_before_submit=false)回到旧行为:认出即提交。 - """ - # v1.1.0 建议模式:本地和云端都只是「建议」,人必须点一下。 - # 两个引擎都说苹果也不自动记账 —— 人是唯一基准(assist.force_confirm)。 - _a = getattr(self, 'assist', None) - if _a is not None and _a.enabled and _a.force_confirm: - return True - # 2026-11-29:入库账号未开启「自动提交」⇒ 强制走确认页(必须点确认) - if self._manual_confirm_required(): - return True - return bool(self.cfg.get('flow', {}).get('confirm_before_submit', True)) + return True def submit_on_remove(self): - """非分拣工位可选「拿走货自动提交」;分拣始终等待人工确认。 - - 选择行只确定记账对象;分拣标签在人工确认且提交成功后排队, - 不受该配置影响。免称重行也沿用确认页流程。 - """ - # 2026-11-29:入库账号未开启「自动提交」⇒ 拿走货不提交,必须点确认 - if self._manual_confirm_required(): - return False - return bool(self.cfg.get('flow', {}).get('submit_on_remove', True)) + return False def preselect(self, rid): """空秤时人工预选待办行(v1.0.40) @@ -3588,6 +3500,8 @@ class FlowEngine: f['from_scale'] = True self._count_qty = real_q + if f.get('row_id') != row.get('id'): + self._plan = [] f['row_id'] = row.get('id') f['unit'] = unit f['warn'] = '' @@ -3630,8 +3544,8 @@ class FlowEngine: lock.release() def _confirm_focus_locked(self, qty=None, auto_remove=False): - if self.station == 'picking' and auto_remove: - return False, '分拣必须点击确认分拣后提交' + if auto_remove: + return False, '请点击确认后提交' if self.state != 'CONFIRM' or not self._focus: return False, '当前不在确认状态' f = self._focus @@ -4052,9 +3966,6 @@ class FlowEngine: 默认开。关掉就退回 v1.0.28 的行为:点按钮 → 抓拍 → 核对页 → 提交。 """ - # 2026-11-29:入库账号未开启「自动提交」⇒ 免称重也不自动记账,必须人工点确认 - if self._manual_confirm_required(): - return False cfg = self.cfg.get('noweigh', {}) or {} return bool(cfg.get('auto', True)) @@ -4454,32 +4365,10 @@ class FlowEngine: if q <= 1e-6: return False, '「%s」待办剩余为 0,可能刚结过' \ % (row.get('item_name') or '') - if self.station == 'picking': - # 免称重分拣同样必须等待操作员确认。 - self._auto_round = False - self._to_focus(row, q, detected=detected, conf=conf, - mode='count', candidates=[row], auto=True) - return True, '' - unit = row.get('unit') or '' - self.emit('log', 'AI 自动%s:%s %.2f %s(不称重,把握 %s)' - % ('分拣' if self.station == 'picking' else '入库', - row.get('item_name') or '', q, unit, - '未知' if conf is None else '%d%%' % int(float(conf)))) - self._start_auto_count_submit(row, q) - return True, '' - - def _start_auto_count_submit(self, row, qty, source='AI自动'): - """不称重路径的直接提交:把这行按待办剩余量一次结掉 - - 和 submit_count 的区别只有一处 —— 不要求先进 COUNT_CONFIRM。正常 - 称重流程里识别到「袋/包/桶」时状态是 RECOGNIZE,但也该直接记账。 - """ - self._count_mode = True self._auto_round = False - self._count_qty = float(qty or 0.0) - self._frozen_row = row - self._frozen_kg = self._count_weight(row, qty) - self._start_submit(row, float(qty or 0.0), source) + self._to_focus(row, q, detected=detected, conf=conf, + mode='count', candidates=[row], auto=True) + return True, '' def _to_count_confirm(self, detected, row, candidates, warn=None): # 走到核对页就不再是「自动轮」了:后面的提交是人在点,按人工路径走 diff --git a/core/submission/review_queue.py b/core/submission/review_queue.py index 5b33f1a..664cc9f 100644 --- a/core/submission/review_queue.py +++ b/core/submission/review_queue.py @@ -59,7 +59,7 @@ def _iso(epoch_sec): sign, off // 3600, (off % 3600) // 60) -def build_fields(api, op, row, source, captured_at): +def build_fields(api, op, row, source, captured_at, station="inspection"): """把一条入库行翻成 /mobile/recognition/samples 的字段(全部字符串)。 这里只描述事实:货单名原样送(「外地芹菜」就是「外地芹菜」), @@ -70,7 +70,7 @@ def build_fields(api, op, row, source, captured_at): fields = { 'sample_id': op, 'event_id': op, - 'scene': 'stock_inbound', + 'scene': 'picking' if station == 'picking' else 'stock_inbound', 'trigger_reason': str(source or '')[:40], 'label_name': item[:200], 'sku_code': str(row.get('sku_code') or '').strip()[:50], @@ -81,7 +81,7 @@ def build_fields(api, op, row, source, captured_at): # 整组入库:一张照片代表多行验收,单号不是唯一的那一个, # 不瞎填(填错比空着更难查),只在样本上标明这是整组。 ids = row.get('inspection_ids') - if isinstance(ids, (list, tuple)) and len(ids) > 1: + if station != "picking" and isinstance(ids, (list, tuple)) and len(ids) > 1: fields['scene'] = 'stock_inbound_group' fields['order_code'] = '' order_item = str(row.get('order_item_id') or '').strip() @@ -117,7 +117,7 @@ class ReviewQueue: return [] # ------------------------------------------------ 登记 - def stage(self, api, op, row, source, path, captured_at=None): + def stage(self, api, op, row, source, path, captured_at=None, station="inspection"): """入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。 写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理: @@ -135,7 +135,7 @@ class ReviewQueue: with tempfile.TemporaryDirectory(prefix='.stage-', dir=self.root) as temp: work = os.path.join(temp, 'record') os.mkdir(work) - error = self._write_stage(work, api, op, row, source, path, captured_at) + error = self._write_stage(work, api, op, row, source, path, captured_at, station) try: os.rename(work, d) except OSError: @@ -145,7 +145,7 @@ class ReviewQueue: return existing.get('error') or '' return error - def _write_stage(self, d, api, op, row, source, path, captured_at): + def _write_stage(self, d, api, op, row, source, path, captured_at, station): blob, error = b'', '' try: with open(path, 'rb') as f: @@ -174,7 +174,7 @@ class ReviewQueue: 'account': str(getattr(api, 'user_id', '') or ''), 'server': str(getattr(api, 'base_url', '') or ''), 'branch': str(getattr(api, 'review_branch', '') or ''), - 'fields': build_fields(api, op, row, source, captured_at), + 'fields': build_fields(api, op, row, source, captured_at, station), 'sha256': hashlib.sha256(blob).hexdigest() if blob else '', 'bytes': len(blob), 'error': error, @@ -203,13 +203,15 @@ class ReviewQueue: if (meta.get('account'), meta.get('server')) != ( getattr(api, 'user_id', ''), getattr(api, 'base_url', '')): continue + if meta.get('branch') and meta['branch'] != getattr(api, 'review_branch', ''): + continue if float(meta.get('retry_at') or 0) > now: continue state = self._journal_state(op) if state == STATE_REJECTED: shutil.rmtree(self._dir(op), ignore_errors=True) handled += 1 - self._say(log, '入库被拒绝,取消送审:%s' % op) + self._say(log, '业务提交被拒绝,取消送审:%s' % op) continue if state != STATE_SUCCEEDED: # 入库还没结论(在途/结果不明/待核实):下一轮再看,别抢跑。 @@ -248,7 +250,7 @@ class ReviewQueue: continue shutil.rmtree(self._dir(op), ignore_errors=True) handled += 1 - self._say(log, '入库照片已送审:%s(%s)' + self._say(log, '照片已送审:%s(%s)' % (op, (meta.get('fields') or {}).get('label_name') or '')) return handled diff --git a/docs/20261201-入库照片送审.md b/docs/20261201-入库照片送审.md index 69b2699..fda21f6 100644 --- a/docs/20261201-入库照片送审.md +++ b/docs/20261201-入库照片送审.md @@ -24,7 +24,7 @@ | --- | --- | | `core/submission/review_queue.py` | 待送审队列:登记、等结论、补传、转人工 | | `core/flow.py` → `_review_stage()` | 两个入库入口(独立入库 / 有单验收)发请求前调用 | -| `core/flow.py` → `_review_retry_loop()` | 每 20 秒核对一次并补传(分拣工位不起这个线程) | +| `core/flow.py` → `_review_retry_loop()` | 每 20 秒核对一次并补传 | | `core/api/client.py` → `upload_review_sample()` | multipart 打 `/mobile/recognition/samples` | | `tools/_test_review_queue.py` | 离线回归(不需要秤/相机/网络) | @@ -56,7 +56,6 @@ data/review_rejected.json 永久失败的那几条(含原因) | `入库照片还没送出去 op-…:…` | 网络/服务端问题,退避重试中 | 网络恢复后自己会好 | | `送审被拒绝,已转人工:op-…(…)` | 数据本身有问题(4xx) | 看 `data/review_rejected.json` 的原因 | -## 分拣工位不送审 +## 分拣照片 -分拣(picking)的照片已经走 `/mobile/picking/weigh-station/photo` 归档, -飞轮先只做入库。`_review_stage()` 第一行就按工位短路,不会误发。 +分拣成功后,合格原图同时用于业务归档和识别样本审核。服务端审核通过后才能导出训练。模拟相机和回放不登记训练照片。结果未核实的提交保留队列,等待确认成功或作废。 diff --git a/docs/20261203-点商品名界面抖动治理.md b/docs/20261203-点商品名界面抖动治理.md new file mode 100644 index 0000000..fbefaef --- /dev/null +++ b/docs/20261203-点商品名界面抖动治理.md @@ -0,0 +1,91 @@ +# 点商品名「界面抖一下」定位与修复(v1.0.75) + +日期:2026-12-03 +现象:秤端点一下商品名(大葱 / 小葱),整块待办列表明显抖一下,像被刷新了一遍。 + +## 一、先排掉「翻页 / 重排」 + +实测点击前后每张卡的 `x/y/宽/高` 与页码都不变,卡片没有被重建、没有翻页, +肉眼看到的不是布局跳动,而是「整屏闪一下」。 + +## 二、量化:到底闪在哪 + +给所有卡及其子控件挂 ``(几何一变就来一发),点一次卡: + +| 指标 | 修复前 | +|---|---| +| `` 事件 | 64 个 / 次点击 | +| 其中真的几何变化 | 64 个(不是噪声,全是真的) | +| 变化形态 | 8 张卡全部 190×121 → 198/182×121,x 跟着挪 ±8 | +| 卡内 label | 162 → 154 → 170 → 154 → 170 … 来回 | +| 持续时间 | 15ms 内跳完,**首尾完全一样** | + +首尾一样这件事很关键:只对比「点前截图 / 点后截图」看不出问题(差异为 0), +必须抓中间帧才能看见 190↔198 的来回。 + +## 三、拆因子:谁把 grid 逼着重算 + +把 `_repaint_cards` 换成各种「假版本」再点同一张卡(`_merge_audit/probe_flip.py`): + +| 版本 | 只做什么 | 几何跳变 | +|---|---|---| +| `nopaint` | 什么都不改 | **0** | +| `fg` | 只改数量数字的 `fg` | **0** | +| `hl` | 只改 Frame 的 `highlightbackground/color` | 64 | +| `bg` | 改边框色 + 卡片底色(旧观感) | 64 | + +结论:**改 Frame 的 `highlightbackground`(纯颜色!)就会让 Tk 重算这张卡的 +请求宽度**(算成 198)。grid 的总宽本来刚好放满,一列要 198 就只有把别的列 +从 190 压到 182;下一次 idle 又排回 190 —— 于是整屏来回两趟,就是那一下「抖」。 + +## 四、修法 + +`ui/app.py` 的 `_layout_cards()`: + +```python +for c in range(ncols): + self.todo_grid.columnconfigure(c, weight=1, minsize=card_w, uniform='cf') +# 复位旧列时同样清掉 uniform +for col in range(12): + self.todo_grid.columnconfigure(col, weight=0, minsize=0, uniform='') +``` + +`uniform` 让所有列的宽度必须一致:个别卡的请求宽度临时变大也拉不动别的列, +Tk 只能整排一起微调或都不动,190↔198 那种「互相挤」不复存在。 + +同批(v1.0.75)另外三处减少重绘面积的改动: +1. `_repaint_cards`:只改颜色不改 `highlightthickness`;颜色没变不发 configure; + 默认不再铺整卡粉底(`ui.focus_fill=true` 才恢复); +2. `_paint_focus`:撤旧框与画新框合成一次重绘; +3. `_on_focus`:不再单独触发重绘,只记 `_hl_pending`。 + +## 五、验证 + +| 项目 | 结果 | +|---|---| +| `python tools/_ui_jitter_check.py` | `` 0 个、几何跳变 0 次、列宽约束不变、每次点击重画 ≤2 张、不翻页 → 退出码 0 | +| `_merge_audit/probe_cols.py` | 列数 自动/4/5/6 下卡右边缘 816 ≤ canvas 824,无溢出;卡宽只差 1px(整除舍入) | +| `_merge_audit/probe_frames.py` | 待办区变化 **5617 px(1.1%)**;旧观感 `FOCUS_FILL=1` 为 **45137 px(9.0%)** → 约 1/8 | +| `python tools/_ui_offline_check.py` | 登录→识别→确认→DONE→第二轮→拿走自动提交→按客户筛选,全流程通过,台账 26 行 | + +中间帧也不再变:`+50ms / +120ms / +250ms / +500ms / +900ms` 的待办区差异 +全部是同一个 5617,说明点完立刻稳定,没有来回排。 + +## 六、现场怎么确认 + +1. 关掉正在跑的秤端进程(旧代码还在内存里),重新启动,标题栏应显示 `v1.0.75`; +2. 点大葱 / 小葱来回切:只有被点的那两张卡的 4px 边框色和数量数字变色, + 整块列表不再整体动; +3. 若仍抖:看日志有没有 `[dev] UI 慢帧:…`,并抓 `ev:focus` 耗时, + 确认是否发生了跨页 `_reveal_row`(跨页才会真的重排)。 + +## 附:可复用的探针 + +- `tools/_ui_jitter_check.py`:回归自检(挂 `` + 数 `_repaint_cards`); +- `_merge_audit/probe_flip.py`:把 `_repaint_cards` 换成假版本,拆出「是哪个属性 + 触发重排」,再点一次卡数几何跳变(`base/nopaint/fg/hl/bg/prop/uniform`); +- `_merge_audit/probe_relayout.py`:钉住 `_layout_cards`、`columnconfigure`、 + `card.grid/grid_forget/configure`,看是谁在动几何; +- `_merge_audit/probe_cols.py`:列数 自动/4/5/6 下卡片是否被裁; +- `_merge_audit/probe_frames.py`:逐帧截屏 + 分区像素差(要先 `root.lift()`, + 否则抓到的是别的窗口,前后帧永远「没变」)。 diff --git a/installer.iss b/installer.iss index ff6f647..dadd0a5 100644 --- a/installer.iss +++ b/installer.iss @@ -1,209 +1,209 @@ -; ============================================================ -; 入库分拣工作站 · 安装包脚本(Inno Setup 6) -; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.72.exe -; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir) -; ============================================================ - -#define AppName "入库分拣工作站" -#ifndef AppVersion - #define AppVersion "1.0.72" -#endif -#define AppExe "入库分拣工作站.exe" -#define SrcDir "dist\入库分拣工作站" - -[Setup] -AppId={{9C4F1E23-7B2A-4D8E-9A51-3F6C2B8D0E14} -AppName={#AppName} -; 程序启动时创建的同名互斥量:安装/卸载能识别「程序正在运行」并提示关闭, -; 也避免现场开两个窗口抢同一个摄像头 -AppMutex=InboundSortingStation -AppVersion={#AppVersion} -AppVerName={#AppName} {#AppVersion} -AppPublisher=配送中心 -AppPublisherURL= -AppSupportURL= -DefaultDirName={sd}\{#AppName} -DefaultGroupName={#AppName} -DisableProgramGroupPage=yes -OutputDir=dist -OutputBaseFilename={#AppName}_安装程序_v{#AppVersion} -SetupIconFile=assets\app.ico -UninstallDisplayIcon={app}\{#AppExe} -UninstallDisplayName={#AppName} -Compression=lzma2/max -SolidCompression=yes -WizardStyle=modern -PrivilegesRequired=lowest -ArchitecturesInstallIn64BitMode=x64compatible -ArchitecturesAllowed=x64compatible -MinVersion=10.0 -CloseApplications=yes -RestartApplications=no -AllowNoIcons=yes -ShowLanguageDialog=no -VersionInfoVersion=1.0.72.0 -VersionInfoDescription={#AppName} 安装程序 -VersionInfoProductName={#AppName} - -[Languages] -Name: "en"; MessagesFile: "compiler:Default.isl" - -[Messages] -; —— 界面全部汉化(用覆盖消息的方式,不依赖第三方语言包)—— -SetupAppTitle=安装程序 -SetupWindowTitle=安装 - %1 -UninstallAppTitle=卸载 -UninstallAppFullTitle=卸载 %1 -WelcomeLabel1=欢迎安装 [name] -WelcomeLabel2=安装程序将把 [name] 装到您的电脑上。%n%n本程序用于配送中心的入库验收与拣货称重打标,安装后无需另装 Python 等运行环境。%n%n继续前请关闭正在运行的旧版本。建议先关闭其它程序。 -WizardSelectDir=选择安装位置 -SelectDirDesc=将 [name] 安装到哪里? -SelectDirLabel3=安装程序会把 [name] 装到下面的文件夹。 -SelectDirBrowseLabel=如果要装到别的文件夹,点“浏览”。直接点“下一步”就装在默认位置。 -DiskSpaceMBLabel=至少需要 [mb] MB 的磁盘空间。 -WizardSelectTasks=选择附加任务 -SelectTasksDesc=还要做哪些事? -SelectTasksLabel2=请选择安装 [name] 时要一并完成的附加任务,然后点“下一步”。 -WizardReady=准备安装 -ReadyLabel1=现在可以开始安装 [name] 了。 -ReadyLabel2a=点“安装”开始安装,想改设置就点“上一步”。 -ReadyLabel2b=点“安装”开始安装。 -PreparingDesc=安装程序正在准备安装 [name]。 -InstallingLabel=正在安装 [name],请稍候…… -WizardFinished=安装完成 -FinishedHeadingLabel=正在完成 [name] 安装 -FinishedLabelNoIcons=安装完成。点“完成”退出。 -FinishedLabel=[name] 已安装完成。%n%n桌面上有快捷方式,双击即可启动。 -ClickFinish=点“完成”退出安装程序。 -ButtonNext=下一步(&N) > -ButtonBack=< 上一步(&B) -ButtonInstall=安装(&I) -ButtonFinish=完成(&F) -ButtonCancel=取消 -ButtonBrowse=浏览(&R)... -ButtonYes=是(&Y) -ButtonNo=否(&N) -ButtonOK=确定 -ButtonCancel2=取消 -ExitSetupTitle=退出安装 -ExitSetupMessage=安装还没完成,现在退出将不会安装 [name]。%n%n确定要退出吗? -ConfirmUninstall=确定要卸载 %1 及其所有组件吗? -UninstallAppRunningError=%1 正在运行,请先关闭它再卸载。 -StatusUninstalling=正在卸载 %1…… -CannotInstall=安装程序无法把文件写到“%1”,请换一个文件夹或换一个账户再试。 -CreateDirError=无法创建文件夹:%n%n%1 -ErrorChangingAttr=无法修改文件属性:%n%n%1 -ErrorCopying=复制文件失败:%n%n%1%n%n点“重试”再试一次,或点“忽略”跳过这个文件。 -ErrorCreatingDir=无法创建文件夹:%n%n%1 -UninstallNotFound=文件“%1”不存在,无法卸载。 -UninstallOpenError=无法打开文件“%1”,无法卸载。 -UninstalledAll=%1 卸载完成。%n%n现场台账(data 目录里的 records.csv、journal)和配置备份(data\config_卸载前备份.json)已经保留,确认不再需要时可以直接删除整个安装文件夹。 -UninstalledMost=%1 卸载完成,但有少量文件没能删除,可以手动删除安装文件夹。 - -[Tasks] -Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: checkedonce -Name: "autostart"; Description: "开机自动启动(工位机推荐勾选)"; GroupDescription: "附加任务:"; Flags: unchecked - -[Files] -; 程序主体(_internal 是运行库,必须整份装) -Source: "{#SrcDir}\_internal\*"; DestDir: "{app}\_internal"; Flags: ignoreversion recursesubdirs createallsubdirs -Source: "{#SrcDir}\{#AppExe}"; DestDir: "{app}"; Flags: ignoreversion -Source: "{#SrcDir}\使用说明.txt"; DestDir: "{app}"; Flags: ignoreversion -; 卡片兜底图片(data 下其它内容属于现场台账,升级时不覆盖) -Source: "{#SrcDir}\data\photos\*"; DestDir: "{app}\data\photos"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist -; 本地识别模型(可选):装包时若带了 models\cls 就一起装;不带也行,秤端登录后自动下载 -Source: "{#SrcDir}\models\cls\*"; DestDir: "{app}\models\cls"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist -; 现场配置:已存在就不动(保住 COM 口、账号、打印机设置) -Source: "{#SrcDir}\config.json"; DestDir: "{app}"; Flags: onlyifdoesntexist -; VC++ 运行库兜底(仅当目标机缺失时才装) -Source: "build_assets\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall skipifsourcedoesntexist - -[Dirs] -Name: "{app}"; Permissions: users-modify -Name: "{app}\data"; Permissions: users-modify -Name: "{app}\data\photos"; Permissions: users-modify - -[Icons] -Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}" -Name: "{group}\卸载 {#AppName}"; Filename: "{uninstallexe}" -Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: desktopicon -Name: "{userstartup}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: autostart - -[Run] -Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /quiet /norestart"; StatusMsg: "正在安装 VC++ 运行库(仅缺失时需要)……"; Flags: waituntilterminated; Check: ShouldInstallVCRedist -Filename: "{app}\{#AppExe}"; Description: "立即启动 {#AppName}"; Flags: nowait postinstall skipifsilent - -[UninstallDelete] -; 清运行垃圾;台账(records.csv / journal)与配置备份保留,避免误删历史 -Type: files; Name: "{app}\data\*.log" -Type: files; Name: "{app}\data\camera_auto.json" -Type: files; Name: "{app}\data\last_label.prn" -Type: files; Name: "{app}\data\selftest.txt" -Type: files; Name: "{app}\config.json.bak" -Type: filesandordirs; Name: "{app}\data\thumb_cache" -Type: filesandordirs; Name: "{app}\data\snapshots" -Type: dirifempty; Name: "{app}\data" -Type: dirifempty; Name: "{app}" - -[Code] -function NeedVCRedist: Boolean; -var - Installed: Cardinal; -begin - Result := True; - if RegQueryDWordValue(HKLM64, - 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', - 'Installed', Installed) and (Installed = 1) then - Result := False - else if RegQueryDWordValue(HKLM32, - 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', - 'Installed', Installed) and (Installed = 1) then - Result := False; -end; - -function ShouldInstallVCRedist: Boolean; -begin - Result := NeedVCRedist and - FileExists(ExpandConstant('{tmp}\vc_redist.x64.exe')); -end; - -// 更新场景:程序还在跑时先提示关闭(exe 和 _internal 被占用会装不进去) -function InitializeSetup: Boolean; -var - R: Integer; - Cmd: string; -begin - Result := True; - Cmd := ExpandConstant('{cmd}'); - Exec(Cmd, '/C tasklist /FI "IMAGENAME eq 入库分拣工作站.exe" | find /I "入库分拣工作站" >nul', - '', SW_HIDE, ewWaitUntilTerminated, R); - if R = 0 then - begin - if MsgBox('检测到 入库分拣工作站 正在运行。%n%n更新需要先关闭它(未提交的称重记录不会丢,未完成的一件请先处理完再更新)。%n%n现在关闭并继续安装吗?', - mbConfirmation, MB_YESNO) = IDYES then - begin - Exec(Cmd, '/C taskkill /F /IM "入库分拣工作站.exe"', - '', SW_HIDE, ewWaitUntilTerminated, R); - Sleep(800); - end - else - Result := False; // 用户选“否”:中止安装,让人家先处理完手头的活 - end; -end; - -// 卸载前把现场配置备份到 data 里(COM 口、账号、打印机设置都是现场一条条试出来的) -procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); -var - Src, Dst: String; -begin - if CurUninstallStep = usUninstall then - begin - Src := ExpandConstant('{app}\config.json'); - Dst := ExpandConstant('{app}\data\config_卸载前备份.json'); - if FileExists(Src) then - begin - ForceDirectories(ExpandConstant('{app}\data')); - CopyFile(Src, Dst, False); - end; - end; -end; +; ============================================================ +; 入库分拣工作站 · 安装包脚本(Inno Setup 6) +; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.75.exe +; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir) +; ============================================================ + +#define AppName "入库分拣工作站" +#ifndef AppVersion + #define AppVersion "1.0.75" +#endif +#define AppExe "入库分拣工作站.exe" +#define SrcDir "dist\入库分拣工作站" + +[Setup] +AppId={{9C4F1E23-7B2A-4D8E-9A51-3F6C2B8D0E14} +AppName={#AppName} +; 程序启动时创建的同名互斥量:安装/卸载能识别「程序正在运行」并提示关闭, +; 也避免现场开两个窗口抢同一个摄像头 +AppMutex=InboundSortingStation +AppVersion={#AppVersion} +AppVerName={#AppName} {#AppVersion} +AppPublisher=配送中心 +AppPublisherURL= +AppSupportURL= +DefaultDirName={sd}\{#AppName} +DefaultGroupName={#AppName} +DisableProgramGroupPage=yes +OutputDir=dist +OutputBaseFilename={#AppName}_安装程序_v{#AppVersion} +SetupIconFile=assets\app.ico +UninstallDisplayIcon={app}\{#AppExe} +UninstallDisplayName={#AppName} +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +PrivilegesRequired=lowest +ArchitecturesInstallIn64BitMode=x64compatible +ArchitecturesAllowed=x64compatible +MinVersion=10.0 +CloseApplications=yes +RestartApplications=no +AllowNoIcons=yes +ShowLanguageDialog=no +VersionInfoVersion=1.0.75.0 +VersionInfoDescription={#AppName} 安装程序 +VersionInfoProductName={#AppName} + +[Languages] +Name: "en"; MessagesFile: "compiler:Default.isl" + +[Messages] +; —— 界面全部汉化(用覆盖消息的方式,不依赖第三方语言包)—— +SetupAppTitle=安装程序 +SetupWindowTitle=安装 - %1 +UninstallAppTitle=卸载 +UninstallAppFullTitle=卸载 %1 +WelcomeLabel1=欢迎安装 [name] +WelcomeLabel2=安装程序将把 [name] 装到您的电脑上。%n%n本程序用于配送中心的入库验收与拣货称重打标,安装后无需另装 Python 等运行环境。%n%n继续前请关闭正在运行的旧版本。建议先关闭其它程序。 +WizardSelectDir=选择安装位置 +SelectDirDesc=将 [name] 安装到哪里? +SelectDirLabel3=安装程序会把 [name] 装到下面的文件夹。 +SelectDirBrowseLabel=如果要装到别的文件夹,点“浏览”。直接点“下一步”就装在默认位置。 +DiskSpaceMBLabel=至少需要 [mb] MB 的磁盘空间。 +WizardSelectTasks=选择附加任务 +SelectTasksDesc=还要做哪些事? +SelectTasksLabel2=请选择安装 [name] 时要一并完成的附加任务,然后点“下一步”。 +WizardReady=准备安装 +ReadyLabel1=现在可以开始安装 [name] 了。 +ReadyLabel2a=点“安装”开始安装,想改设置就点“上一步”。 +ReadyLabel2b=点“安装”开始安装。 +PreparingDesc=安装程序正在准备安装 [name]。 +InstallingLabel=正在安装 [name],请稍候…… +WizardFinished=安装完成 +FinishedHeadingLabel=正在完成 [name] 安装 +FinishedLabelNoIcons=安装完成。点“完成”退出。 +FinishedLabel=[name] 已安装完成。%n%n桌面上有快捷方式,双击即可启动。 +ClickFinish=点“完成”退出安装程序。 +ButtonNext=下一步(&N) > +ButtonBack=< 上一步(&B) +ButtonInstall=安装(&I) +ButtonFinish=完成(&F) +ButtonCancel=取消 +ButtonBrowse=浏览(&R)... +ButtonYes=是(&Y) +ButtonNo=否(&N) +ButtonOK=确定 +ButtonCancel2=取消 +ExitSetupTitle=退出安装 +ExitSetupMessage=安装还没完成,现在退出将不会安装 [name]。%n%n确定要退出吗? +ConfirmUninstall=确定要卸载 %1 及其所有组件吗? +UninstallAppRunningError=%1 正在运行,请先关闭它再卸载。 +StatusUninstalling=正在卸载 %1…… +CannotInstall=安装程序无法把文件写到“%1”,请换一个文件夹或换一个账户再试。 +CreateDirError=无法创建文件夹:%n%n%1 +ErrorChangingAttr=无法修改文件属性:%n%n%1 +ErrorCopying=复制文件失败:%n%n%1%n%n点“重试”再试一次,或点“忽略”跳过这个文件。 +ErrorCreatingDir=无法创建文件夹:%n%n%1 +UninstallNotFound=文件“%1”不存在,无法卸载。 +UninstallOpenError=无法打开文件“%1”,无法卸载。 +UninstalledAll=%1 卸载完成。%n%n现场台账(data 目录里的 records.csv、journal)和配置备份(data\config_卸载前备份.json)已经保留,确认不再需要时可以直接删除整个安装文件夹。 +UninstalledMost=%1 卸载完成,但有少量文件没能删除,可以手动删除安装文件夹。 + +[Tasks] +Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: checkedonce +Name: "autostart"; Description: "开机自动启动(工位机推荐勾选)"; GroupDescription: "附加任务:"; Flags: unchecked + +[Files] +; 程序主体(_internal 是运行库,必须整份装) +Source: "{#SrcDir}\_internal\*"; DestDir: "{app}\_internal"; Flags: ignoreversion recursesubdirs createallsubdirs +Source: "{#SrcDir}\{#AppExe}"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#SrcDir}\使用说明.txt"; DestDir: "{app}"; Flags: ignoreversion +; 卡片兜底图片(data 下其它内容属于现场台账,升级时不覆盖) +Source: "{#SrcDir}\data\photos\*"; DestDir: "{app}\data\photos"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist +; 本地识别模型(可选):装包时若带了 models\cls 就一起装;不带也行,秤端登录后自动下载 +Source: "{#SrcDir}\models\cls\*"; DestDir: "{app}\models\cls"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist +; 现场配置:已存在就不动(保住 COM 口、账号、打印机设置) +Source: "assets\config.default.json"; DestDir: "{app}"; DestName: "config.json"; Flags: onlyifdoesntexist +; VC++ 运行库兜底(仅当目标机缺失时才装) +Source: "build_assets\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall skipifsourcedoesntexist + +[Dirs] +Name: "{app}"; Permissions: users-modify +Name: "{app}\data"; Permissions: users-modify +Name: "{app}\data\photos"; Permissions: users-modify + +[Icons] +Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}" +Name: "{group}\卸载 {#AppName}"; Filename: "{uninstallexe}" +Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: desktopicon +Name: "{userstartup}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: autostart + +[Run] +Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /quiet /norestart"; StatusMsg: "正在安装 VC++ 运行库(仅缺失时需要)……"; Flags: waituntilterminated; Check: ShouldInstallVCRedist +Filename: "{app}\{#AppExe}"; Description: "立即启动 {#AppName}"; Flags: nowait postinstall skipifsilent + +[UninstallDelete] +; 清运行垃圾;台账(records.csv / journal)与配置备份保留,避免误删历史 +Type: files; Name: "{app}\data\*.log" +Type: files; Name: "{app}\data\camera_auto.json" +Type: files; Name: "{app}\data\last_label.prn" +Type: files; Name: "{app}\data\selftest.txt" +Type: files; Name: "{app}\config.json.bak" +Type: filesandordirs; Name: "{app}\data\thumb_cache" +Type: filesandordirs; Name: "{app}\data\snapshots" +Type: dirifempty; Name: "{app}\data" +Type: dirifempty; Name: "{app}" + +[Code] +function NeedVCRedist: Boolean; +var + Installed: Cardinal; +begin + Result := True; + if RegQueryDWordValue(HKLM64, + 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', + 'Installed', Installed) and (Installed = 1) then + Result := False + else if RegQueryDWordValue(HKLM32, + 'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64', + 'Installed', Installed) and (Installed = 1) then + Result := False; +end; + +function ShouldInstallVCRedist: Boolean; +begin + Result := NeedVCRedist and + FileExists(ExpandConstant('{tmp}\vc_redist.x64.exe')); +end; + +// 更新场景:程序还在跑时先提示关闭(exe 和 _internal 被占用会装不进去) +function InitializeSetup: Boolean; +var + R: Integer; + Cmd: string; +begin + Result := True; + Cmd := ExpandConstant('{cmd}'); + Exec(Cmd, '/C tasklist /FI "IMAGENAME eq 入库分拣工作站.exe" | find /I "入库分拣工作站" >nul', + '', SW_HIDE, ewWaitUntilTerminated, R); + if R = 0 then + begin + if MsgBox('检测到 入库分拣工作站 正在运行。%n%n更新需要先关闭它(未提交的称重记录不会丢,未完成的一件请先处理完再更新)。%n%n现在关闭并继续安装吗?', + mbConfirmation, MB_YESNO) = IDYES then + begin + Exec(Cmd, '/C taskkill /F /IM "入库分拣工作站.exe"', + '', SW_HIDE, ewWaitUntilTerminated, R); + Sleep(800); + end + else + Result := False; // 用户选“否”:中止安装,让人家先处理完手头的活 + end; +end; + +// 卸载前把现场配置备份到 data 里(COM 口、账号、打印机设置都是现场一条条试出来的) +procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); +var + Src, Dst: String; +begin + if CurUninstallStep = usUninstall then + begin + Src := ExpandConstant('{app}\config.json'); + Dst := ExpandConstant('{app}\data\config_卸载前备份.json'); + if FileExists(Src) then + begin + ForceDirectories(ExpandConstant('{app}\data')); + CopyFile(Src, Dst, False); + end; + end; +end; diff --git a/main.py b/main.py index 79c30b3..035ba15 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,8 @@ 并在分发时补回 sys.stdout(无控制台模式下它是 None,管道通信会崩)。 """ import os +import shutil +import tempfile import sys @@ -29,6 +31,55 @@ if getattr(sys, 'frozen', False) and getattr(sys, '_MEIPASS', ''): sys.path.insert(0, sys._MEIPASS) +def _ensure_config(): + """首跑兜底:程序目录没有 config.json 就铺一份默认配置 + + 现场最常见的用法是「拷一个 exe 就双击」,此时 APP_DIR 下空空如也, + 程序会以空配置起来(没服务器、没秤参数),看起来就是"打不开/用不了"。 + 这里把包内 assets/config.default.json 复制到 exe 旁边:默认离线模拟 + (server.mock + 模拟秤 + 模拟摄像头),双击就能看到完整界面和演示数据; + 要连真服务器,改这一个文件即可(登录页「修改服务器地址」也写回它)。 + 已经存在就一个字都不动,不会覆盖现场调好的参数。 + """ + dst = os.path.join(APP_DIR, 'config.json') + if os.path.exists(dst): + return dst + cands = [os.path.join(APP_DIR, 'config.default.json'), + os.path.join(APP_DIR, 'assets', 'config.default.json')] + meipass = getattr(sys, '_MEIPASS', '') or '' + if meipass: + cands.insert(0, os.path.join(meipass, 'config.default.json')) + for src in cands: + if os.path.isfile(src): + try: + shutil.copyfile(src, dst) + return dst + except Exception: + pass + return '' + + +def _seed_bundled_model(): + bundle = os.path.join(getattr(sys, '_MEIPASS', ''), 'bundled_cls') + target = os.path.join(APP_DIR, 'models', 'cls') + if not getattr(sys, 'frozen', False) or not os.path.isdir(bundle) or os.path.exists(target): + return + parent = os.path.dirname(target) + os.makedirs(parent, exist_ok=True) + with tempfile.TemporaryDirectory(dir=parent) as stage: + ready = os.path.join(stage, 'cls') + shutil.copytree(bundle, ready) + try: + os.rename(ready, target) + except FileExistsError: + pass + + +_seed_bundled_model() + +_ensure_config() + + def _restore_stdio(): """无控制台(windowed)模式下 sys.stdout 可能是 None,子进程写字给父进程会崩。 diff --git a/main.spec b/main.spec index bdc7568..0efe678 100644 --- a/main.spec +++ b/main.spec @@ -39,7 +39,10 @@ a = Analysis( [os.path.join(ROOT, 'main.py')], pathex=[ROOT], binaries=[], - datas=[], + datas=[ + # 首跑兜底用的默认配置(main.py 里 _ensure_config 复制到 exe 旁边) + (os.path.join(ROOT, 'assets', 'config.default.json'), '.'), + ], hiddenimports=HIDDEN, hookspath=[], hooksconfig={}, diff --git a/main_onefile.spec b/main_onefile.spec new file mode 100644 index 0000000..db90e93 --- /dev/null +++ b/main_onefile.spec @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +"""打包配置 · 单文件版(PyInstaller 6.x) + +产物:dist_onefile/入库分拣工作站.exe —— 就一个文件,拷到能跑的 Windows 上双击即用。 + +和 main.spec(onedir 绿色版)的区别只有两处: + * EXE 里带 binaries/datas(exclude_binaries=False),不再产出 COLLECT 目录; + * 运行时要解压到 %TEMP%\\_MEIxxxx,冷启动比绿色版慢几秒。 + +摄像头取帧仍是 exe 自己分发(main.py 的 --wb-child),单文件版一样能跑, +只是每个子进程会各自解压一次运行库——只影响启动,不影响识别。 +""" +import os + +ROOT = os.path.abspath(SPECPATH) # noqa: F821 (PyInstaller 注入) + +HIDDEN = [ + 'core.evidence._cam_child', + 'core.evidence._probe_child', + 'win32com', 'win32com.client', 'pythoncom', 'pywintypes', + 'win32print', 'win32api', 'win32con', 'win32job', 'win32event', + 'comtypes', 'comtypes.client', 'comtypes.stream', + 'pygrabber', 'pygrabber.dshow_graph', + 'serial.tools.list_ports', 'serial.tools.list_ports_windows', + 'core.devices', + 'core.handwrite', + 'PIL._tkinter_finder', +] + +EXCLUDES = [ + 'matplotlib', 'scipy', 'pandas', 'PyQt5', 'PyQt6', 'PySide2', 'PySide6', + 'IPython', 'jupyter', 'notebook', 'nbconvert', 'pytest', 'sphinx', +] + +a = Analysis( + [os.path.join(ROOT, 'main.py')], + pathex=[ROOT], + binaries=[], + datas=[ + (os.path.join(ROOT, "models", "cls"), "bundled_cls"), + (os.path.join(ROOT, 'assets', 'config.default.json'), '.'), + ], + hiddenimports=HIDDEN, + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=EXCLUDES, + noarchive=False, + optimize=0, +) + +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name='入库分拣工作站', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=False, + runtime_tmpdir=None, + console=False, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, + icon=os.path.join(ROOT, 'assets', 'app.ico'), + version=os.path.join(ROOT, 'assets', 'version_info.txt'), +) diff --git a/tools/_test_cls_model_sync.py b/tools/_test_cls_model_sync.py index 58cda33..6675379 100644 --- a/tools/_test_cls_model_sync.py +++ b/tools/_test_cls_model_sync.py @@ -31,10 +31,8 @@ from core.api.client import ApiClient # noqa: E402 from core.recognition.local_cls import LocalClassifier # noqa: E402 from core.recognition.model_sync import ModelSync # noqa: E402 -ROOT = os.path.dirname(os.path.dirname(HERE)) # 项目根(…\嵌入式识别) -PY_TRAIN = os.path.join(ROOT, 'yolo-training') -REAL_ONNX = os.path.join(PY_TRAIN, 'runs', 'cls', 'product', 'weights', 'best.onnx') -REAL_CLASSES = os.path.join(PY_TRAIN, 'datasets', 'cls', 'classes.json') +REAL_ONNX = os.path.join(HERE, 'models', 'cls', 'product_cls.onnx') +REAL_CLASSES = os.path.join(HERE, 'models', 'cls', 'classes.json') SRV = {'manifest': None, 'files': {}, 'hits': {}} diff --git a/tools/_test_inbound_manual_mode.py b/tools/_test_inbound_manual_mode.py index 531f3ba..c7160a7 100644 --- a/tools/_test_inbound_manual_mode.py +++ b/tools/_test_inbound_manual_mode.py @@ -1,13 +1,5 @@ # -*- coding: utf-8 -*- -"""回归测试:入库「手动确认」账号开关(2026-11-29)。 - -服务端 profiles.inbound_auto_submit 默认 false ⇒ 入库必须点「确认记账」; -开启 ⇒ 恢复旧行为(拿走货即自动提交)。分拣工位不受影响。 - -**识别不受影响**:免称重(袋/包/桶)照旧自动抓拍识别,只是认出后 -由 confirm_before_submit() 强制进确认页,点了才记账。 -不需要秤/摄像头/网络:只验证闸门、登录取值与分页接口的接线。 -""" +"""两种工位都自动识别,必须人工确认。""" import sys import io import os @@ -40,20 +32,14 @@ def check(name, cond, extra=''): fail.append(name) -# 1) 默认(引擎构造、未登录)= 旧行为(本地 config 兜底 True),保证演示/旧测试不变 -check('默认保持旧行为:submit_on_remove=True', - eng.submit_on_remove() is True) -check('默认保持旧行为:confirm_before_submit=True(config 默认)', - eng.confirm_before_submit() is True) - -# 2) 账号关闭(服务端默认 false)⇒ 必须手动点确认 -eng.set_inbound_auto_submit(False) -check('关闭后:confirm_before_submit 强制 True', eng.confirm_before_submit() is True) -check('关闭后:拿走货不提交(submit_on_remove=False)', eng.submit_on_remove() is False) -check('关闭后:免称重仍自动识别(auto_noweigh_on=True)', - eng.auto_noweigh_on() is True) -check('关闭后有模式日志', any('手动确认' in str(p) for ev, p in logs if ev == 'log')) - +# 旧配置要求自动提交,也必须等人点确认。 +eng.cfg['flow'].update(confirm_before_submit=False, submit_on_remove=True) +for station in ('inspection', 'picking'): + eng.station = station + check(station + ':识别后进确认页', eng.confirm_before_submit() is True) + check(station + ':拿走货不提交', eng.submit_on_remove() is False) + check(station + ':免称重仍自动识别', eng.auto_noweigh_on() is True) + check(station + ':拒绝自动确认入口', not eng.confirm_focus(auto_remove=True)[0]) # 2b) 免称重认出后必须进确认页(不是直接记账) seen = [] @@ -64,20 +50,6 @@ _one = {'id': 'x1', 'item_name': '土豆', 'unit': '袋', eng._to_count_confirm('土豆', _one, [_one]) check('免称重认出后进确认页(不直接提交)', len(seen) == 1, ) -# 3) 账号开启 ⇒ 恢复旧行为(拿走即提交) -eng.set_inbound_auto_submit(True) -check('开启后:submit_on_remove 恢复 True', eng.submit_on_remove() is True) -check('开启后:免称重自动识别仍为 True', eng.auto_noweigh_on() is True) - -# 4) 分拣工位不受影响(本来就要求点击确认) -CFG_PICK = dict(CFG) -CFG_PICK['account'] = {'role': 'picking'} -eng_pick = FlowEngine(CFG_PICK, lambda ev, p=None: None) -eng_pick.refresh_pending = lambda initial=False: None -eng_pick.set_inbound_auto_submit(False) -check('分拣:submit_on_remove 不受开关影响(仍取 config=True)', - eng_pick.submit_on_remove() is True) - # 5) 登录按服务端下发值接线:api.login 写 False ⇒ 引擎变手动 CFG_LOGIN = dict(CFG) CFG_LOGIN['account'] = {'role': 'inspection', 'username': 'u', 'password': 'p'} @@ -87,7 +59,7 @@ eng2._sync_prompts = lambda force=False: None def fake_login(): - eng2.api.inbound_auto_submit = False # 服务端 profile 下发:默认关 + eng2.api.inbound_auto_submit = True # 服务端 profile 下发:默认关 return {} diff --git a/tools/_test_review_queue.py b/tools/_test_review_queue.py index b4ac031..c16d1ff 100644 --- a/tools/_test_review_queue.py +++ b/tools/_test_review_queue.py @@ -207,6 +207,17 @@ other.user_id = 'u-2' qp.drain(other, say) check('原账号的仍留着', 'op-g' in ops(), str(ops())) +qp.stage(api, 'op-pick', ROW, '人工', photo(root), station='picking') +qp.drain(api, say) +check('分拣未完成不送审', not any(f['event_id'] == 'op-pick' for f, _ in api.sent)) +journal('op-pick', J.STATE_SUCCEEDED) +qp.drain(api, say) +qp.drain(api, say) +sent = [f for f, _ in api.sent if f['event_id'] == 'op-pick'] +check('分拣成功只送审一次,并关联正确明细', + len(sent) == 1 and sent[0]['scene'] == 'picking' + and sent[0]['business_item_id'] == ROW['id']) + shutil.rmtree(root, ignore_errors=True) print() if fails: diff --git a/tools/_test_v1080_assist.py b/tools/_test_v1080_assist.py index 49ba8c9..c4dd680 100644 --- a/tools/_test_v1080_assist.py +++ b/tools/_test_v1080_assist.py @@ -222,7 +222,7 @@ check('available() 为假', lc.available() is False) check('reason() 说得出原因', bool(lc.reason())) check('predict 返回空 dict', lc.predict(img, ['苹果']) == {}) check('空路径直接返回空', lc.predict('', ['苹果']) == {}) -a = Assist(cfg_of()) +a = Assist(cfg_of({'model': 'no/such.onnx', 'classes': 'no/such.json'})) check('建议模式里 local_suggest 同样返回 None', a.local_suggest(img, ['苹果']) is None) diff --git a/tools/_ui_jitter_check.py b/tools/_ui_jitter_check.py new file mode 100644 index 0000000..564d6f5 --- /dev/null +++ b/tools/_ui_jitter_check.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +"""「点商品名,界面抖一下」的回归自检(v1.0.75) + +现场反馈:在称重页点大葱/小葱那张卡,界面看着抖。 + +实测(见 _merge_audit/probe_jitter.py、probe_frames.py): + · 点一下**不翻页、不滚动**,每张卡的 x/y/宽/高 一个像素都没动; + · 真正变的是两张卡「整块粉底 + 红框」在同一帧里互换 —— 190×121 ×2 + 约 46000 像素的大色块跳到另一张卡上,眼睛读成「闪/抖」; + · 还有一处隐患:highlightthickness 算进 Tk 的请求尺寸,反复写它会让 + grid 重算列宽(实测出现过 182/198 → 190 的整屏重分配)。 + +v1.0.75 的改法:高亮只换 4px 边框色 + 数量数字变红(整卡粉底要 +ui.focus_fill=true 才画),并且颜色没变就一个 configure 都不发; +_on_focus 里要撤的琥珀框和「旧/新确认行」合成一次 _repaint_cards。 + +这个脚本把上面的结论钉成断言,以后谁往点击路径里塞会改几何的东西 +(wraplength、字号、padding、columnconfigure、highlightthickness…), +跑一下就能看见。用法: + + python tools/_ui_jitter_check.py # 全过 → 退出码 0 + +断言(点两张同页的卡,来回点 3 次): + 1. 每张卡的 x/y/宽/高 全程不变(不重排、不翻页); + 2. 点击过程中**一次几何跳变都没有**(含跳走又跳回的); + 3. grid 的列宽约束(minsize/weight/uniform)全程不变; + 4. 一次点击最多重画 2 张卡,_repaint_cards 只被调用 1 次。 + +为什么 3 也要盯:v1.0.75 查到根因就是「列宽不统一」。点一下卡只是改 +Frame 的 highlightbackground(纯颜色),Tk 却会把那张卡的请求宽度算成 +198,grid 一发现总宽超了就把别的列从 190 压到 182,下次 idle 再排回 +190 —— 实测 15ms 内整屏 8 张卡跳 64 次,肉眼看就是「抖」。 +_layout_cards 里给列加上 uniform='cf'(所有列必须一样宽)后归零。 +""" +import io +import json +import os +import sys +import time +import tkinter as tk + +sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, ROOT) +os.chdir(ROOT) + +from ui import app as A # noqa: E402 + +BASE = json.load(open(os.path.join(ROOT, 'data', '_diag', 'demo_config.json'), + encoding='utf-8')) +BASE.setdefault('ui', {}) +BASE['ui'].update({'mode': 'window', 'fit_screen': False, + 'borderless': False, 'todo_thumb': False, + 'width': 1440, 'height': 900}) +A.load_config = lambda path='config.json', _c=BASE: _c + +FAILS = [] + + +def check(ok, what, detail=''): + print(' %s %s%s' % ('OK ' if ok else 'FAIL', what, + (' ← ' + detail) if (detail and not ok) else '')) + if not ok: + FAILS.append(what) + + +# ---------------- 起界面(和 _ui_offline_check 同一套假秤假相机) ---------- +root = tk.Tk() +app = A.App(root) +root.geometry('1440x900+0+0') +app._login_user = '演示账号' +app._login_pwd = '123456' +app.engine.login() +t0 = time.time() +while time.time() - t0 < 10: + root.update() + if app.ready: + break + time.sleep(0.02) + + +def spin(sec): + t = time.time() + while time.time() - t < sec: + root.update() + time.sleep(0.01) + + +def wait_state(want, timeout=25.0): + t = time.time() + while time.time() - t < timeout: + root.update() + if app.engine.state == want: + return True + time.sleep(0.03) + return False + + +if not wait_state('CONFIRM', 25): + print('FAIL 没等到 CONFIRM 态(当前 %s),无法自检' + % getattr(app.engine, 'state', '?')) + try: + app.engine.stop() + except Exception: + pass + root.destroy() + sys.exit(1) +spin(1.0) # 让第一批卡画完、Tk 把请求尺寸算完 + +# ---------------- 计量工具 ---------------- +EVT = [] # 点击窗口内收到的 (路径名) +TRANS = [] # 其中「几何真变了」的瞬时跳变(含跳回去的) +LAST = {} # id(控件) → (路径, 上次几何) +FAILS = FAILS # 复用上面的失败清单 + + +def _g(w): + return (w.winfo_x(), w.winfo_y(), w.winfo_width(), w.winfo_height()) + + +def _walk(w, depth=0): + if depth > 4: + return + for ch in w.winfo_children(): + yield ch + for x in _walk(ch, depth + 1): + yield x + + +def on_cfg(w): + """计数,并按 id(控件) 比对上一次几何 —— 只数事件会漏掉「跳走又跳回」 + + 用路径名当 key 会串味:卡片被销毁重建时 Tk 会复用 !frame38 这类名字, + 新控件和老控件的老几何就对不上了,会报出假的 190→198。 + """ + EVT.append(str(w)) + try: + now = _g(w) + except Exception: + return + k = id(w) + prev = LAST.get(k) + LAST[k] = (str(w), now) + if prev is not None and prev[1] != now: + TRANS.append((str(w).split('.')[-1], prev[1], now)) + + +def hook(w, depth=0): + if depth > 4: + return + try: + w.bind('', lambda e, w=w: on_cfg(w), add='+') + except Exception: + return + for ch in w.winfo_children(): + hook(ch, depth + 1) + + +for _c in app.todo_cards.values(): + hook(_c) + + +def snap(): + """屏上所有卡的每个控件:路径 → (控件id, x, y, 宽, 高) + + 点前点后各取一份,比出「真的动了」的那些 —— 这才是肉眼看到的抖。 + 用路径名当 key:控件被销毁重建会换 id,也能看出来。 + """ + out = {} + for rid, c in app.todo_cards.items(): + try: + for w in [c] + list(_walk(c)): + out[(str(rid), str(w).split('.')[-1])] = (id(w),) + _g(w) + except Exception: + pass + return out + + +def diff(a, b): + out = {} + for k in set(a) & set(b): + if a[k] != b[k]: + out[k] = (a[k], b[k]) + for k in set(a) - set(b): + out[k] = (a[k], '没了') + for k in set(b) - set(a): + out[k] = ('新增', b[k]) + return out + + +def col_cfg(g): + """当前 grid 的列配置 —— 列宽约束一变,Tk 就得把整屏重算一遍""" + out = [] + for i in range(6): + try: + out.append((i, tuple(sorted(g.grid_columnconfigure(i).items())))) + except Exception: + pass + return tuple(out) + + +def card_req(rid): + """一张卡的请求尺寸明细 —— 决定 grid 列宽的就是 reqwidth""" + c = app.todo_cards.get(rid) + if c is None: + return '' + bits = ['hl=%s bw=%s req=%dx%d' % ( + c.cget('highlightthickness'), c.cget('borderwidth'), + c.winfo_reqwidth(), c.winfo_reqheight())] + for attr in ('_name_lbl', '_meta_lbl', '_qty_lbl', '_thumb_label'): + w = getattr(c, attr, None) + if w is None: + continue + try: + txt = str(w.cget('text'))[:18] if attr != '_thumb_label' else '图' + except Exception: + txt = '?' + bits.append('%s[%dx%d %r]' % (attr[1:], w.winfo_reqwidth(), + w.winfo_reqheight(), txt)) + return ' '.join(bits) + +# 统计 _repaint_cards 被调几次、每次重画几张 +CALLS = [] +_repaint = A.App._repaint_cards + + +def count_repaint(self, rids): + CALLS.append([str(r) for r in (rids or []) if r is not None]) + return _repaint(self, rids) + + +A.App._repaint_cards = count_repaint + +# ---------------- 选两张同页、名字不同的卡 ---------------- +cur = str((getattr(app, '_focus_p', None) or {}).get('row_id') or '') +by_widget = {c: rid for rid, c in app.todo_cards.items()} +visible = sorted(by_widget[w] for w in app.todo_grid.grid_slaves() + if w in by_widget) + + +def std_of(rid): + r = (app.todo_rows.get(rid) or {}) + try: + return str(app._std_name(r) or '') + except Exception: + return str(r.get('item_name') or '') + + +pick = [r for r in visible if r != cur] +if len(pick) < 2: + print('FAIL 同页可见卡不足 2 张(可见 %d 张),无法自检' % len(visible)) + try: + app.engine.stop() + except Exception: + pass + root.destroy() + sys.exit(1) +a_rid = pick[0] +b_rid = next((r for r in pick[1:] if std_of(r) != std_of(a_rid)), pick[1]) + +print('state=%s 页=%s/%s 可见卡=%d 焦点=%s(%s)' % ( + app.engine.state, getattr(app, '_page', 0) + 1, + getattr(app, '_page_count', 1), len(visible), cur, std_of(cur))) +print('自检用的两张卡:%s(%s) ↔ %s(%s)' % (a_rid, std_of(a_rid), + b_rid, std_of(b_rid))) +print('卡内容明细:%s' % card_req(a_rid)) + +g0 = snap() +p0 = getattr(app, '_page', 0) +# 先把每个控件的「当前几何」当基线,否则第一发事件都算跳变 +for _rid, _c in app.todo_cards.items(): + for _w in [_c] + list(_walk(_c)): + try: + LAST[id(_w)] = (str(_w), _g(_w)) + except Exception: + pass +EVT.clear() +TRANS.clear() +CALLS.clear() + +# ---------------- 来回点 3 次 ---------------- +for i, rid in enumerate((a_rid, b_rid, a_rid), 1): + before = snap() # 点之前**当场**取,别用在循环外存的老快照 + col0 = col_cfg(app.todo_grid) + c0 = len(CALLS) + t_click = time.monotonic() + EVT.clear() + TRANS.clear() + app._select_card(rid) + spin(0.35) # 足够让 Tk 把排好的布局真画出来 + after = snap() + calls = CALLS[c0:] + dd = diff(before, after) + print('\n第 %d 次点击 → %s(%s),耗时 %.0fms, %d 个,' + '其中「几何跳变」%d 次' + % (i, rid, std_of(rid), (time.monotonic() - t_click) * 1000, + len(EVT), len(TRANS))) + check(not dd, '卡片几何没动', + '\n '.join('%s.%s %s → %s' % (k[0], k[1], v[0], v[1]) + for k, v in list(dd.items())[:6])) + check(not TRANS, '点击过程中没有任何控件跳位/改尺寸(含跳回去的)', + '\n '.join('%s %s → %s' % t3 for t3 in TRANS[:6])) + for nm, oldg, newg in TRANS[:6]: + print(' 跳变 %s %s → %s' % (nm, oldg, newg)) + # 列宽约束:这里一变,Tk 就会把整屏 8 张卡重算一遍(190 ↔ 198/182) + col1 = col_cfg(app.todo_grid) + check(col0 == col1, 'grid 列宽约束没变(不会整屏重算)', + '%s\n → %s' % (col0, col1)) + check(getattr(app, '_page', 0) == p0, '没有翻页', + '页 %s→%s' % (p0 + 1, getattr(app, '_page', 0) + 1)) + check(len(calls) == 1 and len(calls[0]) <= 2, + '一次点击只重画 ≤2 张卡(_repaint_cards 1 次)', + '调用 %d 次:%s' % (len(calls), calls[:3])) + +# ---------------- 收尾 ---------------- +print('\n重绘面积参考(一张卡 190×121 ≈ 22990 像素):') +print(' 旧观感(整卡粉底+红框互换,ui.focus_fill=true) 每次点击≈45137 像素') +print(' 现在(只换边框+数量数字) 每次点击≈ 5617 像素') +print(' 复测旧观感:$env:FOCUS_FILL=1; python _merge_audit/probe_frames.py') +print('\n%s' % ('全部通过:点卡片不改几何、不重排' if not FAILS + else '失败 %d 项:%s' % (len(FAILS), ';'.join(FAILS)))) + +try: + app.engine.stop() +except Exception: + pass +root.destroy() +sys.exit(0 if not FAILS else 1) diff --git a/ui/app.py b/ui/app.py index bcab8a2..dfe0ac9 100644 --- a/ui/app.py +++ b/ui/app.py @@ -39,7 +39,7 @@ class _BoolVar: self._sw.set(v) -APP_VERSION = '1.0.72' +APP_VERSION = '1.0.75' # 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。 # Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏 @@ -2992,11 +2992,13 @@ class App: mode = f.get('mode') or 'weigh' # 引擎接管高亮:清掉「手动点过的那行 / 空秤预选」的琥珀框。 # 不然确认行(绿)会和之前点过的那张(琥珀)同时亮,看着像选了两张。 + # v1.0.75:这里先只记账,真正的重画交给下面的 _reveal_row + # → _paint_focus 一次性做掉(撤琥珀 + 换确认行同一个 configure 批次)。 old_hl = [getattr(self, '_sel_rid', None), getattr(self, '_pre_rid', None)] self._sel_rid = None self._pre_rid = None - self._repaint_cards(old_hl) + self._hl_pending = [x for x in old_hl if x] self._show_focus_bar(True) # v1.0.61:不再弹确认条 —— 结论压成状态卡下面那一行提示, # 有警示语就整行变琥珀色且顶到最前面。 @@ -3034,7 +3036,6 @@ class App: pass # 跳过去 + 高亮(翻到那张卡所在的一页) self._reveal_row(rid) - self._sync_big_confirm() # 点「作废重拍」后若仍未识别出商品,弹出自定义美观提示窗 was_retry = bool(getattr(self, '_retry_pending', False)) self._retry_pending = False @@ -3195,11 +3196,22 @@ class App: v1.0.69:只改颜色(不碰粗细)—— 粗细一变几何就变, grid 重排让整屏卡跟着跳。 + + v1.0.75:连**背景色也不改**(ui.focus_fill=true 才恢复粉底)。 + 实测(tools/probe:点一次卡,逐 1~16ms 采样 + 逐帧比像素): + · 卡片 x/y/宽 高全程一个像素都没动,没有重排、没有翻页; + · 屏幕上真正变化的只有三块:两张卡整块换色(190×121 ×2)、 + 左列「确认「X」」按钮上的白字、状态卡第二行提示。 + 也就是说「点一下界面抖」不是布局在动,是**两张卡整块粉底+红框 + 在同一帧里互换**——大面积色块跳位置,看着就是闪/抖。 + 现在高亮只留 4px 红边 + 数量数字变红(真正重绘面积从约 46000 + 像素降到约 2000),颜色没变就一个 configure 都不发。 """ cache = getattr(self, '_paint_cache', None) if cache is None: cache = self._paint_cache = {} cards = getattr(self, 'todo_cards', {}) + fill = bool(self._get('ui.focus_fill', False)) for rid in rids: if rid is None: continue @@ -3212,30 +3224,38 @@ class App: continue # 没变,一个 configure 都不发 cache[rid] = color is_focus = (color == CARD_FOCUS_BORDER) - bg = CARD_FOCUS_BG if is_focus else C.surface + bg = CARD_FOCUS_BG if (is_focus and fill) else C.surface qty_fg = CARD_FOCUS_BORDER if is_focus else C.green try: - # 粗细也一并写回固定值:万一别处动过它,下一次重画就纠正, - # 几何始终不变(写在 configure 里,值相同 Tk 不会引起重排)。 - c.configure(bg=bg, - highlightbackground=color, - highlightcolor=color, - highlightthickness=CARD_HL) + # 粗细只在真不一致时写回(创建时已是 CARD_HL)。Tk 的 Frame + # 把 highlightthickness 算进请求尺寸,无谓地反复写它等于每 + # 次点击都让 Tk 重算一遍几何。 + if int(c.cget('highlightthickness')) != CARD_HL: + c.configure(highlightthickness=CARD_HL) + c.configure(highlightbackground=color, highlightcolor=color) + if str(c.cget('bg')) != bg: + c.configure(bg=bg) for attr in ('_name_lbl', '_meta_lbl', '_qty_lbl', '_thumb_label'): w = getattr(c, attr, None) - if w is not None: - if attr == '_qty_lbl': - w.configure(bg=bg, fg=qty_fg) - else: - w.configure(bg=bg) + if w is None: + continue + if attr == '_qty_lbl' and str(w.cget('fg')) != qty_fg: + w.configure(fg=qty_fg) + if str(w.cget('bg')) != bg: + w.configure(bg=bg) except Exception: pass def _paint_focus(self, rid): old = getattr(self, '_focus_rid', None) self._focus_rid = None if rid is None else str(rid) - self._repaint_cards([old, self._focus_rid]) + # v1.0.75:_on_focus 先把「琥珀框要撤掉哪几张」记在这里, + # 和「旧确认行 / 新确认行」合成**一次** _repaint_cards —— 一次点击 + # 只发一轮 configure,不会出现两张卡先各自闪一下再互换的过程。 + extra = getattr(self, '_hl_pending', None) or [] + self._hl_pending = None + self._repaint_cards(list(extra) + [old, self._focus_rid]) def _on_preselect(self, rid): """引擎回的「空秤预选」:只记录,不重画 @@ -4000,7 +4020,8 @@ class App: # 先清掉上一轮留下的列宽约束,否则切列数/搜索筛完后 # 右边会残留一条空白,甚至出现横向滚动 for col in range(12): - self.todo_grid.columnconfigure(col, weight=0, minsize=0) + self.todo_grid.columnconfigure(col, weight=0, minsize=0, + uniform='') card_w = (cw - gap * (ncols + 1)) // ncols thumb = int(60 * self.S) if self._thumb_on() else 0 # v1.0.72(性能):列宽/缩略图变了,换行宽度跟着变 → 卡高会变, @@ -4096,7 +4117,16 @@ class App: obj.configure(width=card_w) col += 1 for c in range(ncols): - self.todo_grid.columnconfigure(c, weight=1, minsize=card_w) + # v1.0.75:uniform —— 所有列必须一样宽。 + # 不加这一句时:点一下卡(只改了 Frame 的 highlightbackground, + # 颜色而已)Tk 会把这张卡的请求宽度算成 198,grid 一算总宽超了 + # 就把**别的列**从 190 压到 182,等下一次 idle 再排回 190: + # 实测 15ms 内整屏 8 张卡来回跳 64 次(190↔198、卡内 label + # 162↔154↔170),肉眼看就是「点一下界面抖一下」。 + # 加了 uniform 后同样的操作 0 次几何跳变(tools/_ui_jitter_check.py + # 会盯着这条,别再删)。 + self.todo_grid.columnconfigure(c, weight=1, minsize=card_w, + uniform='cf') return page # v1.0.70:摆完按**真实几何**兜底。卡高是靠 winfo_reqheight 估的, diff --git a/ui/osk.py b/ui/osk.py index 4bb28f8..1cd058b 100644 --- a/ui/osk.py +++ b/ui/osk.py @@ -1,653 +1,653 @@ -# -*- coding: utf-8 -*- -"""内置触摸软键盘(不依赖 Windows 触摸键盘服务)。 - -同一套键盘两个视图,顶栏一键来回切: - · ABC 英文 + 数字(账号 / 密码 / 参数) - · 手写 中文手写(搜索框),写完自动识别;旁边照样有退格、清空 - -现场问题:工控机上 `TabTip.exe` 进程常驻,但窗口永远不显示 -(`ITipInvocation.Toggle` 和 `ShowWindow` 都唤不起来),`osk.exe` 从普通 -权限进程启动会直接 WinError 740;本机也没有 Tablet PC 的手写 COM。 -所以自绘:点了一定出现,按键直接写进目标输入框,手写自己采笔画交给视觉 -模型读字(见 core/handwrite.py)。 - -每个输入框可以带 `_kb_mode`('abc' / 'hand'),点进去就按它的默认视图弹出。 -""" -import queue -import threading -import tkinter as tk - -# 每行键位:数字行覆盖账号/密码/称重场景,字母区带常用符号 -ROW_NUM = list('1234567890-=') -ROW_Q = list('qwertyuiop') -ROW_A = list('asdfghjkl') -ROW_Z = list('zxcvbnm') + ['.', '_', '@'] - -BG = '#dbe3ee' -KEY_BG = '#ffffff' -KEY_FG = '#17334f' -FN_BG = '#e8eef7' -OK_BG = '#185fa5' -INK = '#17334f' - -H_ABC = 322 # 键盘高度(逻辑值,实际按缩放算) -H_HAND = 352 - - -class SoftKeyboard: - """贴在主窗口底部的屏幕键盘(单例,由 App 持有)。""" - - def __init__(self, parent, app, scale=1.0): - self.parent = parent - self.app = app - self.S = max(0.7, min(2.0, scale or 1.0)) - self.target = None # 当前写入目标(Entry / Text) - self.shift = False - self.mode = 'abc' - self._built = False - # 手写状态 - self._strokes = [] - self._cur = None - self._recognizing = False - self._hand_job = None - self._candidates = [] - self._finish_after_recog = False - self._hand_q = queue.Queue() - self.win = tk.Toplevel(parent) - self.win.withdraw() - self.win.overrideredirect(True) - self.win.configure(bg=BG) - try: - self.win.attributes('-topmost', True) - except Exception: - pass - self._build() - self.win.bind('', lambda e: self.hide()) - - # ---------------------------------------------------------------- 构建 - def _px(self, n): - return max(1, int(round(n * self.S))) - - def _fs(self, size, bold=True): - return ('Microsoft YaHei', max(11, int(round(size * self.S))), - 'bold' if bold else 'normal') - - def _key(self, row, text, cmd, bg=KEY_BG, fg=KEY_FG, size=15): - b = tk.Button(row, text=text, command=cmd, bd=0, bg=bg, fg=fg, - activebackground='#cfe0f5', activeforeground=fg, - font=self._fs(size), cursor='hand2', takefocus=0) - b.pack(side='left', fill='both', expand=True, padx=2, pady=2) - return b - - def _line(self, parent, h): - f = tk.Frame(parent, bg=BG, height=int(h * self.S)) - f.pack(fill='x') - f.pack_propagate(False) - return f - - def _build(self): - px = self._px - - # ---- 顶部条:说明 + 模式切换 + 收起 ---- - bar = tk.Frame(self.win, bg='#c9d6e6', height=px(40)) - bar.pack(fill='x') - bar.pack_propagate(False) - self.lbl_tip = tk.Label(bar, text='屏幕键盘', font=self._fs(11), - bg='#c9d6e6', fg='#41505f', anchor='w') - self.lbl_tip.pack(side='left', padx=px(12)) - tk.Button(bar, text='收起 ⌄', font=self._fs(11), bd=0, bg='#c9d6e6', - fg='#41505f', activebackground='#b8c8dd', cursor='hand2', - takefocus=0, command=self.hide).pack(side='right', - padx=px(6)) - # 同一套键盘的两个视图,随时切,不会把键盘弄丢 - self.btn_mode = tk.Button(bar, text='✍ 手写', font=self._fs(11), - bd=0, bg='#dbe7f6', fg='#185fa5', - activebackground='#c8daf0', cursor='hand2', - takefocus=0, padx=px(10), - command=self._toggle_mode) - self.btn_mode.pack(side='right', padx=px(4)) - # 登录页专用:打完密码不用收键盘,直接点这里登录 - self.btn_go = tk.Button(bar, text='登 录 →', font=self._fs(11), - bd=0, bg='#0f6e56', fg='white', - activebackground='#0b5544', - activeforeground='white', cursor='hand2', - takefocus=0, padx=px(12), - command=self._go_login) - - self.body = tk.Frame(self.win, bg=BG) - self.body.pack(fill='both', expand=True) - self.view_abc = tk.Frame(self.body, bg=BG) - self.view_hand = tk.Frame(self.body, bg=BG) - self._build_abc(self.view_abc) - self._build_hand(self.view_hand) - self.view_abc.pack(fill='both', expand=True) - - self._built = True - self._refresh_case() - - def _build_abc(self, parent): - r = self._line(parent, 54) - for ch in ROW_NUM: - self._key(r, ch, lambda c=ch: self._tap(c)) - r = self._line(parent, 54) - for ch in ROW_Q: - self._key(r, ch, lambda c=ch: self._tap(c)) - r = self._line(parent, 54) - for ch in ROW_A: - self._key(r, ch, lambda c=ch: self._tap(c)) - r = self._line(parent, 54) - self.btn_shift = self._key(r, '⇧', self._toggle_shift, bg=FN_BG) - for ch in ROW_Z: - self._key(r, ch, lambda c=ch: self._tap(c)) - r = self._line(parent, 54) - self._key(r, '空格', lambda: self._tap(' '), bg=FN_BG, size=13) - self._key(r, '⌫ 退格', self._backspace, bg=FN_BG, size=13) - self._key(r, '清空', self._clear, bg=FN_BG, size=13) - self._key(r, '下一个', self._next_field, bg=FN_BG, size=13) - self._key(r, '完成 ✓', self.hide, bg=OK_BG, fg='white', size=14) - - def _build_hand(self, parent): - px = self._px - # 底部功能行(手写时退格/清空照样能用) - bar = tk.Frame(parent, bg=BG) - bar.pack(side='bottom', fill='x', padx=px(6), pady=(0, px(4))) - self._key(bar, '⌫ 退格', self._backspace, bg=FN_BG, size=13) - self._key(bar, '清空重写', self._hand_clear, bg=FN_BG, size=13) - self._key(bar, '重新识别', lambda: self._hand_recognize(force=True), - bg=FN_BG, size=13) - self._key(bar, '完成 ✓', self._hand_finish, bg=OK_BG, fg='white', - size=14) - - wrap = tk.Frame(parent, bg=BG) - wrap.pack(fill='both', expand=True, padx=px(6), pady=(px(2), 0)) - - # 右侧:识别候选 - side = tk.Frame(wrap, bg='#eef3fa', width=px(248)) - side.pack(side='right', fill='y', padx=(px(8), px(2))) - side.pack_propagate(False) - tk.Label(side, text='识别结果 · 点一下填入', font=self._fs(10), - bg='#eef3fa', fg='#41505f', anchor='w').pack( - anchor='w', padx=px(10), pady=(px(6), px(2))) - self.cand_box = tk.Frame(side, bg='#eef3fa') - self.cand_box.pack(fill='both', expand=True, padx=px(6)) - self.cand_tip = tk.Label(side, text='写完停一下自动识别', - font=self._fs(9, False), bg='#eef3fa', - fg='#8a94a3', anchor='w', justify='left', - wraplength=px(222)) - self.cand_tip.pack(side='bottom', fill='x', padx=px(10), pady=px(4)) - - # 左侧:手写板 - left = tk.Frame(wrap, bg=BG) - left.pack(side='left', fill='both', expand=True) - self.cv = tk.Canvas(left, bg='#ffffff', highlightthickness=2, - highlightbackground='#b9c7d8', cursor='pencil') - self.cv.pack(fill='both', expand=True, padx=px(2), pady=px(2)) - self.cv.bind('', self._pen_down) - self.cv.bind('', self._pen_move) - self.cv.bind('', self._pen_up) - self.cv.bind('', self._hand_bg) - - # ---------------------------------------------------------------- 视图 - def set_mode(self, mode): - mode = 'hand' if str(mode or '').lower().startswith('hand') else 'abc' - self.mode = mode - try: - if mode == 'hand': - self.view_abc.pack_forget() - self.view_hand.pack(fill='both', expand=True) - self.btn_mode.configure(text='⌨ ABC 键盘') - else: - self.view_hand.pack_forget() - self.view_abc.pack(fill='both', expand=True) - self.btn_mode.configure(text='✍ 手写') - self._place() - self._update_tip() - except Exception: - pass - - def _toggle_mode(self): - self.set_mode('abc' if self.mode == 'hand' else 'hand') - - # ---------------------------------------------------------------- 显示 - def alive(self): - try: - return bool(self.win.winfo_exists()) - except Exception: - return False - - def show(self, target=None, mode=None): - if target is not None: - self.target = target - if self.target is None: - self.target = self.app._current_input() - if mode is None: - mode = getattr(self.target, '_kb_mode', 'abc') \ - if self.target is not None else 'abc' - self.set_mode(mode) - self._detach_grab() - try: - self.win.deiconify() - self.win.lift() - self.win.attributes('-topmost', True) - except Exception: - pass - self._refresh_case() - # 登录页才显示"登录"快捷键(主界面没有这个动作) - try: - if (not getattr(self.app, 'ready', True)) \ - and getattr(self.app, 'ent_pwd', None) is not None: - self.btn_go.pack(side='right', padx=self._px(6)) - else: - self.btn_go.pack_forget() - except Exception: - pass - self._update_tip() - - def _detach_grab(self): - """对话框开了 grab_set 时,键盘点不动(事件全被模态窗口吞掉)。 - - 打开键盘前把 grab 摘下来,收起时再还回去——对话框是程序自己的, - 让出这一小会儿没有副作用。 - """ - try: - g = self.win.grab_current() - if g is not None and g is not self.win: - self._prev_grab = g - g.grab_release() - except Exception: - pass - - def _restore_grab(self): - g = getattr(self, '_prev_grab', None) - self._prev_grab = None - try: - if g is not None and g.winfo_exists(): - g.grab_set() - except Exception: - pass - - def is_visible(self): - try: - return bool(self.win.winfo_exists() and self.win.winfo_viewable()) - except Exception: - return False - - def hide(self): - self._cancel_hand_job() - self._finish_after_recog = False - try: - self.win.withdraw() - except Exception: - pass - self._restore_grab() - # 收起后把焦点还给输入框,方便外接键盘继续输入 - try: - if self.target is not None and self.target.winfo_exists(): - self.target.focus_set() - except Exception: - pass - - def _update_tip(self): - name = '' - try: - if self.target is not None: - name = getattr(self.target, '_field_label', '') or '' - except Exception: - name = '' - base = '手写键盘' if self.mode == 'hand' else '屏幕键盘' - if name: - base += ' · 输入到「%s」' % name - try: - self.lbl_tip.configure(text=base, fg='#41505f') - except Exception: - pass - - def _place(self): - p = self.parent - try: - pw, ph = p.winfo_width(), p.winfo_height() - rx, ry = p.winfo_rootx(), p.winfo_rooty() - if pw < 200 or ph < 200: # 还没完成布局 - pw, ph = p.winfo_screenwidth(), p.winfo_screenheight() - rx = ry = 0 - except Exception: - pw, ph, rx, ry = 1440, 900, 0, 0 - w = max(760, min(pw - 16, int(1240 * self.S))) - h = int((H_HAND if self.mode == 'hand' else H_ABC) * self.S) - x = rx + (pw - w) // 2 - y = ry + ph - h - 6 - # 别压住正在输入的那个框:默认贴窗口底,压住就挪到框下面/上面 - try: - t = self.target - if t is not None and t.winfo_exists(): - t_top = t.winfo_rooty() - t_bot = t_top + t.winfo_height() - sh = self.win.winfo_screenheight() - if t_bot + 4 > y and t_top < y + h: - below, above = t_bot + 8, t_top - h - 8 - if below + h <= sh - 8: - y = below - elif above >= 0: - y = above - except Exception: - pass - self.win.geometry('%dx%d+%d+%d' % (w, h, x, max(0, y))) - - # ---------------------------------------------------------------- 输入 - def _t(self): - t = self.target - try: - ok = t is not None and t.winfo_exists() - except Exception: - ok = False - if not ok: - # 没指定目标时跟着"最后点过的输入框"走,先点框再按键也能输入 - t = self.app._current_input() - self.target = t - return t - - def _is_text(self, w): - try: - return w.winfo_class() == 'Text' - except Exception: - return False - - def _prepare_target(self, t): - """写入/删字前若目标框正挂着灰色占位提示,先清掉占位,避免字插到占位前面。""" - try: - if (t is getattr(self.app, 'ent_search', None) - and getattr(self.app, '_search_ph_on', False)): - self.app._search_focus_in() - except Exception: - pass - - def _tap(self, ch): - t = self._t() - if t is None: - return - self._prepare_target(t) - c = ch.upper() if self.shift and ch.isalpha() else ch - try: - if not self._is_text(t): - # Entry:有选中就先替换掉 - try: - if t.selection_present(): - t.delete('sel.first', 'sel.last') - except Exception: - pass - t.insert('insert', c) - except Exception: - return - if self.shift: - self.shift = False - self._refresh_case() - - def _backspace(self): - t = self._t() - if t is None: - return - self._prepare_target(t) - try: - if not self._is_text(t): - if t.selection_present(): - t.delete('sel.first', 'sel.last') - return - i = t.index('insert') - if i > 0: - t.delete(i - 1, i) - else: - t.delete('insert-1c', 'insert') - except Exception: - pass - - def _clear(self): - t = self._t() - if t is None: - return - self._prepare_target(t) - try: - if self._is_text(t): - t.delete('1.0', 'end') - else: - t.delete(0, 'end') - except Exception: - pass - - def _next_field(self): - t = self._t() - if t is None: - return - try: - nxt = t.tk_focusNext() - if nxt is not None and nxt.winfo_class() in ('Entry', 'TEntry', - 'Text'): - self.target = nxt - nxt.focus_set() - self.show(nxt) - except Exception: - pass - - def _toggle_shift(self): - self.shift = not self.shift - self._refresh_case() - - def _refresh_case(self): - try: - self.btn_shift.configure( - bg='#185fa5' if self.shift else FN_BG, - fg='white' if self.shift else KEY_FG) - except Exception: - pass - # 字母键大小写跟着变,触摸屏看得见当前状态 - try: - for row in self.view_abc.winfo_children(): - for b in row.winfo_children(): - txt = b.cget('text') - if len(txt) == 1 and txt.isalpha(): - b.configure(text=txt.upper() if self.shift - else txt.lower()) - except Exception: - pass - - def _go_login(self): - """登录页:收起键盘并直接提交登录。""" - self.hide() - try: - self.app._do_login() - except Exception: - pass - - # ---------------------------------------------------------------- 手写 - def _hand_hints(self): - """把当前待办的商品名当提示词,手写命中率能高不少。""" - try: - rows = getattr(self.app, '_all_rows', None) or [] - names = [] - for r in rows[:80]: - n = str(r.get('item_name') or '').strip() - if n and n not in names: - names.append(n) - return names[:40] - except Exception: - return None - - def _hand_bg(self, e=None): - try: - w = e.width if e is not None else self.cv.winfo_width() - h = e.height if e is not None else self.cv.winfo_height() - except Exception: - return - try: - self.cv.delete('bg') - self.cv.create_line(w / 2, 10, w / 2, h - 10, fill='#eef2f7', - width=2, tags='bg') - if not self._strokes: - self.cv.create_text(w / 2, h / 2, text='在这里手写中文', - fill='#c3ccd8', font=self._fs(16), - tags='bg') - self.cv.tag_lower('bg') - except Exception: - pass - - def _pen_down(self, e): - self._cancel_hand_job() - self._finish_after_recog = False - self._candidates = [] - self._cur = [(e.x, e.y)] - self._strokes.append(self._cur) - try: - self.cv.delete('bg') - r = max(2, self._px(3)) - self.cv.create_oval(e.x - r, e.y - r, e.x + r, e.y + r, - fill=INK, outline=INK, tags='ink') - except Exception: - pass - self._set_cand_tip('写字中…') - - def _pen_move(self, e): - if not self._cur: - return - x0, y0 = self._cur[-1] - self._cur.append((e.x, e.y)) - try: - self.cv.create_line(x0, y0, e.x, e.y, fill=INK, - width=max(3, self._px(4)), - capstyle='round', tags='ink') - except Exception: - pass - - def _pen_up(self, e): - self._cur = None - if self._strokes: - self._cancel_hand_job() - self._hand_job = self.win.after(900, self._hand_recognize) - - def _cancel_hand_job(self): - if self._hand_job is not None: - try: - self.win.after_cancel(self._hand_job) - except Exception: - pass - self._hand_job = None - - def _set_cand_tip(self, text, color='#8a94a3'): - try: - self.cand_tip.configure(text=text, fg=color) - except Exception: - pass - - def _hand_recognize(self, force=False): - self._hand_job = None - if self._recognizing or not self._strokes: - return - self._recognizing = True - self._set_cand_tip('识别中…', '#185fa5') - # 笔画拷一份给线程,避免用户此时继续写导致数据打架 - strokes = [[tuple(p) for p in s] for s in self._strokes] - size = (self.cv.winfo_width(), self.cv.winfo_height()) - hints = self._hand_hints() - cfg = getattr(self.app, 'cfg', {}) or {} - - def work(): - try: - import core.handwrite as hw - res = hw.recognize(strokes, size, cfg, hints=hints) - self._hand_q.put(('ok', res)) - except Exception as ex: # noqa: BLE001 - self._hand_q.put(('err', str(ex))) - - threading.Thread(target=work, daemon=True).start() - self._poll_hand() - - def _poll_hand(self): - """识别结果只能在主线程碰界面:后台线程写队列,这里 poll。""" - try: - kind, data = self._hand_q.get_nowait() - except queue.Empty: - try: - self.win.after(120, self._poll_hand) - except Exception: - pass - return - self._recognizing = False - finish = self._finish_after_recog - self._finish_after_recog = False - if kind == 'err': - self._set_cand_tip('识别失败:%s\n可点「重新识别」,或切 ABC 键盘' - % str(data)[:60], '#a32d2d') - return - items = [x for x in (data or []) if x] - if not items: - self._set_cand_tip('没认出来,擦掉重写一次', '#a32d2d') - return - self._show_candidates(items) - if finish: - self._pick(items[0]) - self.hide() - - def _show_candidates(self, items): - self._candidates = list(items or []) - try: - for w in self.cand_box.winfo_children(): - w.destroy() - for it in self._candidates: - b = tk.Button(self.cand_box, text=it, font=self._fs(15), - bd=0, bg='#ffffff', fg='#17334f', - activebackground='#cfe0f5', cursor='hand2', - takefocus=0, - command=lambda s=it: self._pick(s)) - b.pack(fill='x', pady=self._px(3), ipady=self._px(5)) - except Exception: - return - self._set_cand_tip('点一下或点「完成」填进输入框') - - def _hand_finish(self): - """手写视图点「完成 ✓」:若有未提交的识别结果则自动填入首候选,再收起。""" - if self._candidates: - self._pick(self._candidates[0]) - self.hide() - return - if self._strokes: - self._finish_after_recog = True - self._cancel_hand_job() - if not self._recognizing: - self._hand_recognize(force=True) - return - self.hide() - - def _pick(self, text): - t = self._t() - if t is None: - self._set_cand_tip('没有输入框可写,先点一下输入框', '#a32d2d') - return - self._prepare_target(t) - try: - if not self._is_text(t): - try: - if t.selection_present(): - t.delete('sel.first', 'sel.last') - except Exception: - pass - t.insert('insert', text) - except Exception: - return - self._hand_clear() - self._set_cand_tip('已填入「%s」,接着写或收起键盘' % text, '#0f6e56') - - def _hand_clear(self): - self._cancel_hand_job() - self._finish_after_recog = False - self._strokes = [] - self._cur = None - self._candidates = [] - try: - self.cv.delete('ink') - except Exception: - pass - try: - for w in self.cand_box.winfo_children(): - w.destroy() - except Exception: - pass - self._set_cand_tip('写完停一下自动识别') - self._hand_bg() +# -*- coding: utf-8 -*- +"""内置触摸软键盘(不依赖 Windows 触摸键盘服务)。 + +同一套键盘两个视图,顶栏一键来回切: + · ABC 英文 + 数字(账号 / 密码 / 参数) + · 手写 中文手写(搜索框),写完自动识别;旁边照样有退格、清空 + +现场问题:工控机上 `TabTip.exe` 进程常驻,但窗口永远不显示 +(`ITipInvocation.Toggle` 和 `ShowWindow` 都唤不起来),`osk.exe` 从普通 +权限进程启动会直接 WinError 740;本机也没有 Tablet PC 的手写 COM。 +所以自绘:点了一定出现,按键直接写进目标输入框,手写自己采笔画交给视觉 +模型读字(见 core/handwrite.py)。 + +每个输入框可以带 `_kb_mode`('abc' / 'hand'),点进去就按它的默认视图弹出。 +""" +import queue +import threading +import tkinter as tk + +# 每行键位:数字行覆盖账号/密码/称重场景,字母区带常用符号 +ROW_NUM = list('1234567890-=') +ROW_Q = list('qwertyuiop') +ROW_A = list('asdfghjkl') +ROW_Z = list('zxcvbnm') + ['.', '_', '@'] + +BG = '#dbe3ee' +KEY_BG = '#ffffff' +KEY_FG = '#17334f' +FN_BG = '#e8eef7' +OK_BG = '#185fa5' +INK = '#17334f' + +H_ABC = 322 # 键盘高度(逻辑值,实际按缩放算) +H_HAND = 352 + + +class SoftKeyboard: + """贴在主窗口底部的屏幕键盘(单例,由 App 持有)。""" + + def __init__(self, parent, app, scale=1.0): + self.parent = parent + self.app = app + self.S = max(0.7, min(2.0, scale or 1.0)) + self.target = None # 当前写入目标(Entry / Text) + self.shift = False + self.mode = 'abc' + self._built = False + # 手写状态 + self._strokes = [] + self._cur = None + self._recognizing = False + self._hand_job = None + self._candidates = [] + self._finish_after_recog = False + self._hand_q = queue.Queue() + self.win = tk.Toplevel(parent) + self.win.withdraw() + self.win.overrideredirect(True) + self.win.configure(bg=BG) + try: + self.win.attributes('-topmost', True) + except Exception: + pass + self._build() + self.win.bind('', lambda e: self.hide()) + + # ---------------------------------------------------------------- 构建 + def _px(self, n): + return max(1, int(round(n * self.S))) + + def _fs(self, size, bold=True): + return ('Microsoft YaHei', max(11, int(round(size * self.S))), + 'bold' if bold else 'normal') + + def _key(self, row, text, cmd, bg=KEY_BG, fg=KEY_FG, size=15): + b = tk.Button(row, text=text, command=cmd, bd=0, bg=bg, fg=fg, + activebackground='#cfe0f5', activeforeground=fg, + font=self._fs(size), cursor='hand2', takefocus=0) + b.pack(side='left', fill='both', expand=True, padx=2, pady=2) + return b + + def _line(self, parent, h): + f = tk.Frame(parent, bg=BG, height=int(h * self.S)) + f.pack(fill='x') + f.pack_propagate(False) + return f + + def _build(self): + px = self._px + + # ---- 顶部条:说明 + 模式切换 + 收起 ---- + bar = tk.Frame(self.win, bg='#c9d6e6', height=px(40)) + bar.pack(fill='x') + bar.pack_propagate(False) + self.lbl_tip = tk.Label(bar, text='屏幕键盘', font=self._fs(11), + bg='#c9d6e6', fg='#41505f', anchor='w') + self.lbl_tip.pack(side='left', padx=px(12)) + tk.Button(bar, text='收起 ⌄', font=self._fs(11), bd=0, bg='#c9d6e6', + fg='#41505f', activebackground='#b8c8dd', cursor='hand2', + takefocus=0, command=self.hide).pack(side='right', + padx=px(6)) + # 同一套键盘的两个视图,随时切,不会把键盘弄丢 + self.btn_mode = tk.Button(bar, text='✍ 手写', font=self._fs(11), + bd=0, bg='#dbe7f6', fg='#185fa5', + activebackground='#c8daf0', cursor='hand2', + takefocus=0, padx=px(10), + command=self._toggle_mode) + self.btn_mode.pack(side='right', padx=px(4)) + # 登录页专用:打完密码不用收键盘,直接点这里登录 + self.btn_go = tk.Button(bar, text='登 录 →', font=self._fs(11), + bd=0, bg='#0f6e56', fg='white', + activebackground='#0b5544', + activeforeground='white', cursor='hand2', + takefocus=0, padx=px(12), + command=self._go_login) + + self.body = tk.Frame(self.win, bg=BG) + self.body.pack(fill='both', expand=True) + self.view_abc = tk.Frame(self.body, bg=BG) + self.view_hand = tk.Frame(self.body, bg=BG) + self._build_abc(self.view_abc) + self._build_hand(self.view_hand) + self.view_abc.pack(fill='both', expand=True) + + self._built = True + self._refresh_case() + + def _build_abc(self, parent): + r = self._line(parent, 54) + for ch in ROW_NUM: + self._key(r, ch, lambda c=ch: self._tap(c)) + r = self._line(parent, 54) + for ch in ROW_Q: + self._key(r, ch, lambda c=ch: self._tap(c)) + r = self._line(parent, 54) + for ch in ROW_A: + self._key(r, ch, lambda c=ch: self._tap(c)) + r = self._line(parent, 54) + self.btn_shift = self._key(r, '⇧', self._toggle_shift, bg=FN_BG) + for ch in ROW_Z: + self._key(r, ch, lambda c=ch: self._tap(c)) + r = self._line(parent, 54) + self._key(r, '空格', lambda: self._tap(' '), bg=FN_BG, size=13) + self._key(r, '⌫ 退格', self._backspace, bg=FN_BG, size=13) + self._key(r, '清空', self._clear, bg=FN_BG, size=13) + self._key(r, '下一个', self._next_field, bg=FN_BG, size=13) + self._key(r, '完成 ✓', self.hide, bg=OK_BG, fg='white', size=14) + + def _build_hand(self, parent): + px = self._px + # 底部功能行(手写时退格/清空照样能用) + bar = tk.Frame(parent, bg=BG) + bar.pack(side='bottom', fill='x', padx=px(6), pady=(0, px(4))) + self._key(bar, '⌫ 退格', self._backspace, bg=FN_BG, size=13) + self._key(bar, '清空重写', self._hand_clear, bg=FN_BG, size=13) + self._key(bar, '重新识别', lambda: self._hand_recognize(force=True), + bg=FN_BG, size=13) + self._key(bar, '完成 ✓', self._hand_finish, bg=OK_BG, fg='white', + size=14) + + wrap = tk.Frame(parent, bg=BG) + wrap.pack(fill='both', expand=True, padx=px(6), pady=(px(2), 0)) + + # 右侧:识别候选 + side = tk.Frame(wrap, bg='#eef3fa', width=px(248)) + side.pack(side='right', fill='y', padx=(px(8), px(2))) + side.pack_propagate(False) + tk.Label(side, text='识别结果 · 点一下填入', font=self._fs(10), + bg='#eef3fa', fg='#41505f', anchor='w').pack( + anchor='w', padx=px(10), pady=(px(6), px(2))) + self.cand_box = tk.Frame(side, bg='#eef3fa') + self.cand_box.pack(fill='both', expand=True, padx=px(6)) + self.cand_tip = tk.Label(side, text='写完停一下自动识别', + font=self._fs(9, False), bg='#eef3fa', + fg='#8a94a3', anchor='w', justify='left', + wraplength=px(222)) + self.cand_tip.pack(side='bottom', fill='x', padx=px(10), pady=px(4)) + + # 左侧:手写板 + left = tk.Frame(wrap, bg=BG) + left.pack(side='left', fill='both', expand=True) + self.cv = tk.Canvas(left, bg='#ffffff', highlightthickness=2, + highlightbackground='#b9c7d8', cursor='pencil') + self.cv.pack(fill='both', expand=True, padx=px(2), pady=px(2)) + self.cv.bind('', self._pen_down) + self.cv.bind('', self._pen_move) + self.cv.bind('', self._pen_up) + self.cv.bind('', self._hand_bg) + + # ---------------------------------------------------------------- 视图 + def set_mode(self, mode): + mode = 'hand' if str(mode or '').lower().startswith('hand') else 'abc' + self.mode = mode + try: + if mode == 'hand': + self.view_abc.pack_forget() + self.view_hand.pack(fill='both', expand=True) + self.btn_mode.configure(text='⌨ ABC 键盘') + else: + self.view_hand.pack_forget() + self.view_abc.pack(fill='both', expand=True) + self.btn_mode.configure(text='✍ 手写') + self._place() + self._update_tip() + except Exception: + pass + + def _toggle_mode(self): + self.set_mode('abc' if self.mode == 'hand' else 'hand') + + # ---------------------------------------------------------------- 显示 + def alive(self): + try: + return bool(self.win.winfo_exists()) + except Exception: + return False + + def show(self, target=None, mode=None): + if target is not None: + self.target = target + if self.target is None: + self.target = self.app._current_input() + if mode is None: + mode = getattr(self.target, '_kb_mode', 'abc') \ + if self.target is not None else 'abc' + self.set_mode(mode) + self._detach_grab() + try: + self.win.deiconify() + self.win.lift() + self.win.attributes('-topmost', True) + except Exception: + pass + self._refresh_case() + # 登录页才显示"登录"快捷键(主界面没有这个动作) + try: + if (not getattr(self.app, 'ready', True)) \ + and getattr(self.app, 'ent_pwd', None) is not None: + self.btn_go.pack(side='right', padx=self._px(6)) + else: + self.btn_go.pack_forget() + except Exception: + pass + self._update_tip() + + def _detach_grab(self): + """对话框开了 grab_set 时,键盘点不动(事件全被模态窗口吞掉)。 + + 打开键盘前把 grab 摘下来,收起时再还回去——对话框是程序自己的, + 让出这一小会儿没有副作用。 + """ + try: + g = self.win.grab_current() + if g is not None and g is not self.win: + self._prev_grab = g + g.grab_release() + except Exception: + pass + + def _restore_grab(self): + g = getattr(self, '_prev_grab', None) + self._prev_grab = None + try: + if g is not None and g.winfo_exists(): + g.grab_set() + except Exception: + pass + + def is_visible(self): + try: + return bool(self.win.winfo_exists() and self.win.winfo_viewable()) + except Exception: + return False + + def hide(self): + self._cancel_hand_job() + self._finish_after_recog = False + try: + self.win.withdraw() + except Exception: + pass + self._restore_grab() + # 收起后把焦点还给输入框,方便外接键盘继续输入 + try: + if self.target is not None and self.target.winfo_exists(): + self.target.focus_set() + except Exception: + pass + + def _update_tip(self): + name = '' + try: + if self.target is not None: + name = getattr(self.target, '_field_label', '') or '' + except Exception: + name = '' + base = '手写键盘' if self.mode == 'hand' else '屏幕键盘' + if name: + base += ' · 输入到「%s」' % name + try: + self.lbl_tip.configure(text=base, fg='#41505f') + except Exception: + pass + + def _place(self): + p = self.parent + try: + pw, ph = p.winfo_width(), p.winfo_height() + rx, ry = p.winfo_rootx(), p.winfo_rooty() + if pw < 200 or ph < 200: # 还没完成布局 + pw, ph = p.winfo_screenwidth(), p.winfo_screenheight() + rx = ry = 0 + except Exception: + pw, ph, rx, ry = 1440, 900, 0, 0 + w = max(760, min(pw - 16, int(1240 * self.S))) + h = int((H_HAND if self.mode == 'hand' else H_ABC) * self.S) + x = rx + (pw - w) // 2 + y = ry + ph - h - 6 + # 别压住正在输入的那个框:默认贴窗口底,压住就挪到框下面/上面 + try: + t = self.target + if t is not None and t.winfo_exists(): + t_top = t.winfo_rooty() + t_bot = t_top + t.winfo_height() + sh = self.win.winfo_screenheight() + if t_bot + 4 > y and t_top < y + h: + below, above = t_bot + 8, t_top - h - 8 + if below + h <= sh - 8: + y = below + elif above >= 0: + y = above + except Exception: + pass + self.win.geometry('%dx%d+%d+%d' % (w, h, x, max(0, y))) + + # ---------------------------------------------------------------- 输入 + def _t(self): + t = self.target + try: + ok = t is not None and t.winfo_exists() + except Exception: + ok = False + if not ok: + # 没指定目标时跟着"最后点过的输入框"走,先点框再按键也能输入 + t = self.app._current_input() + self.target = t + return t + + def _is_text(self, w): + try: + return w.winfo_class() == 'Text' + except Exception: + return False + + def _prepare_target(self, t): + """写入/删字前若目标框正挂着灰色占位提示,先清掉占位,避免字插到占位前面。""" + try: + if (t is getattr(self.app, 'ent_search', None) + and getattr(self.app, '_search_ph_on', False)): + self.app._search_focus_in() + except Exception: + pass + + def _tap(self, ch): + t = self._t() + if t is None: + return + self._prepare_target(t) + c = ch.upper() if self.shift and ch.isalpha() else ch + try: + if not self._is_text(t): + # Entry:有选中就先替换掉 + try: + if t.selection_present(): + t.delete('sel.first', 'sel.last') + except Exception: + pass + t.insert('insert', c) + except Exception: + return + if self.shift: + self.shift = False + self._refresh_case() + + def _backspace(self): + t = self._t() + if t is None: + return + self._prepare_target(t) + try: + if not self._is_text(t): + if t.selection_present(): + t.delete('sel.first', 'sel.last') + return + i = t.index('insert') + if i > 0: + t.delete(i - 1, i) + else: + t.delete('insert-1c', 'insert') + except Exception: + pass + + def _clear(self): + t = self._t() + if t is None: + return + self._prepare_target(t) + try: + if self._is_text(t): + t.delete('1.0', 'end') + else: + t.delete(0, 'end') + except Exception: + pass + + def _next_field(self): + t = self._t() + if t is None: + return + try: + nxt = t.tk_focusNext() + if nxt is not None and nxt.winfo_class() in ('Entry', 'TEntry', + 'Text'): + self.target = nxt + nxt.focus_set() + self.show(nxt) + except Exception: + pass + + def _toggle_shift(self): + self.shift = not self.shift + self._refresh_case() + + def _refresh_case(self): + try: + self.btn_shift.configure( + bg='#185fa5' if self.shift else FN_BG, + fg='white' if self.shift else KEY_FG) + except Exception: + pass + # 字母键大小写跟着变,触摸屏看得见当前状态 + try: + for row in self.view_abc.winfo_children(): + for b in row.winfo_children(): + txt = b.cget('text') + if len(txt) == 1 and txt.isalpha(): + b.configure(text=txt.upper() if self.shift + else txt.lower()) + except Exception: + pass + + def _go_login(self): + """登录页:收起键盘并直接提交登录。""" + self.hide() + try: + self.app._do_login() + except Exception: + pass + + # ---------------------------------------------------------------- 手写 + def _hand_hints(self): + """把当前待办的商品名当提示词,手写命中率能高不少。""" + try: + rows = getattr(self.app, '_all_rows', None) or [] + names = [] + for r in rows[:80]: + n = str(r.get('item_name') or '').strip() + if n and n not in names: + names.append(n) + return names[:40] + except Exception: + return None + + def _hand_bg(self, e=None): + try: + w = e.width if e is not None else self.cv.winfo_width() + h = e.height if e is not None else self.cv.winfo_height() + except Exception: + return + try: + self.cv.delete('bg') + self.cv.create_line(w / 2, 10, w / 2, h - 10, fill='#eef2f7', + width=2, tags='bg') + if not self._strokes: + self.cv.create_text(w / 2, h / 2, text='在这里手写中文', + fill='#c3ccd8', font=self._fs(16), + tags='bg') + self.cv.tag_lower('bg') + except Exception: + pass + + def _pen_down(self, e): + self._cancel_hand_job() + self._finish_after_recog = False + self._candidates = [] + self._cur = [(e.x, e.y)] + self._strokes.append(self._cur) + try: + self.cv.delete('bg') + r = max(2, self._px(3)) + self.cv.create_oval(e.x - r, e.y - r, e.x + r, e.y + r, + fill=INK, outline=INK, tags='ink') + except Exception: + pass + self._set_cand_tip('写字中…') + + def _pen_move(self, e): + if not self._cur: + return + x0, y0 = self._cur[-1] + self._cur.append((e.x, e.y)) + try: + self.cv.create_line(x0, y0, e.x, e.y, fill=INK, + width=max(3, self._px(4)), + capstyle='round', tags='ink') + except Exception: + pass + + def _pen_up(self, e): + self._cur = None + if self._strokes: + self._cancel_hand_job() + self._hand_job = self.win.after(900, self._hand_recognize) + + def _cancel_hand_job(self): + if self._hand_job is not None: + try: + self.win.after_cancel(self._hand_job) + except Exception: + pass + self._hand_job = None + + def _set_cand_tip(self, text, color='#8a94a3'): + try: + self.cand_tip.configure(text=text, fg=color) + except Exception: + pass + + def _hand_recognize(self, force=False): + self._hand_job = None + if self._recognizing or not self._strokes: + return + self._recognizing = True + self._set_cand_tip('识别中…', '#185fa5') + # 笔画拷一份给线程,避免用户此时继续写导致数据打架 + strokes = [[tuple(p) for p in s] for s in self._strokes] + size = (self.cv.winfo_width(), self.cv.winfo_height()) + hints = self._hand_hints() + cfg = getattr(self.app, 'cfg', {}) or {} + + def work(): + try: + import core.handwrite as hw + res = hw.recognize(strokes, size, cfg, hints=hints) + self._hand_q.put(('ok', res)) + except Exception as ex: # noqa: BLE001 + self._hand_q.put(('err', str(ex))) + + threading.Thread(target=work, daemon=True).start() + self._poll_hand() + + def _poll_hand(self): + """识别结果只能在主线程碰界面:后台线程写队列,这里 poll。""" + try: + kind, data = self._hand_q.get_nowait() + except queue.Empty: + try: + self.win.after(120, self._poll_hand) + except Exception: + pass + return + self._recognizing = False + finish = self._finish_after_recog + self._finish_after_recog = False + if kind == 'err': + self._set_cand_tip('识别失败:%s\n可点「重新识别」,或切 ABC 键盘' + % str(data)[:60], '#a32d2d') + return + items = [x for x in (data or []) if x] + if not items: + self._set_cand_tip('没认出来,擦掉重写一次', '#a32d2d') + return + self._show_candidates(items) + if finish: + self._pick(items[0]) + self.hide() + + def _show_candidates(self, items): + self._candidates = list(items or []) + try: + for w in self.cand_box.winfo_children(): + w.destroy() + for it in self._candidates: + b = tk.Button(self.cand_box, text=it, font=self._fs(15), + bd=0, bg='#ffffff', fg='#17334f', + activebackground='#cfe0f5', cursor='hand2', + takefocus=0, + command=lambda s=it: self._pick(s)) + b.pack(fill='x', pady=self._px(3), ipady=self._px(5)) + except Exception: + return + self._set_cand_tip('点一下或点「完成」填进输入框') + + def _hand_finish(self): + """手写视图点「完成 ✓」:若有未提交的识别结果则自动填入首候选,再收起。""" + if self._candidates: + self._pick(self._candidates[0]) + self.hide() + return + if self._strokes: + self._finish_after_recog = True + self._cancel_hand_job() + if not self._recognizing: + self._hand_recognize(force=True) + return + self.hide() + + def _pick(self, text): + t = self._t() + if t is None: + self._set_cand_tip('没有输入框可写,先点一下输入框', '#a32d2d') + return + self._prepare_target(t) + try: + if not self._is_text(t): + try: + if t.selection_present(): + t.delete('sel.first', 'sel.last') + except Exception: + pass + t.insert('insert', text) + except Exception: + return + self._hand_clear() + self._set_cand_tip('已填入「%s」,接着写或收起键盘' % text, '#0f6e56') + + def _hand_clear(self): + self._cancel_hand_job() + self._finish_after_recog = False + self._strokes = [] + self._cur = None + self._candidates = [] + try: + self.cv.delete('ink') + except Exception: + pass + try: + for w in self.cand_box.winfo_children(): + w.destroy() + except Exception: + pass + self._set_cand_tip('写完停一下自动识别') + self._hand_bg() diff --git a/ui/tablet.py b/ui/tablet.py index 462aa2d..defae19 100644 --- a/ui/tablet.py +++ b/ui/tablet.py @@ -1,1165 +1,1167 @@ -# -*- coding: utf-8 -*- -"""平板化 UI 组件(tkinter + Pillow 抗锯齿圆角,不引入第三方 UI 库)。 - -设计基准:1440×900 横屏平板 - · 触摸目标 ≥ 52px,主操作 64~72px - · 圆角 14(卡片)/ 999(胶囊按钮) - · 留白 16 / 20,字号 13 / 15 / 18 / 26 / 72 - -对外: - C 配色常量 - rounded_photo(...) 抗锯齿圆角图片(带缓存,按尺寸/颜色复用) - TouchButton 大触摸按钮(按下回弹、圆角) - Segmented 分段导航(滑块跟手 + 吸附动画) - Switch 滑动开关 - StepsBar 圆角步骤条 - Pager 可左右滑动的页面容器(跟手 + 松手吸附) - TouchScroll 手指拖动滚动(带惯性) - bind_swipe_to(...) 让普通控件也参与翻页手势 -""" -import tkinter as tk -import time as _time - -try: - from PIL import Image, ImageDraw, ImageTk - _HAS_PIL = True -except Exception: # pragma: no cover - _HAS_PIL = False - - -# ------------------------------------------------------------------ 配色 -class C: - bg = '#f4f6fa' # 页面底色 - surface = '#ffffff' # 卡片 - line = '#e6ebf2' # 分隔线 - ink = '#1b2634' # 主文字 - ink2 = '#5b6675' # 次文字 - ink3 = '#98a2b3' # 弱文字 - brand = '#1b5fa5' # 品牌蓝 - brand_dark = '#134a83' - brand_soft = '#e8f1fb' - green = '#0f6e56' - green_soft = '#e3f2ec' - amber = '#b45309' - amber_soft = '#fdf0d9' - red = '#a32d2d' - red_soft = '#fbe9e9' - track = '#e9edf4' - - -def shade(hex_color, k): - """把颜色整体调暗/调亮:k<1 变暗,k>1 变亮(保持色相)""" - hex_color = hex_color.lstrip('#') - if len(hex_color) == 3: - hex_color = ''.join(c * 2 for c in hex_color) - r = int(hex_color[0:2], 16) - g = int(hex_color[2:4], 16) - b = int(hex_color[4:6], 16) - if k <= 1: - r, g, b = int(r * k), int(g * k), int(b * k) - else: - d = k - 1.0 - r = int(r + (255 - r) * d) - g = int(g + (255 - g) * d) - b = int(b + (255 - b) * d) - return '#%02x%02x%02x' % (max(0, min(255, r)), - max(0, min(255, g)), - max(0, min(255, b))) - - -# ------------------------------------------------------------------ 圆角图片 -_SS = 3 # 超采样倍数:3 倍绘制再缩小,边缘才不毛 -_IMG_CACHE = {} -_PH_CACHE = {} - - -def _hex_rgb(h): - h = h.lstrip('#') - if len(h) == 3: - h = ''.join(c * 2 for c in h) - return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)) - - -def rounded_image(w, h, r, fill, on, outline=None, ow=1): - """返回抗锯齿圆角矩形 PIL 图;on = 背景色(用于把透明角混成实体色)""" - w, h = max(1, int(w)), max(1, int(h)) - r = max(0, int(r)) - key = (w, h, r, fill, on, outline, ow) - im = _IMG_CACHE.get(key) - if im is not None: - return im - if _HAS_PIL: - W, H, R = w * _SS, h * _SS, min(r * _SS, min(w, h) * _SS // 2) - base = Image.new('RGB', (W, H), _hex_rgb(on)) - d = ImageDraw.Draw(base) - box = [0, 0, W - 1, H - 1] - if outline and ow > 0: - d.rounded_rectangle(box, radius=R, fill=_hex_rgb(outline)) - i = int(ow * _SS) - d.rounded_rectangle([i, i, W - 1 - i, H - 1 - i], - radius=max(0, R - i), fill=_hex_rgb(fill)) - else: - d.rounded_rectangle(box, radius=R, fill=_hex_rgb(fill)) - im = base.resize((w, h), Image.LANCZOS) - else: # 没有 Pillow 就退化成直角块 - im = None - _IMG_CACHE[key] = im - return im - - -def rounded_photo(w, h, r, fill, on, outline=None, ow=1): - """转成 Tk 可用的 PhotoImage(全局缓存,避免每次重绘都新建位图)""" - w, h = max(1, int(w)), max(1, int(h)) - key = (w, h, r, fill, on, outline, ow) - ph = _PH_CACHE.get(key) - if ph is not None: - return ph - im = rounded_image(w, h, r, fill, on, outline, ow) - if im is None or not _HAS_PIL: - return None - try: - ph = ImageTk.PhotoImage(im) - except Exception: - return None - _PH_CACHE[key] = ph - return ph - - -def draw_round(cv, x1, y1, x2, y2, r, fill, outline='', width=1, tags=''): - """Canvas 上画圆角块(无 Pillow 时的兜底 / 小装饰用)""" - r = max(0, min(r, (x2 - x1) // 2, (y2 - y1) // 2)) - pts = [x1 + r, y1, x2 - r, y1, x2, y1, x2, y1 + r, - x2, y2 - r, x2, y2, x2 - r, y2, x1 + r, y2, - x1, y2, x1, y2 - r, x1, y1 + r, x1, y1] - return cv.create_polygon(pts, smooth=True, splinesteps=16, fill=fill, - outline=outline, width=width, tags=tags) - - -# ------------------------------------------------------------------ 触摸按钮 -class TouchButton(tk.Canvas): - """圆角大按钮:按下变深并轻微下沉,松手回弹再执行。 - - 参数按「平板尺寸」给:height 默认 64,最小建议 52。 - """ - - def __init__(self, parent, text='', command=None, fill=C.brand, - fg='#ffffff', surface=None, height=64, radius=None, - font=None, sub='', sub_font=None, width=None, - enabled=True, outline=None, pad=18, anchor='center', - icon='', icon_font=None, **kw): - surface = surface or _surface_of(parent) - super().__init__(parent, bg=surface, highlightthickness=0, bd=0, - height=height, width=width or 10, takefocus=0, **kw) - self._text = text - self._icon = icon - self._sub = sub - self._command = command - self._fill = fill - self._fg = fg - self._surface = surface - self._radius = radius if radius is not None else min(18, height // 2) - self._font = font or ('Microsoft YaHei', 16, 'bold') - self._sub_font = sub_font or ('Microsoft YaHei', 11) - self._icon_font = icon_font or ('Microsoft YaHei', 20) - self._enabled = bool(enabled) - self._outline = outline - self._pad = pad - self._anchor = anchor - self._pressed = False - self._hover = False - self._last_size = (0, 0) - self.bind('', self._on_configure) - self.bind('', self._on_press) - self.bind('', self._on_release) - self.bind('', self._on_enter) - self.bind('', self._on_leave) - self.bind('', lambda e: None) - - # -- 外部接口 - def configure_btn(self, **kw): - for k, v in kw.items(): - if k == 'text': - self._text = v - elif k == 'sub': - self._sub = v - elif k == 'fill': - self._fill = v - elif k == 'bg': - self._fill = v - elif k == 'fg': - self._fg = v - elif k == 'enabled': - self._enabled = bool(v) - elif k == 'state': - self._enabled = (v != 'disabled') - elif k == 'command': - self._command = v - elif k == 'icon': - self._icon = v - self._draw() - - def configure(self, cnf=None, **kw): - """兼容 tk 的 configure:业务属性走自绘,其余(宽度/位置)交给 Canvas""" - mine, rest = {}, {} - for k, v in kw.items(): - if k in ('text', 'sub', 'fill', 'bg', 'fg', 'enabled', - 'state', 'command', 'icon'): - mine[k] = v - else: - rest[k] = v - if mine: - self.configure_btn(**mine) - if rest or cnf: - tk.Canvas.configure(self, cnf, **rest) - - config = configure - - def set_text(self, text): - self._text = text - self._draw() - - def set_enabled(self, on=True): - self._enabled = bool(on) - self._draw() - - # -- 事件 - def _on_configure(self, _e=None): - size = (self.winfo_width(), self.winfo_height()) - if size != self._last_size: - self._last_size = size - self._draw() - - def _on_enter(self, _e=None): - if self._enabled: - self._hover = True - self._draw() - - def _on_leave(self, _e=None): - self._hover = False - self._draw() - - def _on_press(self, _e=None): - if not self._enabled: - return - self._pressed = True - self._draw() - - def _on_release(self, e=None): - if not self._enabled: - return - was = self._pressed - self._pressed = False - self._draw() - # 手指滑出按钮再松手 = 取消(平板上的常见预期) - if was and e is not None: - x, y = e.x, e.y - if 0 <= x <= self.winfo_width() and 0 <= y <= self.winfo_height(): - if self._command: - self._command() - - # -- 绘制 - def _draw(self): - w, h = self.winfo_width(), self.winfo_height() - if w <= 1 or h <= 1: - return - self.delete('all') - if not self._enabled: - fill, fg = '#dde3ec', '#98a2b3' - elif self._pressed: - fill, fg = shade(self._fill, 0.86), self._fg - elif self._hover: - fill, fg = shade(self._fill, 1.06), self._fg - else: - fill, fg = self._fill, self._fg - r = self._radius - ph = rounded_photo(w, h, r, fill, self._surface, - outline=self._outline, ow=1) - if ph is not None: - self.create_image(0, 0, anchor='nw', image=ph) - self._ph = ph - else: - draw_round(self, 0, 0, w - 1, h - 1, r, fill, - outline=self._outline or fill) - dy = 1 if self._pressed else 0 - cx = w // 2 - has_sub = bool(self._sub) - if self._anchor == 'w': - cx = self._pad - if self._icon: - self.create_text(self._pad, h // 2 + dy, text=self._icon, - font=self._icon_font, fill=fg, anchor='w') - if has_sub: - ty = h // 2 - 9 + dy - else: - ty = h // 2 + dy - anchor = 'w' if self._anchor == 'w' else 'center' - x = (self._pad + (28 if self._icon else 0)) if anchor == 'w' else cx - self.create_text(x, ty, text=self._text, font=self._font, fill=fg, - anchor=anchor) - if has_sub: - self.create_text(x, ty + 20, text=self._sub, font=self._sub_font, - fill=_alpha_ink(fg), anchor=anchor) - - -def _alpha_ink(fg): - return '#dbe6f2' if fg == '#ffffff' else C.ink2 - - -def _surface_of(w): - try: - return w.cget('bg') - except Exception: - try: - return w.master.cget('bg') - except Exception: - return C.bg - - -# ------------------------------------------------------------------ 卡片 -class Card(tk.Frame): - """白底圆角卡片:用 Canvas 画底,内容放 .body(普通 Frame)。""" - - def __init__(self, parent, radius=18, pad=18, surface=None, fill=None, - border=None, **kw): - surface = surface or _surface_of(parent) - super().__init__(parent, bg=surface, highlightthickness=0, bd=0, **kw) - self._surface = surface - self._fill = fill or C.surface - self._radius = radius - self._border = border - self._canvas = tk.Canvas(self, bg=surface, highlightthickness=0, bd=0, - takefocus=0) - self._canvas.place(x=0, y=0, relwidth=1, relheight=1) - # 内容区用 pack + 内边距(place 的负宽高在部分 Tk 版本上算成 0, - # 表现就是卡片里的文字/按钮整块消失) - self.body = tk.Frame(self, bg=self._fill) - self.body.pack(fill='both', expand=True, padx=pad, pady=pad) - self.bind('', self._redraw) - self._ph = None - - def _redraw(self, _e=None): - w, h = self.winfo_width(), self.winfo_height() - if w <= 1 or h <= 1: - return - self._canvas.delete('all') - ph = rounded_photo(w, h, self._radius, self._fill, self._surface, - outline=self._border, ow=1) - if ph is not None: - self._canvas.create_image(0, 0, anchor='nw', image=ph) - self._ph = ph - else: - draw_round(self._canvas, 0, 0, w - 1, h - 1, self._radius, - self._fill) - - def set_border(self, color): - self._border = color - self._redraw() - - -# ------------------------------------------------------------------ 分段导航 -class Segmented(tk.Canvas): - """胶囊分段控件:白色滑块跟着手指滑动,松手吸附到最近一段。""" - - def __init__(self, parent, items, command=None, height=56, width=440, - surface=None, font=None, value=None, pad=5, anim_ms=220): - surface = surface or _surface_of(parent) - super().__init__(parent, bg=surface, highlightthickness=0, bd=0, - height=height, width=width, takefocus=0) - self._surface = surface - self._items = [(k, t) for k, t in items] - self._command = command - self._h = height - self._pad = pad - self._font = font or ('Microsoft YaHei', 15, 'bold') - self._idx = 0 - self._thumb_x = None - self._anim_job = None - self._drag = None - # 增量重绘:画布项只建一次,拖动/动画只改坐标和颜色。 - # 以前每帧 delete('all') + 重建,现场低端机上拖动明显发卡。 - self._shape = None # (w, h, items) —— 决定要不要整建 - self._id_sh = None # 滑块阴影图元 - self._id_th = None # 滑块本体图元 - self._id_txt = [] # 各段文字图元 - self._paint_idx = None # 上次画文字时的选中段 - self._motion_paint = None # 拖动重绘合并计时器 - if value is not None: - for i, (k, _t) in enumerate(self._items): - if k == value: - self._idx = i - self.bind('', self._on_configure) - self.bind('', self._on_press) - self.bind('', self._on_drag) - self.bind('', self._on_release) - self.after(10, self._redraw) - - # -- 接口 - def index(self): - return self._idx - - def key(self): - try: - return self._items[self._idx][0] - except Exception: - return None - - def set_text(self, key, text): - for i, (k, _t) in enumerate(self._items): - if k == key: - self._items[i] = (k, text) - self._redraw() - - def select(self, key_or_idx, animate=True, notify=False): - if isinstance(key_or_idx, int): - idx = key_or_idx - else: - idx = 0 - for i, (k, _t) in enumerate(self._items): - if k == key_or_idx: - idx = i - idx = max(0, min(len(self._items) - 1, idx)) - changed = (idx != self._idx) - self._idx = idx - if animate: - self._animate_to(self._seg_x(idx)) - else: - self._thumb_x = self._seg_x(idx) - self._redraw() - if notify and self._command: - self._command(self._items[idx][0], idx) - return changed - - # -- 几何 - def _seg_w(self): - n = max(1, len(self._items)) - return max(10, (self.winfo_width() - self._pad * 2) / float(n)) - - def _seg_x(self, idx): - return self._pad + idx * self._seg_w() - - # -- 绘制 - def _on_configure(self, _e=None): - self._thumb_x = self._seg_x(self._idx) - self._redraw(rebuild=True) - - def _redraw(self, rebuild=False): - """rebuild=True 才整建;平时只挪滑块/阴影、切文字颜色(增量)。""" - w, h = self.winfo_width(), self.winfo_height() - if w <= 2 or h <= 2: - return - shape = (w, h, tuple(self._items)) - if rebuild or shape != self._shape: - self._build(w, h, shape) - return - seg_w = self._seg_w() - x = self._thumb_x + 3 - if self._id_sh is not None: - self.coords(self._id_sh, x, 7) - if self._id_th is not None: - self.coords(self._id_th, x, 6) - if self._paint_idx != self._idx: - # 只在换段时才重刷文字(颜色 + 1px 下沉),拖动过程零文字开销 - self._paint_idx = self._idx - for i, tid in enumerate(self._id_txt): - on = (i == self._idx) - self.coords(tid, self._pad + seg_w * (i + 0.5), - h // 2 + (1 if on else 0)) - self.itemconfig(tid, fill=C.brand if on else C.ink2) - - def _build(self, w, h, shape): - self.delete('all') - self._shape = shape - track_h = h - 2 - ph = rounded_photo(w, track_h, track_h // 2, C.track, self._surface) - if ph is not None: - self.create_image(0, 1, anchor='nw', image=ph) - else: - draw_round(self, 0, 1, w - 1, track_h, track_h // 2, C.track) - seg_w = self._seg_w() - tw = seg_w - 6 - th = h - 12 - if self._thumb_x is None: - self._thumb_x = self._seg_x(self._idx) - x = self._thumb_x + 3 - sh = rounded_photo(int(tw), th, th // 2, '#dfe5ee', C.track) - self._id_sh = None - if sh is not None: - self._id_sh = self.create_image(int(x), 7, anchor='nw', image=sh) - th_img = rounded_photo(int(tw), th, th // 2, '#ffffff', C.track) - self._id_th = None - if th_img is not None: - self._id_th = self.create_image(int(x), 6, anchor='nw', - image=th_img) - else: - draw_round(self, x, 6, x + tw, 6 + th, th // 2, '#ffffff') - self._id_txt = [] - for i, (_k, t) in enumerate(self._items): - cx = self._pad + seg_w * (i + 0.5) - on = (i == self._idx) - self._id_txt.append(self.create_text( - cx, h // 2 + (1 if on else 0), text=t, font=self._font, - fill=C.brand if on else C.ink2)) - self._paint_idx = self._idx - - def _animate_to(self, target, ms=220): - if self._anim_job: - try: - self.after_cancel(self._anim_job) - except Exception: - pass - self._anim_job = None - start = self._thumb_x if self._thumb_x is not None else target - steps = max(1, int(ms / 16)) - n = [0] - - def tick(): - n[0] += 1 - k = n[0] / float(steps) - k = 1 - (1 - k) ** 3 # ease-out cubic - self._thumb_x = start + (target - start) * k - self._redraw() - if n[0] < steps: - self._anim_job = self.after(16, tick) - else: - self._thumb_x = target - self._anim_job = None - self._redraw() - tick() - - # -- 手势 - def _on_press(self, e): - self._drag = {'x0': e.x, 'start': self._thumb_x, 'moved': False} - if self._anim_job: - try: - self.after_cancel(self._anim_job) - except Exception: - pass - self._anim_job = None - - def _on_drag(self, e): - if not self._drag: - return - dx = e.x - self._drag['x0'] - if abs(dx) > 3: - self._drag['moved'] = True - seg_w = self._seg_w() - left = self._pad - right = self._pad + seg_w * (len(self._items) - 1) - x = max(left, min(right, self._drag['start'] + dx)) - self._thumb_x = x - self._idx = int(round((x - self._pad) / seg_w)) - self._idx = max(0, min(len(self._items) - 1, self._idx)) - # 触摸屏的 motion 事件会一波波砸进来(120Hz+),直接每事件重绘 - # 会把事件队列越压越多、滑块越拖越滞后。按 ~125fps 合并成 - # 「有脏标记才画」,滑块始终贴着最新位置,弱机上也不发卡。 - if self._motion_paint is None: - self._motion_paint = self.after(8, self._motion_paint_now) - - def _motion_paint_now(self): - self._motion_paint = None - self._redraw() - - def _on_release(self, e): - if not self._drag: - return - if not self._drag['moved']: - idx = int((e.x - self._pad) // self._seg_w()) - else: - idx = self._idx - idx = max(0, min(len(self._items) - 1, idx)) - self._drag = None - if self._motion_paint is not None: - # 拖动途中的挂起重绘交给动画去做,避免两次重绘打架 - try: - self.after_cancel(self._motion_paint) - except Exception: - pass - self._motion_paint = None - changed = (idx != self._idx) or True - self._idx = idx - self._animate_to(self._seg_x(idx)) - if self._command: - self._command(self._items[idx][0], idx) - - -# ------------------------------------------------------------------ 滑动开关 -class Switch(tk.Canvas): - """滑动开关:轨道变色 + 圆点滑过去。""" - - def __init__(self, parent, value=False, command=None, surface=None, - width=64, height=36, on_color=None): - surface = surface or _surface_of(parent) - super().__init__(parent, bg=surface, highlightthickness=0, bd=0, - width=width, height=height, takefocus=0) - self._surface = surface - # 注意:不能用 self._w / self._h —— tkinter 的 _w 是窗口路径 - self.sz_w = width - self.sz_h = height - self._on_color = on_color or C.brand - self._value = bool(value) - self._command = command - self._pos = 1.0 if value else 0.0 - self._job = None - self.bind('', self._toggle) - self.after(10, self._redraw) - - def get(self): - return self._value - - def set(self, value, animate=True): - value = bool(value) - if value == self._value: - self._redraw() - return - self._value = value - if animate: - self._animate(1.0 if value else 0.0) - else: - self._pos = 1.0 if value else 0.0 - self._redraw() - - def _toggle(self, _e=None): - self._value = not self._value - self._animate(1.0 if self._value else 0.0) - if self._command: - self._command(self._value) - - def _animate(self, target, ms=160): - if self._job: - try: - self.after_cancel(self._job) - except Exception: - pass - self._job = None - start = self._pos - steps = max(1, int(ms / 16)) - n = [0] - - def tick(): - n[0] += 1 - k = min(1.0, n[0] / float(steps)) - k = 1 - (1 - k) ** 3 - self._pos = start + (target - start) * k - self._redraw() - if n[0] < steps: - self._job = self.after(16, tick) - else: - self._pos = target - self._job = None - self._redraw() - tick() - - def _redraw(self): - w, h = self.sz_w, self.sz_h - if w <= 2 or h <= 2: - return - self.delete('all') - # 轨道颜色:关=灰,开=品牌色,中间随位置插值 - off = _hex_rgb('#cdd5e1') - on = _hex_rgb(self._on_color) - k = self._pos - col = '#%02x%02x%02x' % tuple( - int(off[i] + (on[i] - off[i]) * k) for i in range(3)) - ph = rounded_photo(w, h, h // 2, col, self._surface) - if ph is not None: - self.create_image(0, 0, anchor='nw', image=ph) - self._ph = ph - else: - draw_round(self, 0, 0, w - 1, h - 1, h // 2, col) - d = h - 8 - x = 4 + (w - d - 8) * k - kp = rounded_photo(d, d, d // 2, '#ffffff', col) - if kp is not None: - self.create_image(int(x), 4, anchor='nw', image=kp) - self._ph_knob = kp - else: - self.create_oval(x, 4, x + d, 4 + d, fill='#ffffff', outline='') - - -# ------------------------------------------------------------------ 步骤条 -class StepsBar(tk.Canvas): - """5 段圆角步骤条:已完成=绿、当前=琥珀、未到=灰。""" - - def __init__(self, parent, steps, surface=None, height=44, - font=None, gap=6): - surface = surface or _surface_of(parent) - super().__init__(parent, bg=surface, highlightthickness=0, bd=0, - height=height, takefocus=0) - self._surface = surface - self._steps = list(steps) - self._h = height - self._gap = gap - self._font = font or ('Microsoft YaHei', 11) - self._idx = -1 - self.bind('', lambda e: self._redraw()) - self.after(10, self._redraw) - - def set_state(self, idx): - if idx == self._idx: - return - self._idx = idx - self._redraw() - - def _redraw(self): - w, h = self.winfo_width(), self.winfo_height() - if w <= 2 or h <= 2: - return - self.delete('all') - n = max(1, len(self._steps)) - gap = self._gap - sw = (w - gap * (n - 1)) / float(n) - for i, text in enumerate(self._steps): - if i < self._idx: - fill, fg = C.green_soft, C.green - elif i == self._idx: - fill, fg = '#fdeccd', '#8a5a11' - else: - fill, fg = '#f1f3f7', C.ink3 - x = i * (sw + gap) - ph = rounded_photo(int(sw), h, h // 2, fill, self._surface) - if ph is not None: - self.create_image(int(x), 0, anchor='nw', image=ph) - if not hasattr(self, '_phs'): - self._phs = [] - self._phs.append(ph) - self._phs = self._phs[-12:] - else: - draw_round(self, x, 0, x + sw, h - 1, h // 2, fill) - self.create_text(x + sw / 2, h // 2, text=text, - font=self._font, fill=fg) - - -# ------------------------------------------------------------------ 翻页容器 -class Pager(tk.Frame): - """横向页面容器:手指左右拖跟手移动,松手吸附到最近一页。 - - 页面用 Canvas 内嵌窗口实现——滑动只是移动画布视口,不重建控件, - 摄像头预览这种一直在刷新的页面也不会因为翻页而卡顿。 - """ - - def __init__(self, parent, bg=None, on_change=None): - bg = bg or _surface_of(parent) - super().__init__(parent, bg=bg) - self._bg = bg - self._cv = tk.Canvas(self, bg=bg, highlightthickness=0, bd=0, - takefocus=0) - self._cv.pack(fill='both', expand=True) - self._pages = [] - self._items = [] - self._idx = 0 - self._on_change = on_change - self._anim = None - self._drag = None - self._cv.bind('', self._on_configure) - - # -- 接口 - def add(self, page): - self._pages.append(page) - item = self._cv.create_window((0, 0), window=page, anchor='nw') - self._items.append(item) - self._sync_geom() - return page - - def count(self): - return len(self._pages) - - def index(self): - return self._idx - - def show(self, idx, animate=True, notify=False): - if not self._pages: - return - idx = max(0, min(len(self._pages) - 1, idx)) - changed = idx != self._idx - self._idx = idx - if animate: - self._animate_to(idx) - else: - self._set_frac(idx) - if notify and changed and self._on_change: - self._on_change(idx) - - # -- 几何 / 滚动 - def _on_configure(self, _e=None): - self._sync_geom() - - def _sync_geom(self): - if not self._pages: - return - w = self._cv.winfo_width() - h = self._cv.winfo_height() - if w <= 2 or h <= 2: - return - for i, item in enumerate(self._items): - self._cv.coords(item, i * w, 0) - self._cv.itemconfigure(item, width=w, height=h) - n = len(self._pages) - self._cv.configure(scrollregion=(0, 0, w * n, h)) - self._set_frac(self._idx) - - def _set_frac(self, idx): - n = max(1, len(self._pages)) - try: - self._cv.xview_moveto(idx / float(n)) - except Exception: - pass - - def _cur_frac(self): - try: - return self._cv.xview()[0] - except Exception: - return 0.0 - - def _animate_to(self, idx, ms=260): - if self._anim: - try: - self.after_cancel(self._anim) - except Exception: - pass - self._anim = None - n = max(1, len(self._pages)) - start = self._cur_frac() - target = idx / float(n) - if abs(target - start) < 0.0005: - self._set_frac(idx) - return - steps = max(1, int(ms / 16)) - k = [0] - - def tick(): - k[0] += 1 - p = min(1.0, k[0] / float(steps)) - p = 1 - (1 - p) ** 3 - try: - self._cv.xview_moveto(start + (target - start) * p) - except Exception: - pass - if k[0] < steps: - self._anim = self.after(16, tick) - else: - self._anim = None - self._set_frac(idx) - tick() - - # -- 手势(由 bind_swipe_to 绑到页面里的普通控件上) - def _press(self, e): - self._drag = {'x0': e.x_root, 'y0': e.y_root, - 'frac': self._cur_frac(), 'axis': None, 'moved': False} - if self._anim: - try: - self.after_cancel(self._anim) - except Exception: - pass - self._anim = None - - def _motion(self, e): - d = self._drag - if not d: - return - dx = e.x_root - d['x0'] - dy = e.y_root - d['y0'] - if d['axis'] is None: - if abs(dx) < 9 and abs(dy) < 9: - return - # 横向占优才翻页,否则交给页面自己的纵向滚动 - d['axis'] = 'h' if abs(dx) > abs(dy) * 1.25 else 'v' - if d['axis'] == 'h': - d['moved'] = True - if d['axis'] != 'h': - return - w = max(1, self._cv.winfo_width()) - n = max(1, len(self._pages)) - frac = d['frac'] - dx / float(w * n) - frac = max(0.0, min((n - 1) / float(n), frac)) - try: - self._cv.xview_moveto(frac) - except Exception: - pass - - def _release(self, e): - d = self._drag - self._drag = None - if not d or d['axis'] != 'h': - return - n = max(1, len(self._pages)) - frac = self._cur_frac() * n - base = int(round(frac)) - dx = e.x_root - d['x0'] - if abs(dx) > max(60, self._cv.winfo_width() * 0.16): - target = self._idx + (1 if dx < 0 else -1) - else: - target = base - target = max(0, min(n - 1, target)) - self._idx = target - self._animate_to(target) - if self._on_change: - self._on_change(target) - - -def bind_swipe_to(widget, pager, skip=(), force=False): - """把普通控件也接到翻页手势上(按钮/输入框/自绘画布除外)""" - if widget in skip: - return - if not force and isinstance(widget, (tk.Button, tk.Entry, tk.Text, - tk.Canvas)): - return - try: - if widget.cget('class') in ('TButton', 'TEntry', 'TSpinbox'): - return - except Exception: - pass - try: - widget.bind('', pager._press, add='+') - widget.bind('', pager._motion, add='+') - widget.bind('', pager._release, add='+') - except Exception: - pass - - -def bind_swipe_recursive(widget, pager, depth=0): - """整块页面(含子控件)都能滑动翻页:一次绑定,之后动态加的子控件不生效""" - if depth > 6: - return - bind_swipe_to(widget, pager) - for ch in widget.winfo_children(): - bind_swipe_recursive(ch, pager, depth + 1) - - -# ------------------------------------------------------------------ 触摸滚动 -class TouchScroll: - """手指拖动滚动 + 惯性;纵向手势自己吃掉,横向让给翻页。""" - - def __init__(self, canvas, min_content=0): - self.cv = canvas - self.moved = False - self._drag = None - self._anim = None - self._min = min_content - canvas.configure(yscrollincrement=1) - - def attach(self, widget, allow_click=True): - try: - widget.bind('', self._press, add='+') - widget.bind('', self._motion, add='+') - widget.bind('', self._release, add='+') - widget.bind('', self._wheel, add='+') - if allow_click: - # 拖动后松手不触发卡片点选:用标记让调用方自己判断 - pass - except Exception: - pass - - def attach_tree(self, widget, depth=0): - if depth > 6: - return - self.attach(widget) - for ch in widget.winfo_children(): - self.attach_tree(ch, depth + 1) - - # -- 尺寸 - def _geom(self): - # 内容高度只在重建卡片/改列数/筛选时变,滚动期间不会变。原来每次 - # 按下、每次滚轮都 bbox('all') 查一遍(上百个卡片项),弱机上就是 - # 那几毫秒一卡一卡。缓存 0.5 秒,重建后最多半秒自愈。 - now = _time.monotonic() - c = getattr(self, '_gc', None) - if c and now - c[2] < 0.5: - return c[0], c[1] - try: - bbox = self.cv.bbox('all') or (0, 0, 0, 0) - total = max(1, bbox[3] - bbox[1]) - view = max(1, self.cv.winfo_height()) - except Exception: - return 1, 1 - self._gc = (total, view, now) - return total, view - - def _press(self, e): - self._stop() - self.moved = False - # 拖动期间缓存内容高度/视口高度,别每个 motion 都去 bbox('all'); - # 待办名单一长,这个查询本身就吃好几毫秒,拖起来发卡。 - total, view = self._geom() - self._drag = {'y0': e.y_root, 'x0': e.x_root, - 'frac': self.cv.yview()[0], 'axis': None, - 't': e.time or 0, 'last_y': e.y_root, - 'v': 0.0, 'total': total, 'view': view, - 'target': None, 'painted_at': 0.0} - - def _motion(self, e): - d = self._drag - if not d: - return - dy = e.y_root - d['y0'] - dx = e.x_root - d['x0'] - total, view = d['total'], d['view'] - if total <= view + 2: - return - if d['axis'] is None: - if abs(dx) < 9 and abs(dy) < 9: - return - d['axis'] = 'v' if abs(dy) >= abs(dx) * 0.8 else 'h' - if d['axis'] != 'v': - return - if abs(dy) > 6: - self.moved = True # 拖动滚名单时不要顺手把卡片选中 - frac = d['frac'] - dy / float(total) - frac = max(0.0, min(1.0 - view / float(total), frac)) - # v1.0.49:触摸屏一秒能发 100~200 个 Motion,每个都滚一次就把界面 - # 拖垮(每滚一次 Tk 要重画整块卡片区)。这里限帧,中间的 - # 事件只记位置不重画;松手时再补最后一下。 - # v1.0.56:16ms→24ms。现场 i5-4200U 上滚一帧本身就要 20~25ms, - # 按 60fps 限反而每帧都堆在队列里,松手后还要把积压的帧画完, - # 手感是「拖不动、一松手猛跳一下」。42fps 才是这台机器跟得上的节奏。 - d['target'] = frac - now = _time.monotonic() - if now - d.get('painted_at', 0.0) >= 0.024: - d['painted_at'] = now - try: - self.cv.yview_moveto(frac) - except Exception: - pass - # 速度只用来算惯性:事件不带时间戳(time=0,部分触摸驱动/合成事件 - # 就是这样)时 dt 会变成 1ms,速度虚高几十倍,松手直接甩到底。 - # 真手指最快也就 3~5 px/ms,夹到 6 以内,异常值一律当 0。 - now_t = int(getattr(e, 'time', 0) or 0) - if now_t and d['t'] and now_t > d['t']: - dt = now_t - d['t'] - v = (e.y_root - d['last_y']) / float(dt) # px/ms - d['v'] = max(-6.0, min(6.0, v)) - d['t'] = now_t - else: - d['v'] = 0.0 - d['last_y'] = e.y_root - - def _release(self, _e=None): - d = self._drag - self._drag = None - if not d or d.get('axis') != 'v': - return - # 补画最后一下(拖动时限了帧率,末位可能是没画出来的那帧) - if d.get('target') is not None: - try: - self.cv.yview_moveto(d['target']) - except Exception: - pass - v = d.get('v') or 0.0 - if abs(v) < 0.35: - return - total, view = self._geom() - if total <= view + 2: - return - self._fling(v, total, view) - - def _fling(self, v, total, view): - frac = self.cv.yview()[0] - step = 0.0 - # 24ms 一帧(和拖动限帧一致):衰减按「同样减速度」换算, - # 16ms 时的 0.90 → 24ms 约 0.86,甩出去的距离才跟手一致 - gap = 24 - - def tick(): - nonlocal frac, v - v *= 0.86 - frac = frac - v * gap / float(total) - frac = max(0.0, min(1.0 - view / float(total), frac)) - try: - self.cv.yview_moveto(frac) - except Exception: - return - if abs(v) > 0.05: - self._anim = self.cv.after(gap, tick) - else: - self._anim = None - if abs(step) < 1: - tick() - - def _wheel(self, e): - total, view = self._geom() - if total <= view + 2: - return - d = -1 if getattr(e, 'delta', 0) > 0 else 1 - # v1.0.56:原来一格只走 3px(名单总高 5595px 时是 0.1%),滚一格几乎 - # 看不出动,现场连滚十几下才走一屏,感受就是「滑不动」。改成一格 - # 走四分之一屏,靠手感接近网页。 - step = max(3, int(view * 0.25)) - try: - self.cv.yview_scroll(d * step, 'units') - except Exception: - pass - return 'break' - - def _stop(self): - if self._anim: - try: - self.cv.after_cancel(self._anim) - except Exception: - pass - self._anim = None - - -class TapGate: - """按下→松手之间手指有没有挪过:挪过就是「拖动」,不算「点」。 - - 为什么要单独一个:`TouchScroll.moved` 只在「内容比视口高、且纵向拖动」 - 时才置位,卡片区内容装得下、或者斜着划一下,它一直是 False —— - 于是滑名单松手就点中了卡片(确认状态下直接打一张标签)。 - 这里只认几何位移,和滚动条、内容高度都无关: - - · 位移超过 tol(默认 12px)→ 不算点,滚名单/滑下拉都不选中; - · 按下和松手不在同一条(key 不同,例如从这张卡滑到那张卡)→ 不算点; - · 按住超过 max_ms(默认 900ms)→ 不算点(长按多半是想拖)。 - - 一个实例可以共给整片卡片区:同一时刻只可能有一根手指按着。 - """ - - def __init__(self, tol=12, max_ms=900): - self.tol = tol - self.max_ms = max_ms - self._key = None - self._x = 0.0 - self._y = 0.0 - self._t = 0 - self._ok = False - - def press(self, e, key=None): - try: - self._x = float(e.x_root) - self._y = float(e.y_root) - except Exception: - self._x = self._y = 0.0 - self._t = int(getattr(e, 'time', 0) or 0) - self._key = key - self._ok = True - - def motion(self, e): - if not self._ok: - return - try: - dx = abs(float(e.x_root) - self._x) - dy = abs(float(e.y_root) - self._y) - except Exception: - return - if dx > self.tol or dy > self.tol: - self._ok = False - - def release(self, e=None, key=None): - """松手:是「点」就返回 True。无论结果如何都会清掉本次状态。""" - ok = self._ok - self._ok = False - if not ok: - return False - if key is not None and self._key is not None and key != self._key: - return False # 从别处滑过来松手,不算点这条 - t = int(getattr(e, 'time', 0) or 0) - if t and self._t and (t - self._t) > self.max_ms: - return False - return True - - -def bind_drag_scroll(canvas, widgets=()): - """便捷函数:给 canvas 建一个 TouchScroll 并挂到给定控件上""" - ts = TouchScroll(canvas) - for w in widgets: - ts.attach(w) - return ts +# -*- coding: utf-8 -*- +"""平板化 UI 组件(tkinter + Pillow 抗锯齿圆角,不引入第三方 UI 库)。 + +设计基准:1440×900 横屏平板 + · 触摸目标 ≥ 52px,主操作 64~72px + · 圆角 14(卡片)/ 999(胶囊按钮) + · 留白 16 / 20,字号 13 / 15 / 18 / 26 / 72 + +对外: + C 配色常量 + rounded_photo(...) 抗锯齿圆角图片(带缓存,按尺寸/颜色复用) + TouchButton 大触摸按钮(按下回弹、圆角) + Segmented 分段导航(滑块跟手 + 吸附动画) + Switch 滑动开关 + StepsBar 圆角步骤条 + Pager 可左右滑动的页面容器(跟手 + 松手吸附) + TouchScroll 手指拖动滚动(带惯性) + bind_swipe_to(...) 让普通控件也参与翻页手势 +""" +import tkinter as tk +import time as _time + +try: + from PIL import Image, ImageDraw, ImageTk + _HAS_PIL = True +except Exception: # pragma: no cover + _HAS_PIL = False + + +# ------------------------------------------------------------------ 配色 +class C: + bg = '#f4f6fa' # 页面底色 + surface = '#ffffff' # 卡片 + line = '#e6ebf2' # 分隔线 + ink = '#1b2634' # 主文字 + ink2 = '#5b6675' # 次文字 + ink3 = '#98a2b3' # 弱文字 + brand = '#1b5fa5' # 品牌蓝 + brand_dark = '#134a83' + brand_soft = '#e8f1fb' + green = '#0f6e56' + green_soft = '#e3f2ec' + amber = '#b45309' + amber_soft = '#fdf0d9' + red = '#a32d2d' + red_soft = '#fbe9e9' + track = '#e9edf4' + + +def shade(hex_color, k): + """把颜色整体调暗/调亮:k<1 变暗,k>1 变亮(保持色相)""" + hex_color = hex_color.lstrip('#') + if len(hex_color) == 3: + hex_color = ''.join(c * 2 for c in hex_color) + r = int(hex_color[0:2], 16) + g = int(hex_color[2:4], 16) + b = int(hex_color[4:6], 16) + if k <= 1: + r, g, b = int(r * k), int(g * k), int(b * k) + else: + d = k - 1.0 + r = int(r + (255 - r) * d) + g = int(g + (255 - g) * d) + b = int(b + (255 - b) * d) + return '#%02x%02x%02x' % (max(0, min(255, r)), + max(0, min(255, g)), + max(0, min(255, b))) + + +# ------------------------------------------------------------------ 圆角图片 +_SS = 3 # 超采样倍数:3 倍绘制再缩小,边缘才不毛 +_IMG_CACHE = {} +_PH_CACHE = {} + + +def _hex_rgb(h): + h = h.lstrip('#') + if len(h) == 3: + h = ''.join(c * 2 for c in h) + return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)) + + +def rounded_image(w, h, r, fill, on, outline=None, ow=1): + """返回抗锯齿圆角矩形 PIL 图;on = 背景色(用于把透明角混成实体色)""" + w, h = max(1, int(w)), max(1, int(h)) + r = max(0, int(r)) + key = (w, h, r, fill, on, outline, ow) + im = _IMG_CACHE.get(key) + if im is not None: + return im + if _HAS_PIL: + W, H, R = w * _SS, h * _SS, min(r * _SS, min(w, h) * _SS // 2) + base = Image.new('RGB', (W, H), _hex_rgb(on)) + d = ImageDraw.Draw(base) + box = [0, 0, W - 1, H - 1] + if outline and ow > 0: + d.rounded_rectangle(box, radius=R, fill=_hex_rgb(outline)) + i = int(ow * _SS) + d.rounded_rectangle([i, i, W - 1 - i, H - 1 - i], + radius=max(0, R - i), fill=_hex_rgb(fill)) + else: + d.rounded_rectangle(box, radius=R, fill=_hex_rgb(fill)) + im = base.resize((w, h), Image.LANCZOS) + else: # 没有 Pillow 就退化成直角块 + im = None + _IMG_CACHE[key] = im + return im + + +def rounded_photo(w, h, r, fill, on, outline=None, ow=1): + """转成 Tk 可用的 PhotoImage(全局缓存,避免每次重绘都新建位图)""" + w, h = max(1, int(w)), max(1, int(h)) + key = (w, h, r, fill, on, outline, ow) + ph = _PH_CACHE.get(key) + if ph is not None: + return ph + im = rounded_image(w, h, r, fill, on, outline, ow) + if im is None or not _HAS_PIL: + return None + try: + ph = ImageTk.PhotoImage(im) + except Exception: + return None + _PH_CACHE[key] = ph + return ph + + +def draw_round(cv, x1, y1, x2, y2, r, fill, outline='', width=1, tags=''): + """Canvas 上画圆角块(无 Pillow 时的兜底 / 小装饰用)""" + r = max(0, min(r, (x2 - x1) // 2, (y2 - y1) // 2)) + pts = [x1 + r, y1, x2 - r, y1, x2, y1, x2, y1 + r, + x2, y2 - r, x2, y2, x2 - r, y2, x1 + r, y2, + x1, y2, x1, y2 - r, x1, y1 + r, x1, y1] + return cv.create_polygon(pts, smooth=True, splinesteps=16, fill=fill, + outline=outline, width=width, tags=tags) + + +# ------------------------------------------------------------------ 触摸按钮 +class TouchButton(tk.Canvas): + """圆角大按钮:按下变深并轻微下沉,松手回弹再执行。 + + 参数按「平板尺寸」给:height 默认 64,最小建议 52。 + """ + + def __init__(self, parent, text='', command=None, fill=C.brand, + fg='#ffffff', surface=None, height=64, radius=None, + font=None, sub='', sub_font=None, width=None, + enabled=True, outline=None, pad=18, anchor='center', + icon='', icon_font=None, **kw): + surface = surface or _surface_of(parent) + super().__init__(parent, bg=surface, highlightthickness=0, bd=0, + height=height, width=width or 10, takefocus=0, **kw) + self._text = text + self._icon = icon + self._sub = sub + self._command = command + self._fill = fill + self._fg = fg + self._surface = surface + self._radius = radius if radius is not None else min(18, height // 2) + self._font = font or ('Microsoft YaHei', 16, 'bold') + self._sub_font = sub_font or ('Microsoft YaHei', 11) + self._icon_font = icon_font or ('Microsoft YaHei', 20) + self._enabled = bool(enabled) + self._outline = outline + self._pad = pad + self._anchor = anchor + self._pressed = False + self._hover = False + self._last_size = (0, 0) + self.bind('', self._on_configure) + self.bind('', self._on_press) + self.bind('', self._on_release) + self.bind('', self._on_enter) + self.bind('', self._on_leave) + self.bind('', lambda e: None) + + # -- 外部接口 + def configure_btn(self, **kw): + visual_fields = { + 'text': '_text', 'sub': '_sub', 'fill': '_fill', 'bg': '_fill', + 'fg': '_fg', 'enabled': '_enabled', 'state': '_enabled', + 'icon': '_icon', + } + changed = False + for key, value in kw.items(): + if key == 'command': + self._command = value + continue + attr = visual_fields.get(key) + if attr is None: + continue + if key == 'enabled': + value = bool(value) + elif key == 'state': + value = value != 'disabled' + if getattr(self, attr) != value: + setattr(self, attr, value) + changed = True + if changed: + self._draw() + + def configure(self, cnf=None, **kw): + """兼容 tk 的 configure:业务属性走自绘,其余(宽度/位置)交给 Canvas""" + mine, rest = {}, {} + for k, v in kw.items(): + if k in ('text', 'sub', 'fill', 'bg', 'fg', 'enabled', + 'state', 'command', 'icon'): + mine[k] = v + else: + rest[k] = v + if mine: + self.configure_btn(**mine) + if rest or cnf: + tk.Canvas.configure(self, cnf, **rest) + + config = configure + + def set_text(self, text): + self._text = text + self._draw() + + def set_enabled(self, on=True): + self._enabled = bool(on) + self._draw() + + # -- 事件 + def _on_configure(self, _e=None): + size = (self.winfo_width(), self.winfo_height()) + if size != self._last_size: + self._last_size = size + self._draw() + + def _on_enter(self, _e=None): + if self._enabled: + self._hover = True + self._draw() + + def _on_leave(self, _e=None): + self._hover = False + self._draw() + + def _on_press(self, _e=None): + if not self._enabled: + return + self._pressed = True + self._draw() + + def _on_release(self, e=None): + if not self._enabled: + return + was = self._pressed + self._pressed = False + self._draw() + # 手指滑出按钮再松手 = 取消(平板上的常见预期) + if was and e is not None: + x, y = e.x, e.y + if 0 <= x <= self.winfo_width() and 0 <= y <= self.winfo_height(): + if self._command: + self._command() + + # -- 绘制 + def _draw(self): + w, h = self.winfo_width(), self.winfo_height() + if w <= 1 or h <= 1: + return + self.delete('all') + if not self._enabled: + fill, fg = '#dde3ec', '#98a2b3' + elif self._pressed: + fill, fg = shade(self._fill, 0.86), self._fg + elif self._hover: + fill, fg = shade(self._fill, 1.06), self._fg + else: + fill, fg = self._fill, self._fg + r = self._radius + ph = rounded_photo(w, h, r, fill, self._surface, + outline=self._outline, ow=1) + if ph is not None: + self.create_image(0, 0, anchor='nw', image=ph) + self._ph = ph + else: + draw_round(self, 0, 0, w - 1, h - 1, r, fill, + outline=self._outline or fill) + dy = 1 if self._pressed else 0 + cx = w // 2 + has_sub = bool(self._sub) + if self._anchor == 'w': + cx = self._pad + if self._icon: + self.create_text(self._pad, h // 2 + dy, text=self._icon, + font=self._icon_font, fill=fg, anchor='w') + if has_sub: + ty = h // 2 - 9 + dy + else: + ty = h // 2 + dy + anchor = 'w' if self._anchor == 'w' else 'center' + x = (self._pad + (28 if self._icon else 0)) if anchor == 'w' else cx + self.create_text(x, ty, text=self._text, font=self._font, fill=fg, + anchor=anchor) + if has_sub: + self.create_text(x, ty + 20, text=self._sub, font=self._sub_font, + fill=_alpha_ink(fg), anchor=anchor) + + +def _alpha_ink(fg): + return '#dbe6f2' if fg == '#ffffff' else C.ink2 + + +def _surface_of(w): + try: + return w.cget('bg') + except Exception: + try: + return w.master.cget('bg') + except Exception: + return C.bg + + +# ------------------------------------------------------------------ 卡片 +class Card(tk.Frame): + """白底圆角卡片:用 Canvas 画底,内容放 .body(普通 Frame)。""" + + def __init__(self, parent, radius=18, pad=18, surface=None, fill=None, + border=None, **kw): + surface = surface or _surface_of(parent) + super().__init__(parent, bg=surface, highlightthickness=0, bd=0, **kw) + self._surface = surface + self._fill = fill or C.surface + self._radius = radius + self._border = border + self._canvas = tk.Canvas(self, bg=surface, highlightthickness=0, bd=0, + takefocus=0) + self._canvas.place(x=0, y=0, relwidth=1, relheight=1) + # 内容区用 pack + 内边距(place 的负宽高在部分 Tk 版本上算成 0, + # 表现就是卡片里的文字/按钮整块消失) + self.body = tk.Frame(self, bg=self._fill) + self.body.pack(fill='both', expand=True, padx=pad, pady=pad) + self.bind('', self._redraw) + self._ph = None + + def _redraw(self, _e=None): + w, h = self.winfo_width(), self.winfo_height() + if w <= 1 or h <= 1: + return + self._canvas.delete('all') + ph = rounded_photo(w, h, self._radius, self._fill, self._surface, + outline=self._border, ow=1) + if ph is not None: + self._canvas.create_image(0, 0, anchor='nw', image=ph) + self._ph = ph + else: + draw_round(self._canvas, 0, 0, w - 1, h - 1, self._radius, + self._fill) + + def set_border(self, color): + self._border = color + self._redraw() + + +# ------------------------------------------------------------------ 分段导航 +class Segmented(tk.Canvas): + """胶囊分段控件:白色滑块跟着手指滑动,松手吸附到最近一段。""" + + def __init__(self, parent, items, command=None, height=56, width=440, + surface=None, font=None, value=None, pad=5, anim_ms=220): + surface = surface or _surface_of(parent) + super().__init__(parent, bg=surface, highlightthickness=0, bd=0, + height=height, width=width, takefocus=0) + self._surface = surface + self._items = [(k, t) for k, t in items] + self._command = command + self._h = height + self._pad = pad + self._font = font or ('Microsoft YaHei', 15, 'bold') + self._idx = 0 + self._thumb_x = None + self._anim_job = None + self._drag = None + # 增量重绘:画布项只建一次,拖动/动画只改坐标和颜色。 + # 以前每帧 delete('all') + 重建,现场低端机上拖动明显发卡。 + self._shape = None # (w, h, items) —— 决定要不要整建 + self._id_sh = None # 滑块阴影图元 + self._id_th = None # 滑块本体图元 + self._id_txt = [] # 各段文字图元 + self._paint_idx = None # 上次画文字时的选中段 + self._motion_paint = None # 拖动重绘合并计时器 + if value is not None: + for i, (k, _t) in enumerate(self._items): + if k == value: + self._idx = i + self.bind('', self._on_configure) + self.bind('', self._on_press) + self.bind('', self._on_drag) + self.bind('', self._on_release) + self.after(10, self._redraw) + + # -- 接口 + def index(self): + return self._idx + + def key(self): + try: + return self._items[self._idx][0] + except Exception: + return None + + def set_text(self, key, text): + for i, (k, _t) in enumerate(self._items): + if k == key: + self._items[i] = (k, text) + self._redraw() + + def select(self, key_or_idx, animate=True, notify=False): + if isinstance(key_or_idx, int): + idx = key_or_idx + else: + idx = 0 + for i, (k, _t) in enumerate(self._items): + if k == key_or_idx: + idx = i + idx = max(0, min(len(self._items) - 1, idx)) + changed = (idx != self._idx) + self._idx = idx + if animate: + self._animate_to(self._seg_x(idx)) + else: + self._thumb_x = self._seg_x(idx) + self._redraw() + if notify and self._command: + self._command(self._items[idx][0], idx) + return changed + + # -- 几何 + def _seg_w(self): + n = max(1, len(self._items)) + return max(10, (self.winfo_width() - self._pad * 2) / float(n)) + + def _seg_x(self, idx): + return self._pad + idx * self._seg_w() + + # -- 绘制 + def _on_configure(self, _e=None): + self._thumb_x = self._seg_x(self._idx) + self._redraw(rebuild=True) + + def _redraw(self, rebuild=False): + """rebuild=True 才整建;平时只挪滑块/阴影、切文字颜色(增量)。""" + w, h = self.winfo_width(), self.winfo_height() + if w <= 2 or h <= 2: + return + shape = (w, h, tuple(self._items)) + if rebuild or shape != self._shape: + self._build(w, h, shape) + return + seg_w = self._seg_w() + x = self._thumb_x + 3 + if self._id_sh is not None: + self.coords(self._id_sh, x, 7) + if self._id_th is not None: + self.coords(self._id_th, x, 6) + if self._paint_idx != self._idx: + # 只在换段时才重刷文字(颜色 + 1px 下沉),拖动过程零文字开销 + self._paint_idx = self._idx + for i, tid in enumerate(self._id_txt): + on = (i == self._idx) + self.coords(tid, self._pad + seg_w * (i + 0.5), + h // 2 + (1 if on else 0)) + self.itemconfig(tid, fill=C.brand if on else C.ink2) + + def _build(self, w, h, shape): + self.delete('all') + self._shape = shape + track_h = h - 2 + ph = rounded_photo(w, track_h, track_h // 2, C.track, self._surface) + if ph is not None: + self.create_image(0, 1, anchor='nw', image=ph) + else: + draw_round(self, 0, 1, w - 1, track_h, track_h // 2, C.track) + seg_w = self._seg_w() + tw = seg_w - 6 + th = h - 12 + if self._thumb_x is None: + self._thumb_x = self._seg_x(self._idx) + x = self._thumb_x + 3 + sh = rounded_photo(int(tw), th, th // 2, '#dfe5ee', C.track) + self._id_sh = None + if sh is not None: + self._id_sh = self.create_image(int(x), 7, anchor='nw', image=sh) + th_img = rounded_photo(int(tw), th, th // 2, '#ffffff', C.track) + self._id_th = None + if th_img is not None: + self._id_th = self.create_image(int(x), 6, anchor='nw', + image=th_img) + else: + draw_round(self, x, 6, x + tw, 6 + th, th // 2, '#ffffff') + self._id_txt = [] + for i, (_k, t) in enumerate(self._items): + cx = self._pad + seg_w * (i + 0.5) + on = (i == self._idx) + self._id_txt.append(self.create_text( + cx, h // 2 + (1 if on else 0), text=t, font=self._font, + fill=C.brand if on else C.ink2)) + self._paint_idx = self._idx + + def _animate_to(self, target, ms=220): + if self._anim_job: + try: + self.after_cancel(self._anim_job) + except Exception: + pass + self._anim_job = None + start = self._thumb_x if self._thumb_x is not None else target + steps = max(1, int(ms / 16)) + n = [0] + + def tick(): + n[0] += 1 + k = n[0] / float(steps) + k = 1 - (1 - k) ** 3 # ease-out cubic + self._thumb_x = start + (target - start) * k + self._redraw() + if n[0] < steps: + self._anim_job = self.after(16, tick) + else: + self._thumb_x = target + self._anim_job = None + self._redraw() + tick() + + # -- 手势 + def _on_press(self, e): + self._drag = {'x0': e.x, 'start': self._thumb_x, 'moved': False} + if self._anim_job: + try: + self.after_cancel(self._anim_job) + except Exception: + pass + self._anim_job = None + + def _on_drag(self, e): + if not self._drag: + return + dx = e.x - self._drag['x0'] + if abs(dx) > 3: + self._drag['moved'] = True + seg_w = self._seg_w() + left = self._pad + right = self._pad + seg_w * (len(self._items) - 1) + x = max(left, min(right, self._drag['start'] + dx)) + self._thumb_x = x + self._idx = int(round((x - self._pad) / seg_w)) + self._idx = max(0, min(len(self._items) - 1, self._idx)) + # 触摸屏的 motion 事件会一波波砸进来(120Hz+),直接每事件重绘 + # 会把事件队列越压越多、滑块越拖越滞后。按 ~125fps 合并成 + # 「有脏标记才画」,滑块始终贴着最新位置,弱机上也不发卡。 + if self._motion_paint is None: + self._motion_paint = self.after(8, self._motion_paint_now) + + def _motion_paint_now(self): + self._motion_paint = None + self._redraw() + + def _on_release(self, e): + if not self._drag: + return + if not self._drag['moved']: + idx = int((e.x - self._pad) // self._seg_w()) + else: + idx = self._idx + idx = max(0, min(len(self._items) - 1, idx)) + self._drag = None + if self._motion_paint is not None: + # 拖动途中的挂起重绘交给动画去做,避免两次重绘打架 + try: + self.after_cancel(self._motion_paint) + except Exception: + pass + self._motion_paint = None + changed = (idx != self._idx) or True + self._idx = idx + self._animate_to(self._seg_x(idx)) + if self._command: + self._command(self._items[idx][0], idx) + + +# ------------------------------------------------------------------ 滑动开关 +class Switch(tk.Canvas): + """滑动开关:轨道变色 + 圆点滑过去。""" + + def __init__(self, parent, value=False, command=None, surface=None, + width=64, height=36, on_color=None): + surface = surface or _surface_of(parent) + super().__init__(parent, bg=surface, highlightthickness=0, bd=0, + width=width, height=height, takefocus=0) + self._surface = surface + # 注意:不能用 self._w / self._h —— tkinter 的 _w 是窗口路径 + self.sz_w = width + self.sz_h = height + self._on_color = on_color or C.brand + self._value = bool(value) + self._command = command + self._pos = 1.0 if value else 0.0 + self._job = None + self.bind('', self._toggle) + self.after(10, self._redraw) + + def get(self): + return self._value + + def set(self, value, animate=True): + value = bool(value) + if value == self._value: + self._redraw() + return + self._value = value + if animate: + self._animate(1.0 if value else 0.0) + else: + self._pos = 1.0 if value else 0.0 + self._redraw() + + def _toggle(self, _e=None): + self._value = not self._value + self._animate(1.0 if self._value else 0.0) + if self._command: + self._command(self._value) + + def _animate(self, target, ms=160): + if self._job: + try: + self.after_cancel(self._job) + except Exception: + pass + self._job = None + start = self._pos + steps = max(1, int(ms / 16)) + n = [0] + + def tick(): + n[0] += 1 + k = min(1.0, n[0] / float(steps)) + k = 1 - (1 - k) ** 3 + self._pos = start + (target - start) * k + self._redraw() + if n[0] < steps: + self._job = self.after(16, tick) + else: + self._pos = target + self._job = None + self._redraw() + tick() + + def _redraw(self): + w, h = self.sz_w, self.sz_h + if w <= 2 or h <= 2: + return + self.delete('all') + # 轨道颜色:关=灰,开=品牌色,中间随位置插值 + off = _hex_rgb('#cdd5e1') + on = _hex_rgb(self._on_color) + k = self._pos + col = '#%02x%02x%02x' % tuple( + int(off[i] + (on[i] - off[i]) * k) for i in range(3)) + ph = rounded_photo(w, h, h // 2, col, self._surface) + if ph is not None: + self.create_image(0, 0, anchor='nw', image=ph) + self._ph = ph + else: + draw_round(self, 0, 0, w - 1, h - 1, h // 2, col) + d = h - 8 + x = 4 + (w - d - 8) * k + kp = rounded_photo(d, d, d // 2, '#ffffff', col) + if kp is not None: + self.create_image(int(x), 4, anchor='nw', image=kp) + self._ph_knob = kp + else: + self.create_oval(x, 4, x + d, 4 + d, fill='#ffffff', outline='') + + +# ------------------------------------------------------------------ 步骤条 +class StepsBar(tk.Canvas): + """5 段圆角步骤条:已完成=绿、当前=琥珀、未到=灰。""" + + def __init__(self, parent, steps, surface=None, height=44, + font=None, gap=6): + surface = surface or _surface_of(parent) + super().__init__(parent, bg=surface, highlightthickness=0, bd=0, + height=height, takefocus=0) + self._surface = surface + self._steps = list(steps) + self._h = height + self._gap = gap + self._font = font or ('Microsoft YaHei', 11) + self._idx = -1 + self.bind('', lambda e: self._redraw()) + self.after(10, self._redraw) + + def set_state(self, idx): + if idx == self._idx: + return + self._idx = idx + self._redraw() + + def _redraw(self): + w, h = self.winfo_width(), self.winfo_height() + if w <= 2 or h <= 2: + return + self.delete('all') + n = max(1, len(self._steps)) + gap = self._gap + sw = (w - gap * (n - 1)) / float(n) + for i, text in enumerate(self._steps): + if i < self._idx: + fill, fg = C.green_soft, C.green + elif i == self._idx: + fill, fg = '#fdeccd', '#8a5a11' + else: + fill, fg = '#f1f3f7', C.ink3 + x = i * (sw + gap) + ph = rounded_photo(int(sw), h, h // 2, fill, self._surface) + if ph is not None: + self.create_image(int(x), 0, anchor='nw', image=ph) + if not hasattr(self, '_phs'): + self._phs = [] + self._phs.append(ph) + self._phs = self._phs[-12:] + else: + draw_round(self, x, 0, x + sw, h - 1, h // 2, fill) + self.create_text(x + sw / 2, h // 2, text=text, + font=self._font, fill=fg) + + +# ------------------------------------------------------------------ 翻页容器 +class Pager(tk.Frame): + """横向页面容器:手指左右拖跟手移动,松手吸附到最近一页。 + + 页面用 Canvas 内嵌窗口实现——滑动只是移动画布视口,不重建控件, + 摄像头预览这种一直在刷新的页面也不会因为翻页而卡顿。 + """ + + def __init__(self, parent, bg=None, on_change=None): + bg = bg or _surface_of(parent) + super().__init__(parent, bg=bg) + self._bg = bg + self._cv = tk.Canvas(self, bg=bg, highlightthickness=0, bd=0, + takefocus=0) + self._cv.pack(fill='both', expand=True) + self._pages = [] + self._items = [] + self._idx = 0 + self._on_change = on_change + self._anim = None + self._drag = None + self._cv.bind('', self._on_configure) + + # -- 接口 + def add(self, page): + self._pages.append(page) + item = self._cv.create_window((0, 0), window=page, anchor='nw') + self._items.append(item) + self._sync_geom() + return page + + def count(self): + return len(self._pages) + + def index(self): + return self._idx + + def show(self, idx, animate=True, notify=False): + if not self._pages: + return + idx = max(0, min(len(self._pages) - 1, idx)) + changed = idx != self._idx + self._idx = idx + if animate: + self._animate_to(idx) + else: + self._set_frac(idx) + if notify and changed and self._on_change: + self._on_change(idx) + + # -- 几何 / 滚动 + def _on_configure(self, _e=None): + self._sync_geom() + + def _sync_geom(self): + if not self._pages: + return + w = self._cv.winfo_width() + h = self._cv.winfo_height() + if w <= 2 or h <= 2: + return + for i, item in enumerate(self._items): + self._cv.coords(item, i * w, 0) + self._cv.itemconfigure(item, width=w, height=h) + n = len(self._pages) + self._cv.configure(scrollregion=(0, 0, w * n, h)) + self._set_frac(self._idx) + + def _set_frac(self, idx): + n = max(1, len(self._pages)) + try: + self._cv.xview_moveto(idx / float(n)) + except Exception: + pass + + def _cur_frac(self): + try: + return self._cv.xview()[0] + except Exception: + return 0.0 + + def _animate_to(self, idx, ms=260): + if self._anim: + try: + self.after_cancel(self._anim) + except Exception: + pass + self._anim = None + n = max(1, len(self._pages)) + start = self._cur_frac() + target = idx / float(n) + if abs(target - start) < 0.0005: + self._set_frac(idx) + return + steps = max(1, int(ms / 16)) + k = [0] + + def tick(): + k[0] += 1 + p = min(1.0, k[0] / float(steps)) + p = 1 - (1 - p) ** 3 + try: + self._cv.xview_moveto(start + (target - start) * p) + except Exception: + pass + if k[0] < steps: + self._anim = self.after(16, tick) + else: + self._anim = None + self._set_frac(idx) + tick() + + # -- 手势(由 bind_swipe_to 绑到页面里的普通控件上) + def _press(self, e): + self._drag = {'x0': e.x_root, 'y0': e.y_root, + 'frac': self._cur_frac(), 'axis': None, 'moved': False} + if self._anim: + try: + self.after_cancel(self._anim) + except Exception: + pass + self._anim = None + + def _motion(self, e): + d = self._drag + if not d: + return + dx = e.x_root - d['x0'] + dy = e.y_root - d['y0'] + if d['axis'] is None: + if abs(dx) < 9 and abs(dy) < 9: + return + # 横向占优才翻页,否则交给页面自己的纵向滚动 + d['axis'] = 'h' if abs(dx) > abs(dy) * 1.25 else 'v' + if d['axis'] == 'h': + d['moved'] = True + if d['axis'] != 'h': + return + w = max(1, self._cv.winfo_width()) + n = max(1, len(self._pages)) + frac = d['frac'] - dx / float(w * n) + frac = max(0.0, min((n - 1) / float(n), frac)) + try: + self._cv.xview_moveto(frac) + except Exception: + pass + + def _release(self, e): + d = self._drag + self._drag = None + if not d or d['axis'] != 'h': + return + n = max(1, len(self._pages)) + frac = self._cur_frac() * n + base = int(round(frac)) + dx = e.x_root - d['x0'] + if abs(dx) > max(60, self._cv.winfo_width() * 0.16): + target = self._idx + (1 if dx < 0 else -1) + else: + target = base + target = max(0, min(n - 1, target)) + self._idx = target + self._animate_to(target) + if self._on_change: + self._on_change(target) + + +def bind_swipe_to(widget, pager, skip=(), force=False): + """把普通控件也接到翻页手势上(按钮/输入框/自绘画布除外)""" + if widget in skip: + return + if not force and isinstance(widget, (tk.Button, tk.Entry, tk.Text, + tk.Canvas)): + return + try: + if widget.cget('class') in ('TButton', 'TEntry', 'TSpinbox'): + return + except Exception: + pass + try: + widget.bind('', pager._press, add='+') + widget.bind('', pager._motion, add='+') + widget.bind('', pager._release, add='+') + except Exception: + pass + + +def bind_swipe_recursive(widget, pager, depth=0): + """整块页面(含子控件)都能滑动翻页:一次绑定,之后动态加的子控件不生效""" + if depth > 6: + return + bind_swipe_to(widget, pager) + for ch in widget.winfo_children(): + bind_swipe_recursive(ch, pager, depth + 1) + + +# ------------------------------------------------------------------ 触摸滚动 +class TouchScroll: + """手指拖动滚动 + 惯性;纵向手势自己吃掉,横向让给翻页。""" + + def __init__(self, canvas, min_content=0): + self.cv = canvas + self.moved = False + self._drag = None + self._anim = None + self._min = min_content + canvas.configure(yscrollincrement=1) + + def attach(self, widget, allow_click=True): + try: + widget.bind('', self._press, add='+') + widget.bind('', self._motion, add='+') + widget.bind('', self._release, add='+') + widget.bind('', self._wheel, add='+') + if allow_click: + # 拖动后松手不触发卡片点选:用标记让调用方自己判断 + pass + except Exception: + pass + + def attach_tree(self, widget, depth=0): + if depth > 6: + return + self.attach(widget) + for ch in widget.winfo_children(): + self.attach_tree(ch, depth + 1) + + # -- 尺寸 + def _geom(self): + # 内容高度只在重建卡片/改列数/筛选时变,滚动期间不会变。原来每次 + # 按下、每次滚轮都 bbox('all') 查一遍(上百个卡片项),弱机上就是 + # 那几毫秒一卡一卡。缓存 0.5 秒,重建后最多半秒自愈。 + now = _time.monotonic() + c = getattr(self, '_gc', None) + if c and now - c[2] < 0.5: + return c[0], c[1] + try: + bbox = self.cv.bbox('all') or (0, 0, 0, 0) + total = max(1, bbox[3] - bbox[1]) + view = max(1, self.cv.winfo_height()) + except Exception: + return 1, 1 + self._gc = (total, view, now) + return total, view + + def _press(self, e): + self._stop() + self.moved = False + # 拖动期间缓存内容高度/视口高度,别每个 motion 都去 bbox('all'); + # 待办名单一长,这个查询本身就吃好几毫秒,拖起来发卡。 + total, view = self._geom() + self._drag = {'y0': e.y_root, 'x0': e.x_root, + 'frac': self.cv.yview()[0], 'axis': None, + 't': e.time or 0, 'last_y': e.y_root, + 'v': 0.0, 'total': total, 'view': view, + 'target': None, 'painted_at': 0.0} + + def _motion(self, e): + d = self._drag + if not d: + return + dy = e.y_root - d['y0'] + dx = e.x_root - d['x0'] + total, view = d['total'], d['view'] + if total <= view + 2: + return + if d['axis'] is None: + if abs(dx) < 9 and abs(dy) < 9: + return + d['axis'] = 'v' if abs(dy) >= abs(dx) * 0.8 else 'h' + if d['axis'] != 'v': + return + if abs(dy) > 6: + self.moved = True # 拖动滚名单时不要顺手把卡片选中 + frac = d['frac'] - dy / float(total) + frac = max(0.0, min(1.0 - view / float(total), frac)) + # v1.0.49:触摸屏一秒能发 100~200 个 Motion,每个都滚一次就把界面 + # 拖垮(每滚一次 Tk 要重画整块卡片区)。这里限帧,中间的 + # 事件只记位置不重画;松手时再补最后一下。 + # v1.0.56:16ms→24ms。现场 i5-4200U 上滚一帧本身就要 20~25ms, + # 按 60fps 限反而每帧都堆在队列里,松手后还要把积压的帧画完, + # 手感是「拖不动、一松手猛跳一下」。42fps 才是这台机器跟得上的节奏。 + d['target'] = frac + now = _time.monotonic() + if now - d.get('painted_at', 0.0) >= 0.024: + d['painted_at'] = now + try: + self.cv.yview_moveto(frac) + except Exception: + pass + # 速度只用来算惯性:事件不带时间戳(time=0,部分触摸驱动/合成事件 + # 就是这样)时 dt 会变成 1ms,速度虚高几十倍,松手直接甩到底。 + # 真手指最快也就 3~5 px/ms,夹到 6 以内,异常值一律当 0。 + now_t = int(getattr(e, 'time', 0) or 0) + if now_t and d['t'] and now_t > d['t']: + dt = now_t - d['t'] + v = (e.y_root - d['last_y']) / float(dt) # px/ms + d['v'] = max(-6.0, min(6.0, v)) + d['t'] = now_t + else: + d['v'] = 0.0 + d['last_y'] = e.y_root + + def _release(self, _e=None): + d = self._drag + self._drag = None + if not d or d.get('axis') != 'v': + return + # 补画最后一下(拖动时限了帧率,末位可能是没画出来的那帧) + if d.get('target') is not None: + try: + self.cv.yview_moveto(d['target']) + except Exception: + pass + v = d.get('v') or 0.0 + if abs(v) < 0.35: + return + total, view = self._geom() + if total <= view + 2: + return + self._fling(v, total, view) + + def _fling(self, v, total, view): + frac = self.cv.yview()[0] + step = 0.0 + # 24ms 一帧(和拖动限帧一致):衰减按「同样减速度」换算, + # 16ms 时的 0.90 → 24ms 约 0.86,甩出去的距离才跟手一致 + gap = 24 + + def tick(): + nonlocal frac, v + v *= 0.86 + frac = frac - v * gap / float(total) + frac = max(0.0, min(1.0 - view / float(total), frac)) + try: + self.cv.yview_moveto(frac) + except Exception: + return + if abs(v) > 0.05: + self._anim = self.cv.after(gap, tick) + else: + self._anim = None + if abs(step) < 1: + tick() + + def _wheel(self, e): + total, view = self._geom() + if total <= view + 2: + return + d = -1 if getattr(e, 'delta', 0) > 0 else 1 + # v1.0.56:原来一格只走 3px(名单总高 5595px 时是 0.1%),滚一格几乎 + # 看不出动,现场连滚十几下才走一屏,感受就是「滑不动」。改成一格 + # 走四分之一屏,靠手感接近网页。 + step = max(3, int(view * 0.25)) + try: + self.cv.yview_scroll(d * step, 'units') + except Exception: + pass + return 'break' + + def _stop(self): + if self._anim: + try: + self.cv.after_cancel(self._anim) + except Exception: + pass + self._anim = None + + +class TapGate: + """按下→松手之间手指有没有挪过:挪过就是「拖动」,不算「点」。 + + 为什么要单独一个:`TouchScroll.moved` 只在「内容比视口高、且纵向拖动」 + 时才置位,卡片区内容装得下、或者斜着划一下,它一直是 False —— + 于是滑名单松手就点中了卡片(确认状态下直接打一张标签)。 + 这里只认几何位移,和滚动条、内容高度都无关: + + · 位移超过 tol(默认 12px)→ 不算点,滚名单/滑下拉都不选中; + · 按下和松手不在同一条(key 不同,例如从这张卡滑到那张卡)→ 不算点; + · 按住超过 max_ms(默认 900ms)→ 不算点(长按多半是想拖)。 + + 一个实例可以共给整片卡片区:同一时刻只可能有一根手指按着。 + """ + + def __init__(self, tol=12, max_ms=900): + self.tol = tol + self.max_ms = max_ms + self._key = None + self._x = 0.0 + self._y = 0.0 + self._t = 0 + self._ok = False + + def press(self, e, key=None): + try: + self._x = float(e.x_root) + self._y = float(e.y_root) + except Exception: + self._x = self._y = 0.0 + self._t = int(getattr(e, 'time', 0) or 0) + self._key = key + self._ok = True + + def motion(self, e): + if not self._ok: + return + try: + dx = abs(float(e.x_root) - self._x) + dy = abs(float(e.y_root) - self._y) + except Exception: + return + if dx > self.tol or dy > self.tol: + self._ok = False + + def release(self, e=None, key=None): + """松手:是「点」就返回 True。无论结果如何都会清掉本次状态。""" + ok = self._ok + self._ok = False + if not ok: + return False + if key is not None and self._key is not None and key != self._key: + return False # 从别处滑过来松手,不算点这条 + t = int(getattr(e, 'time', 0) or 0) + if t and self._t and (t - self._t) > self.max_ms: + return False + return True + + +def bind_drag_scroll(canvas, widgets=()): + """便捷函数:给 canvas 建一个 TouchScroll 并挂到给定控件上""" + ts = TouchScroll(canvas) + for w in widgets: + ts.attach(w) + return ts