diff --git a/backend/core/settings.py b/backend/core/settings.py index d5a6c36..fd64935 100644 --- a/backend/core/settings.py +++ b/backend/core/settings.py @@ -217,6 +217,9 @@ def ensure_dirs(): # 卫戍协议速刷核心(service.mjs 所在目录,GPL,不随本程序分发); # 空时按约定位置找:<运行根>/garrison/core 等,见 garrison.core_dir 'garrisonCoreDir': '', + # 主窗口位置/大小(逻辑像素):{x,y,width,height,max}。用户拖动/缩放后 + # 由 main.py 在窗口关闭时写回,下次启动按它还原;空 = 默认大小居中 + 'windowGeom': {}, # 内置助手:只存连接参数,apiKey 走 DPAPI 单独存 config/agent.key 'agent': { 'baseUrl': 'https://api.deepseek.com/v1', @@ -393,6 +396,28 @@ def _norm_op_blacklist(v) -> list: return out +def _norm_window_geom(v) -> dict: + """主窗口几何:只收 {x,y,width,height,max},坏值丢弃 + + 坐标允许负数(多显示器左侧/上方),但限个范围防止手改 json 写成天文数字; + 宽高只收像样的窗口尺寸。位置是否还在屏幕上由 main.py 启动时再判断。 + """ + if not isinstance(v, dict): + return {} + out = {} + for k, lo, hi in (('x', -100000, 100000), ('y', -100000, 100000), + ('width', 800, 10000), ('height', 500, 10000)): + try: + n = int(round(float(v.get(k)))) + except (TypeError, ValueError): + continue + if lo <= n <= hi: + out[k] = n + if 'max' in v: + out['max'] = bool(v.get('max')) + return out + + def _merged_dirs(dirs, extra): """历史目录列表并入一个新目录(过滤脏值,大小写不敏感去重)""" out = [d for d in (dirs or []) if isinstance(d, str) and d] @@ -435,6 +460,8 @@ def save(patch: dict) -> dict: v = _norm_dir(v) if v else '' elif k == 'garrisonCoreDir': v = _norm_dir(v) if v else '' + elif k == 'windowGeom': + v = _norm_window_geom(v) elif k == 'emulatorAutoStart': # 前端可能传 "false" / 0 / 空串,别让字符串 "false" 变成真 v = bool(v) and str(v).strip().lower() not in ('0', 'false', 'no', '') diff --git a/backend/main.py b/backend/main.py index d8b5bd3..294a7eb 100644 --- a/backend/main.py +++ b/backend/main.py @@ -399,6 +399,10 @@ def _quit(code=0, reason='退出'): app.log 里也看不出个所以然。退出前最多等 5 秒,等不完就如实记录。 """ log('正在退出(%s)…' % reason) + try: + _wingeom_save() # 窗口几何先落盘(窗口还活着时读得到实际位置) + except Exception: + pass try: from core import watch as _watch _watch.stop_all() # 观测线程是 daemon,但主动停能让它把最后一条日志写完 @@ -424,6 +428,84 @@ def _quit(code=0, reason='退出'): os._exit(code) +# ---------------------------------------------------------------- 窗口位置记忆 +# pywebview 的 moved/resized/maximized/restored 事件都是逻辑像素,和 +# create_window(x=, y=, width=, height=) 的口径一致。关闭时写回 +# settings.json 的 windowGeom,下次启动按它还原;位置不在任何屏幕上 +# (换显示器/拔屏)就退回居中,别把窗口丢到看不见的地方。 +_WINGEOM = {'x': None, 'y': None, 'width': None, 'height': None, + 'max': False, 'min': False} +_WINGEOM_LOCK = threading.Lock() +_WIN = [None] # 主窗口(供 _quit 兜底保存) +_WIN_SHOWN = [False] + + +def _geom_visible(g: dict, screens) -> bool: + """保存的位置至少让标题栏露出 120x30,否则当没存过""" + try: + x, y, w, h = (int(g.get(k)) for k in ('x', 'y', 'width', 'height')) + except (TypeError, ValueError): + return False + for s in screens or []: + ix = min(x + w, s.x + s.width) - max(x, s.x) + iy = min(y + 40, s.y + s.height) - max(y, s.y) + if ix >= 120 and iy >= 30: + return True + return False + + +def _wingeom_moved(x, y): + with _WINGEOM_LOCK: + if not (_WINGEOM['max'] or _WINGEOM['min']): + _WINGEOM['x'], _WINGEOM['y'] = int(x), int(y) + + +def _wingeom_resized(w, h): + with _WINGEOM_LOCK: + if not (_WINGEOM['max'] or _WINGEOM['min']): + _WINGEOM['width'], _WINGEOM['height'] = int(w), int(h) + + +def _wingeom_maximized(): + with _WINGEOM_LOCK: + _WINGEOM['max'] = True + _WINGEOM['min'] = False + + +def _wingeom_minimized(): + with _WINGEOM_LOCK: + _WINGEOM['min'] = True + + +def _wingeom_restored(): + with _WINGEOM_LOCK: + _WINGEOM['max'] = False + _WINGEOM['min'] = False + + +def _wingeom_save(): + """把主窗口几何写回 settings.json(窗口关闭/进程退出时调用,幂等)""" + with _WINGEOM_LOCK: + g = {k: _WINGEOM[k] for k in ('x', 'y', 'width', 'height') + if _WINGEOM.get(k) is not None} + g['max'] = bool(_WINGEOM.get('max')) + frozen = bool(_WINGEOM.get('max') or _WINGEOM.get('min')) + win = _WIN[0] + if win is not None and _WIN_SHOWN[0] and not frozen: + # 最大化/最小化时读出来的是屏幕尺寸或 -32000,用事件里攒的正常值 + try: + g.update(x=int(win.x), y=int(win.y), + width=int(win.width), height=int(win.height)) + except Exception: + pass + try: + if g.get('width') and g.get('height'): + settings.save({'windowGeom': g}) + except Exception: + log(traceback.format_exc()) + return True # closing 事件:不返回 False 就不会拦关闭 + + def main(): # CLI 入口:打包后同一个 exe 用 `MAA-PRTS.exe --cli accounts` 调 # (给外部 harness / 脚本用,不启窗口、不起 HTTP) @@ -536,16 +618,36 @@ def main(): unblock_bundle() # 必须先于 webview:MOTW 会让 pythonnet 的程序集加载失败 import webview - webview.create_window( - 'MAA-PRTS · 作业控制台', - url, - width=1520, - height=960, - min_size=(1120, 720), - background_color='#0b0e14', - easy_drag=False, - js_api=Bridge(), - ) + geom = st.get('windowGeom') or {} + win_w = max(1120, min(10000, int(geom.get('width') or 1520))) + win_h = max(720, min(10000, int(geom.get('height') or 960))) + try: + screens = list(webview.screens) # 逻辑像素,和 create_window 同口径 + except Exception: + screens = [] + win_x, win_y = geom.get('x'), geom.get('y') + if win_x is None or win_y is None or not _geom_visible(geom, screens): + win_x = win_y = None # 位置不在了(换屏/拔显示器)→ 居中 + win_kw = dict(width=win_w, height=win_h, min_size=(1120, 720), + background_color='#0b0e14', easy_drag=False, js_api=Bridge()) + if win_x is not None: + win_kw.update(x=int(win_x), y=int(win_y)) + if geom.get('max'): + win_kw['maximized'] = True + window = webview.create_window('MAA-PRTS · 作业控制台', url, **win_kw) + _WIN[0] = window + with _WINGEOM_LOCK: + _WINGEOM.update(x=int(win_x) if win_x is not None else None, + y=int(win_y) if win_y is not None else None, + width=win_w, height=win_h, + max=bool(geom.get('max')), min=False) + window.events.shown += lambda: _WIN_SHOWN.__setitem__(0, True) + window.events.moved += _wingeom_moved + window.events.resized += _wingeom_resized + window.events.maximized += _wingeom_maximized + window.events.minimized += _wingeom_minimized + window.events.restored += _wingeom_restored + window.events.closing += _wingeom_save webview.start(debug=debug, private_mode=False) _quit(0, '窗口已关闭') diff --git a/resources/garrison/patches.json b/resources/garrison/patches.json index e11ca8f..faca6df 100644 --- a/resources/garrison/patches.json +++ b/resources/garrison/patches.json @@ -126,6 +126,18 @@ "why": "操作间隔选项已从界面移除。之前一版把非调试分支的 speed:1 改成跟随用户设置,这条把已经打过的核心恢复成 speed:1(未打过的核心 find 不中,自动跳过),避免账号里残留的旧 speed 值在无界面可调的情况下继续生效。", "find": "verifyPurchase:!1,verifyFreeReward:!1,identifyUnknown:!1,fullBoard:!1,speed:Math.min(5,Math.max(.5,Math.round((Number(n.speed)||1.5)*2)/2)),forceStrategy:void 0}", "replace": "verifyPurchase:!1,verifyFreeReward:!1,identifyUnknown:!1,fullBoard:!1,speed:1,forceStrategy:void 0}" + }, + { + "id": "free-cards-unreadable-v1111", + "why": "三合一后的免费三选一在标准模拟里不一定显示「请选择奖励」横幅,三个 0 价格气泡比正常价格位左移 62px(rewardShift);核心只在读到「请选择奖励」时才用偏中气泡重读,于是 reward=false,卡在「尚未回到普通购买界面,等待免费候选卡识别」无限重试,免费干员一直领不到(游戏又必须领)。改为:正常价格位一个数字都没读到时也做一次偏中气泡重读(正常能读到价格的页面不多做 OCR)。", + "find": "async function la(u,n,t,e={}){const i=await Ii(u,n,t,!1);if(!e.rewardHint||i.reward)return i;const f=await Ii(u,n,t,!0);return f.reward?(console.error(`[free] \\u53F3\\u4E0A\\u6C14\\u6CE1\\u672A\\u8BFB\\u51FA\\u5956\\u52B1\\uFF0C\\u6309\\u504F\\u4E2D\\u6C14\\u6CE1\\u8BFB\\u5230 ${f.prices.filter(o=>o.value===0).length} \\u5F20\\u514D\\u8D39\\u5361`),f):i}", + "replace": "async function la(u,n,t,e={}){const i=await Ii(u,n,t,!1);if(i.reward)return i;if(!e.rewardHint&&i.readable)return i;const f=await Ii(u,n,t,!0);return f.reward?(console.error(`[free] ${e.rewardHint?\"右上气泡未读出奖励\":\"商店价格未读出\"},按偏中气泡读到 ${f.prices.filter(o=>o.value===0).length} 张免费卡`),f):i}" + }, + { + "id": "free-geometry-claim-v1111", + "why": "标准模拟下三合一免费三选一的 0 价格气泡 OCR 读不出(偏中气泡重读也没命中)时,prep 循环会一直抛「尚未回到普通购买界面,等待免费候选卡识别」。三张免费卡在商店状态里(名字已读出,x 为卡槽位置);这里补一条几何盲领:先用 Du(免费卡, 状态) 走核心自己的优先级(优先生成精锐 > 标准模拟推荐 > 购卡评分 > 品级),取不到再退回 x 最小的一张,按原免费领取同样的 blind 调用 Ye(x,\"免费奖励\",true,null,true)(跳过名字核对)。", + "find": "if((Rt.reward||gt(C))&&!tu.length&&W<2){const re=Rt.scan.prices.filter(ot=>ot.value===0).map(ot=>ot.x).sort((ot,eu)=>ot-eu);if(re.length){W++;const ot=C.pc?Z.pcUiScale/100:1,eu=Math.round(re[0]-120*ot);H(`\\u7B2C ${N.round} \\u56DE\\u5408 \\xB7 \\u514D\\u8D39\\u4E09\\u9009\\u4E00\\u7684\\u5361\\u540D\\u90FD\\u6CA1\\u8BA4\\u51FA\\uFF08\\u53EF\\u80FD\\u662F\\u9884\\u5907\\u5E72\\u5458\\uFF09\\uFF0C\\u76F4\\u63A5\\u9886\\u53D6\\u6700\\u5DE6\\u8FB9\\u4E00\\u5F20`),e.diagnostics.note(\"\\u514D\\u8D39\\u5956\\u52B1.\\u76F2\\u9886\",{round:N.round,zeroXs:re,x0:eu,shop:Bt.shop.map(pu=>pu.name??\"?\")}),await Ye(eu,\"\\u514D\\u8D39\\u5956\\u52B1\",!0,null,!0)&&(e.clearSoldCards(),_t=null,Mt.clear()),Be=!1,me=!0;continue}}", + "replace": "if((Rt.reward||gt(C))&&!tu.length&&W<2){const re=Rt.scan.prices.filter(ot=>ot.value===0).map(ot=>ot.x).sort((ot,eu)=>ot-eu);if(re.length){W++;const ot=C.pc?Z.pcUiScale/100:1,eu=Math.round(re[0]-120*ot);H(`\\u7B2C ${N.round} \\u56DE\\u5408 \\xB7 \\u514D\\u8D39\\u4E09\\u9009\\u4E00\\u7684\\u5361\\u540D\\u90FD\\u6CA1\\u8BA4\\u51FA\\uFF08\\u53EF\\u80FD\\u662F\\u9884\\u5907\\u5E72\\u5458\\uFF09\\uFF0C\\u76F4\\u63A5\\u9886\\u53D6\\u6700\\u5DE6\\u8FB9\\u4E00\\u5F20`),e.diagnostics.note(\"\\u514D\\u8D39\\u5956\\u52B1.\\u76F2\\u9886\",{round:N.round,zeroXs:re,x0:eu,shop:Bt.shop.map(pu=>pu.name??\"?\")}),await Ye(eu,\"\\u514D\\u8D39\\u5956\\u52B1\",!0,null,!0)&&(e.clearSoldCards(),_t=null,Mt.clear()),Be=!1,me=!0;continue}const _fcList=zt.shop.filter(ot=>!!ot.name);const _fc=Du(_fcList,Bt).pick||_fcList.slice().sort((ot,eu)=>ot.x-eu.x)[0];if(_fc){W++;H(`第 ${N.round} 回合 · 免费三选一价格未读出,按优先级盲领 ${_fc.name}`);e.diagnostics.note(\"免费奖励.几何盲领\",{round:N.round,x:_fc.x,name:_fc.name,shop:zt.shop.map(ot=>ot.name??\"?\")});if(await Ye(_fc.x,\"免费奖励\",!0,null,!0)){e.clearSoldCards();_t=null;Mt.clear()}Be=!1;me=!0;continue}}" } ] } diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index e565a84..07b2c39 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -3536,6 +3536,18 @@ def check_settings_panel(tmp): assert {'root', 'accounts', 'config', 'logs', 'appLog'} <= set(boot['paths']), boot['paths'] assert boot['paths']['logs'].replace('/', '\\').endswith('debug') + # 6) 主窗口几何:只收合法数值/布尔,坏值丢弃(位置是否还在屏幕上由 + # main.py 启动时用 webview.screens 判断) + from core import settings + settings.save({'windowGeom': {'x': '-100', 'y': 'bad', 'width': 1600, + 'height': 900, 'max': 'yes'}}) + g = settings.load()['windowGeom'] + assert g == {'x': -100, 'width': 1600, 'height': 900, 'max': True}, g + settings.save({'windowGeom': {'x': 1e9, 'width': 10, 'height': 900}}) + assert settings.load()['windowGeom'] == {'height': 900}, settings.load()['windowGeom'] + settings.save({'windowGeom': 'nope'}) + assert settings.load()['windowGeom'] == {}, settings.load()['windowGeom'] + # ---------------------------------------------------------------- B39 培养干员 def check_oper_train(tmp):