Files
pricing_review/CostReview/app/shell.py

462 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
M5 窗口壳:双击这个脚本 → 直接弹出「造价审核」软件窗口(没有地址栏、没有标签页)。
内部仍然是本地服务 + 网页内容(同一个 Edge WebView2 渲染引擎),但你看到的就是一个普通软件窗口。
排错:每一步都会打印,并同时写进 造价审核\\data\\launch.log
"""
import os, re, sys, json, time, threading, urllib.request, urllib.error, urllib.parse, socket, traceback
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) # 造价审核/
sys.path.insert(0, os.path.join(HERE, "server"))
sys.path.insert(0, os.path.join(HERE, "core"))
import api_server
PORT = api_server.PORT
def _page_ver(name):
"""页面文件 mtime 作版本参数(2026-10-12):文件一更新 URL 就变,任何内核的
磁盘缓存都必然失配。起因:主人的 WebView2 对静态响应的 no-store 不完全遵守,
价格库重设计后壳里一直显示旧界面(IAB/新浏览器带 ?v= 才是新的)。"""
try:
return str(int(os.path.getmtime(os.path.join(api_server.ROOT, name))))
except Exception:
return "0"
URL = "http://127.0.0.1:%d/workbench.html?v=%s" % (PORT, _page_ver("workbench.html"))
ADMIN_URL = "http://127.0.0.1:%d/admin.html?v=%s" % (PORT, _page_ver("admin.html"))
LOG = os.path.join(ROOT, "data", "launch.log")
# ---------- 原生「另存为」桥(决策 91,2026-10-17 主人定「全部是另存为」)----------
# 壳里的 WebView2 对 JS 的 showSaveFilePicker 支持不稳(实测直接抛错掉进静默下载,
# 文件落到下载目录深处主人找不到)——由 Python 侧接管:页面调
# window.pywebview.api.download_save_as(相对url, 建议名),这里弹**原生另存为对话框**
# (文件名预填 工程名-审核版.原后缀),把本地服务的下载内容写到所选位置。
# 普通浏览器没有这个桥,页面自动落回原有 showSaveFilePicker 分支,互不影响。
_LAST_SAVE_DIR = {"d": ""} # 本次运行记住的上一另存位置(下次同目录打开)
class _BridgeApi:
def export_save_as(self, session_id, suggested_name=""):
"""决策 92(主人定流程):点导出=①先弹原生另存为选路径(此刻还不生成,大工程不再干等)
→②后台线程生成+分块写盘(逐条目进度经 evaluate_js 推给页面进度条)
→③完成/失败也推给页面(模态收尾或后台 toast)。"""
try:
sid = int(session_id)
except Exception:
return {"ok": False, "msg": "会话参数不合法"}
name = (suggested_name or "").strip()
if not name:
try:
req = urllib.request.urlopen(
"http://127.0.0.1:%d/api/session/export/meta?session_id=%d" % (PORT, sid), timeout=15)
j = json.loads(req.read().decode("utf-8", "replace"))
if j.get("ok"):
name = j.get("name") or name
except Exception:
pass
if not name:
name = "工程导出.cos4"
import webview
win = webview.windows[0] if webview.windows else None
if win is None:
return {"ok": False, "msg": "窗口未就绪"}
ext = os.path.splitext(name)[1]
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
fd = getattr(webview, "FileDialog", None)
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
save_filename=name, file_types=ftypes)
if not picked:
return {"ok": False, "cancel": True}
p = picked if isinstance(picked, str) else picked[0]
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
threading.Thread(target=self._export_worker, args=(win, sid, p, name), daemon=True).start()
return {"ok": True, "started": True, "path": p, "name": name}
def _push(self, win, payload):
"""进度推给页面(window.__exportProgress 由 workbench 定义;后台与否页面自己决定展示)。"""
try:
win.evaluate_js("window.__exportProgress && window.__exportProgress(%s)"
% json.dumps(payload, ensure_ascii=False))
except Exception:
pass
def _export_worker(self, win, sid, path, name):
token = "x%d" % int(time.time() * 1000000)
base = "http://127.0.0.1:%d" % PORT
stop = threading.Event()
def poller(): # 生成阶段(响应头没回来)轮询逐条目进度
while not stop.is_set():
try:
r = urllib.request.urlopen(
base + "/api/session/export/progress?token=" + token, timeout=5)
j = json.loads(r.read().decode("utf-8", "replace"))
if j.get("total"):
self._push(win, {"phase": "gen", "done": j.get("done", 0),
"total": j.get("total", 0)})
except Exception:
pass
stop.wait(1.0)
pt = threading.Thread(target=poller, daemon=True)
pt.start()
tmp = path + ".part"
try:
self._push(win, {"phase": "gen"})
req = urllib.request.urlopen(base + "/api/session/export?session_id=%d&token=%s" % (sid, token),
timeout=3600)
stop.set() # 响应头到了=生成完毕,轮询停;接下来按字节真实进度
if "json" in (req.headers.get("Content-Type") or "").lower():
j = json.loads(req.read().decode("utf-8", "replace"))
self._push(win, {"done": False, "msg": j.get("msg") or "服务端返回错误"})
return
total = int(req.headers.get("Content-Length") or 0)
done, last = 0, -1
with open(tmp, "wb") as f:
while True:
chunk = req.read(262144)
if not chunk:
break
f.write(chunk)
done += len(chunk)
if total:
pct = int(done * 100 / total)
if pct != last:
last = pct
self._push(win, {"phase": "put", "pct": pct})
if total and done != total:
raise IOError("下载不完整 %d/%d 字节" % (done, total))
os.replace(tmp, path)
_log("已另存为:%s(%d 字节)" % (path, done))
self._push(win, {"done": True, "path": path, "name": os.path.basename(path)})
except Exception as e:
stop.set()
try:
os.remove(tmp)
except OSError:
pass
_log("导出失败:%s\n%s" % (e, traceback.format_exc()))
self._push(win, {"done": False, "msg": str(e)})
finally:
stop.set()
def download_save_as(self, url, suggested_name=""):
try:
if not url or not url.startswith("/") or url.startswith("//"):
return {"ok": False, "msg": "非法下载地址"}
req = urllib.request.urlopen("http://127.0.0.1:%d%s" % (PORT, url), timeout=600)
data = req.read()
if "json" in (req.headers.get("Content-Type") or "").lower():
j = json.loads(data.decode("utf-8", "replace"))
return {"ok": False, "msg": j.get("msg") or "服务端返回错误"}
cd = req.headers.get("Content-Disposition") or ""
name = (suggested_name or "").strip()
m = re.search(r"filename\*=UTF-8''([^;]+)", cd)
if not m:
m = re.search(r'filename="([^"]+)"', cd)
if m:
try:
name = urllib.parse.unquote(m.group(1), errors="replace")
except Exception:
pass
if not name:
name = "下载文件"
import webview
win = webview.windows[0] if webview.windows else None
if win is None:
return {"ok": False, "msg": "窗口未就绪"}
ext = os.path.splitext(name)[1]
ftypes = ("文件 (*%s)" % ext, "所有文件 (*.*)") if ext else ("所有文件 (*.*)",)
fd = getattr(webview, "FileDialog", None)
dtype = fd.SAVE if fd is not None else webview.SAVE_DIALOG
picked = win.create_file_dialog(dtype, directory=_LAST_SAVE_DIR["d"],
save_filename=name, file_types=ftypes)
if not picked:
return {"ok": False, "cancel": True}
p = picked if isinstance(picked, str) else picked[0]
_LAST_SAVE_DIR["d"] = os.path.dirname(p)
with open(p, "wb") as f:
f.write(data)
_log("已另存为:%s(%d 字节)" % (p, len(data)))
return {"ok": True, "path": p, "name": os.path.basename(p)}
except Exception as e:
_log("另存为失败:%s\n%s" % (e, traceback.format_exc()))
return {"ok": False, "msg": str(e)}
def _log(msg):
line = "[%s] %s" % (time.strftime("%H:%M:%S"), msg)
print(line, flush=True)
try:
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write(line + "\n")
except Exception:
pass
def port_in_use():
s = socket.socket()
s.settimeout(0.5)
ok = s.connect_ex(("127.0.0.1", PORT)) == 0
s.close()
return ok
def server_healthy():
"""端口有监听 ≠ 服务能用:垂死进程的套接字还能完成 TCP 握手,但 HTTP 已不应答。
用一次带超时的 HTTP 探活区分健康/垂死(2026-10-11 启动竞态加固)。
有任何 HTTP 应答(含 404/403)都算活;只有连接被拒/超时才算垂死。"""
try:
urllib.request.urlopen("http://127.0.0.1:%d/admin.html" % PORT, timeout=1)
return True
except urllib.error.HTTPError:
return True
except Exception:
return False
def _code_mtime():
"""程序代码更新时间——与 api_server._code_mtime 同口径(api_server.py + core/*.py +
server/*.py 的最新 mtime)。启动器拿它和端口上实例自报的版本比,判断是不是旧代码。"""
import glob
files = [os.path.abspath(__file__)]
for sub in ("core", "server"):
files += glob.glob(os.path.join(api_server.ROOT, sub, "*.py"))
mt = 0.0
for f in files:
try:
mt = max(mt, os.path.getmtime(f))
except OSError:
pass
return mt
def remote_code_mtime():
"""端口上健康实例自报的代码时间;报不出来(更老的实例没有 /api/version)→ None=视为过期。"""
import json
try:
r = urllib.request.urlopen("http://127.0.0.1:%d/api/version" % PORT, timeout=2)
j = json.loads(r.read().decode("utf-8"))
return float(j["code_mtime_f"]) if j.get("ok") else None
except Exception:
return None
def kill_port_owner():
"""结束占用本端口的进程——只可能是我们自己的旧实例(单实例互斥保证)。"""
import subprocess
try:
out = subprocess.check_output(["netstat", "-ano", "-p", "TCP"], text=True, errors="replace")
except Exception:
return False
pids = set()
for line in out.splitlines():
parts = line.split()
if len(parts) >= 5 and parts[1] == "127.0.0.1:%d" % PORT and parts[3] == "LISTENING":
pids.add(parts[4])
hit = False
for pid in pids:
try:
subprocess.run(["taskkill", "/PID", pid, "/F"], capture_output=True)
hit = True
except Exception:
pass
return hit
def wait_ready(timeout=15):
for _ in range(int(timeout / 0.25)):
try:
urllib.request.urlopen("http://127.0.0.1:%d/admin.html" % PORT, timeout=1)
return True
except Exception:
time.sleep(0.25)
return False
def serve_admin_mode():
"""后台管理模式:起服务 + 用默认浏览器打开后台管理,本窗口保持运行即服务在跑。"""
import webbrowser
_log("后台管理模式:用默认浏览器打开 %s" % ADMIN_URL)
webbrowser.open(ADMIN_URL)
print("已打开后台管理。要停止服务,直接关掉这个黑窗口。", flush=True)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
return 0
def fallback_to_browser(reason):
"""独立窗口起不来时的兜底:用默认浏览器打开,至少保证能用。"""
import webbrowser
_log("兜底:改用默认浏览器打开(%s)" % reason)
webbrowser.open(URL)
print("已改用默认浏览器打开。若浏览器也没反应,请手动访问:%s" % URL, flush=True)
time.sleep(2)
WEBVIEW2_KEY = r"Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
WEBVIEW2_DL = "https://developer.microsoft.com/microsoft-edge/webview2/"
def webview2_available():
"""WebView2 运行库装没装:查 EdgeUpdate 的 pv 版本号(HKLM/HKCU、两种注册表视图都查)。
返回 True/False/None —— None = 检测不了(非 Windows / 注册表读不到),当作"可能行",
让后面的 webview.start 异常兜底去处理,不在这里误杀。
"""
if os.name != "nt":
return None
try:
import winreg
except Exception:
return None
for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
for view in (winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY):
try:
with winreg.OpenKey(root, WEBVIEW2_KEY, 0, view | winreg.KEY_READ) as k:
pv = (winreg.QueryValueEx(k, "pv")[0] or "").strip()
if pv and pv != "0.0.0.0":
return True
except OSError:
continue
return False
def warn_webview2_missing():
"""运行库缺失:弹窗说明 + 提供"打开官方下载页",用户关掉弹窗后走浏览器兜底。"""
try:
import ctypes
MB_OKCANCEL, MB_ICONWARN = 0x0, 0x30
r = ctypes.windll.user32.MessageBoxW(
0,
"独立窗口需要 Microsoft Edge WebView2 运行库,这台电脑上没有检测到。\n\n"
"点「确定」打开官方下载页(免费,装一次即可);\n"
"点「取消」直接用默认浏览器打开软件(功能相同)。",
"造价审核 · 需要一次性安装组件",
MB_OKCANCEL | MB_ICONWARN)
if r == 1:
import webbrowser
webbrowser.open(WEBVIEW2_DL)
except Exception:
pass
def main():
_log("启动中…(端口 %d)" % PORT)
# 1) 后台起本地服务;端口已有服务则直接复用,避免重复占用数据库
# 2026-10-11 加固(主人拍板):端口被占 ≠ 服务健康——关窗后旧进程收尾期间套接字
# 还没释放,新实例会误「复用」一个垂死服务跟着一起死(表现为「关了马上开就打不开」)。
# 现在被占时先 HTTP 探活:健康才复用;不健康等 2 秒重试最多 5 次(约 10 秒),
# 让旧进程把端口让出来后正常自起;等完仍占用且无响应 → 明确报错指引清残留。
reused = False
if port_in_use():
healthy = False
for attempt in range(5):
if server_healthy():
healthy = True
break
if not port_in_use():
break # 收尾进程让位了 → 落到下面正常自起
if attempt < 4:
_log("端口 %d 被占但服务无响应(疑似旧进程收尾中),2 秒后重试 %d/5" % (PORT, attempt + 1))
time.sleep(2)
if healthy:
# 2026-10-17 主人需求「重启后永远是最新程序」:端口上的健康实例,代码比磁盘旧
# (或老到不认识版本接口)→ 自动结束它、加载新代码再开窗;同版本才复用。
remote = remote_code_mtime()
local = _code_mtime()
if remote is not None and remote >= local - 1: # 1 秒容差(mtime 秒级)
_log("端口 %d 服务已是最新版本,直接复用" % PORT)
reused = True
else:
_log("端口 %d 上是旧版本程序(代码时间 %s,磁盘已是 %s),自动升级重启…" % (
PORT,
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(remote)) if remote else "未知(更老的实例)",
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(local))))
kill_port_owner()
for _ in range(40): # 最多 10 秒等端口让出
if not port_in_use():
break
time.sleep(0.25)
if port_in_use():
_log("旧实例未能结束(端口仍被占),请到任务管理器结束 python.exe 后重试")
print("旧版本实例结束失败,请到任务管理器结束 python.exe 后再双击本文件", flush=True)
return 1
_log("旧实例已结束,加载新代码…")
elif port_in_use():
_log("服务启动失败:端口 %d 被占且多次探活无响应(残留进程),请到任务管理器结束 python.exe 后重试" % PORT)
print("端口 %d 被残留进程占用且无响应,请到任务管理器结束 python.exe 后再双击本文件" % PORT, flush=True)
return 1
if not reused:
threading.Thread(target=api_server.run, daemon=True).start()
if not wait_ready():
_log("服务启动失败:端口 %d 起不来(可能被其他程序占用)" % PORT)
print("服务启动失败,请检查端口 %d 是否被占用" % PORT, flush=True)
return 1
_log("本地服务就绪")
# 后台管理入口(launch.py admin):不弹软件窗口,用浏览器打开
if "--admin" in sys.argv:
return serve_admin_mode()
# 2) 弹出独立窗口
try:
import webview
except Exception as e:
_log("缺少 pywebview:%s" % e)
print("缺少 pywebview,请先执行:%s -m pip install pywebview" % sys.executable, flush=True)
return 1
# 2.5) WebView2 运行库预检(2026-10-07 单机分发):没装就先说清楚,给出官方下载页;
# 用户不想装 → 浏览器兜底,软件照常能用(窗口只是更好的壳)。
_w2 = webview2_available()
_log("WebView2 运行库检测结果:%s" % _w2)
if _w2 is False:
warn_webview2_missing()
fallback_to_browser("WebView2 运行库缺失")
return 0
try:
win = webview.create_window(
"造价审核",
URL,
width=1440, height=900, min_size=(1100, 700),
text_select=True, # 允许选中复制表格里的文字
confirm_close=True,
js_api=_BridgeApi(), # 原生另存为桥(决策 91):页面导出/附件一律弹系统保存框
)
except Exception as e:
_log("窗口创建失败:%s" % e)
traceback.print_exc()
fallback_to_browser("窗口创建失败")
return 1
_log("窗口已创建,正在进入界面…")
try:
webview.start(debug=False)
except Exception as e:
_log("窗口运行异常:%s" % e)
traceback.print_exc()
fallback_to_browser("窗口运行异常")
return 1
_log("窗口已关闭,退出")
return 0
if __name__ == "__main__":
sys.exit(main())