diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..f608b05707a633759f2af44fbf9055c30b9a1457 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,28 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/GameTrans_EvalSet/AI评测集正式版4500条.xlsx filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/LQA_WMP/web/public/favicon.ico filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-1.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2-back.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_auto_pipeline.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_filter_config.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_full_vs_restore.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_platform_connection.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_pull_data.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_scene.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_submit.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_text_show.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_translation_font_config.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_upload_data.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_full_vs_notext.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_getnode_on.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_getnode_panel.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_output_folder.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_textid.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_tool_buttons.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/Unity_LQATool_Plugin/docs/images/usage_visdebug.png filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/video/工具链演示视频.mp4 filter=lfs diff=lfs merge=lfs -text +timi_hok_game_translator/video/LQA演示视频.mp4 filter=lfs diff=lfs merge=lfs -text diff --git a/timi_hok_game_translator/.gitattributes b/timi_hok_game_translator/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..3efae2a793f4fba2b5047187630a96853d617487 --- /dev/null +++ b/timi_hok_game_translator/.gitattributes @@ -0,0 +1 @@ +/video/LQA演示视频.mp4 filter=lfs diff=lfs merge=lfs -text diff --git a/timi_hok_game_translator/.gitignore b/timi_hok_game_translator/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1f6f038a4d4597bbd09e1b51aa0a07e720e49af7 --- /dev/null +++ b/timi_hok_game_translator/.gitignore @@ -0,0 +1,14 @@ +# IDE +.idea/ + +# 临时补丁 / 本地工具文件 +fix__修改开源协议.patch + +# Python +__pycache__/ +*.py[cod] +.venv/ +venv/ +env/ +.pytest_cache/ +.mypy_cache/ diff --git "a/timi_hok_game_translator/GameTrans_EvalSet/AI\350\257\204\346\265\213\351\233\206\346\255\243\345\274\217\347\211\2104500\346\235\241.xlsx" "b/timi_hok_game_translator/GameTrans_EvalSet/AI\350\257\204\346\265\213\351\233\206\346\255\243\345\274\217\347\211\2104500\346\235\241.xlsx" new file mode 100644 index 0000000000000000000000000000000000000000..7256fc5623e97f2ce36f631b3067455a42ac78d1 --- /dev/null +++ "b/timi_hok_game_translator/GameTrans_EvalSet/AI\350\257\204\346\265\213\351\233\206\346\255\243\345\274\217\347\211\2104500\346\235\241.xlsx" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67954214e490f2308f5bdaa2df0e189f20712c87589cd874cfcfc0d2d2ab6eab +size 527746 diff --git a/timi_hok_game_translator/LICENSE.txt b/timi_hok_game_translator/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..75e7c3ebd1e4208106a6a4d05ba5be9f48bdecee --- /dev/null +++ b/timi_hok_game_translator/LICENSE.txt @@ -0,0 +1,210 @@ +Tencent is pleased to support the open source community by making TiMi HOK Game Translator available. + +Copyright (C) 2026 Tencent. All rights reserved. + +TiMi HOK Game Translator is licensed under the Apache-2.0. + + +Terms of the Apache-2.0: +-------------------------------------------------------------------- +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/.env.example b/timi_hok_game_translator/LQA_WMP/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..b54ff23c6cd7cb957709764bc8bc4809ab0231e3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/.env.example @@ -0,0 +1,60 @@ +# docker compose 部署配置: cp .env.example .env 后修改 + +# 以下密码/密钥必须修改为随机值 +# 生成方式: python -c "import secrets;print(secrets.token_urlsafe(32))" +MYSQL_ROOT_PASSWORD=change-me-root +MYSQL_PASSWORD=change-me-lqa +REDIS_PASSWORD=change-me-redis +SECRET_KEY=change-me-to-a-long-random-string + +# 首次启动自动创建的超级管理员 (已存在超管时不会覆盖) +LQA_ADMIN_USERNAME=admin +LQA_ADMIN_PASSWORD=ChangeMe123456 + +# 对外端口与访问地址 (缺陷中的截图链接、Webhook 变量 {{lqa_server}} 使用) +LQA_HTTP_PORT=8080 +PUBLIC_URL=http://localhost:8080 + +# 是否开放自助注册 (注册后需管理员分配项目) +ALLOW_REGISTER=true +# HTTPS 部署时开启 +SESSION_COOKIE_SECURE=false +# 截图是否允许匿名访问 (使用禅道且需要在禅道中直接显示截图时开启) +MEDIA_PUBLIC=false + +# --------------------------------------------------------------- +# AI 识别服务 +# --------------------------------------------------------------- + +# 留空则自动使用随本编排启动的 ai 服务 (http://ai:8086) +# 若已有独立部署的识别服务, 填写其地址即可, 此时可用 +# docker compose up -d --scale ai=0 跳过本地 ai 容器 +AI_BASE_URL= + +# 镜像内置的 OCR 引擎 (构建期生效) +# rapidocr 默认, 离线可用, 约 15MB +# paddleocr 精度更高, 镜像约 +2GB +# easyocr 多语种 +# none 不内置, 需配合下方 OCR_* 指向外部/云 OCR +OCR_ENGINE=rapidocr + +# 运行期使用的 OCR provider, 取值见 lqa_service/README.md +# OCR 是可选项: 留空或设为 none 时服务仍可正常启动与检测, +# 仅自动跳过依赖 OCR 的检测项 (错译、文本超文本框) +OCR_PROVIDER=rapidocr +OCR_LANG=ch + +# ai 服务进程数; 识别为 CPU 密集型, 按核数调整 +AI_WORKERS=2 + +# ai 服务对宿主机暴露的地址, 默认只监听本机便于调试 +# 完全不对外暴露可改为 127.0.0.1:0, 或删除 compose 中 ai 的 ports +AI_HTTP_PORT=127.0.0.1:8086 + +# 使用云 OCR 时按需填写 (OCR_PROVIDER=tencentcloud/baidu/azure 等) +OCR_URL= +OCR_HOST= +OCR_API_KEY= +OCR_SECRET_ID= +OCR_SECRET_KEY= +OCR_REGION=ap-guangzhou diff --git a/timi_hok_game_translator/LQA_WMP/.gitattributes b/timi_hok_game_translator/LQA_WMP/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..b25e783ec09eafd6c98359eb3f5b889f67ee8612 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/.gitattributes @@ -0,0 +1,8 @@ +* text=auto eol=lf +*.png binary +*.jpg binary +*.ico binary +*.gif binary +*.woff binary +*.woff2 binary +*.ttf binary diff --git a/timi_hok_game_translator/LQA_WMP/.gitignore b/timi_hok_game_translator/LQA_WMP/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..45432e40a9ede77ff0b9e42f7091c97f58bb40d9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/.gitignore @@ -0,0 +1,38 @@ +# 环境变量与密钥 (.env.example / web 的 .env.development 等需入库, 不要加 .env.*) +.env +*.local + +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +venv/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ + +# Node +node_modules/ +dist/ +dist-ssr/ +.eslintcache + +# 运行时产物 (锚定到具体路径, 避免误伤同名源码目录) +*.log +/server/data/ +/server/media/ +/server/logs/ + +# 编辑器 +.idea/ +.vscode/ +*.swp +*.sw? + +# AI 开发助手本地元数据 +.workbuddy/ + +# 系统 +.DS_Store +Thumbs.db diff --git a/timi_hok_game_translator/LQA_WMP/CONTRIBUTING.md b/timi_hok_game_translator/LQA_WMP/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..059f33110d8ec1aa0c3ff95b8515fb42a5e8ed1e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/CONTRIBUTING.md @@ -0,0 +1,48 @@ +# 贡献指南 + +感谢你对 LQA 项目的关注, 以下是参与贡献的基本流程和规范 + +## 提交 Issue + +- 提交前请先搜索是否已有相关 Issue, 避免重复 +- **Bug 报告**: 请说明复现步骤、预期行为、实际行为,以及环境信息 (操作系统、Python/Node 版本、部署方式) +- **功能建议**: 请描述使用场景和期望的行为, 无需提供完整的实现方案 + +## 提交 Pull Request + +1. Fork 本仓库, 在自己的 Fork 上创建分支, 分支名建议体现改动内容, 如 `fix/bugzilla-reopen` 或 `feat/dingtalk-notify` +2. 保持每个 PR 聚焦于单一目的, 便于 Review +3. 提交前请确认: + - 后端: `python manage.py migrate` 无误, 如有新模型请附带 migration 文件; 相关逻辑有基本测试或冒烟验证 + - 前端: `pnpm lint` 通过, `pnpm build` 无报错 +4. PR 描述中说明改动内容、测试方式, 以及是否有破坏性变更 + +## 本地开发环境 + +见 [README.md](README.md) 的快速概览, 或各子目录的详细文档: + +- 后端: [server/README.md](server/README.md) +- 前端: [web/README.md](web/README.md) + +## 代码规范 + +**后端 (Python)** + +- 遵循项目现有风格, 参考 `server/.pylintrc` +- 数据校验使用 Pydantic schema, 接口返回统一走 `libs/base.py` 中的基类 +- 新增缺陷系统适配器请继承 `libs/bugtracker/base.py` 中的 `BugTracker` 抽象基类, 在 `libs/bugtracker/__init__.py` 的 `TRACKER_TYPES` 中注册, 并在 `scripts/test_bugtracker.py` 中补充测试 + +**前端 (TypeScript / Vue)** + +- 组件放在对应业务目录下, CRUD 配置与视图分文件 +- API 请求统一走 `src/api/` 目录下的封装, 不直接调用 axios +- `pnpm lint` 包含 ESLint + Prettier, 提交前请确保通过 + +## 分支与版本 + +- `main` 为主分支, 保持可发布状态 +- 重大功能或破坏性变更请在 Issue 中先讨论再动手 + +## 许可证 + +提交代码即表示你同意将贡献以 [Apache-2.0 License](LICENSE) 授权给本项目 diff --git a/timi_hok_game_translator/LQA_WMP/LICENSE b/timi_hok_game_translator/LQA_WMP/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eb45d1a9b2822a4daf7df023a4109bd3d73824e2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/LICENSE @@ -0,0 +1,210 @@ +Tencent is pleased to support the open source community by making LQA WMP available. + +Copyright (C) 2024 LQA Contributors. All rights reserved. + +LQA WMP is licensed under the Apache-2.0. + + +Terms of the Apache-2.0: +-------------------------------------------------------------------- +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/README.md b/timi_hok_game_translator/LQA_WMP/README.md new file mode 100644 index 0000000000000000000000000000000000000000..92153371e8c1a29b3b2e998b958754f0215032ae --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/README.md @@ -0,0 +1,119 @@ +# LQA — 本地化质量检查平台 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +LQA (Localization Quality Assurance) 是一个面向游戏 / 应用多语言版本的本地化质量检查平台, 还原端 (如 UE/Unity 编辑器插件) 按任务批量生成各语言截图并上传, 平台调用 AI 识别服务检测 **漏译、错译、超框** 等问题, 测试人员审核结果后一键提交到缺陷系统, 并支持修复后的 **回归验证** + +--- + +## 功能 + +- **账号体系** — 账号密码登录、自助注册 (注册后由管理员分配项目)、管理员创建用户 / 重置密码 / 禁用账号、API access_token +- **项目与角色** — 多项目隔离, 项目管理员 / 测试人员 / 开发人员三种角色, 超级管理员管理全局 +- **还原任务** — 创建任务、选择语言与测试数据; 开始 / 重试时由浏览器直接调用项目配置的 Webhook (Jenkins / GitLab CI / 自建服务) 触发还原端 +- **AI 识别** — 截图上传后异步调用 AI 识别服务, 支持全量识别与差异识别 +- **缺陷管理** — 每个项目可选择 平台内记录 / Bugzilla 5.x / 禅道(开源版 REST API v1), 支持单个 / 批量 / 自动提单与回归验证 + +--- + +## 技术栈 + +| 层次 | 技术 | +|---|---| +| 后端语言与框架 | Python 3.12 + Django 5.1 | +| 异步任务 | Celery 5 + Redis | +| 数据库 | MySQL 8 | +| 缓存 / 会话 | Redis 7 | +| 后端服务器 | Gunicorn | +| 前端框架 | Vue 3 + Vite 5 + TypeScript | +| UI 组件库 | Element Plus + fast-crud | +| 前端状态管理 | Pinia | +| 前端基础模板 | [v3-admin-vite](https://github.com/un-pany/v3-admin-vite) | +| 容器化部署 | Docker Compose | + +--- + +## 目录结构 + +``` +LQA-WMP/ +├── server/ 后端 (Python / Django) +│ ├── apps/ +│ │ ├── user/ 账号、登录/注册、项目角色、access_token +│ │ ├── project/ 项目、项目配置 (缺陷类型/语言/Webhook/缺陷系统) +│ │ ├── job/ 还原任务、Webhook 触发、回归 +│ │ ├── image/ 截图上传与 AI 识别 +│ │ ├── bug/ 缺陷提单与同步 +│ │ ├── data/ 测试数据 +│ │ ├── system/ 枚举 +│ │ └── lqa/ 健康检查、上传、管理命令 +│ ├── libs/ +│ │ └── bugtracker/ 缺陷系统适配器: none(平台内记录) / bugzilla / zentao +│ ├── scripts/ 冒烟测试、缺陷系统适配器测试 +│ ├── requirements.txt +│ └── README.md 后端开发文档 +├── web/ 前端 (Vue 3) +│ └── README.md 前端开发文档 +├── lqa_service/ AI 识别服务 (Flask) +│ ├── common/ocr_provider/ 可插拔 OCR 适配层 (9 种实现) +│ ├── task/ 检测算法: 漏译/超框/漏key/重叠/错译 +│ └── README.md 识别服务文档 +├── docker-compose.yml 一键部署 +└── .env.example 环境变量模板 +``` + +--- + +## 文档 + +### API 协议 + +| 文档 | 说明 | +|---|---| +| [通用约定](docs/api/overview.md) | 认证方式、响应格式、错误码 | +| [用户接口](docs/api/user.md) | 登录、注册、账号管理、access_token | +| [项目接口](docs/api/project.md) | 项目管理、项目配置、模块 | +| [任务接口](docs/api/job.md) | 还原任务创建、启停、进度 | +| [截图接口](docs/api/image.md) | 截图上传、AI 识别、审核 | +| [缺陷接口](docs/api/bug.md) | 提单、批量提单、缺陷系统信息 | +| [测试数据接口](docs/api/data.md) | 测试数据管理 | +| [系统工具接口](docs/api/system.md) | 健康检查、枚举、文件上传 | + +### 使用指南 + +| 文档 | 说明 | +|---|---| +| [Web 平台使用文档](docs/web-guide.md) | 面向测试 / 项目管理员 / 开发的 Web 平台操作手册 | +| [平台部署指南](docs/deploy-guide.md) | 全新电脑 / 服务器从零把平台跑起来的操作手册(Docker 一键部署 + 本地源码部署) | + +### 集成指南 + +| 文档 | 说明 | +|---|---| +| [还原端集成指南](docs/integration/restorer.md) | 还原端(Unity 插件等)与平台对接的完整流程 | + +### 快速索引: 还原端需要的接口 + +还原端只需关注以下三个接口, 认证使用 `LQA-Authorization: ` 请求头: + +| 接口 | 说明 | +|---|---| +| `GET /api/job/datas` | 拉取任务测试数据 | +| `POST /api/image/entity` | 上传截图 (multipart/form-data) | +| `POST /api/job/device` | 上报设备信息与执行进度 | + +详见 [还原端集成指南](docs/integration/restorer.md)。 + +--- + +## 贡献 + +欢迎提交 Issue 和 Pull Request,详见 [CONTRIBUTING.md](CONTRIBUTING.md)。 + +--- + +## 许可证 + +本项目后端代码以 **Apache-2.0** 开源,详见 [LICENSE](LICENSE)。 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docker-compose.yml b/timi_hok_game_translator/LQA_WMP/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..afde17fd199da62c2aa33dafe69ab9463ea6945e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docker-compose.yml @@ -0,0 +1,110 @@ +# 一键部署: cp .env.example .env 修改密码后执行 docker compose up -d --build +# 访问 http://<服务器>:${LQA_HTTP_PORT:-8080}, 使用 LQA_ADMIN_USERNAME / LQA_ADMIN_PASSWORD 登录 +services: + mysql: + image: mysql:8.0 + restart: unless-stopped + command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?请在 .env 中设置 MYSQL_ROOT_PASSWORD} + MYSQL_DATABASE: lqa + MYSQL_USER: lqa + MYSQL_PASSWORD: ${MYSQL_PASSWORD:?请在 .env 中设置 MYSQL_PASSWORD} + volumes: + - mysql_data:/var/lib/mysql + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "-p${MYSQL_ROOT_PASSWORD}"] + interval: 5s + timeout: 5s + retries: 30 + + redis: + image: redis:7-alpine + restart: unless-stopped + command: redis-server --requirepass ${REDIS_PASSWORD:?请在 .env 中设置 REDIS_PASSWORD} + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"] + interval: 5s + timeout: 5s + retries: 30 + + server: &server + build: ./server + image: lqa-server:latest + restart: unless-stopped + environment: &server_env + DEBUG: "false" + SECRET_KEY: ${SECRET_KEY:?请在 .env 中设置 SECRET_KEY} + ALLOWED_HOSTS: "*" + MYSQL_URL: mysql://lqa:${MYSQL_PASSWORD}@mysql:3306/lqa + REDIS_URL: rediscache://:${REDIS_PASSWORD}@redis:6379/1 + CELERY_BROKER_URL: redis://:${REDIS_PASSWORD}@redis:6379/2 + CELERY_BACKEND_URL: redis://:${REDIS_PASSWORD}@redis:6379/2 + ALLOW_REGISTER: ${ALLOW_REGISTER:-true} + SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false} + PUBLIC_URL: ${PUBLIC_URL:-} + MEDIA_PUBLIC: ${MEDIA_PUBLIC:-false} + # 默认指向随本编排启动的 ai 服务; 如需用外部识别服务, 在 .env 中覆盖 + AI_BASE_URL: ${AI_BASE_URL:-http://ai:8086} + LQA_ADMIN_USERNAME: ${LQA_ADMIN_USERNAME:-admin} + LQA_ADMIN_PASSWORD: ${LQA_ADMIN_PASSWORD:-} + volumes: + - lqa_data:/data + depends_on: + mysql: + condition: service_healthy + redis: + condition: service_healthy + command: ["web"] + + worker: + <<: *server + command: ["worker"] + # AI 识别由 Celery worker 发起 (apps/image/service.py), 需等 ai 就绪 + depends_on: + server: + condition: service_started + ai: + condition: service_healthy + + ai: + build: + context: ./lqa_service + args: + # 内置的 OCR 引擎: rapidocr (默认, 轻量) / paddleocr (精度更高, 镜像约+2GB) + # easyocr (多语种) / none (不内置, 需指向外部 OCR 服务) + OCR_ENGINE: ${OCR_ENGINE:-rapidocr} + image: lqa-ai:latest + restart: unless-stopped + environment: + DEBUG_MODE: ${AI_DEBUG_MODE:-False} + # OCR 为可选能力; 设为 none 则不做 OCR, 仅跳过错译与文本超框检测 + OCR_PROVIDER: ${OCR_PROVIDER:-rapidocr} + OCR_LANG: ${OCR_LANG:-ch} + GUNICORN_WORKERS: ${AI_WORKERS:-2} + # 使用外部/云 OCR 时按需设置, 详见 lqa_service/README.md + OCR_URL: ${OCR_URL:-} + OCR_HOST: ${OCR_HOST:-} + OCR_API_KEY: ${OCR_API_KEY:-} + OCR_SECRET_ID: ${OCR_SECRET_ID:-} + OCR_SECRET_KEY: ${OCR_SECRET_KEY:-} + OCR_REGION: ${OCR_REGION:-ap-guangzhou} + # 默认仅在内部网络暴露; 需从宿主机直接调试时在 .env 设置 AI_HTTP_PORT + ports: + - "${AI_HTTP_PORT:-127.0.0.1:8086}:8086" + + web: + build: ./web + image: lqa-web:latest + restart: unless-stopped + ports: + - "${LQA_HTTP_PORT:-8080}:80" + depends_on: + - server + +volumes: + mysql_data: + redis_data: + lqa_data: diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/bug.md b/timi_hok_game_translator/LQA_WMP/docs/api/bug.md new file mode 100644 index 0000000000000000000000000000000000000000..6075151d8c7e460561c42b691d02cffbb32e539f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/bug.md @@ -0,0 +1,250 @@ +# 缺陷接口 + +## 获取缺陷系统信息及提单选项 + +``` +GET /api/bug/tracker_meta?project_id= +``` + +返回当前项目配置的缺陷系统类型, 以及提单时需要的下拉选项 (版本列表等), 需要项目成员权限 + +**响应 data:** + +```json +{ + "type": "bugzilla", + "label": "Bugzilla", + "remote": true, + "enabled": true, + "version_report_list": ["1.0", "1.1"], + "version_fix_list": ["1.2"], + "release_id_list": [], + "error": "" +} +``` + +`type` 取值: `none`(平台内记录)、`bugzilla`、`zentao` + +--- + +## 获取缺陷系统自定义字段 + +``` +GET /api/bug/tracker_fields?project_id= +``` + +返回缺陷系统中可作为 "自定义提单字段" 的字段及其选项 (Bugzilla/禅道专用), 需要项目成员权限 + +**响应 data:** + +```json +{ + "type": "bugzilla", + "fields": [ + { + "name": "cf_game_version", + "label": "游戏版本", + "options": ["1.0", "1.1"] + } + ] +} +``` + +--- + +## 测试缺陷系统连接 + +``` +POST /api/bug/tracker_test +Content-Type: application/json +``` + +需要项目管理员权限, 用于保存配置前验证连接, `api_key` 传 `******` 时使用已保存的密钥 + +**请求体 (Bugzilla 示例):** + +```json +{ + "project_id": 2, + "tracker_type": "bugzilla", + "url": "https://bugzilla.example.com", + "api_key": "abc123", + "product": "MyGame", + "component": "本地化" +} +``` + +--- + +## 获取单条提单预览 + +``` +GET /api/bug/build_info?project_id=&image_id=&bug_types=1,2 +``` + +提单前预览将要填入缺陷系统的标题、描述等内容, 需要项目成员权限 + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `project_id` | int | 项目 ID | +| `image_id` | int | 截图 ID | +| `bug_types` | string | 逗号分隔的缺陷类型 ID | + +**响应 data:** + +```json +{ + "title": "[漏译][主界面] ui_main_zh.png", + "description": "...", + "bug_keys": [...], + "current_owner": "dev_user", + "title_pre": "", + "version_report": "1.0" +} +``` + +--- + +## 提交单个缺陷 + +``` +POST /api/bug/entity +Content-Type: application/json +``` + +需要项目成员权限, 提单为异步操作, 返回 Celery 任务 ID + +**请求体:** + +```json +{ + "project_id": 2, + "image_id": 200, + "bug_types": [1, 2], + "title": "[漏译] ui_main_zh.png", + "description": "详细描述...", + "current_owner": "dev_user", + "version_report": "1.0", + "version_fix": "1.2", + "priority": "P2", + "severity": "normal" +} +``` + +**响应 data:** + +```json +{ "task": "celery-task-id-abc123" } +``` + +--- + +## 获取缺陷列表 + +``` +GET /api/bug/list?job_id= +``` + +`job_id` 和 `image_id` 二选一, 返回时会同步查询外部缺陷系统的最新状态 (`tracker_status`、`tracker_open`) + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `job_id` | int | 按任务查询 | +| `image_id` | int | 按截图查询 | +| `page` / `page_size` | int | 分页 | +| `title__contains` | string | 标题模糊搜索 | +| `info_type` | int | `1` 简略信息 (不同步缺陷系统) | + +**响应 data:** + +```json +{ + "list": [ + { + "id": 300, + "project_id": 2, + "job_id": 10, + "image_id": 200, + "title": "[漏译] ui_main_zh.png", + "priority": "P2", + "severity": "normal", + "reporter": "test_user", + "current_owner": "dev_user", + "version_report": "1.0", + "version_fix": "1.2", + "tracker": "bugzilla", + "external_id": "1234", + "external_url": "https://bugzilla.example.com/show_bug.cgi?id=1234", + "status": "open", + "bill_status": 1, + "tracker_status": "NEW", + "tracker_open": true, + "is_delete": 0, + "regress_status": 0, + "regress_job_ids": [] + } + ], + "total": 5, + "page": 1, + "page_size": 20 +} +``` + +--- + +## 批量提交缺陷 + +``` +POST /api/bug/list +Content-Type: application/json +``` + +需要项目成员权限, 批量异步提单 + +**请求体:** + +```json +{ + "project_id": 2, + "job_id": 10, + "image_ids": [200, 201, 202], + "bug_types": [1, 2], + "version_report": "1.0", + "version_fix": "1.2" +} +``` + +**响应 data:** + +```json +{ + "success": [200, 201], + "failed": [[202, "错误原因"]] +} +``` + +--- + +## 批量更新缺陷 + +``` +PATCH /api/bug/list +Content-Type: application/json +``` + +目前主要用于批量更新回归状态 + +**请求体:** + +```json +{ + "bug_ids": [300, 301], + "regress_status": 1 +} +``` + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/data.md b/timi_hok_game_translator/LQA_WMP/docs/api/data.md new file mode 100644 index 0000000000000000000000000000000000000000..3927e2f730489b2c60680b4c565e365800f5be5c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/data.md @@ -0,0 +1,93 @@ +# 测试数据接口 + +测试数据 (Data) 是还原任务的基础单元, 代表一个需要截图的界面/资源节点, 数据由平台管理员或通过导入工具维护 + +--- + +## 获取测试数据详情 + +``` +GET /api/data/entity?id= +``` + +--- + +## 获取测试数据列表 + +``` +GET /api/data/list +``` + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `page` / `page_size` | int | 分页 | +| `project_id` | int | 按项目筛选 | +| `module_id` | int | 按模块筛选 | +| `cur_id` | int | 游标分页 | + +--- + +## 创建/修改测试数据 + +``` +POST /api/data/entity +PATCH /api/data/entity +Content-Type: application/json +``` + +**请求体 (主要字段):** + +```json +{ + "project_id": 2, + "module_id": 10, + "file_path": "Assets/UI/main.prefab", + "key": "ui_main_title", + "shot_img_path": "/media/..." +} +``` + +修改时需额外传 `"id": ` + +--- + +## 获取资源版本列表 + +``` +GET /api/data/resource_version/list?project_id= +``` + +返回当前项目所有测试数据中出现过的资源版本号列表, 用于提单时的 "报告版本" 下拉选项 + +--- + +## 图片资源管理 + +``` +GET /api/data/image_resource?project_id= +POST /api/data/image_resource +``` + +管理每个测试数据关联的参考截图资源 + +**GET 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `project_id` | int | 项目 ID | +| `data_id` | int | 测试数据 ID | + +--- + +## 图片资源合并 + +``` +POST /api/data/image_resource/merge +Content-Type: application/json +``` + +将多个图片资源合并处理 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/image.md b/timi_hok_game_translator/LQA_WMP/docs/api/image.md new file mode 100644 index 0000000000000000000000000000000000000000..55821ef90b62f6f532ffeecad5fea9d567b618a1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/image.md @@ -0,0 +1,201 @@ +# 截图接口 + +## 上传截图 (还原端调用) + +``` +POST /api/image/entity +Content-Type: multipart/form-data +LQA-Authorization: +``` + +还原端上传每张截图, 上传后可选择同步触发 AI 识别 + +**Form 字段:** + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `file` | file | 是 | 截图文件 (PNG/JPG) | +| `project_id` | int | 是 | 项目 ID | +| `job_id` | int | 是 | 任务 ID | +| `data_id` | int | 是 | 测试数据 ID (来自 `/api/job/datas`) | +| `language` | int | 是 | 语言值 | +| `rect_locations` | string | 是 | 文本控件位置信息 JSON 字符串 | +| `ai_sign` | int | 否 | `1` 上传后立即触发 AI 识别, 默认 `0` | +| `discern` | int | 否 | 识别模式: `0` 全量, `1` 差异 | +| `create_bug` | int | 否 | `1` 识别后自动提单 | +| `regression` | int | 否 | `1` 表示回归任务 | +| `bug_ids` | string | 否 | 回归时传入需回归的缺陷 ID, 逗号分隔 | + +**响应 data:** + +```json +{ + "image": { + "id": 200, + "project_id": 2, + "job_id": 10, + "data_id": 501, + "language": 2, + "file_name": "ui_main_zh.png", + "file_path": "/media/...", + "iteration": 1, + "is_latest": 1, + "ai_sign": 0 + }, + "task_id": "abc123..." +} +``` + +`task_id` 为 Celery 任务 ID, `ai_sign=1` 时返回; 可用于追踪异步识别进度 + +--- + +## 获取截图详情 + +``` +GET /api/image/entity?image_id= +``` + +**响应 data:** + +```json +{ + "image": { + "id": 200, + "file_path": "/media/...", + "ai_mark_img_path": "/media/...", + "ai_rect_img_path": "/media/...", + "ai_check_detail": {...}, + "ai_bug_types": "[1,2]", + "will_review": 1, + "reviewed": 0, + "bug_num": 2, + ... + } +} +``` + +--- + +## 获取截图列表 + +``` +GET /api/image/list +``` + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `page` / `page_size` | int | 分页 | +| `job_id` | int | 按任务筛选 | +| `data_id` | int | 按测试数据筛选 (需同时传 `job_id`) | +| `language` | int | 按语言筛选 | +| `languages` | string | 逗号分隔, 多语言筛选 | +| `is_latest` | int | `1` 只返回最新截图 | +| `will_review` | int | 是否需要审核 | +| `reviewed` | int | 审核状态 | +| `err_type` | int | 错误类型 | +| `ai_bug_types` | string | 逗号分隔, 按 AI 识别出的缺陷类型筛选 | +| `module_ids` | string | 逗号分隔的模块 ID | +| `info_type` | int | `0` 简略信息 (不含大字段) | +| `pk__gte` / `pk__lte` | int | ID 范围查询 | + +**PATCH 批量更新:** + +``` +PATCH /api/image/list +Content-Type: application/json +``` + +```json +{ + "ids": [200, 201, 202], + "reviewed": 1, + "will_review": 0 +} +``` + +--- + +## 删除截图 + +``` +DELETE /api/image/entity +Content-Type: application/json +``` + +```json +{ + "project_id": 2, + "image_ids": [200, 201] +} +``` + +或单个: `"image_id": 200` + +--- + +## 触发 AI 识别 + +``` +POST /api/image/ai_sign +Content-Type: application/json +``` + +手动触发 AI 识别, 可针对单张或整个任务批量触发 + +**请求体:** + +```json +{ + "image_id": 200, + "job_id": null, + "discern": 0, + "languages": [2, 3] +} +``` + +`image_id` 和 `job_id` 二选一: 传 `image_id` 为同步识别单张; 传 `job_id` 为异步批量识别整个任务 + +`discern`: `0` 全量识别, `1` 差异识别 + +--- + +## 数据审核记录 + +``` +GET /api/image/data_review?data_id=&project_id= +PATCH /api/image/data_review +Content-Type: application/json +``` + +**GET 响应 data:** + +```json +{ + "data_review": { + "id": 50, + "data_id": 501, + "project_id": 2, + "rect_location": [...], + "check_rect_location": "{}", + "dirty_rect_location": "{}", + "size": "1920,1080", + "reviewer": "system", + "image_id": 200 + } +} +``` + +**PATCH 请求体 (人工审核修正文本框):** + +```json +{ + "id": 50, + "check_rect_location": "{}", + "dirty_rect_location": "{}" +} +``` + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/job.md b/timi_hok_game_translator/LQA_WMP/docs/api/job.md new file mode 100644 index 0000000000000000000000000000000000000000..21d5354ca9064a5fe56af64cb6df542ae0b467a1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/job.md @@ -0,0 +1,299 @@ +# 任务接口 + +## 获取任务列表 + +``` +GET /api/job/list +``` + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `page` / `page_size` | int | 分页 | +| `cur_id` | int | 游标分页 | +| `project_id` | int | 按项目筛选 | +| `id` | int | 按任务 ID 精确查询 (同时返回子任务列表) | +| `name__icontains` | string | 任务名模糊搜索 | +| `status` | int | 任务状态筛选 | +| `creator_id` | int | 按创建人筛选 | +| `language` | int | 按语言筛选 | +| `created_begin_at` | string | 创建时间起始 | +| `created_end_at` | string | 创建时间结束 | +| `is_parent` | int | `0` 只返回普通任务, `1` 只返回回归任务 | +| `info_type` | int | `0` 简略信息 (不含扩展字段), 其他含扩展字段 | + +**响应 data:** + +```json +{ + "list": [ + { + "id": 10, + "project_id": 2, + "name": "2024-01 全量还原", + "languages": [2, 3], + "status": 2, + "reason": "", + "created_at": "...", + "updated_at": "...", + "parent_id": 0, + "regress_num": 1, + "bug_num": 5 + } + ], + "total": 20, + "page": 1, + "page_size": 20 +} +``` + +**任务状态 (status) 枚举:** + +| 值 | 说明 | +|---|---| +| `1` | 未执行 | +| `2` | 执行中 | +| `3` | 已完成 | +| `4` | 异常终止 | + +--- + +## 获取任务详情 + +``` +GET /api/job/entity?job_id=[&progress=1][&fields=f1,f2][&mappings=1] +``` + +| 参数 | 说明 | +|---|---| +| `job_id` | 任务 ID | +| `progress` | `1` 时额外返回识别进度 (`progress_rate`、`all_count`、`ai_signed_count`) | +| `fields` | 逗号分隔,只返回指定字段 | +| `mappings` | `1` 时额外返回语言/缺陷类型/状态的枚举映射 | + +**响应 data:** + +```json +{ + "job": { + "id": 10, + "project_id": 2, + "name": "2024-01 全量还原", + "languages": [2, 3], + "status": 2, + "progress_rate": "15/20", + ... + } +} +``` + +--- + +## 创建任务 + +``` +POST /api/job/entity +Content-Type: application/json +``` + +需要项目成员权限 + +**请求体 (主要字段):** + +```json +{ + "project_id": 2, + "name": "2024-01 全量还原", + "languages": [2, 3], + "plan_start_at": "2024-01-10T09:00:00", + "plan_end_at": "2024-01-12T18:00:00" +} +``` + +**响应 data:** + +```json +{ "job": { "id": 10, ... } } +``` + +--- + +## 修改任务 + +``` +PATCH /api/job/entity +Content-Type: application/json +``` + +需要项目成员权限, 请求体同创建, 额外传 `"id": ` + +--- + +## 任务操作 (启动 / 重试 / 回调 / 停止) + +``` +POST /api/job/action +Content-Type: application/json +``` + +**请求体:** + +```json +{ + "job_id": 10, + "action": "start", + "build_id": "", + "regression": 0 +} +``` + +**`action` 取值:** + +| action | 说明 | 返回内容 | +|---|---|---| +| `start` | 启动任务: 返回渲染好的 Webhook 请求, 由浏览器发起调用 | `trigger` 对象 | +| `retry` | 重试: 补提未识别的截图, 并返回 Webhook 请求 | `trigger` 对象 | +| `started` | 浏览器调用 Webhook 成功后回调, 将任务置为执行中 | 无 | +| `stop` | 结束任务 | 无 | + +`started` 时需额外传 `build_id` (Webhook 响应中的构建 ID) 和 `regression` (`0` 普通, `1` 回归, `2` 重试) + +**`start`/`retry` 响应 data:** + +```json +{ + "job_id": 10, + "regression": 0, + "trigger": { + "url": "https://jenkins.example.com/job/...", + "method": "POST", + "headers": { "Authorization": "..." }, + "body": "..." + } +} +``` + +--- + +## 创建回归任务 + +``` +POST /api/job/bug_regress +Content-Type: application/json +``` + +基于已有缺陷创建回归任务, 创建后调用 `/api/job/action` 的 `start` action 触发执行 + +**请求体:** + +```json +{ + "project_id": 2, + "parent_id": 10, + "bug_ids": [101, 102, 103], + "languages": [2, 3] +} +``` + +--- + +## 获取任务进度 + +``` +GET /api/job/progress?job_id= +``` + +返回各语言的截图上传进度 + +**响应 data:** + +```json +{ + "all_data_count": 100, + "all_imaged_count": 45, + "languges": [ + { + "language": 2, + "imaged_count": 25, + "imaged_count_per": "25%" + } + ] +} +``` + +--- + +## 获取任务测试数据 (还原端调用) + +``` +GET /api/job/datas +LQA-Authorization: +``` + +还原端拉取本次任务需要还原的数据列表 + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `job_id` | int | 必填 | +| `language` | int | 语言值, 必填 | +| `regression` | int | `0` 普通, `1` 回归 | +| `count` | int | 本次拉取条数, 默认全部 | +| `minID` | int | 增量拉取: 只返回 `id > minID` 的数据 | +| `module_ids` | string | 逗号分隔的模块 ID, 按模块筛选 | +| `iteration` | int | 迭代轮次 | +| `use_cache` | int | `1` 使用缓存 | + +**响应 data:** + +```json +{ + "datas": [ + { + "id": 501, + "file_path": "/media/...", + "module_id": 10 + } + ], + "bug_ids": [] +} +``` + +回归任务时 `bug_ids` 中包含需要回归验证的缺陷 ID 列表 + +--- + +## 上报设备与进度 (还原端调用) + +``` +POST /api/job/device +Content-Type: application/json +LQA-Authorization: +``` + +还原端上报执行设备信息和当前进度 + +**请求体:** + +```json +{ + "job_id": 10, + "execute_pc": "PC-001", + "language": 2, + "status": 2, + "progress": 50, + "total": 100 +} +``` + +**GET 查询设备列表:** + +``` +GET /api/job/device?job_id= +``` + +返回该任务下所有设备的执行状态列表 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/overview.md b/timi_hok_game_translator/LQA_WMP/docs/api/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..8c2b1a97640bac4ddb3e22813d4aa66820fa9c88 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/overview.md @@ -0,0 +1,121 @@ +# API 通用约定 + +## Base URL + +所有接口均以 `/api/` 为前缀, Docker Compose 部署时, Nginx 将 `/api-pro/` 反向代理到后端, 前端通过 `/api-pro/` 访问; 后端本身监听 `/api/` + +本文档中的路径均为 **后端实际路径** (`/api/...`) + +--- + +## 认证 + +平台支持两种认证方式, 通过请求头区分: + +### 浏览器 (Session Cookie) + +登录后服务端颁发 Session Cookie, 后续请求自动携带, 同时需要携带请求头: + +``` +LQA-Authorization: web +``` + +### API 调用方 (access_token) + +适用于还原端、脚本等非浏览器场景 + +``` +LQA-Authorization: +``` + +**获取 access_token 的两种方式:** + +1. 管理命令 (推荐, 由平台管理员执行): + ```bash + python manage.py update_access_token -u [-e <有效期秒数,默认30天>] + ``` + +2. 接口方式: + - `GET /api/ticket` 获取一次性 ticket (需已登录) + - 携带请求头 `LQA-Ticket: ` 调用 `POST /api/user/access_token` + - 返回新的 access_token (旧 token 同时失效) + +**免登录接口** (无需认证): +- `GET /api/health` +- `GET /api/user/auth_config` +- `POST /api/user/login` +- `POST /api/user/register` (需 `ALLOW_REGISTER=true`) + +--- + +## 响应格式 + +所有接口返回 JSON, 结构如下: + +```json +{ + "code": 0, + "msg": "", + "data": {} +} +``` + +| 字段 | 类型 | 说明 | +|---|---|---| +| `code` | int | `0` 表示成功, 非 0 表示错误 | +| `msg` | string | 成功时通常为空或提示文字, 失败时为错误描述 | +| `data` | object | 业务数据, 成功时才有意义 | + +--- + +## 错误码 + +| code | 常量 | 含义 | +|---|---|---| +| `0` | — | 成功 | +| `1001` | `ERROR` | 通用业务错误 | +| `1002` | `ERROR_PARAM` | 参数错误 | +| `1003` | `ERROR_AUTH` | 认证失败 (未登录或 token 失效) | +| `1004` | `ERROR_PERMISSION` | 无权限 | +| `1005` | `NOT_EXIST` | 资源不存在 | + +认证失败 (`1003`) 时前端应跳转到登录页; 还原端应检查 access_token 是否过期 + +--- + +## 分页参数 + +列表接口通用分页参数 (Query String): + +| 参数 | 类型 | 默认值 | 说明 | +|---|---|---|---| +| `page` | int | `1` | 页码 (从 1 开始) | +| `page_size` | int | `20` | 每页条数 | +| `cur_id` | int | — | 游标分页: 返回 `id < cur_id` 的记录 | + +分页响应体: + +```json +{ + "code": 0, + "data": { + "list": [...], + "total": 100, + "page": 1, + "page_size": 20 + } +} +``` + +--- + +## 角色说明 + +| 角色值 | 名称 | 说明 | +|---|---|---| +| `1` | 项目管理员 | 可管理项目配置、成员、缺陷系统 | +| `2` | 测试人员 | 可创建任务、审核截图、提单 | +| `3` | 开发人员 | 可查看任务、截图、缺陷 | +| — | 超级管理员 | `is_admin=1`, 管理全局用户和项目, 不受项目角色限制 | + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/project.md b/timi_hok_game_translator/LQA_WMP/docs/api/project.md new file mode 100644 index 0000000000000000000000000000000000000000..5a17f31fc49c3f455e25f6b4c3e1dc2378f952ab --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/project.md @@ -0,0 +1,174 @@ +# 项目接口 + +## 获取项目信息 + +``` +GET /api/project/entity?project_id= +``` + +**响应 data:** + +```json +{ + "project": { + "id": 2, + "code": "game_cn", + "name": "某游戏中文版", + "label": "", + "team": "QA团队", + "game_type": 1, + "project_type": 2, + "project_phase": 1 + } +} +``` + +--- + +## 创建/修改项目 + +``` +POST /api/project/entity +PATCH /api/project/entity +Content-Type: application/json +``` + +需要超级管理员权限, 创建时会自动初始化项目的缺陷类型、语言等配置 (从系统模板复制) + +**请求体:** + +```json +{ + "code": "game_cn", + "name": "某游戏中文版", + "label": "", + "team": "QA团队", + "game_type": 1, + "project_type": 2, + "project_phase": 1 +} +``` + +修改时需额外传 `"project_id": ` + +**`game_type` 枚举:** + +| 值 | 说明 | +|---|---| +| `1` | 手游 | +| `2` | 端游 | +| `3` | 页游 | +| `4` | App | +| `5` | 小游戏 | + +**`project_type` 枚举:** `1` 平台级, `2` 项目级 + +**`project_phase` 枚举:** `1` 上线运营, `2` 下线, `3` 研发期, `4` 保密 + +--- + +## 获取项目列表 + +``` +GET /api/project/list +``` + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `page` / `page_size` | int | 分页 | +| `project_id` | int | 按 ID 精确查询 | +| `name__icontains` | string | 名称模糊搜索 | +| `team__icontains` | string | 团队模糊搜索 | +| `game_type` | int | 游戏类型筛选 | +| `project_type` | int | 项目类型筛选 | +| `project_phase` | int | 项目阶段筛选 | + +--- + +## 获取项目角色树 + +``` +GET /api/project/roles?project_id= +``` + +`project_id=0` 时返回所有项目的角色树, 用于用户管理表单的角色下拉选项 + +--- + +## 项目配置 + +``` +GET /api/project/config?project_id=&cate= +POST /api/project/config?cate= +PATCH /api/project/config?cate= +DELETE /api/project/config?cate= +Content-Type: application/json +``` + +POST/PATCH/DELETE 需要 **项目管理员** 权限 + +**`cate` 取值:** + +| cate | 说明 | +|---|---| +| `BugType` | 缺陷类型配置 (多条) | +| `Language` | 区域语言配置 (多条) | +| `ImgRevert` | 图片还原配置 (单条): `GET` 时加 `&editor=1` 返回还原端格式 | +| `BugBillMethod` | 提单配置 (单条) | +| `BugBillUser` | 提单人员配置 | +| `BugTracker` | 缺陷系统配置 (单条), `api_key` 字段返回时以 `******` 掩码 | +| `CustomField` | 自定义提单字段 | +| `Other` | 其他配置 (单条) | + +**GET 响应 data:** + +```json +{ "list": [...] } +``` + +**PATCH 响应 data:** + +```json +{ "config": { ... } } +``` + +--- + +## 模块管理 + +``` +GET /api/project/module/list?project_id=[&all=1] +POST /api/project/module +PATCH /api/project/module +DELETE /api/project/module +Content-Type: application/json +``` + +需要项目成员权限 (增删改需项目管理员) + +**创建/修改请求体:** + +```json +{ + "project_id": 2, + "name": "ui_main", + "show_name": "主界面" +} +``` + +修改时需额外传 `"id": ` + +**删除请求体:** + +```json +{ + "project_id": 2, + "module_id": 10 +} +``` + +**GET 带 `all=1`** 时返回项目下所有模块 (不分页), 格式为 `{"modules": [...], "total": N}` + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/system.md b/timi_hok_game_translator/LQA_WMP/docs/api/system.md new file mode 100644 index 0000000000000000000000000000000000000000..66d082a6a55322cca57f9cf63e7640617c17231a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/system.md @@ -0,0 +1,122 @@ +# 系统工具接口 + +## 健康检查 + +``` +GET /api/health +``` + +免登录, 用于容器健康检查、监控探活 + +**响应 data:** + +```json +{ "status": "ok" } +``` + +--- + +## 获取一次性 Ticket + +``` +GET /api/ticket +``` + +需要登录, 获取一个 5 分钟有效的一次性 ticket, 用于换取 `access_token` (详见[用户接口 - 获取 access_token](user.md#获取-access_token)) + +**响应 data:** + +```json +{ "ticket": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" } +``` + +--- + +## 磁盘使用情况 + +``` +GET /api/disk_usage +``` + +需要登录, 返回媒体文件目录的磁盘用量 + +**响应 data:** + +```json +{ + "total": 107374182400, + "used": 21474836480, + "free": 85899345920 +} +``` + +单位: 字节 + +--- + +## 上传文件 + +``` +POST /api/upload_file +Content-Type: multipart/form-data +``` + +通用文件上传, 用于上传项目配置相关的附件 (如还原配置文件) + +**响应 data:** + +```json +{ + "file_name": "config.json", + "file_path": "/media/tmp/..." +} +``` + +--- + +## 获取枚举值 + +``` +GET /api/system/enums/ +``` + +获取系统内置枚举的标签与值, 用于前端下拉选项 + +**`cate` 取值示例:** + +| cate | 说明 | +|---|---| +| `game_type` | 游戏类型 | +| `project_type` | 项目类型 | +| `project_phase` | 项目阶段 | +| `role` | 项目角色 | +| `user_status` | 用户状态 | +| `job_status` | 任务状态 | + +**响应 data (示例):** + +```json +{ + "list": [ + { "value": 1, "label": "手游" }, + { "value": 2, "label": "端游" } + ] +} +``` + +--- + +## 媒体文件访问 + +``` +GET /media/ +``` + +截图等上传文件的访问路径 + +- `MEDIA_PUBLIC=false` (默认): 需要登录认证 (由登录中间件鉴权) +- `MEDIA_PUBLIC=true`: 允许匿名访问, 适用于禅道需要内嵌显示截图的场景 + +生产环境建议由 Nginx 直接提供 `APP_MEDIA_ROOT/media/` 目录, 避免经过 Django 处理 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/api/user.md b/timi_hok_game_translator/LQA_WMP/docs/api/user.md new file mode 100644 index 0000000000000000000000000000000000000000..6a781d0c5462523b99b8d80a12d75f731037c5c4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/api/user.md @@ -0,0 +1,292 @@ +# 用户接口 + +## 获取登录页配置 + +``` +GET /api/user/auth_config +``` + +免登录, 返回是否开放注册等前端需要的公开配置 + +**响应 data:** + +```json +{ + "allow_register": true, + "app_name": "LQA" +} +``` + +--- + +## 登录 + +``` +POST /api/user/login +Content-Type: application/json +``` + +免登录, 连续失败次数过多会锁定一段时间 + +**请求体:** + +```json +{ + "username": "admin", + "password": "Admin123456" +} +``` + +**响应 data:** + +```json +{ + "user": { + "id": 1, + "name": "admin", + "name_zh": "管理员", + "is_admin": 1 + } +} +``` + +登录成功后服务端设置 Session Cookie, 后续浏览器请求自动携带 + +--- + +## 退出登录 + +``` +POST /api/user/logout +GET /api/user/logout +``` + +清除 Session + +--- + +## 注册 + +``` +POST /api/user/register +Content-Type: application/json +``` + +免登录, 仅在 `ALLOW_REGISTER=true` 时可用, 注册后需管理员分配项目角色 + +**请求体:** + +```json +{ + "username": "testuser", + "password": "Password123", + "name_zh": "测试用户", + "email": "test@example.com" +} +``` + +--- + +## 修改自己的密码 + +``` +POST /api/user/password +Content-Type: application/json +``` + +**请求体:** + +```json +{ + "old_password": "OldPass123", + "new_password": "NewPass456" +} +``` + +--- + +## 修改自己的资料 + +``` +PATCH /api/user/profile +Content-Type: application/json +``` + +**请求体 (字段均可选):** + +```json +{ + "name_zh": "新昵称", + "email": "new@example.com" +} +``` + +--- + +## 重置他人密码 + +``` +POST /api/user/reset_password +Content-Type: application/json +``` + +需要超级管理员权限 + +**请求体:** + +```json +{ + "id": 5, + "new_password": "NewPass789" +} +``` + +--- + +## 获取用户列表 + +``` +GET /api/user/list +``` + +**Query 参数:** + +| 参数 | 类型 | 说明 | +|---|---|---| +| `page` / `page_size` | int | 分页 | +| `cur_id` | int | 游标分页 | +| `name__icontains` | string | 用户名模糊搜索 | +| `name_zh__icontains` | string | 显示名模糊搜索 | +| `department__icontains` | string | 部门模糊搜索 | +| `status` | int | 状态: `1` 正常, `0` 禁用 | +| `project_id` | int | 筛选属于某项目的成员 | +| `is_admin` | int | `1` 只返回项目管理员, `0` 只返回非管理员 | +| `info_type` | int | `0` 基础信息, `1` 简略信息, `2` 含项目角色 | + +**响应 data:** + +```json +{ + "list": [ + { + "id": 1, + "name": "admin", + "name_zh": "管理员", + "email": "", + "department": "", + "status": 1, + "is_admin": 1, + "projects": [...], + "roles": [...] + } + ], + "total": 10, + "page": 1, + "page_size": 20 +} +``` + +--- + +## 获取/创建/修改/删除用户 + +``` +GET /api/user/entity?id=&info_type=<0|1> +POST /api/user/entity +PATCH /api/user/entity +DELETE /api/user/entity +``` + +**GET 参数:** + +| 参数 | 说明 | +|---|---| +| `id` | 用户 ID, 不传则返回当前登录用户 | +| `info_type` | `0` 基础信息, `1` 含项目角色 (默认) | + +本人查询时可在响应中看到自己的 `access_token` + +**POST 请求体 (创建用户):** + +```json +{ + "name": "newuser", + "password": "Pass123456", + "name_zh": "新用户", + "email": "new@example.com", + "department": "QA", + "project_id": 2, + "roles": [[2, 2]] +} +``` + +超级管理员可创建任意用户; 项目管理员只能为本项目创建成员 + +**PATCH 请求体 (修改用户):** + +```json +{ + "id": 5, + "project_id": 2, + "name_zh": "新名字", + "status": 0, + "is_admin": 0, + "roles": [[2, 2]] +} +``` + +**DELETE 请求体 (软删除, 需超管):** + +```json +{ "id": 5 } +``` + +--- + +## 获取当前用户权限信息 + +``` +GET /api/user/permission +``` + +返回当前用户的基本信息及可访问的项目列表 (含角色), 前端用于初始化路由权限 + +**响应 data:** + +```json +{ + "user": { + "id": 1, + "is_admin": 1, + "name": "admin", + "name_zh": "管理员" + }, + "projects": [ + { + "id": 2, + "code": "game_cn", + "name": "某游戏中文版", + "roles": ["2_1", "2_2"] + } + ] +} +``` + +--- + +## 获取 access_token + +``` +POST /api/user/access_token +LQA-Ticket: +``` + +需先通过 `GET /api/ticket` 获取一次性 ticket, 再携带 `LQA-Ticket` 请求头调用本接口, 生成新 token 后旧 token 立即失效 + +**响应 data:** + +```json +{ "access_token": "eyJ..." } +``` + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/deploy-guide.md b/timi_hok_game_translator/LQA_WMP/docs/deploy-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..4f7a1eb102fe66e6c9bf697eed38d3a5daf270a8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/deploy-guide.md @@ -0,0 +1,298 @@ +# LQA 平台部署指南 + +> 适用对象: 需要在一台 **全新电脑 / 全新服务器** 上从零把 LQA (本地化质量检查) 平台跑起来的人 +> +> 适用版本: Docker Compose 一键部署 (推荐) 或 本地源码开发部署, +> 本文档基于仓库根目录的 `README.md`、`docker-compose.yml`、`.env.example` 及 `server/README.md`、`web/README.md` 整理 + +--- + +## 一、平台简介与组件 + +LQA 平台由以下服务组成, 部署时它们要么打包进容器, 要么在本地分别启动: + +| 组件 | 作用 | 技术 | +|---|---|---| +| MySQL 8 | 主数据库 | 容器 / 本地 | +| Redis 7 | 缓存、Session、Celery 消息队列 | 容器 / 本地 | +| server | 后端 API (Django + Gunicorn) | Python 3.12 | +| worker | Celery 异步任务 (AI 识别、自动提单、回归) | Python 3.12 | +| ai | AI 识别服务 (Flask, 内置离线 OCR) | 容器 / 外部服务 | +| web | 前端静态资源 + 反向代理 (Nginx) | Vue 3 + Vite | + +**对外访问端口**: 默认 `8080` (容器部署), 本地开发前端 `3333`、后端 `8000` + +--- + +## 二、两种部署方式对比 + +| 方式 | 适合场景 | 难度 | 依赖 | +|---|---|---|---| +| **A. Docker Compose 一键部署 (推荐)** | 生产 / 演示 / 给不懂 Python 的人 | ⭐ 简单 | 只需装 Docker | +| **B. 本地源码开发部署** | 二次开发、调试 | ⭐⭐⭐ 需配环境 | Python 3.12、Node 20、MySQL、Redis | + +下面分别说明 + +--- + +## 三、方式 A: Docker Compose 一键部署 (推荐) + +### 3.1 前置准备: 安装 Docker + +- **Windows**: 下载安装 [Docker Desktop](https://www.docker.com/products/docker-desktop/), 安装后需在设置里勾选 **"Use the WSL 2 based engine"**; 首次启动需开启 WSL2 (控制面板 → 程序 → 启用或关闭 Windows 功能 → 勾选 "虚拟机平台" 和 "适用于 Linux 的 Windows 子系统", 重启后执行 `wsl --install`) +- **macOS**: 下载 [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop/) +- **Linux (Ubuntu 示例)**: + ```bash + sudo apt update + sudo apt install -y docker.io docker-compose-plugin + sudo usermod -aG docker $USER # 退出重登后免 sudo 用 docker + ``` + +验证: +```bash +docker --version # 需 20.10+ (Windows/Mac 桌面版自带) +docker compose version # 需 v2 (命令是 docker compose, 不是 docker-compose) +``` + +### 3.2 获取代码 + +```bash +git clone git@github.com:your-org/WMP.git +cd WMP +``` + +> 若使用 HTTPS: `git clone https://github.com/your-org/WMP.git` + +### 3.3 配置环境变量 + +```bash +cp .env.example .env +``` + +**必须修改的 4 项 (否则容器会因 `${VAR:?}` 校验报错或存在安全风险)**: + +```ini +MYSQL_ROOT_PASSWORD=请改成随机串 +MYSQL_PASSWORD=请改成随机串 +REDIS_PASSWORD=请改成随机串 +SECRET_KEY=请改成随机串 +``` + +生成随机串 (任选其一): +```bash +# 方式 1:用 Python +python -c "import secrets;print(secrets.token_urlsafe(48))" +# 方式 2:用 openssl +openssl rand -base64 48 +``` + +**其余常用项 (按需修改)**: + +| 变量 | 默认值 | 说明 | +|---|---|---| +| `LQA_ADMIN_USERNAME` | `admin` | 初始超级管理员账号, 已存在时不覆盖 | +| `LQA_ADMIN_PASSWORD` | 空 (必填) | 初始超管密码, **必须设置** | +| `LQA_HTTP_PORT` | `8080` | 平台对外 HTTP 端口 | +| `PUBLIC_URL` | `http://localhost:8080` | 缺陷截图链接与 Webhook `{{lqa_server}}` 变量使用; 部署到别的主机需改成实际域名/IP | +| `ALLOW_REGISTER` | `true` | 是否开放自助注册 | +| `SESSION_COOKIE_SECURE` | `false` | HTTPS 部署时需设为 `true`, 否则浏览器可能拒绝发送会话 Cookie | +| `AI_BASE_URL` | 空 (用内置 ai 容器) | 若已有独立识别服务, 填其地址, 并加 `--scale ai=0` 跳过本地 ai | +| `OCR_ENGINE` / `OCR_PROVIDER` | `rapidocr` | 离线 OCR, 开箱即用; `paddleocr` 精度更高但镜像 +2GB | +| `AI_WORKERS` | `2` | ai 服务进程数, 按并发识别量调整 | +| `AI_HTTP_PORT` | `127.0.0.1:8086` | 默认只本机可访问 ai, 仅供调试 | + +> `OCR_ENGINE` / `OCR_PROVIDER` 完整可选项与说明见 [lqa_service/README.md](../lqa_service/README.md) + +### 3.4 启动 + +```bash +docker compose up -d --build +``` + +首次会拉取/构建镜像 (ai 镜像内含 OCR, 首次构建较慢, 约几分钟到十几分钟) + +查看状态: +```bash +docker compose ps # 看各容器是否 healthy +docker compose logs -f # 实时看日志; Ctrl+C 退出 +``` + +### 3.5 验证与登录 + +浏览器打开 `http://<服务器IP>:8080` (本机即 `http://localhost:8080`), 用 `.env` 里的 `LQA_ADMIN_USERNAME` / `LQA_ADMIN_PASSWORD` 登录 + +> 若打不开: ① 确认防火墙放行 `8080`; ② `docker compose ps` 看 `web` / `server` 是否 `healthy`; ③ `docker compose logs web` 看 Nginx 是否起来 + +### 3.6 首次使用必做配置 + +1. **系统管理 → 项目管理**: 创建项目, 并给使用平台的账号分配项目与角色 (超管默认无项目, 需自己建) +2. **项目设置 → 基础配置 → 还原执行**: 配置 Webhook (Jenkins / GitLab CI / 自建服务), 变量如 `{{job_id}}`、`{{regression}}`、`{{lqa_server}}` 见页面提示 +3. **项目设置 → 缺陷系统**: 选择 平台内记录 / Bugzilla / 禅道, 填连接信息后点 "测试连接" + +### 3.7 常用运维 + +```bash +docker compose down # 停止 (不删数据) +docker compose down -v # 停止并删除数据卷 (慎用! 会清空库) +docker compose restart server # 只重启后端 +docker compose up -d --build # 改了 .env 或代码后重建 +``` + +--- + +## 四、方式 B: 本地源码开发部署 + +适合需要改代码、跑测试的场景, 需要 **本机** 具备: Python 3.12、Node.js 20+、pnpm 11、MySQL 8、Redis 7 + +### 4.1 安装基础依赖 + +- **Python 3.12**: [python.org](https://www.python.org/downloads/) 或 `pyenv`; Windows 勾选 "Add to PATH" +- **Node.js 20 + pnpm 11**: + ```bash + # 先装 Node 20 (含 npm), 再装 pnpm + npm install -g pnpm@11 + node -v && pnpm -v + ``` +- **MySQL 8**: Windows 可用 [MySQL Installer](https://dev.mysql.com/downloads/installer/); Linux `sudo apt install mysql-server` + 创建库与用户: + ```sql + CREATE DATABASE lqa CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + CREATE USER 'lqa'@'localhost' IDENTIFIED BY '你的密码'; + GRANT ALL PRIVILEGES ON lqa.* TO 'lqa'@'localhost'; + FLUSH PRIVILEGES; + ``` +- **Redis 7**: Windows 用 [Memurai](https://www.memurai.com/) 或 WSL 内装; Linux `sudo apt install redis-server` + 启动并设置密码 (与下面 `.env` 中 `REDIS_PASSWORD` 一致): + ```bash + redis-server --requirepass 你的Redis密码 + ``` + +### 4.2 后端 + +```bash +cd server +python -m venv .venv +.venv\Scripts\activate # Windows 激活; Linux/macOS: source .venv/bin/activate +pip install -r requirements.txt + +cp .env.example .env # 修改 MYSQL_URL / REDIS_URL 等 (见 4.5) +python manage.py migrate # 建表 +python manage.py init_data # 初始化系统模板 (缺陷类型、区域语言) +python manage.py init_admin --username admin --password 'Admin123456' +``` + +启动 (两个终端): + +```bash +# 终端 1: API 服务 +python manage.py runserver 0.0.0.0:8000 + +# 终端 2: Celery 异步任务 (Windows 必须加 -P solo) +celery -A celery_app worker -l info -P solo # Windows +# celery -A celery_app worker -l info # Linux/macOS +``` + +### 4.3 前端 + +```bash +cd web +pnpm install +pnpm dev # http://localhost:3333 +``` + +开发时接口请求 `/api-pro/*` 由 Vite 代理到后端 `http://127.0.0.1:8000/`, +要指向别的后端地址, 在 `web/` 下新建 `.env.development.local` (已被 git 忽略): + +``` +VITE_PROXY_TARGET = 'http://192.168.1.10:8000/' +``` + +### 4.4 后端 .env 关键项 (本地开发) + +`server/.env` 至少要有: + +```ini +SECRET_KEY=随机串 +MYSQL_URL=mysql://lqa:你的密码@127.0.0.1:3306/lqa +REDIS_URL=rediscache://:你的Redis密码@127.0.0.1:6379/1 +CELERY_BROKER_URL=redis://:你的Redis密码@127.0.0.1:6379/2 +CELERY_BACKEND_URL=redis://:你的Redis密码@127.0.0.1:6379/2 +LQA_ADMIN_USERNAME=admin +LQA_ADMIN_PASSWORD=Admin123456 +AI_BASE_URL=http://<外部AI服务地址>:8086 # 指向外部 AI 识别服务, 详见下方 "对接外部 AI 平台" +``` + +### 4.5 对接外部 AI 平台 + +平台本身不内置 AI 识别算法, 识别能力由 **外部 AI 识别服务** 提供, 二者通过 HTTP 对接: + +- **容器部署**: 默认随编排启动内置的 `ai` 容器, 无需配置; 若你已有独立部署的识别服务, 在 `.env` 中设置 `AI_BASE_URL` 指向它, 并用 `docker compose up -d --scale ai=0` 跳过本地 `ai` 容器即可 +- **本地源码部署**: 在 `server/.env` 中设置 `AI_BASE_URL` 指向外部识别服务地址, 重启后端生效 + +> 平台调用约定: 对 `POST {AI_BASE_URL}/image/lqa_check/` 发起请求, 并自动带上 `project-method: _lqa` 请求头 ("AI识别项目名" 在 Web 端 "项目设置" 中配置), 具体的识别服务如何部署、支持哪些 OCR 引擎, 不属于本平台部署文档范畴 + +### 4.6 验证 + +1. 浏览器打开 `http://localhost:3333`, 用上面的超管账号登录 +2. `GET http://127.0.0.1:8000/api/health` (免登录) 返回健康信息 + +--- + +## 五、为还原端生成 access_token (对接必做) + +还原端 (Unity / UE 插件) 通过 `LQA-Authorization: ` 调用接口, 需要给对应账号生成 token: + +```bash +cd server +.venv\Scripts\activate +python manage.py update_access_token -u <用户ID或用户名> [-e 2592000] # 默认 30 天有效 +``` + +或在 Web 端登录后: `GET /api/ticket` 取一次性 ticket → 带 `LQA-Ticket` 调 `POST /api/user/access_token` 换 token + +还原端只需 3 个接口: + +| 接口 | 说明 | +|---|---| +| `GET /api/job/datas` | 拉取任务测试数据 | +| `POST /api/image/entity` | 上传截图 (multipart/form-data) | +| `POST /api/job/device` | 上报设备信息与执行进度 | + +详见 [还原端集成指南](../docs/integration/restorer.md)。 + +--- + +## 六、常见问题 (FAQ) + +**Q1: 容器起不来, 报 `${MYSQL_PASSWORD:?请在 .env 中设置 ...}`** +→ 没复制或没填 `.env` 里的必填项, 回去执行 `cp .env.example .env` 并把 4 个必填项填好 + +**Q2: `docker compose` 命令找不到** +→ 用的是旧版 `docker-compose`(带横线), 装 `docker-compose-plugin` 后用 `docker compose` (空格) 即可; 或单独装 `pip install docker-compose` + +**Q3: Windows 上 Celery 启动报错 / 卡死** +→ Windows 必须加 `-P solo`: `celery -A celery_app worker -l info -P solo` + +**Q4: 平台能打开但 "识别" 一直没结果** +→ worker 未启动, 或 `AI_BASE_URL` 指向的 AI 识别服务不可达, 容器部署看 `docker compose logs worker` 和 `docker compose logs ai`; 本地部署确认 `server/.env` 中的 `AI_BASE_URL` 能访问、并已重启后端 + +**Q5: Webhook 触发失败 (CORS)** +→ 还原执行由 **浏览器** 发起, 目标服务 (Jenkins 等) 需允许平台域名跨域; Jenkins 装 CORS 插件或加反向代理 + +**Q6: 改了 .env 不生效** +→ 容器部署需 `docker compose up -d --build` 重建; 本地部署需重启 runserver 与 worker + +--- + +## 七、端口速查表 + +| 端口 | 服务 | 说明 | +|---|---|---| +| 8080 | web (Nginx) | 容器部署对外访问入口 | +| 8000 | server | 本地开发后端 | +| 3333 | web (Vite) | 本地开发前端 | +| 8086 | ai | AI 识别服务 (默认仅本机, 容器内部 `ai:8086`) | +| 3306 | mysql | 数据库 | +| 6379 | redis | 缓存/队列 | + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/integration/restorer.md b/timi_hok_game_translator/LQA_WMP/docs/integration/restorer.md new file mode 100644 index 0000000000000000000000000000000000000000..2e729c38384d82fe2a42a6ef9aa494fd52b5fb70 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/integration/restorer.md @@ -0,0 +1,291 @@ +# 还原端集成指南 + +本文档面向还原端开发者 (Unity/UE 编辑器插件、自动化脚本等), 描述与 LQA 平台交互的完整流程 + +--- + +## 概述 + +还原端的职责: +1. 被 Webhook 触发后启动 +2. 从平台拉取本次任务的测试数据列表 +3. 按数据逐一生成各语言截图, 上传到平台 +4. 上报设备信息与进度 + +平台侧的职责: +- 在浏览器中调用还原端配置的 Webhook, 触发还原 +- 接收截图、异步调用 AI 识别服务、生成缺陷报告 + +--- + +## 认证 + +还原端使用 **access_token** 认证, 每个请求携带请求头: + +``` +LQA-Authorization: +``` + +**获取 access_token (由平台管理员操作):** + +```bash +# 在后端服务器上执行 +python manage.py update_access_token -u -e 2592000 +# -e 指定有效期 (秒), 默认 30 天 +``` + +也可以通过接口方式获取, 详见 [API 通用约定 - 认证](../api/overview.md) + +--- + +## 交互流程 + +``` +平台(浏览器) 还原端 + │ │ + │── Webhook 触发 ──→ │ 携带 job_id、languages、lqa_server 等参数 + │ │ + │ │── GET /api/job/datas ──→ 平台 + │ │←── 测试数据列表 ───────── + │ │ + │ (循环处理每个数据) │ + │ │── POST /api/image/entity ──→ 平台 (上传截图) + │ │←── image_id ───────────── + │ │ + │ │── POST /api/job/device ──→ 平台 (上报进度) + │ │←── 确认 ──────────────── + │ │ +``` + +Webhook 参数由平台在 "项目设置 > 基础配置 > 还原执行" 中配置, 可用变量: + +| 变量 | 说明 | +|---|---| +| `{{job_id}}` | 任务 ID | +| `{{languages}}` | 语言列表 (逗号分隔的平台标准编码, 如 `LAN_EN_US,LAN_JA_JP`) | +| `{{language_values}}` | 平台标准语言编码数组 (JSON), 如 `["LAN_EN_US","LAN_JA_JP"]` | +| `{{ue_languages}}` | UE 还原插件专用语言编码 (逗号分隔), 如 `LAN_EU_EN,LAN_JP_JP`; 拉起 UE 时命令行 `-Language=` 应使用此值 | +| `{{ue_language_values}}` | UE 还原插件专用语言编码数组(JSON) | +| `{{regression}}` | `0` 普通, `1` 回归 | +| `{{lqa_server}}` | 平台访问地址 (来自 `PUBLIC_URL` 配置) | + +> **UE 还原插件语言编码说明** +> 平台内部统一使用 ISO 国家码 (如韩语 `LAN_KO_KR`、日语 `LAN_JA_JP`), 而 UE 还原插件 `ConfigManager.cpp` 的 `LanguageMap` 使用另一套命名 (如韩语 `LAN_KO_KO`、日语 `LAN_JP_JP`) +> 当还原端直接拼接 UE 启动命令时, 请优先使用 `{{ue_languages}}` / `{{ue_language_values}}` 变量, 平台已完成反向翻译; 否则 UE 命令行 `-Language=` 传入平台标准编码将无法被插件识别, 还原会降级到默认语言 (英语) + +--- + +## 接口说明 + +### 1. 拉取测试数据 + +``` +GET /api/job/datas?job_id=&language=®ression=<0|1> +LQA-Authorization: +``` + +建议分语言分批拉取 + +**完整请求示例:** + +``` +GET https://lqa.example.com/api/job/datas?job_id=10&language=2®ression=0&count=500 +LQA-Authorization: eyJ... +``` + +**响应示例:** + +```json +{ + "code": 0, + "data": { + "datas": [ + { "id": 501, "file_path": "Assets/UI/main.prefab", "module_id": 10 }, + { "id": 502, "file_path": "Assets/UI/shop.prefab", "module_id": 11 } + ], + "bug_ids": [] + } +} +``` + +回归任务时 `bug_ids` 包含需要回归的缺陷 ID, 还原端在上传截图时需要传回这些 `bug_ids` + +**增量拉取 (分批):** + +``` +GET /api/job/datas?job_id=10&language=2&count=100&minID=0 +GET /api/job/datas?job_id=10&language=2&count=100&minID=502 +``` + +--- + +### 2. 上传截图 + +``` +POST /api/image/entity +Content-Type: multipart/form-data +LQA-Authorization: +``` + +**Form 字段:** + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `file` | file | 是 | 截图文件 (PNG 推荐) | +| `project_id` | int | 是 | 项目 ID | +| `job_id` | int | 是 | 任务 ID | +| `data_id` | int | 是 | 测试数据 ID (来自上一步) | +| `language` | int | 是 | 语言值 | +| `rect_locations` | string | 是 | 文本控件位置 JSON (见下方格式) | +| `ai_sign` | int | 否 | `1` 上传后立即触发 AI 识别 | +| `discern` | int | 否 | `0` 全量 (默认), `1` 差异识别 | +| `create_bug` | int | 否 | `1` 识别后自动提单 | +| `regression` | int | 否 | `1` 表示回归任务 | +| `bug_ids` | string | 否 | 回归时: 需回归的缺陷 ID, 逗号分隔 | + +**`rect_locations` 格式:** + +`rect_locations` 是一个 JSON 字符串, 描述截图中各文本控件的位置 (用于 AI 识别定位文字区域): + +```json +[ + { + "x": 100, + "y": 200, + "width": 300, + "height": 50, + "key": "ui_title", + "text": "标题文本" + } +] +``` + +字段含义: + +| 字段 | 说明 | +|---|---| +| `x`, `y` | 控件左上角坐标 (像素) | +| `width`, `height` | 控件宽高 (像素) | +| `key` | 控件唯一标识 | +| `text` | 控件当前显示文本 | + +**响应示例:** + +```json +{ + "code": 0, + "data": { + "image": { + "id": 200, + "file_path": "/media/project/2/job/10/image/ui_main_zh.png" + }, + "task_id": "abc123-..." + } +} +``` + +--- + +### 3. 上报设备与进度 + +``` +POST /api/job/device +Content-Type: application/json +LQA-Authorization: +``` + +建议每完成一批截图上传后上报一次进度 + +**请求体:** + +```json +{ + "job_id": 10, + "execute_pc": "PC-RENDER-001", + "language": 2, + "status": 2, + "progress": 45, + "total": 100 +} +``` + +| 字段 | 说明 | +|---|---| +| `execute_pc` | 还原设备标识 (机器名或 IP) | +| `language` | 当前正在处理的语言 | +| `status` | `1` 等待, `2` 执行中, `3` 完成, `4` 失败 | +| `progress` | 已完成数量 | +| `total` | 总数量 | + +--- + +## 错误处理 + +所有接口返回 `code != 0` 时为错误, `msg` 字段包含错误描述 + +| code | 建议处理方式 | +|---|---| +| `1003` | access_token 失效, 需重新获取 | +| `1002` | 请求参数错误, 检查字段 | +| `1005` | 资源不存在, `job_id` 或 `data_id` 可能已被删除 | +| `1001` | 通用错误, 记录日志, 可重试 | + +建议对上传失败的截图进行重试 (最多 3 次), 重试时使用相同的 `data_id` 和 `language`, 平台会自动管理 `iteration` 版本 + +--- + +## 完整示例 (Python 伪代码) + +```python +import requests + +LQA_SERVER = "https://lqa.example.com" +ACCESS_TOKEN = "eyJ..." +HEADERS = {"LQA-Authorization": ACCESS_TOKEN} + +def run_restore(job_id, project_id, languages): + for language in languages: + # 1. 拉取测试数据 + resp = requests.get( + f"{LQA_SERVER}/api/job/datas", + params={"job_id": job_id, "language": language}, + headers=HEADERS + ) + datas = resp.json()["data"]["datas"] + + for i, data in enumerate(datas): + # 2. 生成截图(业务逻辑) + screenshot, rect_locations = render_screenshot(data, language) + + # 3. 上传截图 + requests.post( + f"{LQA_SERVER}/api/image/entity", + data={ + "project_id": project_id, + "job_id": job_id, + "data_id": data["id"], + "language": language, + "rect_locations": json.dumps(rect_locations), + "ai_sign": 1, + }, + files={"file": ("screenshot.png", screenshot, "image/png")}, + headers=HEADERS + ) + + # 4. 上报进度 + if i % 10 == 0: + requests.post( + f"{LQA_SERVER}/api/job/device", + json={ + "job_id": job_id, + "execute_pc": "MY-PC-001", + "language": language, + "status": 2, + "progress": i + 1, + "total": len(datas) + }, + headers=HEADERS + ) +``` + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/docs/web-guide.md b/timi_hok_game_translator/LQA_WMP/docs/web-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..aa9006cb3bd460342307cf266f181e1d020c6d01 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/docs/web-guide.md @@ -0,0 +1,492 @@ +# LQA Web 平台使用文档 + +本手册面向 **测试工程师 / 项目管理员 / 开发同学**, 介绍如何通过 LQA Web 平台 (以下简称 “平台”) 完成本地化质量检查的日常工作: 从登录、创建项目、配置还原端与缺陷系统, 到执行还原任务、审核 AI 识别结果、提交并回归验证缺陷 + +> 平台默认访问地址: `http://<服务器IP>:8080` (由 `.env` 中 `LQA_HTTP_PORT` 决定, 默认 `8080`), +> 部署与运维相关内容请参阅项目根 [README.md](../README.md) + +--- + +## 1. 概览 + +### 1.1 功能地图 + +```mermaid +flowchart LR + A[登录 / 注册] --> B[系统管理] + A --> C[项目设置] + A --> D[任务管理] + A --> E[数据管理] + + B --> B1[项目管理] + B --> B2[用户管理] + B --> B3[全局设置] + + C --> C1[缺陷类型] + C --> C2[区域语言] + C --> C3[图片还原] + C --> C4[模块] + C --> C5[还原执行 Webhook] + C --> C6[缺陷系统] + C --> C7[提单模板] + + D --> D1[创建/编辑任务] + D --> D2[开始/重试/结束] + D --> D3[执行进度] + D --> D4[结果审核] + D --> D5[缺陷单] +``` + +### 1.2 角色 + +| 角色 | 可见菜单 | 典型操作 | +|---|---|---| +| **超级管理员** | 系统管理 (项目/用户/全局设置) + 所有项目 | 创建项目、创建/禁用用户、全局配置 | +| **项目管理员** | 自己的项目下 全部菜单 | 配置 Webhook/缺陷系统、建任务、建缺陷类型 | +| **测试人员** | 任务管理、数据管理、结果审核、缺陷单 | 跑任务、审核结果、提单、回归 | +| **开发人员** | 任务管理 (只读)、缺陷单 | 查看任务、处理缺陷 | + +> 角色由 **超级管理员** 在 “项目设置 → 用户管理” 中为用户在具体项目下分配, 一个用户可同时在多个项目中拥有不同角色 + +### 1.3 顶部与左侧导航 + +- **左侧菜单**: 按当前选中的项目动态生成, 顶部切换项目后, 整个左侧菜单会刷新为该项目下的功能 +- **顶部项目选择器**: 切换项目视角; **系统管理** 视角独立, 用于全局配置 +- **右上角头像**: 个人信息、修改密码、退出登录 + +--- + +## 2. 账号与登录 + +### 2.1 登录 + +1. 浏览器访问平台地址, 输入用户名与密码 +2. 平台支持自助注册 (由 `.env` 中 `ALLOW_REGISTER` 控制, 默认开启), 注册后账号默认无任何项目权限, 需由超级管理员到 “系统管理 → 用户管理” 中分配项目角色 +3. 忘记密码请联系超级管理员, 在用户管理页面点击 “重置密码” + +### 2.2 自助注册 + +- 登录页右下角若出现 **注册账号** 入口即为开放注册状态 +- 注册流程: 填写 **用户名 / 中文名 / 所属部门 / 密码 / 确认密码** → 提交, 无需邮件验证, 注册后请联系管理员分配项目 + +### 2.3 修改密码 / 退出登录 + +- 点击右上角头像 → **修改密码**: 需要输入原密码 +- 退出登录: 点击头像 → **退出登录** + +--- + +## 3. 系统管理 (超级管理员) + +### 3.1 项目管理 (`系统管理 → 项目管理`) + +用于创建和维护所有项目, 字段说明: + +| 字段 | 必填 | 说明 | +|---|---|---| +| 所属团队 | 否 | 用于分组标识 | +| 名称 | 是 | 项目中文名 | +| 项目代号 (code) | 是 | 英文代号, `[A-Za-z0-9_-]{2,100}`, **创建后不可修改**; 用于提单模板目录 `templates/spec2/<代号小写>` | +| AI 识别项目名 (cvtest_project) | 是 | AI 识别服务中的项目标识, 调用时拼成 `<项目名>_lqa` 作为 `project-method`, 未填写时 **无法创建任务** | +| 项目类型 | 是 | 平台级 / 项目级 (默认项目级) | +| 游戏类型 | 是 | 多选:手游 / 端游 / 页游 / app / 小游戏 | +| 研发阶段 | 是 | 上线运营 / 下线 / 研发期 / 保密 | +| 测试经理 | 是 | 平台用户名; 创建项目后会自动赋予 “项目管理员” 角色, 多人以 `;` 分隔 | + +> 创建完成后, 顶部项目选择器会出现新项目, 切换过去即可进入该项目的功能菜单 + +### 3.2 用户管理 (`系统管理 → 用户管理`) + +- **全局视角**: 可按 `英文名 / 中文名 / 所属部门 / 所属项目 / 是否管理员` 搜索; 可新增用户、重置密码、禁用账号 +- **按项目视角**: 进入某个项目的 `项目设置 → 用户管理`, 这里的新增/编辑作用于当前项目的角色分配 +- 支持 **导出用户列表 CSV** (右上角 “导出” 按钮), 角色会翻译成 `项目名/角色名` 的可读文本 + +字段: + +| 字段 | 说明 | +|---|---| +| 英文名 | 唯一标识, 创建后不可改 | +| 中文名 / 所属部门 | 用户自助注册时填写, 管理员可改 | +| 角色 | 多选, 格式 `项目/角色`, 使用级联选择器 | + +### 3.3 全局设置 (`系统管理 → 设置`) + +- 调整系统级别开关、全局提示等 (具体项按部署版本不同略有差异) + +--- + +## 4. 项目设置 (项目管理员) + +进入某个项目后, 左侧菜单会出现 **项目设置**, 分为以下 Tab: + +> 不同角色可见的 Tab 不同, 普通测试人员只能看到 **模块** 和 **提单** + +### 4.1 缺陷类型 + +维护项目的缺陷分类 (如: **漏译**、**超框**、**错译**、**漏 Key**、**重叠** 等) + +- 新建缺陷类型时需填写: **名称、是否启用、排序、是否 AI 识别类型** +- AI 识别类型会在 **创建任务 → 识别缺陷类型** 多选中出现, 决定本次任务 AI 会检查哪些问题 + +### 4.2 区域语言 + +维护项目使用的区域语言编码, 例如: + +| 显示名 | 编码 | PO 代码 | +|---|---|---| +| 英语 | `LAN_EU_EN` | `en` | +| 日语 | `LAN_JP_JP` | `ja` | +| 简体中文 | `LAN_CHS_CHS` | `zh` | + +- 可增删, 但 **编码必须与还原端插件保持一致** (在 UE/Unity 插件配置或命令行传入) +- 排序决定了创建任务时语言选择器的默认顺序 + +### 4.3 图片还原 + +配置 **语言根目录** 和 **路径模板**, 用于还原端定位每种语言的截图位置 + +- 多条配置可共存: 每条配置可展开编辑 **语言编码 ↔ 文件路径** 的映射表 +- 该配置写入变量 `{{language_path}}`, 可在 Webhook 请求体中直接使用 + +### 4.4 模块 + +维护业务模块树 (如: **登录 / 大厅 / 战斗 / 商店**) + +- 模块用于筛选测试数据、组织任务与缺陷 +- 支持多级, 字段: **上级模块、名称、显示名、备注、是否启用** + +### 4.5 还原执行 (Webhook) + +> 这是接入 Jenkins / GitLab CI / 自建还原服务 的核心配置 +> **开始任务 / 重试任务** 时, 由 **浏览器** 直接请求该 Webhook, 再由 Webhook 后端拉起还原进程 + +#### 字段 + +| 字段 | 示例 | 说明 | +|---|---|---| +| Webhook 地址 | `https://jenkins.example.com/job/lqa/buildWithParameters?token=xxx&JOB_ID={{job_id}}` | `http(s)://` 开头 | +| 请求方法 | `POST` / `PUT` / `GET` | GET 不填请求体 | +| 请求头 (JSON) | `{"Authorization": "Bearer xxx"}` | JSON 对象, 可为空 | +| 请求体 (JSON) | `{"job_id": "{{job_id}}", "regression": "{{regression}}"}` | JSON 对象/数组, **留空时自动发送全部变量** | +| 编辑器路径 | `D:/UE/Engine/Binaries/Win64/UE4Editor.exe` | 还原端拉取配置时返回, 也可作为 `{{editor_path}}` | +| 编辑器版本 | `5.3.2` | `{{editor_version}}` | + +#### 可用变量 (在地址、请求头、请求体中以 `{{变量名}}` 使用) + +| 变量 | 说明 | +|---|---| +| `job_id` / `job_name` | 任务 ID / 名称 | +| `parent_job_id` | 父任务 ID (回归任务时有值, 否则为 0) | +| `project_id` / `project_code` / `project_name` | 项目信息 | +| `languages` | 还原语言编码, 逗号分隔, 如 `LAN_EU_EN,LAN_JP_JP` | +| `language_values` | 还原语言值数组, 如 `[2, 6]` | +| `regression` | **执行类型: 0 普通 / 1 回归 / 2 重试** | +| `discern` | 识别方式: 0 全量 / 1 差异 | +| `create_bug` | 识别后是否自动提单: 0/1 | +| `svn_url` / `svn_version` | 资源仓库与版本 | +| `language_path` | 图片还原配置中的语言根目录 | +| `editor_path` / `editor_version` | 本页填写的编辑器路径与版本 | +| `lqa_server` | 平台对外地址 (后端 `PUBLIC_URL`) | + +> **提示**: 请求体中如果某个值 **恰好** 写成 `"{{变量名}}"` (整段加引号)), 框架会保留原始类型 (数字/数组), 否则按字符串替换 + +#### 跨域 (CORS) + +Webhook 由浏览器直接请求, 目标服务必须允许平台域名跨域, 常见做法: +- Jenkins 安装 **CORS Filter Plugin** 并在系统设置里把平台域名加入白名单; +- 或在 Jenkins/Gitlab 前加一层 Nginx 反向代理, 由该代理返回 `Access-Control-Allow-Origin` + +### 4.6 缺陷系统 + +决定项目的 Bug 存放位置, 支持三种模式: + +| 类型 | 必填配置 | 说明 | +|---|---|---| +| **平台内记录 (none)** | 无 | 缺陷只保存在平台内, 回归时由平台关闭/重新打开 | +| **Bugzilla 5.x** | 系统地址、API Key、产品名称、组件 | API Key 在 Bugzilla “用户偏好 → API Keys” 中生成 | +| **禅道 (zentao)** | 系统地址、账号、密码、产品 ID | 系统地址 **不含** `/api.php`; 产品 ID 在产品页 URL 中可见 | + +#### 高级配置 (JSON) + +- **Bugzilla**: + ```json + { + "assignee_field": "email", // 指派人取用户的 email (默认) 或 name + "reopen_status": "CONFIRMED", // 回归不通过时重新打开的状态 + "default_version": "unspecified" // 未选择发现版本时使用的版本 + } + ``` +- **禅道**: + ```json + { + "project_id": 5, // 禅道项目/执行 ID, 用于拉取版本 (Build) 列表 + "bug_type": "others" // 缺陷类型, 默认 others + } + ``` + +#### 操作 + +- 填完后点击 **测试连接**, 会以当前表单内容调用真实接口试探, 错误信息会原样展示 (含编号列表) +- 点击 **保存** 持久化, 密钥字段 **只写不读**: 已保存的 API Key / 密码 显示为 `******`, 不修改则保持原值 + +### 4.7 提单模板 + +- 配置自动/手动提单时, 默认带入的 **标题模板**、**描述模板**、**附件模板** +- 支持变量 (`{{language}}` / `{{module}}` / `{{bug_type}}` 等) +- 项目代号对应的 `templates/spec2/<代号小写>` 目录存在时, 会优先使用该目录下的自定义模板 + +--- + +## 5. 任务管理 + +### 5.1 列表 + +左侧菜单 **任务管理**, 表格字段: + +| 字段 | 说明 | +|---|---| +| ID / 名称 | 任务编号与中文名 | +| 模块 / 区域语言 | 本任务涉及的模块与语言 | +| 状态 | 未执行 / 执行中 / 成功 / 失败 (失败悬浮可见原因) | +| 缺陷数 | AI 识别产生的缺陷总数 | +| 回归 | 是否为回归子任务 | +| 回归任务数 | 本任务产生的回归子任务个数 | +| 创建人 / 创建时间 / 更新时间 | 元信息 | + +搜索栏支持: **时间范围 (默认 3 个月)、ID、名称、模块、区域语言、状态、是否回归、创建人** + +### 5.2 创建任务 + +点击右上角 **添加**, 弹出任务表单, 核心字段分组如下: + +#### 5.2.1 基础信息 + +- **任务名称** (必填) +- **区域语言** (多选, 必填) +- **识别缺陷类型** (多选) +- **是否开启差异识别 (discern)**: 开启后 AI 只对比变化部分, 速度更快 +- **是否开启 OCR** (ocr_detect) +- **计划时间 (plan_time)**: 仅记录 + +#### 5.2.2 测试数据 + +两种来源二选一: +- **选取数据** (`data_ds`): 按模块 + 过滤条件选择; +- **按版本生成** (`GeneratePictureByVersion`): 填写 **SVN 地址、SVN 版本号**, 还原端按版本拉取并生成 + +#### 5.2.3 项目资源 / 译文资源 + +- 嵌入组件: **项目资源** 和 **译文资源**, 用于指定本次还原使用的工程版本和译文版本 +- 具体字段随还原端插件约定而不同 + +#### 5.2.4 自动提单 + +- **create_bug = 1** 时任务完成后自动把 AI 识别出的缺陷提到配置好的缺陷系统 +- 关联字段: **发现版本、修复版本、发布计划、严重度 (severity)、优先级 (priority)、提单缺陷类型 (bill_bug_types)** + +### 5.3 操作按钮 (行内) + +| 按钮 | 显示条件 | 作用 | +|---|---|---| +| 查看 | 任意状态 | 以只读模式打开任务表单, 展示详细字段 | +| 编辑 | 状态=未执行 | 修改任务配置 | +| 追加 | 状态=执行中 | 为运行中的任务追加语言 / 数据 | +| 开始 ▶ | 状态=未执行 | 调用 **Webhook** 启动还原 | +| 结束 ■ | 状态=执行中 | 发送 stop 指令结束 | +| 重试 | 执行中/失败/成功 | 对未生成图片的数据再次触发还原; 弹窗二次确认 | +| 执行进度 | 任意 | 弹窗展示每台设备的进度、已完成/总数 | +| 审核 | 任意 | 跳转到 **结果审核** 页 | +| 缺陷 | 任意 | 跳转到 **缺陷单** 页 | + +> **开始失败怎么办?** 多半是 Webhook 返回了非 2xx 或者浏览器被 CORS 拦截, +> 可在浏览器 DevTools → Network 面板看 `jenkins/...` 请求的响应内容 + +### 5.4 执行进度 + +弹窗展示: +- 每台设备 (还原端) 的在线状态、当前任务、已完成数 / 总数、剩余时间估算 +- 若还原端周期性上报 (通过 `POST /api/job/device`), 此处会实时刷新 + +--- + +## 6. 结果审核 + +从任务行的 **审核** 按钮进入, URL 为 `/image-results?job_id=xxx` + +### 6.1 功能 + +- 列出本任务所有截图 + AI 识别到的缺陷框 +- 左右切图, 支持 **放大/缩小/平移**, 缺陷框按类型以不同颜色高亮 +- 单张图片可: + - **确认缺陷**: 保留并进入待提单队列; + - **忽略**: 标记为误报, 不进入提单; + - **编辑框**: 修正 AI 画错的位置、改类型; + - **手动新增框**: 补 AI 没识别到的问题 + +### 6.2 快捷键 + +| 键 | 作用 | +|---|---| +| `← / →` | 上一张 / 下一张 | +| `Enter` | 确认当前框 | +| `Delete` | 删除当前框 | +| `Esc` | 退出编辑 | + +### 6.3 批量操作 + +顶部支持按 **缺陷类型 / 置信度 / 状态** 筛选, 然后批量确认 / 忽略 + +--- + +## 7. 缺陷单管理 + +从任务行的 **缺陷** 按钮或任务列表外部菜单进入, URL 为 `/bugs?job_id=xxx` + +### 7.1 列表字段 + +- **缺陷 ID** (平台内编号)、**外部编号** (Bugzilla/禅道中的 ID, 可点击直达) +- **语言**、**模块**、**缺陷类型**、**严重度**、**状态** +- **提单状态**: 未提 / 已提 / 提单失败 (鼠标悬浮可见错误信息) +- **回归结果**: 待回归 / 通过 / 不通过 + +### 7.2 操作 + +| 操作 | 说明 | +|---|---| +| **单条提单** | 把当前缺陷同步到外部缺陷系统 | +| **批量提单** | 勾选多条 → 批量提单; 按模块或语言合并策略由模板决定 | +| **自动提单** | 任务配置勾选 `create_bug=1` 时任务结束后由后台自动触发 | +| **回归验证** | 对已修复的缺陷重新跑一遍 AI, 通过则关闭 Bugzilla/禅道单, 不通过则重新打开 | +| **查看截图** | 点开缺陷查看原图 + 画框 | + +### 7.3 自动回归 + +- 在任务管理里对某任务 **创建回归子任务** (`regression=1`), 平台会: + 1. 以 `regression=1` 触发 Webhook, 还原端按父任务的数据重新生图; + 2. 新生成的图再跑一遍 AI; + 3. 比对结果: 如果原缺陷在新图中消失 → 标记 **通过**, 关闭外部单; 否则 **不通过**, 重新打开外部单 + +--- + +## 8. 数据管理 + +左侧菜单 **数据管理**, 用于维护项目的 **测试数据集** + +### 8.1 列表 + +- 可按 **模块、版本、创建人、关键字** 搜索 +- 字段: ID、名称、所属模块、版本、备注、创建人、创建/更新时间 + +### 8.2 操作 + +- **新增 / 导入**: 手工录入或 Excel 导入 (具体导入模板见页面提示) +- **批量编辑**: 勾选后点 “编辑” 按钮, 可统一改模块 / 版本等 +- **批量删除**: 勾选后点 “删除”, 二次确认 +- **预览 JSON**: 行内按钮打开 JSON 弹窗 (引擎可直接读取的格式) +- **图片画框**: 对 UI 类数据可直接在图上标注 + +--- + +## 9. 典型使用流程 + +### 9.1 从零接入一个项目 + +```mermaid +sequenceDiagram + participant SA as 超管 + participant PM as 项目管理员 + participant QA as 测试人员 + participant R as 还原端 (UE/Unity 插件) + + SA->>SA: 系统管理 → 项目管理 → 创建项目 (填 code 与 cvtest_project) + SA->>PM: 分配项目管理员角色 + PM->>PM: 项目设置 → 缺陷类型 / 区域语言 / 模块 + PM->>PM: 项目设置 → 图片还原 (语言根目录 + 路径) + PM->>PM: 项目设置 → 还原执行 (配 Webhook) + PM->>PM: 项目设置 → 缺陷系统 (选 none/bugzilla/zentao 并测试连接) + PM->>PM: 项目设置 → 提单 (配模板) + QA->>QA: 数据管理 → 导入测试数据 + QA->>QA: 任务管理 → 添加任务 → 开始 + R->>R: 被 Webhook 唤起,按任务拉取数据、还原、上传截图 + QA->>QA: 结果审核 → 确认缺陷 + QA->>QA: 缺陷单 → 批量提单 + PM->>PM: 修复后创建回归任务 (regression=1) +``` + +### 9.2 一次常规版本回归 + +1. **准备**: 开发合入新译文/新资源, 交付新版本号 +2. **跑任务**: 到 **任务管理 → 添加** 创建新任务, 选择新版本和需要校验的语言 + 模块; 或直接对上一轮任务点 **重试** +3. **审核**: 任务完成后点 **审核**, 批量确认/忽略 +4. **提单**: 点 **缺陷**, 批量提单到 Bugzilla / 禅道 +5. **跟进修复**: 开发在外部系统修复 Bug, 关闭或改状态为 FIXED +6. **回归**: 对父任务点 **创建回归任务**, 让平台重新还原 + 识别 + 自动开关外部单 + +--- + +## 10. 常见问题 (FAQ) + +### Q1: 登录后左侧菜单只有 “系统管理”, 看不到 “任务管理” 等? +A: 你当前尚未加入任何项目, 请超管在 **项目管理 → 测试经理** 填上你, 或在 **用户管理** 中为你分配项目角色, 登出重登后菜单会刷新 + +### Q2: 点“开始”任务按钮, 弹出 “启动失败:Network Error / CORS”? +A: Webhook 由浏览器直接请求 Jenkins/CI, 必须允许平台域名跨域 +- 让 CI 服务返回 `Access-Control-Allow-Origin: <平台域名>` 响应头; +- 或在 CI 前搭一层 Nginx 代理添加跨域头 + +### Q3: 缺陷系统“测试连接”失败? +A: 错误信息会原样显示, 常见原因: +- 地址填错 (禅道地址 **不要带** `/api.php`); +- API Key / 密码错误 (Bugzilla 请到用户偏好重新生成); +- 产品名称 / 产品 ID 不存在; +- 内网部署的 Bugzilla/禅道没向平台服务器开白名单 + +### Q4: 任务成功了, 但是 “缺陷数=0”? +A: +- 检查 **区域语言** 是否勾对 (截图上的语言和平台配的要一致); +- 检查 **识别缺陷类型** 是否勾了至少一项; +- 检查 **图片还原路径** 是否正确, 否则 AI 可能没拿到图; +- 查看任务 **执行进度**, 确认设备确实上传过图片 + +### Q5: 自动提单 (`create_bug=1`) 没有触发外部系统? +A: +- 任务表单里把 **create_bug** 勾上; +- 项目的 **缺陷系统** 不能是 `平台内记录(none)`; +- 查看 **缺陷单** 页, 若 “提单状态=提单失败”, 鼠标悬浮即可看到错误原因 + +### Q6: 回归任务跑了, 但是外部单据状态没变? +A: +- Bugzilla 需要在 **高级配置** 里把 `reopen_status` 配成你的工作流里允许回退的状态; +- 禅道需确保 **账号** 对该 Bug 有编辑权限; +- 平台只在 **回归结果** 产生变化时才会调用外部 API, 可到 **缺陷单** 页手动点 “重新同步” 触发 + +### Q7: 想把某项目的提单格式改一改? +A: 复制一份 `server/templates/spec2/default/`, 重命名为 `server/templates/spec2/<项目代号小写>/`, 修改其中的 `.md.jinja` 模板文件, 重启后端即可生效 + +--- + +## 11. 关联接口(供排错) + +| 场景 | 接口 | 文档 | +|---|---|---| +| 登录 / 注册 / 用户 | `/api/user/*` | [api/user.md](api/user.md) | +| 项目 / 项目配置 | `/api/project/*` | [api/project.md](api/project.md) | +| 任务 / 启停 / 进度 | `/api/job/*` | [api/job.md](api/job.md) | +| 截图上传 / AI 识别 | `/api/image/*` | [api/image.md](api/image.md) | +| 缺陷 / 提单 / 回归 | `/api/bug/*` | [api/bug.md](api/bug.md) | +| 测试数据 | `/api/data/*` | [api/data.md](api/data.md) | +| 枚举 / 健康检查 | `/api/system/*` | [api/system.md](api/system.md) | + +> 还原端 (UE/Unity 插件) 的接入细节请阅读 [integration/restorer.md](integration/restorer.md) + +--- + +## 12. 变更建议 / 反馈 + +- 使用过程中遇到 Bug 或建议, 请在仓库提 Issue, 并附带: + - 平台版本 (可在页脚或 `/api/system/health` 看到) + - 浏览器与版本 + - 复现步骤 + 截图 / 控制台报错 +- 或者可直接联系项目维护者 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/.gitignore b/timi_hok_game_translator/LQA_WMP/lqa_service/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..39ea92495f82264157782089803478dd9d0fb8ea --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/.gitignore @@ -0,0 +1,21 @@ +# 日志 +/*.log +/log/ + +# 测试样例 (真实游戏截图与文案涉及版权, 不入库) +# 运行 python tests/gen_samples.py 生成可用的合成样例 +/tests/test/ +/tests/screenShot.png +/tests/v3_result.json +/tests/object/* +/tests/lqa_mark_img.png +/tests/lqa_rect_img.png + +# 虚拟环境与隐藏目录 +/.*/ +.idea +.vscode + +# Python 产物 +*.py[cod] +__pycache__/ diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/Dockerfile b/timi_hok_game_translator/LQA_WMP/lqa_service/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fa3bb99626b3073b3f3894c08340d9de7cb19698 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/Dockerfile @@ -0,0 +1,48 @@ +FROM python:3.12-slim + +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + DEBUG_MODE=False \ + TZ=Asia/Shanghai + +# opencv 运行所需的系统库 +RUN apt-get update && apt-get install -y --no-install-recommends \ + libgl1 \ + libglib2.0-0 \ + tzdata \ + && ln -sf /usr/share/zoneinfo/$TZ /etc/localtime \ + && echo $TZ > /etc/timezone \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /data/lqa + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt \ + && pip install --no-cache-dir gunicorn gevent + +# 默认 OCR 引擎 rapidocr: 离线可用、体积小 (约 15MB), 开箱即用 +ARG OCR_ENGINE=rapidocr +RUN set -eux; \ + case "$OCR_ENGINE" in \ + rapidocr) pip install --no-cache-dir rapidocr-onnxruntime ;; \ + paddleocr) pip install --no-cache-dir paddlepaddle paddleocr ;; \ + easyocr) pip install --no-cache-dir easyocr ;; \ + none) echo "不安装本地 OCR, 需在运行时指向外部 OCR 服务" ;; \ + *) echo "未知 OCR_ENGINE=$OCR_ENGINE" >&2; exit 1 ;; \ + esac + +COPY . . + +# 预热: 构建期完成模型加载/下载, 避免首个请求超时 +# 运行期默认 provider 跟随构建期引擎 (OCR_ENGINE=none 时即 OCR_PROVIDER=none) +ENV OCR_PROVIDER=${OCR_ENGINE} +RUN if [ "$OCR_ENGINE" != "none" ]; then \ + python -c "from common.ocr_provider import get_provider; print(get_provider().test_connection())" || true; \ + fi + +EXPOSE 8086 + +HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8086/health',timeout=5).status==200 else 1)" || exit 1 + +CMD ["gunicorn", "-c", "config/gunicorn_config.py", "portal:app", "--preload"] diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/README.md b/timi_hok_game_translator/LQA_WMP/lqa_service/README.md new file mode 100644 index 0000000000000000000000000000000000000000..294f8a8869b0a16d4d2717942d9682763eeaa2bc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/README.md @@ -0,0 +1,350 @@ +# LQA AI 识别服务 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +LQA 平台的 AI 识别后端, 基于 Flask, 平台通过 `AI_BASE_URL` 调用本服务完成本地化异常检测 + +## 功能 + +1. **LQA 本地化文本异常检测** `POST /image/lqa_check/` + - 支持多语种 + - 支持多类型检测: 文本超文本框、文本超图像框、漏 key、漏译、错译及其他自定义异常类型 + +2. **图像前景提取** `POST /image/image_extraction/` + - 只支持含 alpha 通道的 `.png` 格式图像 + +--- + +## 快速开始 + +```bash +cd lqa_service + +python -m venv .venv +.venv\Scripts\activate # Linux/macOS: source .venv/bin/activate + +pip install -r requirements.txt +pip install rapidocr-onnxruntime # 默认 OCR 引擎, 离线可用 + +python portal.py # 监听 0.0.0.0:8086 +``` + +自检 OCR 是否就绪: + +```bash +python tests/check_ocr.py # 检测当前配置 +python tests/check_ocr.py --list # 列出全部可选引擎 +``` + +跑完整冒烟测试: + +```bash +python tests/gen_samples.py # 首次需先生成测试样例 +python tests/smoke_test.py 127.0.0.1:8086 lqa +``` + +--- + +## OCR 引擎选择 + +OCR 是**可选**能力, 未配置时服务仍可正常启动并完成大部分检测, 只会自动跳过, 必须依赖 OCR 的检测项 (见下方「OCR 不可用时的降级行为」) + +依赖 OCR 的检测需要同时拿到 **文本内容 + 精确边界框**, 因此只支持能同时提供两者的 OCR, 通过环境变量 `OCR_PROVIDER` 切换, 默认 `rapidocr` + +| `OCR_PROVIDER` | 类型 | 离线 | 安装 | 说明 | +|---|---|---|---|---| +| `rapidocr` | 开源 | ✅ | `pip install rapidocr-onnxruntime` | **推荐**, PaddleOCR 模型的 ONNX 推理版, 约 15MB,CPU 即可, 中英文效果好 | +| `paddleocr` | 开源 | ✅ | `pip install paddleocr paddlepaddle` | 精度最高, 中日韩支持好; 依赖较重 (约 2GB) | +| `paddleocr_http` | 开源 | ✅ | 无 | 调用独立部署的 PaddleOCR hubserving/PaddleX 服务, 适合 GPU 集中推理 | +| `easyocr` | 开源 | ✅ | `pip install easyocr` | 支持 80+ 语种, 泰文/越南文等小语种可选它 | +| `tesseract` | 开源 | ✅ | `pip install pytesseract` + 安装 tesseract | 老牌引擎; **对游戏 UI 的复杂背景、艺术字识别率明显偏低**, 仅建议简单场景 | +| `tencentcloud` | 商业 | ❌ | `pip install tencentcloud-sdk-python-ocr` | 腾讯云通用印刷体识别 | +| `baidu` | 商业 | ❌ | 无 | 百度智能云通用文字识别 (含位置) | +| `azure` | 商业 | ❌ | 无 | Azure AI Vision Read API | +| `cvtest` | 自建 | ❌ | 无 | 兼容内网自建 OCR 服务协议 | +| `none` | — | ✅ | 无 | **显式关闭 OCR**, 不产生任何识别调用 | + +> 游戏本地化场景文本密集、字体特殊, 建议优先 `rapidocr` 或 `paddleocr`, 商业 API 按量计费, 批量识别需评估成本与 QPS 限制 + +### OCR 不可用时的降级行为 + +以下任一情况都视为「OCR 不可用」, 服务 **不会报错**, 而是自动降级: + +- `OCR_PROVIDER=none` 或留空 (显式关闭) +- `OCR_PROVIDER` 名称写错 +- 选定的引擎未安装 (如未 `pip install rapidocr-onnxruntime`) +- 云服务密钥缺失、外部 OCR 服务连不通 + +降级后各检测类型的可用性: + +| 检测类型 | 需要 OCR | 降级后 | +|---|---|---| +| 1 漏译 (`##` 等标记) | ❌ | ✅ 正常 | +| 2-0 文本超文本框 | ✅ | ⛔ 跳过 | +| 2-1 文本框与图像框重叠 | ❌ | ✅ 正常 | +| 3 漏 key | ❌ | ✅ 正常 | +| 4 文本框重叠 | ❌ | ✅ 正常 (纯几何) | +| 5 错译 | ✅ | ⛔ 跳过 | +| 6 non_problem | ❌ | ✅ 正常 | +| 7 非标准框 | ❌ | ✅ 正常 | + +降级时响应体额外返回三个字段, 便于调用方识别: + +```json +{ + "success": true, + "result": { + "ocr_degraded": true, + "ocr_message": "未配置 OCR (OCR_PROVIDER=none), 依赖 OCR 的检测项将跳过", + "skipped_check_type": ["2-0", "5"] + } +} +``` + +`GET /health` 始终返回 200 (服务本身健康), OCR 状态在 `ocr` 字段中体现: + +```json +{"status": "ok", "ocr": {"available": false, "message": "...", "degraded": true}} +``` + +探测结果在进程内缓存 (成功 1 小时, 失败 60 秒后重试), 不会给每个请求带来额外开销, 可用 `python tests/check_ocr.py` 单独自检当前配置 + +### 配置示例 + +**完全不使用 OCR** + +```bash +export OCR_PROVIDER=none +``` + +**离线 (推荐, 无任何外部依赖)** + +```bash +export OCR_PROVIDER=rapidocr +``` + +**PaddleOCR 本地** + +```bash +export OCR_PROVIDER=paddleocr +export OCR_LANG=ch # ch / en / japan / korean / fr / german ... +export OCR_USE_GPU=false +``` + +**PaddleOCR 独立服务** + +```bash +export OCR_PROVIDER=paddleocr_http +export OCR_URL=http://:8868/predict/ocr_system +``` + +**腾讯云** + +```bash +export OCR_PROVIDER=tencentcloud +export OCR_SECRET_ID=xxx +export OCR_SECRET_KEY=xxx +export OCR_REGION=ap-guangzhou +``` + +**百度** + +```bash +export OCR_PROVIDER=baidu +export OCR_API_KEY=xxx +export OCR_SECRET_KEY=xxx +``` + +**自建 / 内网服务** + +```bash +export OCR_PROVIDER=cvtest +export OCR_HOST=http://:80 +export OCR_DEFAULT_PROJECT=lqa # 该服务用 project-method 头鉴权 +``` + +### 接入自定义 OCR + +实现 `common/ocr_provider/base.py` 中的 `OcrProvider`, 返回统一结构即可: + +```python +[{"area": [x1, y1, x2, y2], "result": "识别出的文本"}, ...] +``` + +然后在 `common/ocr_provider/__init__.py` 的 `PROVIDERS` 中注册 + +--- + +## 环境变量 + +| 变量 | 默认值 | 说明 | +|---|---|---| +| `DEBUG_MODE` | `True` | `True` 时 `python portal.py` 直接启动开发服务器 (容器内已置为 `False`, 由 gunicorn 托管) | +| `OCR_PROVIDER` | `rapidocr` | OCR 引擎, 见上表; `none`/留空表示不使用 OCR | +| `OCR_URL` | 空 | HTTP 型 OCR 服务地址 | +| `OCR_HOST` | 空 | 服务 endpoint (`cvtest` / `azure` 使用) | +| `OCR_LANG` | `ch` | 识别语种 (本地引擎) | +| `OCR_USE_GPU` | `false` | 本地引擎是否用 GPU | +| `OCR_TIMEOUT` | `60` | 远程 OCR 超时 (秒) | +| `OCR_API_KEY` / `OCR_SECRET_ID` / `OCR_SECRET_KEY` | 空 | 云厂商鉴权 | +| `OCR_REGION` | `ap-guangzhou` | 腾讯云地域 | +| `OCR_TESSERACT_CMD` | 空 | tesseract 可执行文件路径 | +| `OCR_DEFAULT_PROJECT` | 空 | `cvtest` 的默认项目标识 | +| `LOG_PATH` | `./log` | 日志目录 | +| `BIND` | `0.0.0.0:8086` | gunicorn 监听地址 | +| `GUNICORN_WORKERS` | `3` | gunicorn worker 数 | +| `NO_TRANS_MARK_LIST` | `["##","#N","WWWW","N/A"]` | 漏译标记 | +| `ERROR_TRANS_MARK_LIST` | `[" `gunicorn` + `gevent` 不支持 Windows, Windows 下请用 `python portal.py` + +### 容器部署 + +```bash +# 默认内置 rapidocr, 开箱即可离线运行 +docker build -t lqa-ai-service . + +# 内置 PaddleOCR (镜像约 +2GB, 精度更高) +docker build --build-arg OCR_ENGINE=paddleocr -t lqa-ai-service:paddle . + +# 不内置任何引擎 (镜像最小; 可指向外部 OCR, 或完全不用 OCR) +docker build --build-arg OCR_ENGINE=none -t lqa-ai-service:slim . + +docker run -d -p 8086:8086 -e OCR_PROVIDER=rapidocr lqa-ai-service +``` + +--- + +## 调用约定 + +### 请求头 + +``` +project-method: <项目名>_lqa +``` + +服务会剥离 `_lqa` 后缀得到项目名, 传递给 OCR provider, `cvtest` 等依赖该标识鉴权的服务必须传; 离线引擎可省略 + +LQA 平台侧对应 "项目设置" 中的 **AI识别项目名** + +### 请求体 + +```json +{ + "img_base64": "当前截图 base64", + "rect_locations": { "text": [...], "image": [...] }, + "language": null, + "supervised": null, + "check_type": ["1", "2-0"], + "history_img_base64": null, + "history_result": null, + "no_trans_marks": [], + "error_trans_marks": [], + "ocr_detect": 1 +} +``` + +| 字段 | 类型 | 说明 | +|---|---|---| +| `img_base64` | string | 必填, 待检测截图 | +| `rect_locations` | **object** | 必填, `{"text": [...], "image": [...]}`, 注意是对象不是数组 | +| `language` | int | 语种, 见下方枚举,`null` 为不限 | +| `check_type` | list[str] | 指定检测类型, `null` 为全部 | +| `ocr_detect` | int | `1` 文本框非精确位置需 OCR 定位 (默认); `0` 文本框已是最小外接矩 | +| `history_img_base64` | string | 差异识别时的上一次截图 | + +> 注意: `ocr_detect=0` 分支 **同样会调用 OCR** (用于错译检测), 只是不再用 OCR 结果做位置校准 + +### 响应体 + +```json +{ + "success": true, + "err_msg": null, + "result": { + "overframe": false, + "mark_img": "标注后图片 base64", + "rect_img": "文本框图片 base64", + "check_detail": {} + } +} +``` + +### 枚举 + +**检测类型 (`check_type`)** + +| 值 | 说明 | +|---|---| +| `1` | 漏译 | +| `2` | 超框 (`2-0` 文本超文本框, `2-1` 文本超图像框) | +| `3` | 漏 key | +| `4` | 文本框重叠 | +| `5` | 错译 | +| `6` | non_problem 自定义 | +| `7` | 非标准框 | + +**语种 (`language`)** + +| 值 | 语种 | +|---|---| +| `0` | 简体中文 | +| `1` | 繁体中文 (台湾) | +| `2` | 英文 | +| `3` | 日文 | +| `4` | 泰文 | +| `5` | 越南文 | + +--- + +## 测试样例 + +真实游戏截图与 UI 文案涉及版权, **未随仓库发布** (`tests/test/` 已在 `.gitignore` 中排除), 仓库提供生成器, 用 OpenCV 合成结构等价的样例: + +```bash +python tests/gen_samples.py # 生成到 tests/test/ +python tests/gen_samples.py --force # 覆盖已有样例 +``` + +生成的场景: + +| case | 场景 | 预期 | +|---|---|---| +| 0 | 正常界面 | 无异常 | +| 1 | 标准框小于文本 | 可能触发超框 (取决于 OCR 实际识别区域与阈值) | +| 2 | 含 `##` / `N/A` 标记 | 检出漏译 (类型 1) | +| 3 | `textStr` 缺失 / 空串 | 不崩溃且无异常 | +| 4 | 标准框相交 | 可能触发重叠 | +| 5 | 密集文本 | 压力场景 | +| 6 | 非中文界面混入简体中文 | 检出漏 key (类型 3) | + +> 合成图使用 OpenCV 内置字体, 仅含拉丁字符, 与真实游戏的艺术字、复杂背景差异较大, 它用于验证 **服务链路与接口契约** 是否正常, 不能用来评估检测算法的实际准确率, 调优算法请使用自有的真实截图 + +### 关于标准数据中的空文本 + +`rect_locations.text[*].textStr` 允许为 `None` / 空串, 表示该文本框未提供文本内容, 此时依赖文本内容的检测项 (漏译、漏 key、错译、non_problem) 会跳过该文本框, +不依赖文本的检测项 (超框、重叠、非标准框) 仍正常进行 + +--- + +## 与 LQA 平台对接 + +```bash +# LQA-OSS/.env +AI_BASE_URL=http://<本服务地址>:8086 +``` + +平台会调用 `POST {AI_BASE_URL}/image/lqa_check/`, 并自动带上 `project-method: _lqa` 请求头 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/interface_ocr.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/interface_ocr.py new file mode 100644 index 0000000000000000000000000000000000000000..3138bfb5973bec3add0dc528968b845c51d7f5e2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/interface_ocr.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +""" +# @file: interface_ocr.py +# @desc: OCR 能力统一接口模块, 对接 common/ocr_provider 实现, 提供以下能力: +# - ocr_available: 检测当前 OCR 能力是否可用 (带缓存), 未配置 OCR 时返回 False 而非报错, +# 便于调用方据此降级处理 +# - ocr: 统一 OCR 识别入口, 具体识别逻辑由 OCR_PROVIDER 配置决定 (见 ocr_provider 模块), +# OCR 为可选能力, 未配置/调用失败时捕获异常并返回 None, 由调用方判空后 +# 跳过依赖 OCR 的检测项, 而非视为服务错误 +# - find_lcsubstr: 查找两个字符串的最长公共子串 (动态规划) +# - find_lcseque: 查找两个字符串的最长公共子序列 (动态规划+回溯), +# 可用于比对 OCR 识别文本与标准文本的相似度 +""" +import traceback +from common.log import logger +from common.ocr_provider import get_provider, is_available, OcrError + + +def find_lcsubstr(s1, s2): + """ 查找最长公共子串 + :param s1: str, 字符串 + :param s2: str, 字符串 + :return: 最长公共子串 + """ + m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] + mmax = 0 + p = 0 + for i in range(len(s1)): + for j in range(len(s2)): + if s1[i] == s2[j]: + m[i + 1][j + 1] = m[i][j] + 1 + if m[i + 1][j + 1] > mmax: + mmax = m[i + 1][j + 1] + p = i + 1 + return s1[p - mmax:p], mmax + + +def find_lcseque(s1, s2): + """查找最长公共子序列 + :param s1: str, 字符串 + :param s2: str, 字符串 + :return: 最长公共子序列 + """ + # 生成字符串长度加 1 的 0 矩阵, m 用来保存对应位置匹配的结果 + m = [[0 for x in range(len(s2) + 1)] for y in range(len(s1) + 1)] + # d 用来记录转移方向 + d = [[None for x in range(len(s2) + 1)] for y in range(len(s1) + 1)] + + for p1 in range(len(s1)): + for p2 in range(len(s2)): + if s1[p1] == s2[p2]: # 字符匹配成功, 则该位置的值为左上方的值加 1 + m[p1 + 1][p2 + 1] = m[p1][p2] + 1 + d[p1 + 1][p2 + 1] = 'ok' + elif m[p1 + 1][p2] > m[p1][p2 + 1]: # 左值大于上值, 则该位置的值为左值, 并标记回溯时的方向 + m[p1 + 1][p2 + 1] = m[p1 + 1][p2] + d[p1 + 1][p2 + 1] = 'left' + else: # 上值大于左值, 则该位置的值为上值, 并标记方向 up + m[p1 + 1][p2 + 1] = m[p1][p2 + 1] + d[p1 + 1][p2 + 1] = 'up' + (p1, p2) = (len(s1), len(s2)) + s = [] + while m[p1][p2]: # 不为 None 时 + c = d[p1][p2] + if c == 'ok': # 匹配成功, 插入该字符, 并向左上角找下一个 + s.append(s1[p1 - 1]) + p1 -= 1 + p2 -= 1 + if c == 'left': # 根据标记, 向左找下一个 + p2 -= 1 + if c == 'up': # 根据标记, 向上找下一个 + p1 -= 1 + s.reverse() + return ''.join(s), len(s) + + +def ocr_available(force=False): + """OCR 能力是否可用 (带缓存, 未配置 OCR 时返回 False 而非报错) + + :param force: True 时忽略缓存重新探测 + :return: (bool, str) 是否可用、描述信息 + """ + return is_available(force=force) + + +def ocr(img_base64, location=None, project_id=19998, project=None): + """OCR 识别接口 (具体实现由 OCR_PROVIDER 决定, 见 common/ocr_provider) + + OCR 为可选能力: 未配置或不可用时返回 None, 调用方需判空并跳过 + 依赖 OCR 的检测项, 而非视作错误 + + :param img_base64: str, base64 格式的图像数据 + :param location: list, 保留参数, 当前实现统一识别整图后再按标准框过滤 + :param project_id: int, 保留参数, cvtest provider 通过配置项传入 + :param project: str, 调用方项目标识 (部分服务用于鉴权/路由) + :return: 识别结果 [{"area": [x1, y1, x2, y2], "result": '{text}'}, ..., {}] + 失败或未配置时返回 None (调用方需判空) + """ + try: + return get_provider().recognize(img_base64, project=project) + except OcrError as ex: + # 配置缺失/鉴权失败/服务不可用等可预期错误, 打印明确原因便于排障 + logger.error('OCR 调用失败: %s', ex) + return None + except Exception as ex: # pylint: disable=broad-except + logger.error(ex) + logger.error(traceback.format_exc()) + return None diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/log.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/log.py new file mode 100644 index 0000000000000000000000000000000000000000..237a6099c09c6210da9186a617ac250d8ba8a1a8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/log.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +""" +# @file: log.py +# @desc: 日志配置初始化模块, 提供以下能力: +# - get_logger: 创建并配置名为 'handle' 的 logger, 日志级别为 INFO; +# 日志目录通过环境变量 LOG_PATH 指定 (默认 ./log), 不存在时自动创建; +# 日志输出到文件 log_lqa.log, 格式包含时间、级别、文件名、函数名、行号及消息内容 +# - logger: 模块加载时创建的全局 logger 实例, 供其他模块直接导入使用 +""" +import os +import logging + + +def get_logger(): + _logger = logging.getLogger('handle') + log_path = os.environ.get('LOG_PATH', './log') + if not os.path.exists(log_path): + os.makedirs(log_path) + _logger.setLevel(logging.INFO) + fh = logging.FileHandler('{}/log_lqa.log'.format(log_path)) + fh.setFormatter( + logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s %(funcName)s %(lineno)s - %(message)s")) + _logger.addHandler(fh) + return _logger + + +logger = get_logger() diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/__init__.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d3f64651d1b654302d456f770973dde7245e8d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/__init__.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/__init__.py +# @desc: OCR 适配层统一入口模块, 职责包括: +# - PROVIDERS: 注册表, 维护 OCR_PROVIDER 名称 -> (模块路径, 类名) 的映射, +# 支持 paddleocr/paddleocr_http/rapidocr/easyocr/tesseract/ +# tencentcloud/baidu/azure/cvtest/none 共 10 种实现 +# - resolve_name: 归一化 provider 名称, 空值及关闭别名 (''/none/null/off/ +# disabled/false) 统一映射为 'none' +# - get_provider: 按配置懒加载并缓存 provider 实例, 避免重复初始化本地模型; +# 未配置或显式关闭时返回 NullOcr 空实现, 不抛异常 +# - is_available: 探测当前 OCR 能力是否可用, 结果带缓存 (成功缓存 1 小时, +# 失败缓存 60 秒后允许重试), 可安全在每次请求中调用 +# - reset_cache: 清空 provider 实例与可用性探测缓存 (用于测试) +# +# OCR 在本服务中是可选能力, 通过环境变量 OCR_PROVIDER 选择具体实现, +# 默认 rapidocr (开源离线, 无需额外部署), 当设置为 none 或指定引擎未安装/ +# 不可用时, 服务仍可正常启动并完成检测, 仅会跳过依赖 OCR 的检测项 +# (如错译检测、文本超框检测), 其余检测照常进行 +# +# 典型用法: +# from common.ocr_provider import get_provider, is_available +# available, msg = is_available() +# if available: +# data = get_provider().recognize(img_base64, project='demo') +""" +import logging +import time + +from .base import OcrProvider, OcrError, NullOcr, quad_to_box + +logger = logging.getLogger('handle') + +#: provider 名称 -> (模块路径, 类名) +PROVIDERS = { + 'paddleocr': ('.paddle', 'PaddleOcrLocal'), + 'paddleocr_http': ('.paddle', 'PaddleOcrHttp'), + 'rapidocr': ('.local_engines', 'RapidOcr'), + 'easyocr': ('.local_engines', 'EasyOcr'), + 'tesseract': ('.local_engines', 'TesseractOcr'), + 'tencentcloud': ('.cloud', 'TencentCloudOcr'), + 'baidu': ('.cloud', 'BaiduOcr'), + 'azure': ('.cloud', 'AzureOcr'), + 'cvtest': ('.cvtest', 'CvtestOcr'), + #: 显式关闭 OCR + 'none': ('.base', 'NullOcr'), +} + +#: OCR_PROVIDER 取这些值时等同于 none +_DISABLED_ALIASES = ('', 'none', 'null', 'off', 'disabled', 'false') + +_instance = None +_instance_key = None + +#: 可用性探测缓存: (是否可用, 描述, 过期时间戳) +_probe_cache = None +#: 探测失败后的重试间隔 (秒); 成功结果在进程内长期有效 +_PROBE_RETRY_INTERVAL = 60 +_PROBE_OK_TTL = 3600 + + +def _build(name, config): + if name not in PROVIDERS: + raise OcrError( + ' 未知的 OCR_PROVIDER=%s, 可选: %s' % (name, ', '.join(sorted(PROVIDERS))) + ) + import importlib + + module_path, class_name = PROVIDERS[name] + module = importlib.import_module(module_path, package=__name__) + return getattr(module, class_name)(config) + + +def resolve_name(name=None): + """归一化 provider 名称: 空值/关闭别名统一映射为 none""" + if name is None: + from config import baseconfig + + name = baseconfig.OCR_PROVIDER + name = (name or '').strip().lower() + if name in _DISABLED_ALIASES: + return 'none' + return name + + +def get_provider(name=None, config=None, cache=True): + """获取 OCR provider 实例 (默认按配置缓存, 避免重复加载本地模型) + + 未配置或配置为关闭时返回 :class:`NullOcr`, 不会抛异常 + """ + global _instance, _instance_key # pylint: disable=global-statement + + from config import baseconfig + + name = resolve_name(name) + if config is None: + config = baseconfig.ocr_provider_config() + if not cache: + return _build(name, config) + + key = (name, tuple(sorted((k, str(v)) for k, v in config.items()))) + if _instance is None or _instance_key != key: + _instance = _build(name, config) + _instance_key = key + logger.info('OCR provider 已初始化: %s', name) + return _instance + + +def is_available(force=False): + """OCR 能力是否可用 (结果带缓存, 可安全用于每次请求) + + :param force: True 时忽略缓存重新探测 + :return: (bool 是否可用, str 描述信息) + """ + global _probe_cache # pylint: disable=global-statement + + now = time.time() + if not force and _probe_cache is not None and now < _probe_cache[2]: + return _probe_cache[0], _probe_cache[1] + + name = resolve_name() + if name == 'none': + msg = '未配置 OCR (OCR_PROVIDER=none), 依赖 OCR 的检测项将跳过' + _probe_cache = (False, msg, now + _PROBE_OK_TTL) + return False, msg + + try: + provider = get_provider() + if not getattr(provider, 'capable', True): + msg = 'OCR 已关闭: %s' % name + _probe_cache = (False, msg, now + _PROBE_OK_TTL) + return False, msg + detail = provider.test_connection() + msg = '%s: %s' % (name, detail) + _probe_cache = (True, msg, now + _PROBE_OK_TTL) + logger.info('OCR 可用 - %s', msg) + return True, msg + except OcrError as ex: + msg = 'OCR 不可用 (%s): %s' % (name, ex) + except Exception as ex: # pylint: disable=broad-except + msg = 'OCR 探测异常 (%s): %s' % (name, ex) + _probe_cache = (False, msg, now + _PROBE_RETRY_INTERVAL) + logger.warning('%s; 将跳过依赖 OCR 的检测项', msg) + return False, msg + + +def reset_cache(): + """清空 provider 与探测缓存 (测试用)""" + global _instance, _instance_key, _probe_cache # pylint: disable=global-statement + _instance = None + _instance_key = None + _probe_cache = None diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/base.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a270320e87a0044dae98cdfb1c9791cba74cd063 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/base.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/base.py +# @desc: OCR 适配层抽象接口模块, 定义所有 OCR provider 必须遵循的统一规范, 包括: +# - OcrError: OCR 调用失败的统一异常类型, 各 provider 在识别失败/配置缺失时抛出 +# - base64_to_ndarray: base64 图像数据解码为 OpenCV BGR ndarray, 供本地推理类 +# provider (EasyOCR/RapidOCR/Tesseract/PaddleOCR本地) 使用 +# - quad_to_box: 将任意四点多边形坐标 (如 PaddleOCR/EasyOCR 返回的文本框顶点) +# 转换为轴对齐的矩形包围盒 [x1, y1, x2, y2] +# - OcrProvider: provider 抽象基类, 约定子类属性 (name 标识、remote 是否依赖远程 +# 服务、capable 是否具备真实识别能力) 及抽象方法 recognize; +# 并提供默认的 test_connection 自检方法, 通过识别一张内置测试图 +# 验证 provider 是否正常工作 +# - NullOcr: 空实现 provider(name='none'), 用于显式关闭 OCR 能力; 选用后不会 +# 产生任何识别调用, 依赖 OCR 的检测项 (错译、文本超框) 自动跳过, +# 其余不依赖 OCR 的检测照常进行 +# +# LQA 的超框/漏译检测依赖 OCR 返回「文本内容 + 精确边界框」, 因此只接受能同时 +# 给出两者的 OCR 服务, 各 provider 的 recognize 方法需统一返回以下格式 (与历史 +# 接口保持一致): +# [{"area": [x1, y1, x2, y2], "result": "识别出的文本"}, ...] +""" +from abc import ABC, abstractmethod +import base64 +import logging + +import numpy as np +import cv2 + +logger = logging.getLogger('handle') + + +class OcrError(Exception): + """OCR 调用失败""" + + +def base64_to_ndarray(img_base64): + """base64 -> BGR ndarray""" + raw = base64.b64decode(img_base64) + img = cv2.imdecode(np.frombuffer(raw, np.uint8), cv2.IMREAD_COLOR) + if img is None: + raise OcrError('图像解码失败') + return img + + +def quad_to_box(points): + """任意多边形顶点 -> 轴对齐包围盒 [x1, y1, x2, y2] + + PaddleOCR / EasyOCR 等返回的是四点多边形, 需转为 LQA 需要的矩形 + """ + xs = [int(round(float(p[0]))) for p in points] + ys = [int(round(float(p[1]))) for p in points] + return [min(xs), min(ys), max(xs), max(ys)] + + +class OcrProvider(ABC): + """OCR 提供方抽象基类""" + + name = 'base' + #: 是否依赖外部网络服务 + remote = True + #: 是否提供真实 OCR 能力 (NullOcr 为 False) + capable = True + + def __init__(self, config=None): + self.config = config or {} + + @abstractmethod + def recognize(self, img_base64, project=None): + """识别整图文字 + + :param img_base64: str, base64 编码的图像 + :param project: str, 调用方项目标识 (部分服务用于鉴权/路由, 可忽略) + :return: list[dict], [{"area": [x1,y1,x2,y2], "result": "文本"}, ...] + :raises OcrError: 调用失败 + """ + + def test_connection(self): + """连通性自检, 返回描述信息字符串""" + img = np.full((48, 160, 3), 255, np.uint8) + cv2.putText(img, 'LQA123', (6, 34), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 2) + ok, buf = cv2.imencode('.png', img) + if not ok: + raise OcrError('测试图编码失败') + data = self.recognize(base64.b64encode(buf).decode('ascii')) + texts = [d.get('result', '') for d in (data or [])] + return '连接正常, 识别到 %d 个文本块: %s' % (len(texts), texts[:5]) + + +class NullOcr(OcrProvider): + """空实现: 显式声明「不使用 OCR」(OCR_PROVIDER=none) + + OCR 在本服务中是可选能力, 选用本 provider 时不会产生任何识别调用, + 依赖 OCR 的检测项 (错译、文本超框) 自动跳过, 其余检测照常进行 + """ + + name = 'none' + remote = False + capable = False + + def recognize(self, img_base64, project=None): + return [] + + def test_connection(self): + return '已显式关闭 OCR (OCR_PROVIDER=none), 依赖 OCR 的检测项将跳过' diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cloud.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cloud.py new file mode 100644 index 0000000000000000000000000000000000000000..54e13c1cd448a122f48fe42891ade219903cbbc1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cloud.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/cloud.py +# @desc: 云厂商 OCR 适配模块, 提供以下 provider 实现: +# - TencentCloudOcr (name='tencentcloud') +# 腾讯云通用印刷体识别 GeneralBasicOCR +# 依赖: pip install tencentcloud-sdk-python-ocr +# 相关配置: OCR_SECRET_ID / OCR_SECRET_KEY / OCR_REGION (默认 ap-guangzhou) +# - BaiduOcr (name='baidu') +# 百度智能云通用文字识别 (含位置信息) +# 相关配置: OCR_API_KEY / OCR_SECRET_KEY +# 内部通过 OAuth2 client_credentials 方式获取 access_token 并缓存 (类变量 _token) +# - AzureOcr (name='azure') +# Azure AI Vision Read API +# 相关配置: OCR_HOST (服务 endpoint) / OCR_API_KEY +# +# 这些服务均返回文本内容及对应边界框 (area: [x1,y1,x2,y2]), 满足 LQA 超框检测对 +# 文本精确定位的要求, 均为按量计费的远程调用 (remote=True), 批量识别时需注意 +# 云厂商侧的成本与 QPS 限制, 避免触发限流或产生高额费用 +""" +import json +import logging + +import requests + +from .base import OcrProvider, OcrError, quad_to_box + +logger = logging.getLogger('handle') + + +class TencentCloudOcr(OcrProvider): + """腾讯云通用印刷体识别 GeneralBasicOCR + + 需要 pip install tencentcloud-sdk-python-ocr + 配置: OCR_SECRET_ID / OCR_SECRET_KEY / OCR_REGION + """ + + name = 'tencentcloud' + remote = True + + def recognize(self, img_base64, project=None): + secret_id = self.config.get('secret_id') + secret_key = self.config.get('secret_key') + if not (secret_id and secret_key): + raise OcrError('未配置 OCR_SECRET_ID / OCR_SECRET_KEY') + try: + from tencentcloud.common import credential + from tencentcloud.ocr.v20181119 import ocr_client, models + except ImportError as err: + raise OcrError( + '未安装腾讯云 SDK, 请执行: pip install tencentcloud-sdk-python-ocr' + ) from err + + try: + cred = credential.Credential(secret_id, secret_key) + client = ocr_client.OcrClient(cred, self.config.get('region', 'ap-guangzhou')) + req = models.GeneralBasicOCRRequest() + req.from_json_string(json.dumps({'ImageBase64': img_base64})) + resp = client.GeneralBasicOCR(req) + except Exception as err: # pylint: disable=broad-except + raise OcrError('腾讯云 OCR 调用失败: %s' % err) from err + + results = [] + for item in resp.TextDetections or []: + text = item.DetectedText + poly = item.Polygon + if not text: + continue + if poly: + results.append({'area': quad_to_box([(p.X, p.Y) for p in poly]), 'result': text}) + elif item.ItemPolygon: + p = item.ItemPolygon + results.append({ + 'area': [p.X, p.Y, p.X + p.Width, p.Y + p.Height], + 'result': text, + }) + return results + + +class BaiduOcr(OcrProvider): + """百度智能云通用文字识别 (含位置信息) + + 配置: OCR_API_KEY / OCR_SECRET_KEY + """ + + name = 'baidu' + remote = True + + TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token' + OCR_API = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general' + + _token = None + + def _get_token(self): + if BaiduOcr._token: + return BaiduOcr._token + api_key = self.config.get('api_key') + secret_key = self.config.get('secret_key') + if not (api_key and secret_key): + raise OcrError('未配置 OCR_API_KEY / OCR_SECRET_KEY') + try: + resp = requests.post(self.TOKEN_URL, params={ + 'grant_type': 'client_credentials', + 'client_id': api_key, + 'client_secret': secret_key, + }, timeout=30) + BaiduOcr._token = resp.json()['access_token'] + except Exception as err: # pylint: disable=broad-except + raise OcrError('百度 OCR 获取 token 失败: %s' % err) from err + return BaiduOcr._token + + def recognize(self, img_base64, project=None): + token = self._get_token() + try: + resp = requests.post( + self.OCR_API, + params={'access_token': token}, + data={'image': img_base64, 'recognize_granularity': 'small'}, + headers={'Content-Type': 'application/x-www-form-urlencoded'}, + timeout=int(self.config.get('timeout', 60)), + ) + payload = resp.json() + except Exception as err: # pylint: disable=broad-except + raise OcrError('百度 OCR 调用失败: %s' % err) from err + + if 'error_code' in payload: + raise OcrError('百度 OCR 错误 %s: %s' % (payload['error_code'], payload.get('error_msg'))) + + results = [] + for item in payload.get('words_result') or []: + text = item.get('words') + loc = item.get('location') or {} + if not text or not loc: + continue + x, y = int(loc.get('left', 0)), int(loc.get('top', 0)) + w, h = int(loc.get('width', 0)), int(loc.get('height', 0)) + results.append({'area': [x, y, x + w, y + h], 'result': text}) + return results + + +class AzureOcr(OcrProvider): + """Azure AI Vision Read API + + 配置: OCR_HOST(endpoint) / OCR_API_KEY + """ + + name = 'azure' + remote = True + + def recognize(self, img_base64, project=None): + import base64 as _b64 + + endpoint = (self.config.get('host') or '').rstrip('/') + api_key = self.config.get('api_key') + if not (endpoint and api_key): + raise OcrError('未配置 OCR_HOST(endpoint) / OCR_API_KEY') + url = '%s/computervision/imageanalysis:analyze' % endpoint + try: + resp = requests.post( + url, + params={'features': 'read', 'api-version': '2024-02-01'}, + headers={ + 'Ocp-Apim-Subscription-Key': api_key, + 'Content-Type': 'application/octet-stream', + }, + data=_b64.b64decode(img_base64), + timeout=int(self.config.get('timeout', 60)), + ) + payload = resp.json() + except Exception as err: # pylint: disable=broad-except + raise OcrError('Azure OCR 调用失败: %s' % err) from err + + if resp.status_code != 200: + raise OcrError('Azure OCR 返回 HTTP %s: %s' % (resp.status_code, payload)) + + results = [] + blocks = (payload.get('readResult') or {}).get('blocks') or [] + for block in blocks: + for line in block.get('lines') or []: + text = line.get('text') + poly = line.get('boundingPolygon') or [] + if not text or not poly: + continue + results.append({ + 'area': quad_to_box([(p['x'], p['y']) for p in poly]), + 'result': text, + }) + return results diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cvtest.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cvtest.py new file mode 100644 index 0000000000000000000000000000000000000000..243bdf33f8289e90f8d0fa34c3c2fd919dec4220 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/cvtest.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/cvtest.py +# @desc: CVTest OCR 适配模块 (内网自建服务, 向后兼容历史接口), 提供 CvtestOcr provider 实现: +# - name='cvtest', remote=True, 通过 HTTP 调用内网自建的 OCR 识别服务 +# +# 通信协议: +# POST {OCR_URL} +# headers: {"project-method": "_ocr"} +# project 由调用方传入或取配置 OCR_DEFAULT_PROJECT; 缺失该请求头会被服务端 +# 判为 "No authorization" +# body: {"img_base64": "...", "location": null, "projectid": } +# resp: {"errCode": 0, "data": [{"area": [x1,y1,x2,y2], "result": "文本"}, ...]} +# +# 错误处理与重试: +# - errCode == 0 且 data 非空: 识别成功, 返回 data +# - errCode == 0 但 data 为空: 通常是鉴权失败 (project-method 缺失或项目未授权), +# 抛出 OcrError 并提示检查请求头及项目授权 +# - errCode == -2: 服务侧繁忙, 按 RETRY_INTERVAL(0.6s) 间隔重试, 最多 MAX_RETRY(10) 次 +# - 其他 errCode: 直接抛出 OcrError, 附带 errCode 与 errMsg +# - HTTP 非 200 / 响应非 JSON / 请求异常: 均包装为 OcrError 抛出 +# +# 相关配置: OCR_URL (服务地址)、OCR_TIMEOUT (请求超时, 默认 60s)、 +# OCR_PROJECT_ID (默认项目ID, 默认19998)、OCR_DEFAULT_PROJECT (默认项目标识) +""" +import time +import logging + +import requests + +from .base import OcrProvider, OcrError + +logger = logging.getLogger('handle') + +MAX_RETRY = 10 +RETRY_INTERVAL = 0.6 + + +class CvtestOcr(OcrProvider): + """内网 CVTest OCR 服务""" + + name = 'cvtest' + remote = True + + def recognize(self, img_base64, project=None): + url = self.config.get('url') + if not url: + raise OcrError('未配置 OCR_URL') + timeout = int(self.config.get('timeout', 60)) + project_id = int(self.config.get('project_id', 19998)) + + data = {'img_base64': img_base64, 'location': None, 'projectid': project_id} + headers = {} + # 该服务依赖 project-method 请求头鉴权, 缺失时返回 No authorization 且 data 为 null + project = project or self.config.get('default_project') + if project: + headers['project-method'] = '%s_ocr' % project + + last_err = None + for attempt in range(MAX_RETRY): + try: + resp = requests.post(url=url, json=data, headers=headers, timeout=timeout) + except requests.RequestException as err: + raise OcrError('OCR 服务请求失败: %s' % err) from err + if resp.status_code != 200: + raise OcrError('OCR 服务返回 HTTP %s' % resp.status_code) + try: + payload = resp.json() + except ValueError as err: + raise OcrError('OCR 服务返回非 JSON') from err + + err_code = payload.get('errCode') + if err_code == 0: + result = payload.get('data') + if result is None: + # errCode=0 但 data 为空, 通常是鉴权失败, 历史实现会静默返回 None + raise OcrError( + 'OCR 服务未返回数据: %s (请确认请求头 project-method 及项目授权)' + % (payload.get('err_msg') or payload.get('errMsg') or '未知原因') + ) + return result + if err_code == -2: # 服务侧繁忙, 可重试 + last_err = payload.get('errMsg') + logger.warning('OCR 重试 %s/%s: %s', attempt + 1, MAX_RETRY, last_err) + time.sleep(RETRY_INTERVAL) + continue + raise OcrError('OCR 服务错误 errCode=%s %s' % (err_code, payload.get('errMsg'))) + raise OcrError('OCR 服务重试 %s 次仍失败: %s' % (MAX_RETRY, last_err)) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/local_engines.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/local_engines.py new file mode 100644 index 0000000000000000000000000000000000000000..734d9d009464b80d922ca653ec8199970cc8c462 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/local_engines.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/local_engines.py +# @desc: 其他可离线部署的 OCR 引擎适配模块, 提供以下三个 provider 实现: +# - EasyOcr (name='easyocr') +# 开源 OCR 引擎, 支持 80+ 语种, 识别结果为四点框 +# 依赖: pip install easyocr +# 相关配置: OCR_LANG (逗号分隔的语言列表, 默认 ch_sim,en)、OCR_USE_GPU (是否启用 GPU) +# 引擎以类变量缓存 (_reader), 同进程内仅初始化一次 +# - RapidOcr (name='rapidocr', 默认 provider) +# PaddleOCR 模型的 ONNXRuntime 推理版, 无需安装 paddle 依赖, 体积小、启动快 +# 依赖: pip install rapidocr-onnxruntime +# 引擎以类变量缓存 (_engine), 同进程内仅初始化一次 +# - TesseractOcr (name='tesseract') +# 开源老牌 OCR 引擎 +# 依赖: pip install pytesseract, 并需在系统中安装 tesseract 可执行程序及对应语言包 +# 相关配置: OCR_TESSERACT_CMD (tesseract 可执行文件路径, 未加入 PATH 时需指定)、 +# OCR_LANG (识别语言, 默认 chi_sim+eng) +# 注意: 对游戏 UI 这类复杂背景、艺术字体的识别率明显低于 PaddleOCR, +# 仅建议在简单纯色背景场景下使用 +# +# 通过环境变量 OCR_PROVIDER 设置为对应 name 值 (easyocr/rapidocr/tesseract) 以启用相应实现 +""" +import logging + +from .base import OcrProvider, OcrError, quad_to_box, base64_to_ndarray + +logger = logging.getLogger('handle') + + +class EasyOcr(OcrProvider): + """EasyOCR (开源, 80+ 语种, 返回四点框) + + pip install easyocr + """ + + name = 'easyocr' + remote = False + + _reader = None + + def _get_reader(self): + if EasyOcr._reader is not None: + return EasyOcr._reader + try: + import easyocr + except ImportError as err: + raise OcrError('未安装 EasyOCR, 请执行: pip install easyocr') from err + langs = [x.strip() for x in str(self.config.get('lang', 'ch_sim,en')).split(',') if x.strip()] + use_gpu = str(self.config.get('use_gpu', 'false')).lower() == 'true' + EasyOcr._reader = easyocr.Reader(langs, gpu=use_gpu, verbose=False) + logger.info('EasyOCR 引擎已加载 langs=%s gpu=%s', langs, use_gpu) + return EasyOcr._reader + + def recognize(self, img_base64, project=None): + reader = self._get_reader() + img = base64_to_ndarray(img_base64) + try: + raw = reader.readtext(img) + except Exception as err: # pylint: disable=broad-except + raise OcrError('EasyOCR 识别失败: %s' % err) from err + results = [] + for item in raw or []: + try: + points, text = item[0], item[1] + except (IndexError, TypeError): + continue + if not text: + continue + results.append({'area': quad_to_box(points), 'result': text}) + return results + + +class RapidOcr(OcrProvider): + """RapidOCR (PaddleOCR 模型的 ONNXRuntime 推理版, 无需 paddle 依赖, 体积小) + + pip install rapidocr-onnxruntime + """ + + name = 'rapidocr' + remote = False + + _engine = None + + def _get_engine(self): + if RapidOcr._engine is not None: + return RapidOcr._engine + try: + from rapidocr_onnxruntime import RapidOCR + except ImportError as err: + raise OcrError('未安装 RapidOCR, 请执行: pip install rapidocr-onnxruntime') from err + RapidOcr._engine = RapidOCR() + logger.info('RapidOCR 引擎已加载') + return RapidOcr._engine + + def recognize(self, img_base64, project=None): + engine = self._get_engine() + img = base64_to_ndarray(img_base64) + try: + raw, _elapse = engine(img) + except Exception as err: # pylint: disable=broad-except + raise OcrError('RapidOCR 识别失败: %s' % err) from err + results = [] + for item in raw or []: + try: + points, text = item[0], item[1] + except (IndexError, TypeError): + continue + if not text: + continue + results.append({'area': quad_to_box(points), 'result': text}) + return results + + +class TesseractOcr(OcrProvider): + """Tesseract (开源老牌引擎) + + pip install pytesseract 并安装 tesseract 可执行程序与语言包 + 注意: 对游戏 UI 这类复杂背景、艺术字体的识别率明显低于 PaddleOCR, + 仅建议在简单纯色背景场景使用 + """ + + name = 'tesseract' + remote = False + + def recognize(self, img_base64, project=None): + try: + import pytesseract + from pytesseract import Output + except ImportError as err: + raise OcrError('未安装 pytesseract, 请执行: pip install pytesseract') from err + + cmd = self.config.get('tesseract_cmd') + if cmd: + pytesseract.pytesseract.tesseract_cmd = cmd + lang = self.config.get('lang', 'chi_sim+eng') + img = base64_to_ndarray(img_base64) + try: + data = pytesseract.image_to_data(img, lang=lang, output_type=Output.DICT) + except Exception as err: # pylint: disable=broad-except + raise OcrError('Tesseract 识别失败: %s' % err) from err + + results = [] + count = len(data.get('text', [])) + for i in range(count): + text = (data['text'][i] or '').strip() + if not text: + continue + try: + conf = float(data['conf'][i]) + except (ValueError, TypeError): + conf = -1 + if conf < 0: + continue + x, y = int(data['left'][i]), int(data['top'][i]) + w, h = int(data['width'][i]), int(data['height'][i]) + results.append({'area': [x, y, x + w, y + h], 'result': text}) + return results diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/paddle.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/paddle.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ed77afe03b8c0f2d1ddab8a0091da5ea12bc06 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/ocr_provider/paddle.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +""" +# @file: ocr_provider/paddle.py +# @desc: PaddleOCR 适配模块, 提供两个 OCR provider 实现: +# - PaddleOcrLocal (name='paddleocr') +# 本进程内直接加载 PaddleOCR 模型进行识别 (离线, 无需外部服务) +# 依赖: pip install paddleocr paddlepaddle +# 相关配置: OCR_LANG (识别语言,默认 ch)、OCR_USE_GPU (是否启用 GPU, 默认 false) +# 模型以类变量缓存 (_engine), 同进程内仅加载一次, 兼容新旧版本 PaddleOCR 的初始化参数差异 +# - PaddleOcrHttp (name='paddleocr_http') +# 调用 PaddleOCR 官方 hubserving / PaddleX 部署的 HTTP 服务进行远程识别 +# 相关配置: OCR_URL (服务地址, 必填)、OCR_TIMEOUT (请求超时时间, 默认 60s) +# 期望响应格式: {"results": [[{"text": "abc", "text_region": [[x,y],...]}, ...]]} +# +# PaddleOCR 对中日韩、拉丁语系支持较好, 可离线部署, 是一般场景下的推荐选择 +# 通过环境变量 OCR_PROVIDER 设置为 paddleocr 或 paddleocr_http 以启用对应实现 +""" +import base64 +import logging + +import requests + +from .base import OcrProvider, OcrError, quad_to_box, base64_to_ndarray + +logger = logging.getLogger('handle') + + +class PaddleOcrLocal(OcrProvider): + """进程内加载 PaddleOCR 模型 (离线, 无需外部服务)""" + + name = 'paddleocr' + remote = False + + _engine = None + + def _get_engine(self): + if PaddleOcrLocal._engine is not None: + return PaddleOcrLocal._engine + try: + from paddleocr import PaddleOCR + except ImportError as err: + raise OcrError( + '未安装 PaddleOCR, 请执行: pip install paddleocr paddlepaddle' + ) from err + lang = self.config.get('lang', 'ch') + use_gpu = str(self.config.get('use_gpu', 'false')).lower() == 'true' + kwargs = {'lang': lang, 'show_log': False, 'use_angle_cls': True} + try: + PaddleOcrLocal._engine = PaddleOCR(use_gpu=use_gpu, **kwargs) + except TypeError: + # 新版本 PaddleOCR 移除了 use_gpu / show_log 参数 + PaddleOcrLocal._engine = PaddleOCR(lang=lang) + logger.info('PaddleOCR 本地引擎已加载 lang=%s use_gpu=%s', lang, use_gpu) + return PaddleOcrLocal._engine + + def recognize(self, img_base64, project=None): + engine = self._get_engine() + img = base64_to_ndarray(img_base64) + try: + raw = engine.ocr(img) + except Exception as err: # pylint: disable=broad-except + raise OcrError('PaddleOCR 识别失败: %s' % err) from err + + results = [] + if not raw: + return results + # 兼容 [[...]] 与 [...] 两种返回层级 + lines = raw[0] if raw and isinstance(raw[0], list) else raw + for line in lines or []: + if not line: + continue + try: + points, (text, _score) = line[0], line[1] + except (ValueError, IndexError, TypeError): + continue + if not text: + continue + results.append({'area': quad_to_box(points), 'result': text}) + return results + + +class PaddleOcrHttp(OcrProvider): + """PaddleOCR hubserving / PaddleX HTTP 服务 + + 期望响应形如: + + {"results": [[{"text": "abc", "text_region": [[x,y],...]}, ...]]} + """ + + name = 'paddleocr_http' + remote = True + + def recognize(self, img_base64, project=None): + url = self.config.get('url') + if not url: + raise OcrError('未配置 OCR_URL (PaddleOCR HTTP 服务地址)') + timeout = int(self.config.get('timeout', 60)) + try: + resp = requests.post(url, json={'images': [img_base64]}, timeout=timeout) + except requests.RequestException as err: + raise OcrError('PaddleOCR 服务请求失败: %s' % err) from err + if resp.status_code != 200: + raise OcrError('PaddleOCR 服务返回 HTTP %s' % resp.status_code) + try: + payload = resp.json() + except ValueError as err: + raise OcrError('PaddleOCR 服务返回非 JSON') from err + + groups = payload.get('results') or [] + if groups and isinstance(groups[0], list): + items = groups[0] + else: + items = groups + results = [] + for item in items or []: + text = item.get('text') + region = item.get('text_region') or item.get('text_box_position') + if not text or not region: + continue + results.append({'area': quad_to_box(region), 'result': text}) + return results diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/tools.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a05311b43c0d5cc8fc32173d3322b965fd0aa0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/tools.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" +# @file: tools.py +# @desc: 图像数据处理通用工具模块, 提供以下接口: +# - base64_to_mat: 将 base64 格式的图像数据解码为 OpenCV ndarray 格式, +# 支持灰度图 (gray)、带 alpha 通道 (alpha) 两种解码模式 +# - mat_to_base64: 将 OpenCV ndarray 格式的图像数据编码 (JPEG) 并转换为 base64 字符串 +# - img_draw_rect: 在图像上绘制标记框, 支持标准矩形框 (4维坐标 x1,y1,x2,y2) +# 和非标准四边形框 (8维坐标, 4个点) 两种绘制方式, 可自定义颜色和线宽样式 +""" +import base64 +import cv2 +import numpy as np + + +def base64_to_mat(base64_img, gray=False, alpha=False): + """ 数据base64转ndarray + :param base64_img: str, base64 格式的图像数据 + :param gray: bool, 标记是否是灰度图 + :param alpha: bool, 标记数据是否带有 alpha 通道 + :return: ndarray 格式的图像数据 + """ + if base64_img is None: + return None + img_b64decode = base64.b64decode(base64_img) + # np.fromstring 的二进制模式在 numpy>=1.22 已废弃、2.x 中移除, 改用 frombuffer + img_array = np.frombuffer(img_b64decode, np.uint8) + if gray: + trans_type = cv2.IMREAD_GRAYSCALE + elif alpha: + trans_type = -1 + else: + trans_type = cv2.COLOR_BGR2RGB + img = cv2.imdecode(img_array, trans_type) + return img + + +def mat_to_base64(img): + """ 数据 ndarray 转 base64 + :param img: ndarray, ndarray 格式的图像数据 + :return: base64 格式的图像数据 + """ + if img is None: + return None + # ndarray.tostring() 在 numpy 2.x 中已移除, 改用等价的 tobytes() + image = cv2.imencode('.jpg', img)[1].tobytes() + base64_img = base64.b64encode(image).decode() + return base64_img + + +def img_draw_rect(img, rect, draw_style=((0, 0, 255), 1)): + """标记图像 + :param img: ndarray, 图像 + :param rect: x1, y1, x2, y2, 标记位置 (标准矩形框), 非标框 4 个点 8 维向量 + :param draw_style: tuple, 绘制样式, 取值 DrawStyle, 包括颜色, 线条 size + :return: img, 标记后的图像 + """ + if rect: + if len(rect) == 4: + x1, y1, x2, y2 = rect + cv2.rectangle(img, (x1, y1), (x2, y2), draw_style[0], draw_style[1]) + + if len(rect) == 8: + rect_array = np.array(rect) + rect_reshape = rect_array.reshape(-1, 2, 1) + cv2.polylines(img, [rect_reshape], isClosed=True, color=draw_style[0], thickness=draw_style[1]) # 红色多边形 + + return img diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/common/util_network.py b/timi_hok_game_translator/LQA_WMP/lqa_service/common/util_network.py new file mode 100644 index 0000000000000000000000000000000000000000..fedbcb5c77a43b6a824454880f051aa887d87d8f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/common/util_network.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +""" +# @file: util_network.py +# @desc: 网络请求响应处理工具模块, 提供统一的 HTTP 响应格式封装: +# - response: 构造统一结构的 JSON 响应体 (success/err_msg/result), +# 并支持通过 **args 追加自定义扩展字段, 最终以 Flask jsonify 返回 +""" +from flask import jsonify + + +def response(success=True, err_msg="", result=None, **args): + """ 网络请求response消息处理 + :param success: bool, http 相应码 + :param err_msg: str, 错误消息 + :param result: 结果数据 + :param args: dict, 其他补充内容 + :return: response 数据 + """ + ret = { + "success": success, + "err_msg": err_msg, + "result": result + } + ret.update(args) + return jsonify(ret) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/config/baseconfig.py b/timi_hok_game_translator/LQA_WMP/lqa_service/config/baseconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..6d19b4bd8e10cd9391d463306fc59aa8df00e973 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/config/baseconfig.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +""" +# @file: baseconfig.py +# @desc: LQA 服务基础配置模块, 包含调试模式开关 (DEBUG_MODE)、 +# OCR 服务接入配置 (支持 rapidocr/paddleocr/tesseract/tencentcloud/baidu/azure 等多种 provider)、 +# 以及 LQA 检测所需的未译/错译标记和中文简繁体字符集等常量配置 +""" +import os +import json + +DEBUG_MODE = os.getenv("DEBUG_MODE", 'True').upper() == "TRUE" + +# OCR 服务配置 (OCR 为可选能力) +# OCR_PROVIDER 可选: rapidocr (默认, 开源离线) / paddleocr / paddleocr_http / easyocr / +# tesseract / tencentcloud / baidu / azure / cvtest (自建) / +# none (显式关闭) +# 留空或设为 none 时不进行任何 OCR 调用, 服务仍可启动并完成不依赖 OCR 的检测 +OCR_PROVIDER = os.getenv("OCR_PROVIDER", "rapidocr") +OCR_HOST = os.getenv("OCR_HOST", "") +OCR_URL = os.getenv("OCR_URL", f"{OCR_HOST}/image/general/ocr/uiflow/" if OCR_HOST else "") +OCR_LANG = os.getenv("OCR_LANG", "ch") +OCR_TIMEOUT = int(os.getenv("OCR_TIMEOUT", "60")) +OCR_USE_GPU = os.getenv("OCR_USE_GPU", "false") +# 云厂商 / 自建服务鉴权 +OCR_API_KEY = os.getenv("OCR_API_KEY", "") +OCR_SECRET_ID = os.getenv("OCR_SECRET_ID", "") +OCR_SECRET_KEY = os.getenv("OCR_SECRET_KEY", "") +OCR_REGION = os.getenv("OCR_REGION", "ap-guangzhou") +# tesseract 可执行文件路径 (未加入 PATH 时需指定) +OCR_TESSERACT_CMD = os.getenv("OCR_TESSERACT_CMD", "") +# cvtest 专用 +OCR_PROJECT_ID = int(os.getenv("OCR_PROJECT_ID", "19998")) +OCR_DEFAULT_PROJECT = os.getenv("OCR_DEFAULT_PROJECT", "") + + +def ocr_provider_config(): + """汇总 OCR provider 所需配置""" + return { + "url": OCR_URL, + "host": OCR_HOST, + "lang": OCR_LANG, + "timeout": OCR_TIMEOUT, + "use_gpu": OCR_USE_GPU, + "api_key": OCR_API_KEY, + "secret_id": OCR_SECRET_ID, + "secret_key": OCR_SECRET_KEY, + "region": OCR_REGION, + "tesseract_cmd": OCR_TESSERACT_CMD, + "project_id": OCR_PROJECT_ID, + "default_project": OCR_DEFAULT_PROJECT, + } + +# LQA 识别相关配置 +NO_TRANS_MARK = os.getenv("NO_TRANS_MARK", "##") +NO_TRANS_MARK_LIST = json.loads(os.getenv("NO_TRANS_MARK_LIST", '["##", "#N", "WWWW", "N/A"]')) +ERROR_TRANS_MARK_LIST = json.loads(os.getenv("ERROR_TRANS_MARK_LIST", '[" alpha_t: + h_list.append(j) + w_list.append(i) + if len(w_list) > 0 and len(h_list) > 0: + x1 = np.min(w_list) + y1 = np.min(h_list) + x2 = np.max(w_list) + y2 = np.max(h_list) + else: + x1 = 0 + y1 = 0 + x2 = w + y2 = h + # 处理边界坐标 + if x1 + 1 == 1: + x1 = 0 + if y1 + 1 == 1: + y1 = 0 + if x2 + 1 >= w: + x2 = w + if y2 + 1 >= h: + y2 = h + rect = (x1, y1, x2, y2) + return rect + + @staticmethod + def single_image_extraction(img_base64, zero_type=0, position_type=0, alpha_t=50): + """ 单图像前景提取 + :param img_base64: str, base64 格式的图像数据 + :param zero_type: int, 标记坐标原点方式, 支持左下角和左上角原点 + :param position_type: int, 标记位置表示方式, 支持像素和小数比例表示 + :param alpha_t: int, alpha通道数据阈值 + :return: {图像名: 图像位置,...} + """ + rect_res = None + if img_base64 is None: + return rect_res + img = base64_to_mat(img_base64, alpha=True) + if img.shape[2] != 4: + return rect_res + # 提取 alpha 通道数据 + _, _, _, a = cv2.split(img) + h, w = a.shape + max_a = max([max(item) for item in a.tolist()]) + a_t = alpha_t + if max_a < a_t: + a_t = int(max_a / 3 * 2) + rect = ImageProcessing.get_extraction_rect(a, a_t) + # 根据坐标原点和位置标记类型参数进行坐标转化 + rect_res = ImageProcessing.coordinate_trans(rect, h, w, zero_type=zero_type, position_type=position_type) + if not rect_res: + rect_res = rect + return rect_res + + @staticmethod + def image_extraction(img_base64, zero_type=0, position_type=0, alpha_t=50): + """ 提取图像前景的实际区域, 支持多张图片批量处理 (四通道图像) + :param img_base64: dict, 待处理的图像数据 {图像名: base64 图像数据, ...} + :param zero_type: int, 标记坐标原点方式, 默认 0, 取值 ZeroType + :param position_type: int, 标记位置表示方式, 默认0, 取值 PositionType + :param alpha_t: int, alpha 通道数据阈值 + :return: 提取后的结果 {图像名: 图像位置, ...} + """ + res = { + "image_extraction": {} + } + if img_base64 is None: + return res + for item in img_base64: + rect_res = ImageProcessing.single_image_extraction(img_base64[item], + zero_type=zero_type, + position_type=position_type, + alpha_t=alpha_t) + if rect_res: + res['image_extraction'].update({item: rect_res}) + return res diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa.py b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa.py new file mode 100644 index 0000000000000000000000000000000000000000..db220563a1f5ec56680e9188e86c0d95b3300818 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +""" +# @file: lqa.py +# @desc: LQA 本地化文本异常检测核心逻辑模块, 提供 ImageLqa 类实现以下能力: +# - lqa_check: 基于 OCR 识别的完整检测流程, 支持漏译、超框 (文本超文本框/图像框)、漏key、 +# 文本框重叠、错译、non_problem 自定义、非标准框等多种异常类型检测, +# 并支持人工半监督数据 (supervised) 和历史检测结果 (history_result) 辅助判断 +# - lqa_check_no_ocr: 不依赖 OCR 的检测流程, 直接使用标注文本框的实际位置进行检测, +# 适用于文本框已是文本最小外接矩的场景 +# - degrade_check_type: 当 OCR 服务不可用时, 自动将检测类型降级为仅保留不依赖 OCR 的类型 +# (漏译/文本框与图像框重叠/漏key/文本框重叠/non_problem/非标准框), +# 跳过依赖 OCR 的类型 (文本超文本框/错译) +""" +from common.tools import base64_to_mat, mat_to_base64 +from common.interface_ocr import ocr_available +from common.log import logger +from task.lqa_processing import LqaProcessing +from task.lqa_supervised import Supervised +from task.lqa_abnormal import ErrorTrans, LqaAbnormal +from task.lqa_config import LqaCheckType + +#: 必须依赖 OCR 的检测类型; OCR 不可用时自动剔除 +#: 2-0 文本超文本框需要 OCR 给出文本实际边界; 5 错译需要 OCR 文本内容 +OCR_DEPENDENT_CHECK_TYPES = ('2-0', str(LqaCheckType.ERROR_TRANS.value)) + +#: 不依赖 OCR 的全部检测类型 (纯几何 / 基于标注 textStr) +#: 1 漏译、2-1 文本框与图像框重叠、3 漏key、4 文本框重叠、6 non_problem、7 非标准框 +OCR_FREE_CHECK_TYPES = ('1', '2-1', '3', '4', '6', '7') + + +def degrade_check_type(check_type): + """剔除依赖 OCR 的检测类型 + + :param check_type: list[str] 或 None (None 表示全部类型) + :return: (list[str] 降级后的类型, list[str] 被跳过的类型) + """ + if not check_type: + return list(OCR_FREE_CHECK_TYPES), list(OCR_DEPENDENT_CHECK_TYPES) + kept, skipped = [], [] + for item in check_type: + if str(item) in OCR_DEPENDENT_CHECK_TYPES: + skipped.append(str(item)) + else: + kept.append(item) + return kept, skipped + + +class ImageLqa: + """ + 本地化异常处理类 + """ + + @staticmethod + def lqa_check(img_base64, rect_locations, language, supervised, check_type, history_img_base64, history_result, + project, no_trans_marks, error_trans_marks): + """v0.1: 文本本身超过文本框 + v0.2: 文本框内没有文本; 文本框内文本包含 ##NoTrans; 文本框和图像框重叠 + v0.3: 新增简体中文漏译, 过滤长条状文本框和图像框 + v0.4: 新增图像框缩小 + v1.1: 新增文本框重叠检测 + v1.2: 优化超框和重叠文本框处理 (细分归属判断) + v1.3: 新增人工半监督 + v1.4: 新增历史数据先验知识 + v1.5: 新增错误翻译检测 + v1.6: 新增 non_problem 检测 + v1.7: 新增 project, 记录调用项目 + :param project: str, 项目 + :param img_base64: str, 被测图像 base64 + :param rect_locations: dict, 待检测标准的 text 和 image 矩形框位置信息 + :param language: int, 游戏包语言代码序号 + :param supervised: dict, 监督数据 (人工审核) + :param check_type: list[str], 指定检查类型, 与 LqaCheckType-LqaCheckSubType 一致, 如 ['1','2-0','2-1','3'] + :param history_img_base64: str, 历史图像 base64 (用作对比参考) + :param history_result: dict, 历史图像检测结果 (用作对比参考) + :param project: 项目 + :param no_trans_marks: str, 漏译匹配标记 + :param error_trans_marks: str, 错译匹配标记 + :return: res, dict, 检测结果 + """ + # OCR 为可选能力: 不可用时降级走无 OCR 流程, 跳过依赖 OCR 的检测项, + # 其余检测 (漏译/漏key/框重叠/non_problem/非标准框) 照常返回 + available, ocr_msg = ocr_available() + if not available: + kept, skipped = degrade_check_type(check_type) + logger.warning('OCR 不可用, 降级为无 OCR 检测; 跳过类型 %s (%s)', skipped, ocr_msg) + res = ImageLqa.lqa_check_no_ocr(img_base64, rect_locations, language, supervised, kept, + history_img_base64, history_result, project, + no_trans_marks, error_trans_marks) + res["ocr_degraded"] = True + res["ocr_message"] = ocr_msg + res["skipped_check_type"] = skipped + return res + + res = { + "overframe": False, + "mark_img": None, + "rect_img": None, + "check_detail": None + } + img = base64_to_mat(img_base64) + history_img = base64_to_mat(history_img_base64) + lqa_img = img.copy() + rect_img = img.copy() + text_location_list = rect_locations.get("text", []) + image_location_list = rect_locations.get("image", []) + # 提取所有标准文本框信息, 包括位置信息, 过滤脏数据的索引 + gt_text_info = LqaProcessing.detect_gt_text_locations(img, text_location_list, preprocessing=True) + # 提取所有标准图像框信息 + gt_image_info = LqaProcessing.detect_gt_image_locations(img, image_location_list) + # 绘制提供的标准框 + rect_img = LqaProcessing.draw_gt_locations(rect_img, gt_text_info, gt_image_info) + # 预处理数据 (根据历史数据) + text_location_list, image_location_list, lqa_img, check_detail = Supervised.preprocessing(img, + lqa_img, + rect_locations, + history_img, + history_result) + # 预处理的异常 ———— 直接上报的, 只需要直接绘制结果和返回错误 + lqa_img, check_detail = Supervised.preprocessing_errs(lqa_img, rect_locations, gt_text_info, check_detail) + + if len(check_detail) > 0: + res['overframe'] = True + # 无数据直接返回 + if len(text_location_list) <= 0 and len(image_location_list) <= 0: + res["mark_img"] = mat_to_base64(lqa_img) + res["rect_img"] = mat_to_base64(rect_img) + res["check_detail"] = check_detail + return res + # 获取各类监督信息 + no_trans_list, over_frame_text_text_list, over_frame_text_image_list, no_key_list, overlap_list, \ + error_trans_list, non_problem_list, non_rectangle_list = Supervised.get_supervised_data(supervised) + + # 标准数据预处理: 分类, 过滤脏数据 + # 提取所有标准文本框信息, 包括位置信息, 过滤脏数据的索引 + gt_text_info = LqaProcessing.detect_gt_text_locations(img, text_location_list) + gt_text_locations = gt_text_info['gt_text_locations'] + # 提取所有标准图像框信息 + gt_image_info = LqaProcessing.detect_gt_image_locations(img, image_location_list) + # 提取所有 OCR 检测信息 + all_ocr_dict = LqaProcessing.detect_ocr_data(img, gt_text_info, project=project) + all_ocr_error_trans_dict = ErrorTrans.filter_error_trans_ocr_data(all_ocr_dict, error_trans_marks) + # 标准文本框划分 (判断是否重叠) + classify_text_location_res = LqaProcessing.classify_text_location_overlap(gt_text_info) + for text_index in range(len(gt_text_locations)): + if text_index in gt_text_info['dirty_text_ids']: # 脏标准框数据跳过 + continue + if text_index in gt_text_info['non_rectangle_ids']: # 非标准框数据 + non_rectangle = True + else: + non_rectangle = False + # 判断每一个文本框 + res, check_detail, rect_img, lqa_img = LqaAbnormal.judge_single_text( + check_type, language, text_index, img, gt_image_info, gt_text_locations, classify_text_location_res, + all_ocr_dict, all_ocr_error_trans_dict, no_trans_list, over_frame_text_text_list, + over_frame_text_image_list, no_key_list, error_trans_list, non_problem_list, non_rectangle_list, + text_location_list, lqa_img, rect_img, res, check_detail, no_trans_marks, error_trans_marks, + non_rectangle=non_rectangle, project=project) + # 处理重叠文本框 + overlap_group = classify_text_location_res['overlap_group'] + overlap_group_id = classify_text_location_res['overlap_group_id'] + if len(overlap_group) > 0: + # 处理每一组重叠文本框 + for group_index in range(len(overlap_group)): + res, check_detail, rect_img, lqa_img = LqaAbnormal.judge_single_group_overlap_text( + check_type, group_index, overlap_group, overlap_group_id, + img, gt_text_locations, all_ocr_dict, + classify_text_location_res, text_location_list, + overlap_list, over_frame_text_text_list, error_trans_list, + lqa_img, rect_img, res, check_detail, error_trans_marks, project=project) + res["mark_img"] = mat_to_base64(lqa_img) + res["rect_img"] = mat_to_base64(rect_img) + res["check_detail"] = check_detail + return res + + @staticmethod + def lqa_check_no_ocr(img_base64, rect_locations, language, supervised, check_type, history_img_base64, history_result, + project, no_trans_marks, error_trans_marks): + """ + 无 ocr 识别, 直接返回文本框内文本的直接位置 + :param project: str, 项目 + :param img_base64: str, 被测图像 base64 + :param rect_locations: dict, 待检测标准的 text 和 image 矩形框位置信息 + :param language: int, 游戏包语言代码序号 + :param supervised: dict, 监督数据 (人工审核) + :param check_type: list[str], 指定检查类型, 与 LqaCheckType-LqaCheckSubType 一致, 如 ['1','2-0','2-1','3'] + :param history_img_base64: str, 历史图像 base64 (用作对比参考) + :param history_result: dict, 历史图像检测结果 (用作对比参考) + :param project: 项目 + :param no_trans_marks: str, 漏译匹配标记 + :param error_trans_marks: str, 错译匹配标记 + :return: res, dict, 检测结果 + """ + res = { + "overframe": False, + "mark_img": None, + "rect_img": None, + "check_detail": None + } + img = base64_to_mat(img_base64) + history_img = base64_to_mat(history_img_base64) + lqa_img = img.copy() + rect_img = img.copy() + text_location_list = rect_locations.get("text", []) + image_location_list = rect_locations.get("image", []) + # 提取所有标准文本框信息, 包括位置信息, 过滤脏数据的索引 + gt_text_info = LqaProcessing.detect_gt_text_locations(img, text_location_list, preprocessing=True) + # 提取所有标准图像框信息 + gt_image_info = LqaProcessing.detect_gt_image_locations(img, image_location_list) + # 绘制标准框 + rect_img = LqaProcessing.draw_gt_locations(rect_img, gt_text_info, gt_image_info) + # 预处理数据 (根据历史数据) + text_location_list, image_location_list, lqa_img, check_detail = Supervised.preprocessing(img, + lqa_img, + rect_locations, + history_img, + history_result) + # 预处理的异常 ———— 直接上报的, 只需要直接绘制结果和返回错误 + lqa_img, check_detail = Supervised.preprocessing_errs(lqa_img, rect_locations, gt_text_info, check_detail) + + if len(check_detail) > 0: + res['overframe'] = True + # 无数据直接返回 + if len(text_location_list) <= 0 and len(image_location_list) <= 0: + res["mark_img"] = mat_to_base64(lqa_img) + res["rect_img"] = mat_to_base64(rect_img) + res["check_detail"] = check_detail + return res + # 获取各类监督信息 + no_trans_list, over_frame_text_text_list, over_frame_text_image_list, no_key_list, overlap_list, \ + error_trans_list, non_problem_list, non_rectangle_list = Supervised.get_supervised_data(supervised) + + # 标准数据预处理: 分类, 过滤脏数据 + # 提取所有标准文本框信息, 包括位置信息, 过滤脏数据的索引 + gt_text_info = LqaProcessing.detect_gt_text_locations(img, text_location_list) + gt_text_locations = gt_text_info['gt_text_locations'] + # 提取所有标准图像框信息 + gt_image_info = LqaProcessing.detect_gt_image_locations(img, image_location_list) + + # 指定错译检查__提取所有OCR检测信息 (只检查一遍, 用于判断是否有错译) + check_type_id = LqaCheckType.ERROR_TRANS.value + if not check_type or str(check_type_id) in check_type: + all_ocr_dict = LqaProcessing.detect_ocr_data(img, gt_text_info, project=project) + all_ocr_error_trans_dict = ErrorTrans.filter_error_trans_ocr_data(all_ocr_dict, error_trans_marks) + else: + all_ocr_dict = {} + all_ocr_error_trans_dict = {} + # 所有文本框碰撞检测, 不重复 + dirty_text_ids = gt_text_info['dirty_text_ids'] + overlap_dict = {} + cnt = len(gt_text_locations) + for i in range(cnt): + if i in dirty_text_ids: # 脏数据过滤, 便于后续检测, 无需处理 + continue + overlap_dict = LqaProcessing.judge_overlap_with_text_i(overlap_dict, i, gt_text_locations, dirty_text_ids) + # 判断每一个文本框 + for text_index in range(cnt): + if text_index in dirty_text_ids: # 脏标准框数据跳过 + continue + if text_index in gt_text_info['non_rectangle_ids']: # 非标准框数据 + non_rectangle = True + else: + non_rectangle = False + res, check_detail, rect_img, lqa_img = LqaAbnormal.judge_single_text_no_ocr( + check_type, language, text_index, img, gt_image_info, gt_text_locations, overlap_dict, + all_ocr_dict, all_ocr_error_trans_dict, + no_trans_list, error_trans_list, over_frame_text_text_list, + over_frame_text_image_list, no_key_list, non_problem_list, non_rectangle_list, + text_location_list, lqa_img, rect_img, res, check_detail, no_trans_marks, error_trans_marks, + non_rectangle=non_rectangle, project=project) + + res["mark_img"] = mat_to_base64(lqa_img) + res["rect_img"] = mat_to_base64(rect_img) + res["check_detail"] = check_detail + return res + + +if __name__ == '__main__': + pass diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_abnormal.py b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_abnormal.py new file mode 100644 index 0000000000000000000000000000000000000000..32e4a566ddfde463a860e0f18aff92775fc2f886 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_abnormal.py @@ -0,0 +1,1029 @@ +# -*- coding: utf-8 -*- +""" +# @file: lqa_abnormal.py +# @desc: LQA 本地化异常检测核心判断逻辑模块, 提供以下三个类: +# - ErrorTrans: 错译检测类, 根据错译标记词 (error_trans_marks) 判断文本/OCR 结果是否命中错译, +# 并支持从全图 OCR 结果中过滤出所有错译候选项 +# - OverlapText: 重叠文本框处理类, 当多个标准文本框存在重叠 (合并为一个外接矩形) 时, +# 通过 OCR 识别该区域并按重叠面积归属各子文本框, 必要时对 OCR 结果做二值化 +# 细分割 (split_ocr), 再逐一判断子文本框是否存在错译/超框/重叠等异常 +# - LqaAbnormal: 异常检测主类, 汇总各类判断方法: +# * no_trans: 漏译检测 (命中漏译标记词) +# * no_key: 漏key检测 (简繁体字符集比对, 识别出简体中文残留) +# * custom_abnormal: 自定义 non_problem 标记检测 +# * error_trans: 错译检测 (全局/单文本框两种模式) +# * text_overframe/ocr_image_overlap: 文本超文本框、文本与图像框重叠的碰撞检测 +# * judge_single_text/judge_single_text_no_ocr: 对单个文本框执行全部类型检测 +# (分别对应依赖 OCR 识别定位 和 已知精确坐标两种模式) +# * judge_single_independent_text: 对无重叠的独立文本框做 OCR 位置校准后再检测 +# * judge_single_group_overlap_text: 对一组重叠文本框做 OCR 识别、归属判断及检测 +# * update_check_type_detail/update_check_res: 统一记录检测结果详情, +# 并在结果图上绘制对应的标注框 (需排除已被人工监督确认的数据) +""" +import cv2 +import json +import numpy as np +from config.baseconfig import NO_TRANS_MARK_LIST, SIMPLIFIED_CHINESE_SET, TRADITIONAL_CHINESE_SET, \ + ERROR_TRANS_MARK_LIST, NON_PROBLEM_MARK +from common.tools import img_draw_rect, mat_to_base64 +from common.interface_ocr import ocr +from task.lqa_config import LqaCheckType, LqaCheckSubType, Language, DrawStyle +from task.lqa_processing import LqaProcessing + + +class ErrorTrans: + """错译检测类""" + + @staticmethod + def error_trans_mark(text_str, error_trans_marks): + """判断文本是否包含错误翻译标记 + :param text_str: str, 文本字符串 + :param error_trans_marks: str, 错译标识 + :return: have_error_trans_mark, bool, 是否包含错译标记词条 + """ + have_error_trans_mark = False + if not text_str: # 标准数据未提供文本内容, 无从判断 + return have_error_trans_mark + if error_trans_marks not in ['', None]: # 项目自定义 + error_trans_marks_list = json.loads(error_trans_marks) + else: + error_trans_marks_list = ERROR_TRANS_MARK_LIST # 默认 + for mask in error_trans_marks_list: + if isinstance(mask, list): # 多标记组合 + cnt = 0 + for item in mask: + if item in text_str: + cnt += 1 + if cnt == len(mask): + have_error_trans_mark = True + break + else: + if mask in text_str: + have_error_trans_mark = True + break + return have_error_trans_mark + + @staticmethod + def filter_error_trans_ocr_data(all_ocr_dict, error_trans_marks): + """从检测图像所有 ocr 结果中, 过滤出包含错误翻译标记的数据 + :param all_ocr_dict: dict, 全图 ocr 识别结果 + :param error_trans_marks: str, 错译标识 + :return: all_ocr_error_trans_dict, dict, 所有包含错误翻译标记的 ocr 识别结果 + """ + all_ocr_error_trans_dict = {} + for ocr_result in all_ocr_dict: + if ErrorTrans.error_trans_mark(ocr_result, error_trans_marks): + all_ocr_error_trans_dict[ocr_result] = all_ocr_dict[ocr_result] + return all_ocr_error_trans_dict + + @staticmethod + def all_error_trans(text_location, ocr_data): + """全图文本框区域检测错译 + :param text_location: list, 文本位置信息 + :param ocr_data: dict, ocr识别结果 + :return: bool, 是否错译 + """ + for ocr_str in ocr_data: + for ocr_location in ocr_data[ocr_str]: + # 文本区域与错译 ocr_data 发生碰撞 + is_overlap, ratio, _ = LqaProcessing.overlap(text_location, ocr_location, x_t=0, y_t=0) + if is_overlap and ratio > 0.3: + return True + return False + + @staticmethod + def single_error_trans(ocr_data, error_trans_marks): + """局部文本框区域检测错译 + :param ocr_data: dict, ocr识别结果 + :param error_trans_marks: str, 错译标识 + :return: bool, 是否错译 + """ + if isinstance(ocr_data, list): + for item in ocr_data: + ocr_result = item['result'] + if ErrorTrans.error_trans_mark(ocr_result, error_trans_marks): + return True + elif isinstance(ocr_data, dict) and 'result' in ocr_data: + ocr_result = ocr_data['result'] + if ErrorTrans.error_trans_mark(ocr_result, error_trans_marks): + return True + return False + + +class OverlapText: + """重叠文本框处理类""" + + @staticmethod + def judge_overlap_ocr_belong(align_res, align_ocr_res, group_id, gt_text_locations): + """判断重叠文本框中各个 OCR 子项的归属 + :param align_res: list, ocr识别位置信息 + :param align_ocr_res: list, ocr 识别文本信息 + :param group_id: list, 多个重叠文本框聚合的 id 列表 + :param gt_text_locations: dict, 所有文本框信息 + :return: overlap_info, 重叠文本框归属信息 + """ + overlap_info = {} + for i in range(len(align_res)): + align_location = align_res[i] + ocr_res = align_ocr_res[i] if len(align_ocr_res) == len(align_res) else [] + # 过滤合并区域识别出的非文本框内容 + overlap_item_ratio = [] + overlap_item_sub_px = [] + overlap_item_id = [] + for item in group_id: + is_overlap, ratio, sub_px = LqaProcessing.overlap(gt_text_locations[item], align_location, x_t=0, y_t=0) + if is_overlap and ratio > 0.3: + overlap_item_id.append(item) + overlap_item_ratio.append(ratio) + overlap_item_sub_px.append(sub_px) + if len(overlap_item_id) > 0: + # 计算最大重叠率判断归属 + max_ratio_index = overlap_item_ratio.index(max(overlap_item_ratio)) + belong_id = overlap_item_id[max_ratio_index] + if belong_id not in overlap_info: + overlap_info[belong_id] = [] + overlap_info[belong_id].append({'ocr_res': ocr_res, + 'ocr_location': align_location, + 'gt_location': gt_text_locations[belong_id], + 'ratio': overlap_item_ratio[max_ratio_index], + 'sub_px': overlap_item_sub_px[max_ratio_index]}) + return overlap_info + + @staticmethod + def check_every_overlap_ocr(check_type, rect_img, lqa_img, overlap_info, text_location_list, gt_text_locations, + res, check_detail, supervised_info, error_trans_marks): + """判断重叠文本框中各个 OCR 子项的归属 + :param check_type: list, 检测类型 + :param rect_img: ndarray, 标记图 + :param lqa_img: ndarray, lqa识别结果图 + :param overlap_info: dict, 一组重叠文本框的信息 + :param text_location_list: list, 待测试文本框信息 (去掉脏数据等) + :param gt_text_locations: list, 标准文本框信息 + :param res: dict, 结果数据 + :param check_detail: dict, 已检测结果详情 + :param supervised_info: dict, 监督信息 + :param error_trans_marks: str, 错译标识 + :return: res, 检测结果数据 + check_detail, 检测结果详情 + rect_img, 标记图像 + lqa_img, 检测结果图像 + """ + # 一组重叠文本框各个对象检测 + for g_id in overlap_info: + text_location_dict = text_location_list[g_id] + text_str = text_location_dict.get("textStr") + # 错译 + check_type_id = LqaCheckType.ERROR_TRANS.value + if check_type is None or str(check_type_id) in check_type: + for overlap_item_i in overlap_info[g_id]: + is_abnormal = LqaAbnormal.error_trans(text_str, + overlap_item_i['gt_location'], + overlap_item_i['ocr_res'], + error_trans_marks, + check_type='single') + if is_abnormal: + detail_data = [text_str, list(gt_text_locations[g_id])] + supervised_error_trans = supervised_info['error_trans'] + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + supervised_error_trans, + lqa_img, + overlap_item_i['gt_location'], + DrawStyle.ERROR_TRANS.value) + # 碰撞检测, 文本超过文本框 + type_id = LqaCheckType.OVER_FRAME.value + sub_type_id = LqaCheckSubType.OVER_FRAME_TEXT_TEXT.value + check_type_id = str(type_id) + "-" + str(sub_type_id) + if check_type is None or check_type_id in check_type: + for overlap_item_i in overlap_info[g_id]: + rect_img = img_draw_rect(rect_img, overlap_item_i['ocr_location'], + draw_style=DrawStyle.OVERLAP.value) + is_abnormal = LqaAbnormal.text_overframe(overlap_item_i['ocr_location'], + overlap_item_i['gt_location'], + t=(5, 5, 5, 5)) + if is_abnormal: + detail_data = [text_str, list(gt_text_locations[g_id])] + draw_style = DrawStyle.GT_TEXT.value + supervised_over_frame_text_text = supervised_info['over_frame_text_text'] + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + type_id, + detail_data, + supervised_over_frame_text_text, + lqa_img, + overlap_item_i['gt_location'], + draw_style, + sub_type_id=sub_type_id) + return res, check_detail, rect_img, lqa_img + + @staticmethod + def sorted_detail_data(group_text_id, text_location_list, gt_text_locations): + """结果详情排序 + :param group_text_id: list, 一组重叠文本框对应的索引列表 + :param text_location_list: list, 待测试文本框信息 (去掉脏数据等) + :param gt_text_locations: list, 标准文本框信息 + :return: detail_data, 排序后的结果详情 + """ + detail_data = [] + for text_id in group_text_id: + text_location_dict = text_location_list[text_id] + text_str = text_location_dict.get("textStr") + detail_data_item = [text_str, list(gt_text_locations[text_id])] + detail_data.append(detail_data_item) + detail_data = sorted(detail_data) + return detail_data + + @staticmethod + def judge_split(overlap_item): + """判断文本框是否需要再次细分割 + :param overlap_item: dict, 子文本框 + :return: bool, 是否细分割 + """ + if overlap_item['ratio'] > 0.9 or (overlap_item['sub_px'][0] < 5 and overlap_item['sub_px'][1] < 4): + return False + return True + + @staticmethod + def get_split_tags(binary_img): + """ 提取二值图像的分割标记 + :param binary_img: ndarray, 二值图像 + :return: split_tags, list, 分割标记 + """ + split_tags = [] + h, w = binary_img.shape[:2] + for i in range(w): + split = True + for j in range(h): + if binary_img[j][i] > 0: + split = False + break + if split: + split_tags.append(1) + else: + split_tags.append(0) + return split_tags + + @staticmethod + def get_split_range(split_tags): + """ 根据分割标记提取分割范围 + :param split_tags, list, 分割标记 + :return: split_range, list, 分割范围 + """ + start = -1 + split_range = [] + for i in range(len(split_tags)): + if split_tags[i] == 1 and start == -1: + start = i + elif (split_tags[i] == 0 or i == len(split_tags) - 1) and start != -1: + end = i + split_range.append((end - start, (start, end))) + start = -1 + return split_range + + @staticmethod + def get_split_ocr_locations(ocr_location, split_range, k): + """根据分割目标, 对分割结果排序, 计算分割结果 + :param ocr_location: list, 区域位置 + :param split_range: list, 可能的分割范围 + :param k: int, 分割的子区域数目 + :return: split_ocr_locations, list, 分割结果 + """ + # 根据间隔对预分割线进行排序 + sort_split_range = sorted(split_range, key=lambda x: x[0], reverse=True) + t_k = min(k - 1, len(sort_split_range)) + top_k = sort_split_range[:t_k] + sort_top_k = sorted(top_k, key=lambda x: x[1][0]) + split_ocr_locations = [] + for i in range(t_k): + if i == 0: + ocr_x = (ocr_location[0], sort_top_k[i][1][0] + ocr_location[0] - 1) + else: + ocr_x = (sort_top_k[i - 1][1][1] + ocr_location[0] + 1, sort_top_k[i][1][0] + ocr_location[0] - 1) + split_ocr_location = (ocr_x[0], ocr_location[1], ocr_x[1], ocr_location[3]) + split_ocr_locations.append(split_ocr_location) + tail_ocr_x = (sort_top_k[-1][1][1] + ocr_location[0] + 1, ocr_location[2]) + split_ocr_location = (tail_ocr_x[0], ocr_location[1], tail_ocr_x[1], ocr_location[3]) + split_ocr_locations.append(split_ocr_location) + return split_ocr_locations + + @staticmethod + def split_ocr(img, ocr_location, k): + """ ocr 识别结果细分割, 将 ocr_location 区域分为 k 个子区域 + :param img: ndarray, 图像 + :param ocr_location: list, x1,y1,x2,y2 格式 + :param k: int, 分割子串数目 + :return: split_ocr_locations, list, 分割结果 + """ + # 二值化, 计算预分割线 + rect_img = img.copy() + rect_img = rect_img[ocr_location[1]:ocr_location[3], ocr_location[0]:ocr_location[2]] + gray_img = cv2.cvtColor(rect_img, cv2.COLOR_BGR2GRAY) + binary_threshold = np.mean(gray_img) + _, th = cv2.threshold(gray_img, binary_threshold, 255, cv2.THRESH_BINARY) + if binary_threshold > 150: + th = ~th + # 提取可能分割标记 + split_tags = OverlapText.get_split_tags(th) + # 提取分割范围 + split_range = OverlapText.get_split_range(split_tags) + if len(split_range) <= 0: + return [] + # 根据间隔对预分割线进行排序, 提取分割结果 + split_ocr_locations = OverlapText.get_split_ocr_locations(ocr_location, split_range, k) + return split_ocr_locations + + @staticmethod + def recheck_every_overlap_ocr(check_type, img, rect_img, lqa_img, overlap_item, group_id, gt_text_locations, + res, check_detail, detail_data, supervised_info): + """细粒度判断重叠文本框中的 OCR 子项 + :param check_type: list, 检测类型 + :param img: ndarray, 原测试图 + :param rect_img: ndarray, 标记图 + :param lqa_img: ndarray, lqa 识别结果图 + :param overlap_item: dict, 一组重叠文本框的子文本框 + :param group_id: list, 待测试文本框信息 (去掉脏数据等) + :param gt_text_locations: list, 标准文本框信息 + :param res: dict, 结果数据 + :param check_detail: dict, 已检测结果详情 + :param detail_data: dict, 检测详情 + :param supervised_info: dict, 监督信息 + :return: res, 检测结果数据 + check_detail, 检测结果详情 + rect_img, 标记图像 + lqa_img, 检测结果图像 + """ + draw_style = DrawStyle.OVERLAP.value + # 重叠率足够, 无需细分判断 + if not OverlapText.judge_split(overlap_item): + draw_rect = overlap_item['ocr_location'] + rect_img = img_draw_rect(rect_img, draw_rect, draw_style) + + # 需要细分进行分割 + else: + split_ocr_rect = overlap_item['ocr_location'] + split_ocr_locations = OverlapText.split_ocr(img, split_ocr_rect, k=len(group_id)) + split_overlap_info = OverlapText.judge_overlap_ocr_belong(split_ocr_locations, + [], + group_id, + gt_text_locations) + for split_g_id in split_overlap_info: + for split_item_i in split_overlap_info[split_g_id]: + draw_rect = split_item_i['ocr_location'] + rect_img = img_draw_rect(rect_img, draw_rect, draw_style) + if not OverlapText.judge_split(split_item_i): + continue + else: + check_type_id = LqaCheckType.OVERLAP.value + supervised_overlap = supervised_info['overlap'] + if check_type is None or str(check_type_id) in check_type: + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + supervised_overlap, + lqa_img, + draw_rect, + draw_style) + return res, check_detail, rect_img, lqa_img + + +class LqaAbnormal: + """lqa 数据异常检测类""" + + @staticmethod + def update_check_type_detail(check_detail, type_id, data, sub_type_id=None): + """检测结果分类详情 + :param check_detail: dict, 结果分类详情 + :param type_id: int 问题类型 id + :param data: 记录的详细数据 + :param sub_type_id: int 问题子类型 id + :return: res, 更新后的结果数据 + check_detail, 更新后的检测结果详情 + img, 标记后的图像 + """ + if not check_detail: + check_detail = {} + + if type_id not in check_detail: + if sub_type_id is None: + check_detail[type_id] = [] + else: + check_detail[type_id] = {} + if sub_type_id is None: + if data not in check_detail[type_id]: + check_detail[type_id].append(data) + else: + if sub_type_id not in check_detail[type_id]: + check_detail[type_id][sub_type_id] = [] + if data not in check_detail[type_id][sub_type_id]: + check_detail[type_id][sub_type_id].append(data) + + return check_detail + + @staticmethod + def update_check_res(res, check_detail, type_id, detail_data, supervised_detail_data, + img, draw_rect, draw_style, sub_type_id=None): + """标记异常 + :param res: dict, 结果数据 + :param check_detail: dict, 已检测结果详情 + :param type_id: int, 异常检测类型 id + :param detail_data: list, 待记录数据 + :param supervised_detail_data: list, 监督数据列表 + :param img: ndarray, 图像 + :param draw_rect: x1, y1, x2, y2, 标记位置 + :param draw_style: tuple, 绘制样式, 取值 DrawStyle, 包括颜色, 线条 size + :param sub_type_id: int, 异常检测子类型 id + :return: res, 更新后的结果数据 + check_detail, 更新后的检测结果详情 + img, 标记后的图像 + """ + if detail_data not in supervised_detail_data: + res["overframe"] = True + check_detail = LqaAbnormal.update_check_type_detail(check_detail, type_id, detail_data, + sub_type_id=sub_type_id) + img = img_draw_rect(img, draw_rect, draw_style=draw_style) + return res, check_detail, img + + @staticmethod + def no_key(text_str, language): + """简体中文漏 key 检测 + :param text_str: str, 待检测文本 + :param language: int, 语言 int + :return: is_abnormal, bool, 是否异常 + """ + is_abnormal = False + traditional_chinese = False + if not text_str: # 标准数据未提供文本内容, 无从判断 + return is_abnormal + ocr_set = set(list(text_str)) + # 判断有繁体字 + traditional_intersection = ocr_set & TRADITIONAL_CHINESE_SET + if traditional_intersection: + traditional_chinese = True + # 判断有简体中文 + simple_intersection = ocr_set & SIMPLIFIED_CHINESE_SET + # 异常判断: 1.没有繁体中文但存在简体中文 2.外语误识别的中文 + if not traditional_chinese and simple_intersection: + if language == Language.ja_JP.value: + if len(simple_intersection) == len(ocr_set): + is_abnormal = True + else: + if len(simple_intersection) >= 1: + is_abnormal = True + return is_abnormal + + @staticmethod + def no_trans(text_str, no_trans_marks): + """漏译检测 + :param text_str: str, 待检测文本 + :param no_trans_marks: str, 漏译标识 + :return: is_abnormal, bool, 是否异常 + """ + is_abnormal = False + if not text_str: # 标准数据未提供文本内容, 无从判断 + return is_abnormal + if no_trans_marks not in ['', None]: # 项目自定义 + no_trans_marks_list = json.loads(no_trans_marks) + else: + no_trans_marks_list = NO_TRANS_MARK_LIST # 默认 + for no_trans_mask in no_trans_marks_list: + if no_trans_mask in text_str: + is_abnormal = True + break + return is_abnormal + + @staticmethod + def custom_abnormal(text_str, tag_text=NON_PROBLEM_MARK): + """自定义类型 non_problem 检测 + :param text_str: str, 待检测文本 + :param tag_text: str, 自定义命中的标记文本 + :return: over_frame, bool, 是否异常 + """ + is_abnormal = False + if not text_str: # 标准数据未提供文本内容, 无从判断 + return is_abnormal + if tag_text in text_str: + is_abnormal = True + return is_abnormal + + @staticmethod + def error_trans(text_str, text_location, ocr_data, error_trans_marks, check_type='all'): + """错误翻译检测 + :param text_str: str, 待检测文本 + :param text_location: list, 待检测文本位置 [ x_min, y_min, x_max, y_max] + :param ocr_data: ocr 识别结果数据 + :param error_trans_marks: str, 错译标识 + :param check_type: str, all 全局, single, 单文本框 + :return: is_abnormal, bool, 是否异常 + + """ + is_abnormal = False + # 标注数据不存在错译, 可以直接返回, 无需检测 + if not ErrorTrans.error_trans_mark(text_str, error_trans_marks): + return is_abnormal + if ocr_data and text_location and len(text_location) == 4: + if check_type == 'all' and text_location not in [[], None]: # 全局图像检测 + is_abnormal = ErrorTrans.all_error_trans(text_location, ocr_data) + if check_type == 'single': # 单文本框检测 + is_abnormal = ErrorTrans.single_error_trans(ocr_data, error_trans_marks) + return is_abnormal + + @staticmethod + def text_overframe(ocr_location, text_location, t=(0, 0, 0, 0)): + """文本超文本框 + :param ocr_location: list, 识别的文本区域 [ x_min, y_min, x_max, y_max] + :param text_location: list, 待检测文本位置 [ x_min, y_min, x_max, y_max] + :param t: 上下左右阈值 + :return: bool, 是否异常 + """ + # 直接碰撞检测 + return LqaProcessing.rect_collision_detection(ocr_location, text_location, t) + + @staticmethod + def ocr_image_overlap(img, gt_image_info, ocr_location): + """文本和图像重叠检测 + :param img: ndarray, 图像 + :param gt_image_info: dict, 标准图像框信息 + :param ocr_location: dict, 文本框位置坐标 (x1, y1, x2, y2) + :return: collision, bool, 是否碰撞 + image_location, 发生碰撞的图像框位置坐标 (x1, y1, x2, y2) + """ + collision = False + image_location = None + gt_image_locations = gt_image_info['gt_image_locations'] + dirty_image_ids = gt_image_info['dirty_image_ids'] + for i in range(len(gt_image_locations)): + if i in dirty_image_ids: # 脏图像框数据不检测 + continue + image_location = gt_image_locations[i] + # 碰撞检测, 文本本身超过图像框 + collision = LqaProcessing.rect_collision_detection(ocr_location, image_location, t=(5, 5, 5, 5)) + if collision: + rectified_image_location = LqaProcessing.shrink_image_box(img, image_location) + collision = LqaProcessing.rect_collision_detection(ocr_location, + rectified_image_location, + t=(5, 5, 5, 5)) + if collision: + break + return collision, image_location + + @staticmethod + def judge_single_text(check_type, language, text_index, img, gt_image_info, gt_text_locations, + classify_text_location_res, all_ocr_dict, all_ocr_error_trans_dict, + no_trans_list, over_frame_text_text_list, over_frame_text_image_list, + no_key_list, error_trans_list, non_problem_list, non_rectangle_list, + text_location_list, lqa_img, rect_img, res, check_detail, + no_trans_marks, error_trans_marks, non_rectangle=False, project=None): + """针对每一个文本框做判断和检查 + :param check_type: list, 异常检测类型 + :param language: int, 语种 id + :param text_index: int, 处理的第 text_index 个文本框 + :param img: ndarray, 原图像 + :param gt_image_info: dict, 标准图像框信息 + :param gt_text_locations: list, 标准文本框位置信息 + :param classify_text_location_res: dict, 文本框分类结果 + :param all_ocr_dict: dict, 全图 ocr 识别结果 + :param all_ocr_error_trans_dict, dict, 所有包含错误翻译标记的 ocr 识别结果 + :param no_trans_list: list, 半监督漏译信息 + :param over_frame_text_text_list: list, 半监督文本超框信息 + :param over_frame_text_image_list: list, 半监督文本超图像框信息 + :param no_key_list: list, 半监督漏 key 信息 + :param error_trans_list: list, 半监督错译信息 + :param non_problem_list: list, 半监督 non_problem 信息 + :param non_rectangle_list: list, 半监督 non_rectangle 信息 + :param text_location_list: list, 半监督预处理后的文本信息 + :param lqa_img: ndarray, 结果图像 + :param rect_img: ndarray, 标记图像 + :param res: dict, 结果 + :param check_detail: dict, 结果详情 + :param no_trans_marks: str, 漏译标识 + :param error_trans_marks: str, 错译标识 + :param non_rectangle: bool, 非标框, 默认都是标准框, 非标框不做碰撞检测 + :param project: str, 指定调用项目 + :return: res, check_detail, rect_img, lqa_img + """ + # 判断每一个文本框 + + text_location_dict = text_location_list[text_index] + text_str = text_location_dict.get("textStr") + detail_data = [text_str, list(gt_text_locations[text_index])] + + # 非标准框检测标记 + check_type_id = LqaCheckType.NON_RECTANGLE.value + if check_type is None or str(check_type_id) in check_type: + if non_rectangle: + draw_style = DrawStyle.NON_RECTANGLE.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + non_rectangle_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 自定义类型检测 non_problem 标记 + check_type_id = LqaCheckType.NON_PROBLEM.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.custom_abnormal(text_str, tag_text=NON_PROBLEM_MARK) + if is_abnormal: + draw_style = DrawStyle.NON_PROBLEM.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + non_problem_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 漏译检测 + check_type_id = LqaCheckType.NO_TRANS.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.no_trans(text_str, no_trans_marks) + if is_abnormal: + draw_style = DrawStyle.NO_TRANS.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + no_trans_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + # 漏key检测 + check_type_id = LqaCheckType.NO_KEY.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.no_key(text_str, language) + if is_abnormal: + draw_style = DrawStyle.NO_KEY.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + no_key_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 错译-全局判断 + check_type_id = LqaCheckType.ERROR_TRANS.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.error_trans(text_str, + gt_text_locations[text_index], + all_ocr_error_trans_dict, + error_trans_marks, + check_type='all') + if is_abnormal: + draw_style = DrawStyle.ERROR_TRANS.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + error_trans_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 独立无重叠的文本框 (排除非标框) + if not non_rectangle and text_index in classify_text_location_res['independent_id']: + x1, y1, x2, y2 = gt_text_locations[text_index] + text_location = (x1, y1, x2, y2) + res, check_detail, rect_img, lqa_img = LqaAbnormal.judge_single_independent_text( + check_type, text_index, text_location, text_str, img, gt_image_info, gt_text_locations, all_ocr_dict, + over_frame_text_text_list, over_frame_text_image_list, error_trans_list, + lqa_img, rect_img, res, check_detail, error_trans_marks, project=project) + return res, check_detail, rect_img, lqa_img + + @staticmethod + def judge_single_independent_text(check_type, text_index, text_location, text_str, + img, gt_image_info, gt_text_locations, all_ocr_dict, + over_frame_text_text_list, over_frame_text_image_list, error_trans_list, + lqa_img, rect_img, res, check_detail, error_trans_marks, project=None): + """检测每一个独立文本框 + :param check_type: list, 异常检测类型 + :param text_index: int, 处理的第 text_index 个文本框 + :param text_location: 文本位置信息 + :param text_str: str, 文本内容 + :param img: ndarray, 原图像 + :param gt_image_info: dict, 标准图像框信息 + :param gt_text_locations: list, 标准文本框位置信息 + :param all_ocr_dict: dict, 全图ocr识别结果 + :param over_frame_text_text_list: list, 半监督文本超框信息 + :param over_frame_text_image_list: list, 半监督文本超图像框信息 + :param error_trans_list: list, 半监督错译信息 + :param lqa_img: ndarray, 结果图像 + :param rect_img: ndarray, 标记图像 + :param res: dict, 结果 + :param check_detail: dict, 结果详情 + :param error_trans_marks: str, 错译标识 + :param project: str, 指定调用项目 + :return: res, check_detail, rect_img, lqa_img + """ + # 判断单个文本框 + detail_data = [text_str, list(gt_text_locations[text_index])] + # 判断是否需要扩展 + extend, img_location, text_data = LqaProcessing.judge_ocr_location_extend(img, text_location, text_str, + project=project) + if text_data is None or img_location is None: + return res, check_detail, rect_img, lqa_img + # 文本框 ocr 位置校准微调 + align_res, _ = LqaProcessing.align_ocr_location(text_location, img_location, text_data, all_ocr_dict, + extend=extend) + if len(align_res) != 1: + return res, check_detail, rect_img, lqa_img + # 文本框 ocr 位置校准微调 + ocr_x1, ocr_y1, ocr_x2, ocr_y2 = align_res[0] + rect_img = img_draw_rect(rect_img, align_res[0], draw_style=DrawStyle.OCR.value) + + # 错译-单文本框检测 + check_type_id = LqaCheckType.ERROR_TRANS.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.error_trans(text_str, + gt_text_locations[text_index], + text_data, + error_trans_marks, + check_type='single') + if is_abnormal: + draw_style = DrawStyle.ERROR_TRANS.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + error_trans_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 文本超文本框检测 + type_id = LqaCheckType.OVER_FRAME.value + sub_type_id = LqaCheckSubType.OVER_FRAME_TEXT_TEXT.value + check_type_id = str(type_id) + "-" + str(sub_type_id) + if check_type is None or check_type_id in check_type: + is_abnormal = LqaAbnormal.text_overframe((ocr_x1, ocr_y1, ocr_x2, ocr_y2), text_location, + t=(5, 5, 5, 5)) + if is_abnormal: + draw_style = DrawStyle.GT_TEXT.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + type_id, + detail_data, + over_frame_text_text_list, + lqa_img, + gt_text_locations[text_index], + draw_style, + sub_type_id=sub_type_id) + # 文本框和图像框重叠 + type_id = LqaCheckType.OVER_FRAME.value + sub_type_id = LqaCheckSubType.OVER_FRAME_TEXT_IMAGE.value + check_type_id = str(type_id) + "-" + str(sub_type_id) + if check_type is None or check_type_id in check_type: + ocr_location = (ocr_x1, ocr_y1, ocr_x2, ocr_y2) + collision, image_location = LqaAbnormal.ocr_image_overlap(img, gt_image_info, ocr_location) + if collision and image_location is not None: + detail_data = [text_str, list(gt_text_locations[text_index]), list(image_location)] + draw_style = DrawStyle.GT_TEXT.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + type_id, + detail_data, + over_frame_text_image_list, + lqa_img, + ocr_location, + draw_style, + sub_type_id=sub_type_id) + return res, check_detail, rect_img, lqa_img + + @staticmethod + def judge_single_group_overlap_text(check_type, group_index, overlap_group, overlap_group_id, + img, gt_text_locations, all_ocr_dict, + classify_text_location_res, text_location_list, + overlap_list, over_frame_text_text_list, error_trans_list, + lqa_img, rect_img, res, check_detail, error_trans_marks, + project=None): + """检测每一组重叠文本框 + :param check_type: list, 异常检测类型 + :param group_index: int, 处理的第 group_index 组文本框 + :param overlap_group: list, 重叠文本框信息 + :param overlap_group_id: list, 重叠文本框分组信息 (记录文本框索引) + :param img: ndarray, 原图像 + :param gt_text_locations: list, 标准文本框位置信息 + :param all_ocr_dict: dict, 全图 ocr 识别结果 + :param classify_text_location_res: dict, 文本框分类结果 + :param text_location_list: dict, 预处理后文本框信息 + :param overlap_list: list, 半监督文本框重叠信息 + :param over_frame_text_text_list: list, 半监督文本超框信息 + :param error_trans_list: list, 半监督错译信息 + :param lqa_img: ndarray, 结果图像 + :param rect_img: ndarray, 标记图像 + :param res: dict, 结果 + :param check_detail: dict, 结果详情 + :param error_trans_marks: str, 错译标识 + :param project: str, 指定调用项目 + :return: res, check_detail, rect_img, lqa_img + """ + x1, y1, x2, y2 = overlap_group[group_index] + group_id = overlap_group_id[group_index] + img_location = img[y1:y2, x1: x2] + text_data = ocr(mat_to_base64(img_location), project=project) + if not text_data: + return res, check_detail, rect_img, lqa_img + text_location = (x1, y1, x2, y2) + align_res, align_ocr_res = LqaProcessing.align_ocr_location(text_location, img_location, + text_data, all_ocr_dict, + merge_location=False, + extend=False) + # 判断重叠文本框归属 + overlap_info = OverlapText.judge_overlap_ocr_belong(align_res, align_ocr_res, group_id, + gt_text_locations) + # OCR 识别结果和重叠文本框数相同 + if len(overlap_info) == len(group_id): + supervised_info = {'error_trans': error_trans_list, + 'over_frame_text_text': over_frame_text_text_list + } + res, check_detail, rect_img, lqa_img = OverlapText.check_every_overlap_ocr(check_type, + rect_img, + lqa_img, + overlap_info, + text_location_list, + gt_text_locations, + res, + check_detail, + supervised_info, + error_trans_marks) + else: + group_text_id = classify_text_location_res['overlap_group_id'][group_index] + detail_data = OverlapText.sorted_detail_data(group_text_id, text_location_list, gt_text_locations) + supervised_info = {'overlap': overlap_list} + for g_id in overlap_info: + # 判断每个文本框 + for overlap_item_i in overlap_info[g_id]: + res, check_detail, rect_img, lqa_img = OverlapText.recheck_every_overlap_ocr( + check_type, img, rect_img, lqa_img, overlap_item_i, group_id, gt_text_locations, + res, check_detail, detail_data, supervised_info) + return res, check_detail, rect_img, lqa_img + + @staticmethod + def judge_single_text_no_ocr(check_type, language, text_index, img, gt_image_info, gt_text_locations, overlap_dict, + all_ocr_dict, all_ocr_error_trans_dict, + no_trans_list, error_trans_list, over_frame_text_text_list, over_frame_text_image_list, + no_key_list, non_problem_list, non_rectangle_list, + text_location_list, lqa_img, rect_img, res, check_detail, + no_trans_marks, error_trans_marks, non_rectangle=False, project=None): + """针对每一个文本框做判断和检查 (精准位置, 无 ocr 检测) + :param check_type: list, 异常检测类型 + :param language: int, 语种 id + :param text_index: int, 处理的第 text_index 个文本框 + :param img: ndarray, 原图像 + :param gt_image_info: dict, 标准图像框信息 + :param gt_text_locations: list, 标准文本框位置信息 + :param all_ocr_dict: dict, 全图ocr识别结果 + :param all_ocr_error_trans_dict, dict, 所有包含错误翻译标记的 ocr 识别结果 + :param no_trans_list: list, 半监督漏译信息 + :param error_trans_list: list, 半监督错译信息 + :param over_frame_text_text_list: list, 半监督文本超框信息 + :param over_frame_text_image_list: list, 半监督文本超图像框信息 + :param no_key_list: list, 半监督漏 key 信息 + :param non_problem_list: list, 半监督 non_problem 信息 + :param non_rectangle_list: list, 半监督 non_rectangle 信息 + :param text_location_list: list, 半监督预处理后的文本信息 + :param lqa_img: ndarray, 结果图像 + :param rect_img: ndarray, 标记图像 + :param res: dict, 结果 + :param check_detail: dict, 结果详情 + :param no_trans_marks: str, 漏译标识 + :param error_trans_marks: str, 错译标识 + :param non_rectangle: bool, 非标框, 默认都是标准框, 非标框不做碰撞检测 + :param project: str, 指定调用项目 + :return: res, check_detail, rect_img, lqa_img + """ + # 判断每一个文本框 + + text_location_dict = text_location_list[text_index] + text_str = text_location_dict.get("textStr") + detail_data = [text_str, list(gt_text_locations[text_index])] + + # 非标准框检测标记 + check_type_id = LqaCheckType.NON_RECTANGLE.value + if check_type is None or str(check_type_id) in check_type: + if non_rectangle: + draw_style = DrawStyle.NON_RECTANGLE.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + non_rectangle_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 错译-全局判断 + check_type_id = LqaCheckType.ERROR_TRANS.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.error_trans(text_str, + gt_text_locations[text_index], + all_ocr_error_trans_dict, + error_trans_marks, + check_type='all') + if is_abnormal: + draw_style = DrawStyle.ERROR_TRANS.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + error_trans_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 自定义类型检测 non_problem 标记 + check_type_id = LqaCheckType.NON_PROBLEM.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.custom_abnormal(text_str, tag_text=NON_PROBLEM_MARK) + if is_abnormal: + draw_style = DrawStyle.NON_PROBLEM.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + non_problem_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + # 漏译检测 + check_type_id = LqaCheckType.NO_TRANS.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.no_trans(text_str, no_trans_marks) + if is_abnormal: + draw_style = DrawStyle.NO_TRANS.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + no_trans_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + # 漏 key 检测 + check_type_id = LqaCheckType.NO_KEY.value + if check_type is None or str(check_type_id) in check_type: + is_abnormal = LqaAbnormal.no_key(text_str, language) + if is_abnormal: + draw_style = DrawStyle.NO_KEY.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + check_type_id, + detail_data, + no_key_list, + lqa_img, + gt_text_locations[text_index], + draw_style) + + if not non_rectangle: # 标准文本框 + x1, y1, x2, y2 = gt_text_locations[text_index] + + # 文本框和文本框重叠 + type_id = LqaCheckType.OVER_FRAME.value + sub_type_id = LqaCheckSubType.OVER_FRAME_TEXT_TEXT.value + check_type_id = str(type_id) + "-" + str(sub_type_id) + if check_type is None or check_type_id in check_type: + is_abnormal = True if len(overlap_dict[text_index]) > 1 else False + if is_abnormal: + draw_style = DrawStyle.GT_TEXT.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + type_id, + detail_data, + over_frame_text_text_list, + lqa_img, + gt_text_locations[text_index], + draw_style, + sub_type_id=sub_type_id) + + # 文本框和图像框重叠 + type_id = LqaCheckType.OVER_FRAME.value + sub_type_id = LqaCheckSubType.OVER_FRAME_TEXT_IMAGE.value + check_type_id = str(type_id) + "-" + str(sub_type_id) + if check_type is None or check_type_id in check_type: + ocr_location = (x1, y1, x2, y2) + collision, image_location = LqaAbnormal.ocr_image_overlap(img, gt_image_info, ocr_location) + if collision and image_location is not None: + detail_data = [text_str, list(gt_text_locations[text_index]), list(image_location)] + draw_style = DrawStyle.GT_TEXT.value + res, check_detail, lqa_img = LqaAbnormal.update_check_res(res, + check_detail, + type_id, + detail_data, + over_frame_text_image_list, + lqa_img, + ocr_location, + draw_style, + sub_type_id=sub_type_id) + return res, check_detail, rect_img, lqa_img + + +if __name__ == '__main__': + pass diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_config.py b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_config.py new file mode 100644 index 0000000000000000000000000000000000000000..056960a9dafb9ef48fe98af113ae827837128092 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_config.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +""" +# @file: lqa_config.py +# @desc: LQA 本地化检测相关配置, 定义以下枚举: +# - LqaCheckType: 检测问题类型 (漏译/超框/漏key/文本框重叠/错译/自定义non_problem/非标准框) +# - LqaCheckSubType: 超框问题的细分子类型 (文本超文本框/文本超图像框) +# - DrawStyle: 各类检测结果在图像上标注时使用的颜色 (RGB) 及线宽样式 +# - Language: 支持检测的语言类型 (简体中文/繁体中文/英文/日文/泰文/越南文) +""" +from enum import Enum + + +class LqaCheckType(Enum): + NO_TRANS = 1 # 漏译 + OVER_FRAME = 2 # 超框 + NO_KEY = 3 # 漏key + OVERLAP = 4 # 文本框重叠 + ERROR_TRANS = 5 # 错译 + NON_PROBLEM = 6 # non_problem 自定义 + NON_RECTANGLE = 7 # 非标准框 + + +class LqaCheckSubType(Enum): + OVER_FRAME_TEXT_TEXT = 0 # 文本超文本框 + OVER_FRAME_TEXT_IMAGE = 1 # 文本超图像框 + + +# 结果标记样式 +class DrawStyle(Enum): + GT_IMG = ((255, 255, 255), 2) + GT_TEXT = ((0, 0, 255), 2) + OCR = ((0, 255, 0), 1) + NO_TRANS = ((0, 140, 255), 4) + OVER_FRAME = ((0, 0, 255), 2) + NO_KEY = ((0, 255, 255), 3) + OVERLAP = ((255, 0, 255), 1) + ERROR_TRANS = ((255, 255, 0), 5) + NON_PROBLEM = ((255, 0, 0), 4) + NON_RECTANGLE = ((255, 0, 255), 2) + PRE_ERR = ((255, 0, 255), 5) + + +class Language(Enum): + zh_CN = 0 # 简体中文 + zh_TW = 1 # 繁体中文 (台湾) + en = 2 # 英文 + ja_JP = 3 # 日文 + th = 4 # 泰文 + vn = 5 # 越南 + + +if __name__ == '__main__': + pass diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_processing.py b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..9296c5c991f5c5fccf1dc4163934b8b3ca3fbf3f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_processing.py @@ -0,0 +1,638 @@ +# -*- coding: utf-8 -*- +""" +# @file: lqa_processing.py +# @desc: LQA 本地化检测相关数据预处理工具模块, 提供 LqaProcessing 类实现以下能力: +# - judge_rectangle/coordinate_trans: 判断四点坐标是否为标准矩形框, 并将左下角为原点的 +# 坐标体系转换为图像坐标系 (x1,y1,x2,y2 或 四点坐标) +# - is_dirty_text/detect_gt_text_locations/detect_gt_image_locations: 提取标准文本框/ +# 图像框位置信息,过滤尺寸异常、越界、空文本等脏数据,并标记非标准 (非矩形) 框 +# - draw_gt_locations: 在图像上绘制标准文本框/图像框及非标准框的标注样式 +# - detect_ocr_data/filter_text_data/get_join_ocr_result: 调用 OCR 识别图像文本, +# 并按标准文本框归属过滤、聚合 OCR 结果 +# - overlap/rect_collision_detection: 矩形碰撞检测, 判断两个矩形是否存在重叠/碰撞关系 +# - judge_overlap_with_text_i/merge_and_update_overlap/get_overlap_group_data/ +# save_single_group_classify_res/classify_text_location_overlap: 对所有文本框两两判断 +# 重叠关系并分组合并, 将文本框分类为独立文本框和重叠文本框组 (取最小外接矩形) +# - judge_ocr_location_extend/align_single_ocr_location/align_ocr_location: 根据 OCR +# 识别结果对文本框区域进行扩展判断和位置微调校准, 提升文本定位精度 +# - shrink_image_box: 基于连通域分析, 将图像框收缩到实际前景内容的最小外接矩形 +""" +import math +import cv2 +import numpy as np +from common.interface_ocr import ocr +from common.tools import mat_to_base64 +from task.lqa_config import DrawStyle +from common.tools import img_draw_rect + + +class LqaProcessing: + """lqa 数据预处理类""" + + @staticmethod + def judge_rectangle(location_dict): + """判断是否是标准文本框 + :param location_dict: dict, 位置信息 + :param height: int, 图像高度 + :return: 判断是否是标准矩形框 + """ + x1 = int(location_dict["corners"][0]["x"]) + y1 = int(location_dict["corners"][0]["y"]) + x2 = int(location_dict["corners"][1]["x"]) + y2 = int(location_dict["corners"][1]["y"]) + x3 = int(location_dict["corners"][2]["x"]) + y3 = int(location_dict["corners"][2]["y"]) + x4 = int(location_dict["corners"][3]["x"]) + y4 = int(location_dict["corners"][3]["y"]) + if x1 != x2 or x3 != x4 or y1 != y4 or y2 != y3: + return False + return True + + @staticmethod + def coordinate_trans(location_dict, height, is_rectangle=True): + """坐标变换, 提供的标准数据 text 和 image 的矩形框位置信息是以左下角为原点 + :param location_dict: dict, 位置信息 + :param height: int, 图像高度 + :param is_rectangle: bool, 默认标准文本框, 返回思维向量, 否则保持原 4 个点坐标 + :return: 转化后的位置坐标 (x1, y1, x2, y2) + """ + if is_rectangle: + x1 = int(location_dict["corners"][1]["x"]) + y1 = height - int(location_dict["corners"][1]["y"]) + x2 = int(location_dict["corners"][3]["x"]) + y2 = height - int(location_dict["corners"][3]["y"]) + trans_location = (x1, y1, x2, y2) + else: + x1 = int(location_dict["corners"][0]["x"]) + y1 = height - int(location_dict["corners"][0]["y"]) + x2 = int(location_dict["corners"][1]["x"]) + y2 = height - int(location_dict["corners"][1]["y"]) + x3 = int(location_dict["corners"][2]["x"]) + y3 = height - int(location_dict["corners"][2]["y"]) + x4 = int(location_dict["corners"][3]["x"]) + y4 = height - int(location_dict["corners"][3]["y"]) + trans_location = (x1, y1, x2, y2, x3, y3, x4, y4) + return trans_location + + @staticmethod + def is_dirty_text(text_location, text_location_dict, height, width): + """判断是否是脏文本框 (尺寸不合理、无文本等) + :param text_location: list, 文本位置 + :param text_location_dict: dict, 文本对应信息 + :param height: int, 图像高 + :param width: int, 图像宽 + :return: bool, 是否是脏数据 + """ + w = text_location[2] - text_location[0] + h = text_location[3] - text_location[1] + # 尺度太小 + if w < 13 or h < 13: + return True + # 位置不合理 + for i in range(4): + if text_location[i] < 0: + return True + if text_location[0] > width or text_location[2] > width: + return True + if text_location[1] > height or text_location[3] > height: + return True + # 无文本内容 + text_str = text_location_dict.get("textStr") + if not text_str or text_str == '': + return True + return False + + @staticmethod + def detect_gt_text_locations(img, text_location_list, preprocessing=False): + """ 提取所有标准文本框的位置信息, 进行坐标转换 + :param img: ndarray, 图像 + :param text_location_list: list, 标准文本框信息 + :return: gt_text_info, dict, {'gt_text_locations': 文本框信息, 'dirty_text_ids': 脏文本框id, + 'non_rectangle_ids': 非标框, preprocessing_err 预检测异常 {index: [error类型id列表]}} + """ + # 所有标准文本信息 + height, width = img.shape[:2] + gt_text_info = {'gt_text_locations': [], 'dirty_text_ids': [], 'non_rectangle_ids': [], + 'preprocessing_errs': {}} + text_list_temp = [] + for i in range(len(text_location_list)): + text_location_dict = text_location_list[i] + if text_location_dict not in text_list_temp: + text_list_temp.append(text_location_dict) + else: + gt_text_info['dirty_text_ids'].append(i) # 去重 + is_rectangle = LqaProcessing.judge_rectangle(text_location_dict) + text_location = LqaProcessing.coordinate_trans(text_location_dict, height, is_rectangle) + if is_rectangle: + # 过滤脏数据 + is_dirty = LqaProcessing.is_dirty_text(text_location, text_location_dict, height, width) + if is_dirty and i not in gt_text_info['dirty_text_ids']: + gt_text_info['dirty_text_ids'].append(i) + else: + # 过滤非标框 + gt_text_info['non_rectangle_ids'].append(i) + gt_text_info['gt_text_locations'].append(text_location) + + # 预检测异常 + if preprocessing and text_location_dict.get('preprocessing_err'): + gt_text_info['preprocessing_errs'].update({i: text_location_dict['preprocessing_err']}) + return gt_text_info + + @staticmethod + def detect_gt_image_locations(img, image_location_list): + """提取所有标准图像框的位置信息, 进行坐标转换 + :param img: ndarray, 图像 + :param image_location_list: list, 标准图像框信息 + :return: gt_image_info, dict, {'gt_image_locations': 图像框信息, 'dirty_text_ids': 脏图像框 id} + """ + height, width = img.shape[:2] + gt_image_info = {'gt_image_locations': [], 'dirty_image_ids': []} + image_list_temp = [] + for i in range(len(image_location_list)): + # image 框 + image_location_dict = image_location_list[i] + if image_location_dict not in image_list_temp: + image_list_temp.append(image_location_dict) + else: + gt_image_info['dirty_image_ids'].append(i) # 去重 + image_location = LqaProcessing.coordinate_trans(image_location_dict, height) + if image_location[2] - image_location[0] < 13 or image_location[3] - image_location[1] < 13 \ + or image_location[2] < 0 or image_location[3] < 0 \ + or image_location[0] > width or image_location[1] > height: + gt_image_info['dirty_image_ids'].append(i) + gt_image_info['gt_image_locations'].append(image_location) + return gt_image_info + + @staticmethod + def draw_gt_locations(rect_img, gt_text_info, gt_image_info): + """绘制标记标准信息, 包括文本框和图像框 + :param rect_img: ndarray, 图像 + :param gt_text_info: dict, 标准文本框信息 + :param gt_image_info: dict, 标准图像框信息 + :return: 标记后的 rect_img + """ + gt_text_locations = gt_text_info['gt_text_locations'] + dirty_text_ids = gt_text_info['dirty_text_ids'] + non_rectangle_ids = gt_text_info['non_rectangle_ids'] + for i in range(len(gt_text_locations)): + if i not in dirty_text_ids and i not in non_rectangle_ids: # 矩形 + rect_img = img_draw_rect(rect_img, gt_text_locations[i], DrawStyle.GT_TEXT.value) + if i in non_rectangle_ids: # 非矩形 + rect_img = img_draw_rect(rect_img, gt_text_locations[i], DrawStyle.NON_RECTANGLE.value) + gt_image_locations = gt_image_info['gt_image_locations'] + dirty_image_ids = gt_image_info['dirty_image_ids'] + for i in range(len(gt_image_locations)): + if i not in dirty_image_ids: + rect_img = img_draw_rect(rect_img, gt_image_locations[i], DrawStyle.GT_IMG.value) + return rect_img + + @staticmethod + def detect_ocr_data(img, gt_text_info, project=None): + """检测图像中所有 ocr, 同时过滤不属于标准框内的结果 + :param img: ndarray, 图像 + :param gt_text_info: dict, 标准文本框信息 + :param project: str, 指定调用项目 + :return: all_ocr_dict, 全图 OCR 识别结果 + """ + # 标准信息 + gt_text_locations = gt_text_info['gt_text_locations'] + dirty_text_ids = gt_text_info['dirty_text_ids'] + non_rectangle_ids = gt_text_info['non_rectangle_ids'] + # 所有检测文本信息 + all_ocr_dict = {} + text_data = ocr(mat_to_base64(img), project=project) + if not text_data: # OCR 未配置/不可用: 返回空结果, 由调用方跳过相关检测 + return all_ocr_dict + for text_one in text_data: + ocr_result = text_one["result"] + if ocr_result and len(ocr_result) <= 0: + continue + ocr_x1, ocr_y1, ocr_x2, ocr_y2 = text_one["area"] + center_x = (ocr_x1 + ocr_x2) / 2 + center_y = (ocr_y1 + ocr_y2) / 2 + for i in range(len(gt_text_locations)): + if i in dirty_text_ids or i in non_rectangle_ids: # 脏标准框直接跳过 + continue + x1, y1, x2, y2 = gt_text_locations[i] + if x1 < center_x < x2 and y1 < center_y < y2: + if ocr_result not in all_ocr_dict: + all_ocr_dict[ocr_result] = [] + all_ocr_dict[ocr_result].append((ocr_x1, ocr_y1, ocr_x2, ocr_y2)) + break + return all_ocr_dict + + @staticmethod + def filter_text_data(gt_text_info, text_location_list): + """直接从检测文件中提取 ocr 相关信息, 不需要检测 + :param gt_text_info: 预处理的标准数据, 包括位置信息, 过滤脏数据的索引 + :param text_location_list: list, 半监督预处理后的文本信息 + :return: all_ocr_dict, 全图文本内容 + """ + all_ocr_dict = {} + gt_text_locations = gt_text_info['gt_text_locations'] + for text_index in range(len(gt_text_locations)): + if text_index in gt_text_info['dirty_text_ids']: # 脏标准框数据跳过 + continue + x1, y1, x2, y2 = gt_text_locations[text_index] + text_location_dict = text_location_list[text_index] + text_str = text_location_dict.get("textStr") + all_ocr_dict[text_str].append((x1, y1, x2, y2)) + return all_ocr_dict + + @staticmethod + def overlap(rect1, rect2, x_t=10, y_t=5): + """矩形碰撞检测, 有重叠交集为 True + :param rect1: 矩形框1位置, x1,y1,x2,y2 格式 + :param rect2: 矩形框2位置, x1,y1,x2,y2 格式 + :param x_t: int, 重叠区域 x方向阈值 + :param y_t: int, 重叠区域 y方向阈值 + :return: bool,是否重叠 + ratio, str: 和 rect2 的重叠比率 + (sub_x, sub_y): 和 rect2 的重叠比率 + """ + # 重叠区域 + x_min = max(rect1[0], rect2[0]) + y_min = max(rect1[1], rect2[1]) + x_max = min(rect1[2], rect2[2]) + y_max = min(rect1[3], rect2[3]) + ratio = 0 + sub_x = 0 + sub_y = 0 + if x_max - x_min > x_t and y_max - y_min > y_t: + ratio = (x_max - x_min) * (y_max - y_min) / (rect2[2] - rect2[0]) / (rect2[3] - rect2[1]) + sub_x = abs((x_max - x_min) - (rect2[2] - rect2[0])) + sub_y = abs((y_max - y_min) - (rect2[3] - rect2[1])) + return True, ratio, (sub_x, sub_y) + else: + return False, ratio, (sub_x, sub_y) + + @staticmethod + def judge_overlap_with_text_i(overlap_dict, text_i, text_location_list, dirty_text_ids): + """判断与 text_i 重叠的文本框, 保存在字典里 (只判断索引大于text_i, 减少重复计算) + :param overlap_dict: dict, 保存的重叠关系结果 + :param text_i: int, 当前处理的文本框索引 + :param text_location_list: list, 文本位置信息 + :param dirty_text_ids: list, 脏文本框索引列表 + :return: 更新的overlap_dict + """ + + # 存储分类结果: 分别标记独立文本框和重叠文本框位置、索引 + cnt = len(text_location_list) + overlap_dict[text_i] = [text_i] + for j in range(cnt): + if j > text_i and j not in dirty_text_ids: + # 重叠判断 + is_overlap, _, _ = LqaProcessing.overlap(text_location_list[text_i], text_location_list[j]) + if is_overlap and j not in overlap_dict[text_i]: + overlap_dict[text_i].append(j) + return overlap_dict + + @staticmethod + def merge_and_update_overlap(temp_overlap_list, i_overlaps): + """判断是否是一组重叠文本框, 合并更新分组 id + :param temp_overlap_list: list, 存储分组结果 + :param i_overlaps: list, 第 i 个文本框判断的结果 + :return: 更新后的 temp_overlap_list + """ + in_others = False + for k in i_overlaps: + for j in range(len(temp_overlap_list)): + if k in temp_overlap_list[j]: + in_others = True + temp_overlap_list[j].extend(i_overlaps) + break + if in_others: + break + if in_others: + i_overlaps = [] + temp_overlap_list.append(i_overlaps) + return temp_overlap_list + + @staticmethod + def get_overlap_group_data(gt_text_info): + """获得分组的重叠文本框数据 + :param gt_text_info: dict, 标准文本信息 + :return: temp_overlap_dict, dict, 重叠文本框分组数据 + """ + text_location_list = gt_text_info['gt_text_locations'] + dirty_text_ids = gt_text_info['dirty_text_ids'] + non_rectangle_ids = gt_text_info['non_rectangle_ids'] + cnt = len(text_location_list) + + # 判断文本框与后面文本框的重叠关系 + overlap_dict = {} + for i in range(cnt): + if i in dirty_text_ids or i in non_rectangle_ids: # 脏数据过滤, 便于后续检测, 无需处理 + continue + overlap_dict = LqaProcessing.judge_overlap_with_text_i(overlap_dict, i, text_location_list, dirty_text_ids) + + # 合并文本框结果 + temp_overlap_list = [] + for i in range(cnt): + if i not in overlap_dict: + temp_overlap_list.append([]) # 脏数据占位, 保留索引 + continue + i_overlaps = overlap_dict[i] + if len(temp_overlap_list) == 0: + temp_overlap_list.append(i_overlaps) + else: + # 判断、合并同组文本框 + temp_overlap_list = LqaProcessing.merge_and_update_overlap(temp_overlap_list, i_overlaps) + + temp_overlap_dict = {} + for i in range(cnt): + if len(temp_overlap_list[i]) > 0: + temp_overlap_dict[i] = list(set(temp_overlap_list[i])) + return temp_overlap_dict + + @staticmethod + def save_single_group_classify_res(single_group_overlap, current_index, text_location_list, + classify_text_location_res): + """根据一组文本框分类结果, 结果格式化和保存 + :param single_group_overlap: dict, 单组重叠文本框 (保存的是对应文本框 index) + :param current_index: int, 当前处理的文本索引 + :param text_location_list: list, 文本位置信息 + :param classify_text_location_res: dict, 分类结果 + :return: + """ + x_min_list = [] + y_min_list = [] + x_max_list = [] + y_max_list = [] + for item in single_group_overlap: + x1, y1, x2, y2 = text_location_list[item] + x_min_list.append(x1) + y_min_list.append(y1) + x_max_list.append(x2) + y_max_list.append(y2) + + # 独立文本框 + if len(x_min_list) == 1: + classify_text_location_res['independent'].append((x_min_list[0], y_min_list[0], x_max_list[0], + y_max_list[0])) + classify_text_location_res['independent_id'].append(current_index) + # 有重叠的文本框合并, 最小外接矩形 + elif len(x_min_list) > 1: + group_x1 = np.min(x_min_list) + group_y1 = np.min(y_min_list) + group_x2 = np.max(x_max_list) + group_y2 = np.max(y_max_list) + classify_text_location_res['overlap_group'].append((group_x1, group_y1, group_x2, group_y2)) + classify_text_location_res['overlap_group_id'].append(single_group_overlap) + return classify_text_location_res + + @staticmethod + def classify_text_location_overlap(gt_text_info): + """根据文本框是否有重叠进行分类 + :param gt_text_info: dict, 提取的标准文本框信息 + :return: dict, classify_text_location_res, 文本框分类结果信息 + """ + # 存储分类结果: 分别标记独立文本框和重叠文本框位置、索引 + classify_text_location_res = {'independent': [], 'independent_id': [], + 'overlap_group': [], 'overlap_group_id': []} + text_location_list = gt_text_info['gt_text_locations'] + dirty_text_ids = gt_text_info['dirty_text_ids'] + + # 是否有文本框需要判断 + cnt = len(text_location_list) + if cnt - len(dirty_text_ids) <= 0: + return classify_text_location_res + # 获得分组的重叠文本框数据 + temp_overlap_dict = LqaProcessing.get_overlap_group_data(gt_text_info) + + # 按照分组的文本框结果, 保存格式化分类结果 (重叠文本框合并处理) + for i in temp_overlap_dict: + single_group_overlap = temp_overlap_dict[i] + if len(single_group_overlap) <= 0: + continue + classify_text_location_res = LqaProcessing.save_single_group_classify_res(single_group_overlap, + i, + text_location_list, + classify_text_location_res) + return classify_text_location_res + + @staticmethod + def rect_collision_detection(rect1, rect2, t=(0, 0, 0, 0)): + """矩形碰撞检测, 有交集且不包含为 True + :param rect1: 矩形框1位置, x1,y1,x2,y2 格式 + :param rect2: 矩形框2位置, x1,y1,x2,y2 格式 + :param t: 上下左右阈值 + :return: bool, 是否存在碰撞 + """ + # 无交集 + if rect1[0] + t[0] > rect2[2] or rect1[2] < rect2[0] + t[1] \ + or rect1[1] + t[2] > rect2[3] or rect1[3] < rect2[1] + t[3]: + return False + # 全包含 + if rect2[0] - t[1] <= rect1[0] < rect1[2] <= rect2[2] + t[0] \ + and rect2[1] - t[3] <= rect1[1] < rect1[3] <= rect2[3] + t[2]: + return False + return True + + @staticmethod + def get_join_ocr_result(img, project=None): + """识别图像的 ocr 结果, 并将结果聚合起来 + :param img: ndarray, 图像数据 + :param project: str, 指定调用项目 + :return: text_data: ocr 识别结果 + text_str: 聚合文本 + """ + text_str = '' + text_data = ocr(mat_to_base64(img), project=project) + if not text_data: + return None, None + for text_one in text_data: + ocr_result = text_one["result"] + if ocr_result and len(ocr_result) <= 0: + continue + text_str += ocr_result + return text_data, text_str + + @staticmethod + def judge_ocr_location_extend(img, text_location, text_str, project=None): + """根据文本框信息和 ocr 识别结果判断文本框是否需要进行扩展 + :param img: ndarray, 图像数据 + :param text_location: 文本位置, x1,y1,x2,y2 格式 + :param text_str: str, 文本内容 + :param project: str, 指定调用项目 + :return: bool, 是否扩展 + img_location_extend, ndarray, 文本区域图像数据 + text_data_ext, dict, 文本区域对应的OCR识别结果 + """ + # 原区域提取和识别 + height, width = img.shape[:2] + x1, y1, x2, y2 = text_location + img_location = img[y1: y2, x1: x2] + text_data, text_s = LqaProcessing.get_join_ocr_result(img_location, project=project) + if not text_data: + return False, None, None + # 区域扩展和识别 + img_location_extend = img[max(0, y1 - 5): min(height, y2 + 5), max(0, x1 - 10): min(width, x2 + 10)] + text_data_ext, text_s_ext = LqaProcessing.get_join_ocr_result(img_location_extend, project=project) + if not text_data_ext: + return False, None, None + # 判断是否扩展 (扩展后是否包含非文本框信息) + if text_s == text_s_ext or len(text_s_ext) > len(text_str or ''): + return False, img_location, text_data + else: + return True, img_location_extend, text_data_ext + + @staticmethod + def align_single_ocr_location(text_one, text_data, x1, y1, img_location, all_ocr_dict, align_location_list, + align_ocr_res, extend=False): + """ocr 识别单个结果微调校准 + :param text_one: dict, 单 ocr 识别结果 + :param text_data: list, ocr 识别结果 + :param x1: int, 文本位置坐标 x_min + :param y1: int, 文本位置坐标 y_min + :param img_location: ndarray, 文本区域的图像 + :param all_ocr_dict: dict, 全局 ocr 识别结果 + :param align_location_list: list, 校准的位置信息 + :param align_ocr_res: list, 校准的文本信息 + :param extend: bool, 是否扩展文本区域 + :return: align_location_list, list, 校准的位置信息 + align_ocr_res, list, 校准的文本信息 + """ + + ocr_result = text_one["result"] + if ocr_result and len(ocr_result) <= 0: + return align_location_list, align_ocr_res + ocr_area = text_one["area"] + ocr_x1, ocr_y1, ocr_x2, ocr_y2 = text_one["area"] + img = img_location[ocr_y1:ocr_y2, ocr_x1:ocr_x2] + if 0 in img.shape: + return align_location_list, align_ocr_res + # 灰度值判断, 过滤背景区域 + gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + if np.max(gray_img) < 120 and len(text_data) > 1: + return align_location_list, align_ocr_res + # 二值化提取前景, 文本区域微调 + binary_threshold = np.mean(gray_img) + _, th = cv2.threshold(gray_img, binary_threshold, 255, cv2.THRESH_BINARY) + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) + binary_query = cv2.erode(th, kernel) + h, w = binary_query.shape + h_list = [] + w_list = [] + for j in range(h): + for i in range(w): + if binary_query[j, i] == 255: + h_list.append(j) + w_list.append(i) + if not extend: + ocr_x1 = ocr_area[0] + max(0, x1) + ocr_y1 = ocr_area[1] + max(0, y1) + ocr_x2 = ocr_area[0] + max(0, x1) + ocr_y2 = ocr_area[1] + max(0, y1) + else: + ocr_x1 = ocr_area[0] + max(0, x1 - 10) + ocr_y1 = ocr_area[1] + max(0, y1 - 5) + ocr_x2 = ocr_area[0] + max(0, x1 - 10) + ocr_y2 = ocr_area[1] + max(0, y1 - 5) + if len(w_list) > 0 : + ocr_x1 = ocr_x1 + np.min(w_list) + ocr_y1 = ocr_y1 + np.min(h_list) + ocr_x2 = ocr_x2 + np.max(w_list) + ocr_y2 = ocr_y2 + np.max(h_list) + # 局部识别和全局识别共同校准 + center_x = (ocr_x1 + ocr_x2) / 2 + center_y = (ocr_y1 + ocr_y2) / 2 + align_location = (ocr_x1, ocr_y1, ocr_x2, ocr_y2) + if ocr_result in all_ocr_dict: + for item in all_ocr_dict[ocr_result]: + item_x1, item_y1, item_x2, item_y2 = item + if item_x1 < center_x < item_x2 and item_y1 < center_y < item_y2: + align_ocr_x1 = max(ocr_x1, item_x1) + align_ocr_y1 = max(ocr_y1, item_y1) + align_ocr_x2 = min(ocr_x2, item_x2) + align_ocr_y2 = min(ocr_y2, item_y2) + align_location = (align_ocr_x1, align_ocr_y1, align_ocr_x2, align_ocr_y2) + break + if align_location: + align_location_list.append(align_location) + align_ocr_res.append(text_one) + return align_location_list, align_ocr_res + + @staticmethod + def align_ocr_location(text_location, img_location, text_data, all_ocr_dict, merge_location=True, extend=False): + """ocr 识别结果微调校准 + :param text_location: 文本位置, x1,y1,x2,y2 格式 + :param img_location: ndarray, 文本区域的图像 + :param text_data: list, ocr 识别结果 + :param all_ocr_dict: dict, 全图像 ocr 识别结果 + :param merge_location: bool, 是否合并检测出来的 ocr 文本区域 + :param extend: bool, 是否扩展文本区域 + :return: align_res, list, 校准的位置信息 + align_ocr_res, list, 校准的文本信息 + """ + align_location_list = [] + align_ocr_res = [] + x1, y1, _, _ = text_location + for text_one in text_data: + align_location_list, align_ocr_res = LqaProcessing.align_single_ocr_location(text_one, + text_data, + x1, + y1, + img_location, + all_ocr_dict, + align_location_list, + align_ocr_res, + extend=extend) + # 根据 merge_location 判断是否对文本框进行聚合处理 + align_res = [] + if len(align_location_list) > 0: + if merge_location: + x1_list = [] + x2_list = [] + y1_list = [] + y2_list = [] + for item in align_location_list: + x1_list.append(item[0]) + y1_list.append(item[1]) + x2_list.append(item[2]) + y2_list.append(item[3]) + + align_loc = (np.min(x1_list), np.min(y1_list), np.max(x2_list), np.max(y2_list)) + align_res.append(align_loc) + else: + align_res = align_location_list + return align_res, align_ocr_res + + @staticmethod + def shrink_image_box(img, image_location): + """缩小图像框 + :param img: ndarray, 图像 + :param image_location: 图像框位置, x1,y1,x2,y2 格式 + :return: 调整后的图像框位置 + """ + h, w = img.shape[:2] + img_roi_area = img[ + max(0, image_location[1]): min(h, image_location[3]), + max(0, image_location[0]): min(w, image_location[2]) + ] + img_roi_area_gray = cv2.cvtColor(img_roi_area, cv2.COLOR_BGR2GRAY) + _, th = cv2.threshold(img_roi_area_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + _, _, stats, _ = cv2.connectedComponentsWithStats(th, connectivity=4) + hh, ww = img_roi_area.shape[:2] + sss = hh * ww + distance = 10000000 + min_index = -1 + if stats.shape[0] < 100: + for i, stat in enumerate(stats): + s = stat[2] * stat[3] + if sss * 0.95 > s > 10: + stat_center_x, stat_center_y = stat[0] + stat[2] / 2, stat[1] + stat[3] / 2 + dis = math.sqrt(((stat_center_x - ww / 2) ** 2) + ((stat_center_y - hh / 2) ** 2)) + if dis < distance: + distance = dis + min_index = i + if min_index != -1: + return stats[min_index][0] + max(0, image_location[0]), \ + stats[min_index][1] + max(0, image_location[1]), \ + stats[min_index][0] + stats[min_index][2] + max(0, image_location[0]), \ + stats[min_index][1] + stats[min_index][3] + max(0, image_location[1]) + return image_location + + +if __name__ == '__main__': + pass diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_supervised.py b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..747efc6b047877322aa932291e28985ae648ed7b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/task/lqa_supervised.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +""" +# @file: lqa_supervised.py +# @desc: LQA 本地化文本异常检测——半监督处理模块, 提供 Supervised 类实现以下能力: +# - get_supervised_data/get_over_frame_supervised_data: 解析人工审核的监督数据 (supervised), +# 按漏译/超框 (文本超文本框、文本超图像框)/漏key/文本框重叠/错译/ +# non_problem/非标准框等类型分类提取 +# - judge_location_change: 对比当前图像与历史图像的差异区域, 过滤出发生变化的检测区域, +# 未变化区域可直接复用历史检测结果 +# - extract_history_result_by_other_type/extract_history_result_by_over_frame_type/ +# extract_history_result: 根据历史检测结果 (history_result), 在两次检测图像的相同 (未变化) +# 区域上保留历史异常标记, 并在结果图上绘制对应的标注框 +# - preprocessing: 结合历史图像和历史检测结果, 预处理待检测的文本框/图像框列表, +# 过滤掉未发生变化的区域, 减少重复检测 +# - preprocessing_errs: 处理预处理阶段直接产生的异常 (如脏数据/非标准框等), +# 直接绘制标注并写入检测结果详情, 无需进入后续常规检测流程 +""" +import cv2 +import numpy as np +from task.lqa_config import LqaCheckType, LqaCheckSubType, DrawStyle +from task.lqa_processing import LqaProcessing +from task.lqa_abnormal import LqaAbnormal +from common.tools import img_draw_rect + + +class Supervised: + """监督处理 (历史测试数据)""" + + @staticmethod + def get_supervised_data(data): + """ 获取各类监督数据 + :param data: dict, 监督数据 + :return: 各类监督数据列表 + """ + no_trans_list = [] # 漏译 + over_frame_text_text_list = [] # 文本超文本框 + over_frame_text_image_list = [] # 文本超图像框 + no_key_list = [] # 漏 key + overlap_list = [] # 文本框重叠 + error_trans_list = [] # 错译 + non_problem_list = [] # non_problem + non_rectangle_list = [] # non_problem + if data: + if str(LqaCheckType.NO_TRANS.value) in data: + no_trans_list = data[str(LqaCheckType.NO_TRANS.value)] + if str(LqaCheckType.NO_KEY.value) in data: + no_key_list = data[str(LqaCheckType.NO_KEY.value)] + if str(LqaCheckType.OVERLAP.value) in data: + overlap_list = data[str(LqaCheckType.OVERLAP.value)] + if str(LqaCheckType.OVER_FRAME.value) in data: + over_frame_text_text_list, over_frame_text_image_list = Supervised.get_over_frame_supervised_data(data) + if str(LqaCheckType.ERROR_TRANS.value) in data: + error_trans_list = data[str(LqaCheckType.ERROR_TRANS.value)] + if str(LqaCheckType.NON_PROBLEM.value) in data: + non_problem_list = data[str(LqaCheckType.NON_PROBLEM.value)] + if str(LqaCheckType.NON_RECTANGLE.value) in data: + non_rectangle_list = data[str(LqaCheckType.NON_RECTANGLE.value)] + return no_trans_list, over_frame_text_text_list, over_frame_text_image_list, no_key_list, overlap_list,\ + error_trans_list, non_problem_list, non_rectangle_list + + @staticmethod + def get_over_frame_supervised_data(data): + """ 获取超框类型监督数据 + :param data: dict, 监督数据 + :return: 各类监督数据列表 + """ + over_frame_text_text_list = [] # 文本超文本框 + over_frame_text_image_list = [] # 文本超图像框 + if str(LqaCheckSubType.OVER_FRAME_TEXT_TEXT.value) in data[str(LqaCheckType.OVER_FRAME.value)]: + over_frame_text_text_list = data[str(LqaCheckType.OVER_FRAME.value)][ + str(LqaCheckSubType.OVER_FRAME_TEXT_TEXT.value)] + if str(LqaCheckSubType.OVER_FRAME_TEXT_IMAGE.value) in data[str(LqaCheckType.OVER_FRAME.value)]: + over_frame_text_image_list = data[str(LqaCheckType.OVER_FRAME.value)][ + str(LqaCheckSubType.OVER_FRAME_TEXT_IMAGE.value)] + return over_frame_text_text_list, over_frame_text_image_list + + @staticmethod + def judge_location_change(sub_img, location_list, need_coordinate_trans=True, need_judge_rectangle=False): + """ 对比和提取历史先验数据的图像变更区域 + :param sub_img: ndarray, 两次测试图像的差图 + :param location_list: list, 原始检测区域信息 + :param need_coordinate_trans: bool, 是否需要进行单位转换 + :param need_judge_rectangle: bool, 是否需要进行标准框检查 + :return: res_location_list, list, 过滤发生变化的检测区域 + """ + h, _ = sub_img.shape[:2] + res_location_list = [] + for item in location_list: + if need_coordinate_trans: # 坐标转换 + if need_judge_rectangle: + is_rectangle = LqaProcessing.judge_rectangle(item) + location = LqaProcessing.coordinate_trans(item, h, is_rectangle) + else: + location = LqaProcessing.coordinate_trans(item, h) + + else: + location = item + + if len(location) != 4: # 非标区域直接当作变更区域 + res_location_list.append(item) + else: + x1, y1, x2, y2 = location + location_img = sub_img[y1:y2, x1:x2] + if location_img.any() and np.max(location_img) > 0: + res_location_list.append(item) + return res_location_list + + @staticmethod + def extract_history_result_by_other_type(type_id, diff_img, sub_img, history_result, check_detail): + """ 提取历史非超框类型数据 + :param type_id: int, 异常类型 id + :param diff_img: ndarray, 结果绘制图 + :param sub_img: ndarray, 两次测试图像的差图 + :param history_result: dict, 历史检测结果 + :param check_detail: dict, 检测结果详细信息 + :return: diff_img, 结果绘制图 + check_detail, 检测结果详细信息 + """ + draw_style = None + # 非超框异常 + for item in history_result[type_id]: + if len(item[1]) == 4: # 非标框不处理了, 重新检测 + x1, y1, x2, y2 = item[1] + location_list = [item[1]] + judge_res = Supervised.judge_location_change(sub_img, location_list, + need_coordinate_trans=False) + if len(judge_res) <= 0: # 对比历史检测结果的相同区域, 结果进行保留 + check_detail = LqaAbnormal.update_check_type_detail(check_detail, int(type_id), item) + if int(type_id) == LqaCheckType.NO_TRANS.value: + draw_style = DrawStyle.NO_TRANS.value + if int(type_id) == LqaCheckType.NO_KEY.value: + draw_style = DrawStyle.NO_KEY.value + if int(type_id) == LqaCheckType.OVERLAP.value: + draw_style = DrawStyle.OVERLAP.value + if draw_style: + cv2.rectangle(diff_img, (x1, y1), (x2, y2), draw_style[0], draw_style[1]) + return diff_img, check_detail + + @staticmethod + def extract_history_result_by_over_frame_type(type_id, diff_img, sub_img, history_result, check_detail): + """ 提取历史超框数据 + :param type_id: int, 异常类型 id + :param diff_img: ndarray, 结果绘制图 + :param sub_img: ndarray, 两次测试图像的差图 + :param history_result: dict, 历史检测结果 + :param check_detail: dict, 检测结果详细信息 + :return: diff_img, 结果绘制图 + check_detail, 检测结果详细信息 + """ + # 超框异常: 分为文本超文本框, 文本超图像框 + frame_data = history_result[type_id] + for sub_type_id in frame_data: + for item in frame_data[sub_type_id]: + x1, y1, x2, y2 = item[1] + location_list = [item[1]] + if len(item) > 2: + location_list.append([item[2]]) + judge_res = Supervised.judge_location_change(sub_img, location_list, + need_coordinate_trans=False) + if len(judge_res) <= 0: # 对比历史检测结果的相同区域, 结果进行保留 + check_detail = LqaAbnormal.update_check_type_detail(check_detail, + int(type_id), + item, + int(sub_type_id)) + draw_style = DrawStyle.OVER_FRAME.value + if draw_style: + cv2.rectangle(diff_img, (x1, y1), (x2, y2), draw_style[0], draw_style[1]) + return diff_img, check_detail + + @staticmethod + def extract_history_result(diff_img, sub_img, history_result, check_detail): + """ 根据历史检测结果, 提取并保留 2 次检测图像相同区域的结果 + :param diff_img: ndarray, 结果绘制图 + :param sub_img: ndarray, 两次测试图像的差图 + :param history_result: dict, 历史检测结果 + :param check_detail: dict, 检测结果详细信息 + :return: diff_img, 结果绘制图 + check_detail, 检测结果详细信息 + """ + if history_result: + # 逐类处理结果数据 + for type_id in history_result: + # 非超框异常 + if type_id != str(LqaCheckType.OVER_FRAME.value): + diff_img, check_detail = Supervised.extract_history_result_by_other_type(type_id, + diff_img, + sub_img, + history_result, + check_detail) + else: # 超框异常 + diff_img, check_detail = Supervised.extract_history_result_by_over_frame_type(type_id, + diff_img, + sub_img, + history_result, + check_detail) + return diff_img, check_detail + + @staticmethod + def preprocessing(img, diff_img, rect_locations, history_img, history_result): + """ 半监督数据预处理 + :param img: ndarray, 待检测图像 + :param diff_img: ndarray, 结果绘制图 + :param rect_locations: list, 待检测图像文本、图像框信息 + :param history_img: ndarray, 历史检测图像 + :param history_result: dict, 历史检测结果 + :return: text_location_list, 预处理后需要检测的文本框信息 + image_location_list, 预处理后需要检测的图像框信息 + diff_img, 结果绘制图 + check_detail, 检测结果详细信息 + """ + check_detail = {} + text_location_list_temp = rect_locations.get("text", []) + image_location_list_temp = rect_locations.get("image", []) + if history_img is None or img.shape != history_img.shape: + return text_location_list_temp, image_location_list_temp, diff_img, check_detail + else: + sub = img - history_img + text_location_list = Supervised.judge_location_change(sub, text_location_list_temp, + need_judge_rectangle=True) + image_location_list = Supervised.judge_location_change(sub, image_location_list_temp) + diff_img, check_detail = Supervised.extract_history_result(diff_img, sub, history_result, check_detail) + return text_location_list, image_location_list, diff_img, check_detail + + @staticmethod + def preprocessing_errs(lqa_img, rect_locations, gt_text_info, check_detail): + """ 预处理的异常 ———— 只需要直接绘制结果和返回错误 + :param lqa_img: ndarray, 结果绘制图 + :param rect_locations: list, 待检测图像文本、图像框信息 + :param gt_text_info: dict, 处理的上报文本信息 + :param check_detail: dict, 检测结果 + :return: lqa_img, 预处理后的 lqa_img + check_detail, 预处理后的检测结果详细信息 + """ + gt_text_locations = gt_text_info['gt_text_locations'] + dirty_text_ids = gt_text_info['dirty_text_ids'] + non_rectangle_ids = gt_text_info['non_rectangle_ids'] + pre_errs = gt_text_info['preprocessing_errs'] + for i in range(len(gt_text_locations)): + if i in pre_errs: # 有预检测异常 + errs = pre_errs[i] + text_str = rect_locations['text'][i].get("textStr") + err_rect = gt_text_locations[i] + detail_data = [text_str, list(err_rect)] + if i not in dirty_text_ids and i not in non_rectangle_ids: # 矩形 + lqa_img = img_draw_rect(lqa_img, err_rect, DrawStyle.PRE_ERR.value) + if i in non_rectangle_ids: # 非矩形 + lqa_img = img_draw_rect(lqa_img, err_rect, DrawStyle.PRE_ERR.value) + for item_err in errs: + if item_err not in check_detail: + check_detail[item_err] = [] + if detail_data not in check_detail[item_err]: + check_detail[item_err].append(detail_data) + + return lqa_img, check_detail + + +if __name__ == '__main__': + pass diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/batch_test_lqa.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/batch_test_lqa.py new file mode 100644 index 0000000000000000000000000000000000000000..727408b9f73d2c39564d2e7e5c2c8318bac3ab5d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/batch_test_lqa.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +""" +# @file: batch_test_lqa.py +# @desc: LQA 本地化异常检测批量测试脚本 (用于调参、优化算法时批量查看效果), 提供: +# - test: 单个样例测试, 读取指定目录下的 screenShot.png(截图) + result.json(标准框标注) +# + 可选 supervised.json(半监督数据), 调用 /image/lqa_check/ 接口, +# 并支持将返回的 mark_img(检测标记图)/rect_img(标准框标注图) +# 本地弹窗展示(show_img)和/或保存到磁盘(save_img) +# - batch_test: 批量测试入口, 遍历 data_dir 下所有子目录, 对每个包含完整 +# screenShot.png + result.json 的子目录调用 test 执行检测, +# 并在每次请求间 sleep(1) 避免过快请求 +# - 服务地址可通过环境变量 LQA_TEST_HOST / LQA_TEST_PORT 覆盖 (默认 127.0.0.1:8086), +# 测试数据目录可通过 LQA_TEST_DATA_DIR 指定 (默认 tests/test/) +""" +import os +import json +import base64 +import time +import requests +import cv2 +from common.tools import base64_to_mat + + +def test(data_dir, img_dir, img_path, json_file_path, show_img=True, save_img=False, language=None, + supervised_file_path=None): + """lqa 本地化异常检测 + :param data_dir: str, 测试数据目录 + :param img_dir: str, 数据子文件夹 + :param img_path: str, 图片路径 + :param json_file_path: str, 标准信息文件路径 + :param show_img: bool, 是否显示结果图像 + :param save_img: bool, 是否保存结果图像 + :param language: 测试语种 + :param supervised_file_path: str, 半监督信息文件路径 + :return: + """ + + host = os.getenv("LQA_TEST_HOST", "127.0.0.1") + port = int(os.getenv("LQA_TEST_PORT", "8086")) + + fd = open(img_path, "rb") + img_base64 = base64.b64encode(fd.read()).decode("ascii") + load_f = open(json_file_path, 'rb') + rect_locations = json.load(load_f) + supervised_data = None + if supervised_file_path: + supervised_f = open(supervised_file_path, 'rb') + supervised_data = json.load(supervised_f) + + path = "/image/lqa_check/" + body = { + "img_base64": img_base64, + "rect_locations": rect_locations, + "language": language, + "supervised": supervised_data + + } + url = f"http://{host}:{port}{path}" + res = requests.post(url, json=body) + if res.status_code == 200: + res_dict = res.json() + if res_dict["success"]: + result = res_dict["result"] + mark_img = base64_to_mat(result["mark_img"]) + rect_img = base64_to_mat(result["rect_img"]) + if save_img: + mark_img_save_path = os.path.join(data_dir, img_dir, 'mark_img_ocr_finetuning_overlap.png') + rect_img_save_path = os.path.join(data_dir, img_dir, 'rect_img_ocr_finetuning_overlap.png') + cv2.imwrite(mark_img_save_path, mark_img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) + cv2.imwrite(rect_img_save_path, rect_img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) + if show_img: + cv2.namedWindow("mark_img", cv2.WINDOW_NORMAL) + cv2.imshow("mark_img", mark_img) + cv2.namedWindow("rect_img", cv2.WINDOW_NORMAL) + cv2.imshow("rect_img", rect_img) + cv2.waitKey() + else: + print(res_dict["err_msg"]) + else: + print(res.status_code) + + +def batch_test(data_dir, show_img=True, save_img=False, language=None): + """ 批量测试 + :param data_dir: str, 测试数据路径 + :param show_img: bool, 是否显示结果图像 + :param save_img: bool, 是否保存结果图像 + :param language: 测试语种 + :return: + """ + supervised_file_path = os.path.join(data_dir, 'supervised.json') + for path, dirs, _ in os.walk(data_dir): + for img_dir in dirs: + img_path = os.path.join(path, img_dir, 'screenShot.png') + json_file_path = os.path.join(path, img_dir, 'result.json') + if os.path.exists(img_path) and os.path.exists(json_file_path): + if supervised_file_path is None or not os.path.exists(supervised_file_path): + supervised_file_path = None + test(data_dir, img_dir, img_path, json_file_path, show_img=show_img, save_img=save_img, + language=language, supervised_file_path=supervised_file_path) + time.sleep(1) + + +if __name__ == '__main__': + default_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test') + batch_test(os.getenv('LQA_TEST_DATA_DIR', default_dir), + show_img=False, save_img=True, language=None) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/check_ocr.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/check_ocr.py new file mode 100644 index 0000000000000000000000000000000000000000..a000e32a24510a6257bd8e989cc45bd1a6393f50 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/check_ocr.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +""" +# @file: check_ocr.py +# @desc: OCR provider 自检工具 + +独立于 LQA 业务逻辑, 用于快速验证某个 OCR provider 是否能正常工作, +依次检测以下几个层面: + 1. provider 能否成功初始化 (依赖库是否安装、必要配置是否齐全, + 如密钥/服务地址等缺失会在此阶段报错) + 2. 该 provider 是否为 "空实现" (capable=False, 即 OCR_PROVIDER=none), + 是则提示 OCR 为可选能力, 服务仍可启动, 仅错译/文本超框检测会被跳过 + 3. 真实端到端识别连通性: 构造一张内置测试图 (写有 "LQA123") 调用 + recognize() 做一次真实识别, 验证本地模型推理 或 远程服务的 + 网络连通性/鉴权/返回格式是否正常 + +用法: + python tests/check_ocr.py # 检测当前 OCR_PROVIDER 配置 + python tests/check_ocr.py paddleocr # 指定 provider (不受环境变量/缓存影响) + python tests/check_ocr.py --list # 列出 common/ocr_provider 中已注册的全部 provider + +退出码: 0 表示检测通过 (含 [SKIP] 空实现的情况), 1 表示初始化失败或识别调用失败 +""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from common.ocr_provider import PROVIDERS, get_provider, OcrError # noqa: E402 + + +def main(): + args = sys.argv[1:] + if args and args[0] in ('--list', '-l'): + print('可选 OCR_PROVIDER:') + for name in sorted(PROVIDERS): + print(' -', name) + return 0 + + name = args[0] if args else None + try: + provider = get_provider(name=name, cache=False) + except OcrError as err: + print('[FAIL] 初始化失败: %s' % err) + return 1 + + print('provider = %s (远程服务: %s)' % (provider.name, provider.remote)) + if not getattr(provider, 'capable', True): + print('[SKIP] %s' % provider.test_connection()) + print(' OCR 为可选能力, 当前不影响服务启动;' + '仅「错译」与「文本超文本框」检测会被跳过') + return 0 + try: + print('[OK]', provider.test_connection()) + return 0 + except OcrError as err: + print('[FAIL] %s' % err) + print(' OCR 为可选能力: 服务仍可启动, 但「错译」与' + '「文本超文本框」检测将被跳过') + return 1 + except Exception as err: # pylint: disable=broad-except + print('[FAIL] %s: %s' % (type(err).__name__, err)) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/gen_samples.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/gen_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1df6474093e22f28635ff8e9b07fc5b77a6e91 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/gen_samples.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +""" +# @file: gen_samples.py +# @desc: 合成测试样例生成器 + +真实游戏截图涉及版权, 未随仓库发布, 本脚本用 OpenCV 合成一组 +结构等价的样例 (深色背景 + 面板 + 文本, 模拟游戏 UI), 供 +`tests/smoke_test.py` 开箱即用, 也可供 `test_lqa.py` / +`batch_test_lqa.py` 等手动指定目录测试 + +内置样例场景 (CASES): + 0 case_normal 正常界面, 文本均在标准框内, 预期无异常 + 1 case_overflow 标准框远小于文本实际占用区域, 可能触发超框 + (类型2, 实际是否判定还取决于 OCR 识别结果与阈值) + 2 case_no_trans 文本含 ##/N/A 等未翻译标记, 预期检出漏译 (类型1) + 3 case_missing_text_str 标注数据 textStr 缺失/空串, 验证不应导致服务崩溃 + 4 case_overlap 两个标准文本框在 x 轴上相交, 可能触发重叠 (类型4) + 5 case_dense 密集文本场景 (HUD/列表), 用于压力测试 + 6 case_no_key 非中文界面混入标注的简体中文 (textStr), + 预期检出漏 key (类型3, 基于简繁体字符集比对) + +生成结果: + tests/test//screenShot.png 合成截图 + tests/test//v3_result.json 标准文本框(text)/图像框(image)标注, + 四点坐标格式 (左上->左下->右下->右上) + +用法: + python tests/gen_samples.py # 生成到默认目录 tests/test/ + python tests/gen_samples.py --out DIR # 指定输出目录 + python tests/gen_samples.py --force # 覆盖已存在的样例 (默认跳过已存在的case) + +生成完成后可执行 `python tests/smoke_test.py 127.0.0.1:8086` 批量回归测试 +""" +import os +import sys +import json +import argparse + +import cv2 +import numpy as np + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_OUT = os.path.join(BASE_DIR, 'tests', 'test') + +FONT = cv2.FONT_HERSHEY_SIMPLEX +BG = (38, 34, 30) # 深色背景, 接近游戏 UI +PANEL = (70, 62, 52) +TEXT_COLOR = (236, 240, 245) + + +def _corners(x1, y1, x2, y2): + """转为标注要求的四点格式: 左上 -> 左下 -> 右下 -> 右上""" + return [ + {'x': float(x1), 'y': float(y1)}, + {'x': float(x1), 'y': float(y2)}, + {'x': float(x2), 'y': float(y2)}, + {'x': float(x2), 'y': float(y1)}, + ] + + +def _put_text(img, text, x, y, scale=0.7, thickness=2, color=TEXT_COLOR): + """绘制文本并返回其实际包围盒""" + (tw, th), baseline = cv2.getTextSize(text, FONT, scale, thickness) + cv2.putText(img, text, (x, y + th), FONT, scale, color, thickness, cv2.LINE_AA) + return [x, y, x + tw, y + th + baseline] + + +class SampleBuilder: + """逐个构造样例场景""" + + def __init__(self, width=960, height=540): + self.w, self.h = width, height + self.img = np.full((height, width, 3), BG, np.uint8) + self.texts = [] + self.images = [] + + def panel(self, x1, y1, x2, y2): + cv2.rectangle(self.img, (x1, y1), (x2, y2), PANEL, -1) + cv2.rectangle(self.img, (x1, y1), (x2, y2), (120, 110, 95), 1) + self.images.append({'corners': _corners(x1, y1, x2, y2)}) + return self + + def text(self, content, x, y, scale=0.7, box=None, text_str=None): + """绘制文本 + + :param box: 显式指定标准框; None 时用文本实际包围盒外扩少许 + :param text_str: 标注中记录的文本; 传 None 模拟 "标准数据缺失文本" + """ + actual = _put_text(self.img, content, x, y, scale=scale) + if box is None: + box = [actual[0] - 4, actual[1] - 4, actual[2] + 4, actual[3] + 4] + item = {'corners': _corners(*box)} + if text_str is not False: + item['textStr'] = content if text_str is None else text_str + self.texts.append(item) + return self + + def dump(self, out_dir): + os.makedirs(out_dir, exist_ok=True) + cv2.imwrite(os.path.join(out_dir, 'screenShot.png'), self.img, + [cv2.IMWRITE_PNG_COMPRESSION, 3]) + with open(os.path.join(out_dir, 'v3_result.json'), 'w', encoding='utf-8') as f: + json.dump({'text': self.texts, 'image': self.images}, f, + ensure_ascii=False, indent=1) + + +def case_normal(): + """正常界面: 文本均在框内""" + b = SampleBuilder() + b.panel(40, 40, 460, 200) + b.text('Start Game', 60, 70) + b.text('Settings', 60, 110) + b.text('Exit', 60, 150) + b.panel(500, 40, 900, 200) + b.text('Player Level 42', 520, 70, scale=0.6) + b.text('Gold 12800', 520, 110, scale=0.6) + return b + + +def case_overflow(): + """超框: 标准框明显小于文本实际占用区域 + + 注意: 是否判定为超框还取决于 OCR 识别到的实际文本区域与阈值, + 合成图上的表现可能与真实游戏截图不同 + """ + b = SampleBuilder() + b.panel(40, 40, 500, 220) + # 标准框只覆盖文本左侧一小段, 文本大幅溢出 + b.text('Confirm Purchase Immediately', 60, 80, scale=0.7, box=[58, 74, 120, 102]) + b.text('OK', 60, 150) + return b + + +def case_no_trans(): + """漏译: 包含 ## 等未翻译标记""" + b = SampleBuilder() + b.panel(40, 40, 520, 220) + b.text('##UI_MAIN_TITLE', 60, 70) + b.text('N/A', 60, 115) + b.text('Normal Text', 60, 160) + return b + + +def case_missing_text_str(): + """标准数据缺失 textStr: 验证空值不应导致崩溃""" + b = SampleBuilder() + b.panel(40, 40, 520, 220) + b.text('Hello World', 60, 70, text_str=False) # 不写入 textStr + b.text('Second Line', 60, 120, text_str='') # 显式空串 + return b + + +def case_overlap(): + """文本框重叠: 两个标准框在 x 轴上相交""" + b = SampleBuilder() + b.panel(40, 40, 600, 240) + b.text('Attack Power', 60, 80, box=[56, 72, 300, 108]) + b.text('Defense', 200, 90, box=[196, 82, 400, 118]) + return b + + +def case_no_key(): + """漏 key: 非中文界面中混入简体中文, 触发类型 3 + + 对应真实场景: 泰文/繁体版本里残留了未替换的简体中文文案 + 注意 OpenCV 默认字体不支持中文, 此处用标注文本触发检测, + 图像上以占位符呈现 + """ + b = SampleBuilder() + b.panel(40, 40, 600, 240) + # textStr 写入简体中文, 由检测逻辑比对字符集判定 + b.text('[CN]', 60, 80, box=[56, 72, 260, 108], text_str='确认购买') + b.text('Confirm', 60, 140, box=[56, 132, 260, 168]) + return b + + +def case_dense(): + """密集文本, 接近真实游戏 HUD""" + b = SampleBuilder() + b.panel(30, 30, 930, 110) + labels = ['HP', 'MP', 'EXP', 'LV', 'ATK', 'DEF', 'SPD'] + for i, label in enumerate(labels): + b.text(label, 50 + i * 125, 55, scale=0.6) + b.panel(30, 140, 460, 480) + for i, name in enumerate(['Inventory', 'Equipment', 'Skills', 'Quests', 'Map']): + b.text(name, 50, 170 + i * 46, scale=0.65) + b.panel(500, 140, 930, 480) + for i, name in enumerate(['Guild', 'Friends', 'Shop', 'Mail', 'Ranking']): + b.text(name, 520, 170 + i * 46, scale=0.65) + return b + + +#: (目录名, 构造函数, 预期说明) +CASES = [ + ('0', case_normal, '正常界面, 预期无异常'), + ('1', case_overflow, '标准框小于文本, 可能触发超框 (取决于 OCR 与阈值)'), + ('2', case_no_trans, '含 ## / N/A 标记, 预期检出漏译 (类型1)'), + ('3', case_missing_text_str, 'textStr 缺失/空, 预期不崩溃且无异常'), + ('4', case_overlap, '标准框相交, 可能触发重叠'), + ('5', case_dense, '密集文本压力场景'), + ('6', case_no_key, '非中文界面混入简体中文, 预期检出漏 key (类型3)'), +] + + +def main(): + parser = argparse.ArgumentParser(description='生成合成测试样例') + parser.add_argument('--out', default=DEFAULT_OUT, help='输出目录') + parser.add_argument('--force', action='store_true', help='覆盖已存在的样例') + args = parser.parse_args() + + created = skipped = 0 + for name, factory, desc in CASES: + out_dir = os.path.join(args.out, name) + marker = os.path.join(out_dir, 'v3_result.json') + if os.path.exists(marker) and not args.force: + print('[skip] case %-3s %s' % (name, '已存在 (--force 可覆盖)')) + skipped += 1 + continue + factory().dump(out_dir) + print('[gen ] case %-3s %s' % (name, desc)) + created += 1 + + print('\n生成 %d 个, 跳过 %d 个' % (created, skipped)) + if created: + print('现在可运行: python tests/smoke_test.py 127.0.0.1:8086') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/smoke_test.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..166702ec0a56098b98ab13ed9e7fa14d467fb12d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/smoke_test.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +""" +# @file: smoke_test.py +# @desc: 本地冒烟测试: 用 tests/test/ 下的样例批量调用 lqa_check 接口 + +读取 tests/test/ 目录下各样例子目录 (由 `tests/gen_samples.py` 生成, +每个子目录含 screenShot.png + v3_result.json), 依次携带 +project-method 请求头调用 /image/lqa_check/ 接口, 统计每个样例的: + - 请求是否成功 (HTTP 状态码、success 字段) + - 接口响应耗时 + - 是否判定为 overframe (存在异常) + - 检出的异常类型数量及前 5 个类型 id (check_detail) + - 是否返回了标记图 (mark_img) + +偏向服务级健康检查 (service smoke test): 只验证接口能否正常跑通、 +不报错、不超时, 不对具体检测结果的正确性做断言, 若样例目录 +不存在或为空, 会提示先运行 gen_samples.py 生成样例 + +用法: + python tests/smoke_test.py [host:port] [project] + +参数说明: + host:port LQA 服务地址, 默认 127.0.0.1:8086 + project project-method 请求头中的项目标识, 默认 lqa + (实际请求头为 "_lqa") + +例: + python tests/smoke_test.py 127.0.0.1:8086 lqa + +退出码: 0 表示全部样例通过, 1 表示存在失败样例或样例目录缺失/为空 +""" +import os +import sys +import json +import time +import base64 + +import requests + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CASE_DIR = os.path.join(BASE_DIR, 'tests', 'test') + + +def run_case(url, headers, case_path): + img_file = os.path.join(case_path, 'screenShot.png') + json_file = os.path.join(case_path, 'v3_result.json') + if not (os.path.exists(img_file) and os.path.exists(json_file)): + return None + + with open(img_file, 'rb') as f: + img_base64 = base64.b64encode(f.read()).decode('ascii') + with open(json_file, 'rb') as f: + rect_locations = json.load(f) + + body = { + 'img_base64': img_base64, + 'rect_locations': rect_locations, + 'language': None, + 'supervised': None, + } + start = time.time() + resp = requests.post(url, json=body, headers=headers, timeout=300) + cost = time.time() - start + if resp.status_code != 200: + return {'ok': False, 'msg': 'HTTP %s' % resp.status_code, 'cost': cost} + + data = json.loads(resp.text) + if not data.get('success'): + return {'ok': False, 'msg': data.get('err_msg'), 'cost': cost} + + result = data.get('result') or {} + detail = result.get('check_detail') or {} + return { + 'ok': True, + 'cost': cost, + 'overframe': result.get('overframe'), + 'detail_count': len(detail), + 'types': sorted(detail.keys())[:5], + 'has_mark_img': bool(result.get('mark_img')), + } + + +def main(): + hostport = sys.argv[1] if len(sys.argv) > 1 else '127.0.0.1:8086' + project = sys.argv[2] if len(sys.argv) > 2 else 'lqa' + url = 'http://%s/image/lqa_check/' % hostport + headers = {'project-method': '%s_lqa' % project} + + if not os.path.isdir(CASE_DIR): + print('未找到样例目录: %s' % CASE_DIR) + print('\n真实游戏截图涉及版权未随仓库发布, 请先生成合成样例:') + print(' python tests/gen_samples.py') + return 1 + + cases = sorted(os.listdir(CASE_DIR), key=lambda x: int(x) if x.isdigit() else 1 << 30) + passed = failed = skipped = 0 + print('目标: %s project-method: %s\n' % (url, headers['project-method'])) + for name in cases: + case_path = os.path.join(CASE_DIR, name) + if not os.path.isdir(case_path): + continue + res = run_case(url, headers, case_path) + if res is None: + skipped += 1 + continue + if res['ok']: + passed += 1 + print('[PASS] case %-4s %.2fs overframe=%-5s 异常数=%-3d %s' + % (name, res['cost'], res['overframe'], res['detail_count'], + ','.join(res['types']) if res['types'] else '')) + else: + failed += 1 + print('[FAIL] case %-4s %.2fs %s' % (name, res['cost'], res['msg'])) + + if passed == 0 and failed == 0: + print('样例目录为空: %s' % CASE_DIR) + print('\n请先生成合成样例: python tests/gen_samples.py') + return 1 + + print('\n合计: 通过 %d, 失败 %d, 跳过 %d' % (passed, failed, skipped)) + return 0 if failed == 0 else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation.py new file mode 100644 index 0000000000000000000000000000000000000000..1a37ac7fb4a344e092d120f1530750e462f04736 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +""" +# @file: test_image_extraction.py +# @desc: 图像前景提取服务 HTTP 接口测试脚本 (基于 unittest), 提供 ImageExtractionTestCase 类: +# - batch_test: 遍历指定数据目录下所有 .png 图片, 批量读取并转为 base64, +# 汇总为 {文件名: base64图像数据, ...} 字典, 作为批量请求数据 +# - setUp: 准备测试数据 (调用 batch_test), 并设置默认坐标参数 +# zero_type=1(左下角为原点)、position_type=1(比例坐标)、alpha_t=0 +# - test_image_extraction: 携带批量图像数据调用 /image/image_extraction/ +# 接口, 打印返回的各图像前景提取结果 (image_extraction字段) +# +# 与 test_image_extractation_local.py 的区别: 本脚本经过真实 HTTP 请求, +# 用于验证接口层 (Flask 路由、请求/响应序列化) 是否正常工作, 而非仅验证 +# 底层算法逻辑 +# +# 服务地址与测试数据目录均可通过环境变量覆盖: +# LQA_TEST_HOST / LQA_TEST_PORT / LQA_TEST_DATA_DIR +# +# 用法: python tests/test_image_extractation.py (或 python -m unittest) +""" +import os +import base64 +import unittest +import requests + + +class ImageExtractionTestCase(unittest.TestCase): + # 可通过环境变量覆盖: LQA_TEST_HOST / LQA_TEST_PORT / LQA_TEST_DATA_DIR + host = os.getenv("LQA_TEST_HOST", "127.0.0.1") + port = int(os.getenv("LQA_TEST_PORT", "8086")) + + def batch_test(self, data_dir): + """ 生成批量测试数据 + :param data_dir: str, 测试数数据目录 + :return: dict, 测试数据 (base64 图像) + """ + img_base64_batch = {} + for path, _, files in os.walk(data_dir): + for file in files: + if file.endswith('.png'): + img_path = os.path.join(path, file) + f = open(img_path, "rb") + img_base64 = base64.b64encode(f.read()).decode("ascii") + if img_base64: + img_base64_batch[file] = img_base64 + f.close() + return img_base64_batch + + def setUp(self): + data_dir = os.getenv( + "LQA_TEST_DATA_DIR", + os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test')) + self.img_base64 = self.batch_test(data_dir) + self.zero_type = 1 + self.position_type = 1 + self.alpha_t = 0 + + def test_image_extraction(self): + path = "/image/image_extraction/" + body = { + "img_base64": self.img_base64, + "zero_type": self.zero_type, + "position_type": self.position_type, + "alpha_t": self.alpha_t + } + url = f"http://{self.host}:{self.port}{path}" + print(url) + res = requests.post(url, json=body) + print(res.status_code) + if res.status_code == 200: + res_dict = res.json() + if res_dict["success"]: + result = res_dict["result"]['image_extraction'] + print(result) + else: + print(res_dict["err_msg"]) + else: + print(res.status_code) + + +if __name__ == '__main__': + unittest.main() diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation_local.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation_local.py new file mode 100644 index 0000000000000000000000000000000000000000..05da290431c626ccd96d8b8c53bff6c6fb9eddf3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_image_extractation_local.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +""" +# @file: test_image_extraction_local.py +# @desc: 图像前景提取本地测试脚本 (支持批量测试), 不经过 HTTP 请求, 直接在本地 +# 导入 task.image_processing.ImageProcessing 调用算法逻辑, 便于离线调试 +# (排除网络/Flask 服务因素, 专注验证前景提取算法本身), 提供: +# - batch_test: 遍历 data_dir 下所有 .png 图片, 批量转为 base64 后调用 +# ImageProcessing.image_extraction 提取各图前景区域, +# 返回 {图像名: (x1,y1,x2,y2), ...} 结果字典 +# - save_res: 根据 zero_type(坐标原点)/position_type(像素/比例坐标) +# 对提取结果做坐标还原, 在原图上绘制提取出的矩形框, +# 支持本地弹窗展示 (show_img) 和/或保存到指定目录 (save_img) +# - test: 测试入口, 串联 batch_test 和 save_res, 打印提取结果并输出标注图 +# +# 用法: python tests/test_image_extractation_local.py +# 可通过环境变量 LQA_TEST_DATA_DIR (待测图片目录, 默认 tests/test/) / +# LQA_TEST_SAVE_DIR (结果图保存目录, 默认 tests/test/result/) 指定路径 +""" +import base64 +import os +import cv2 +from task.image_processing import ImageProcessing + + +def batch_test(data_dir, zero_type, position_type): + """批量测试图像前景提取 + :param data_dir: str, 测试数据目录 + :param zero_type: int, 原点位置类型 + :param position_type: int, 位置表示方式类型 + :return: dict, 测试结果 + """ + img_base64_batch = {} + for path, _, files in os.walk(data_dir): + for file in files: + print('当前检测: ', path, file) + if file.endswith('.png'): + img_path = os.path.join(path, file) + f = open(img_path, "rb") + img_base64 = base64.b64encode(f.read()).decode("ascii") + if img_base64: + img_base64_batch[file] = img_base64 + res = ImageProcessing.image_extraction(img_base64_batch, zero_type=zero_type, position_type=position_type) + return res + + +def save_res(data_dir, res_data, zero_type, position_type, show_img=False, save_img=False, save_dir=None): + """图像前景提取结果保存 + :param data_dir: str, 测试数据目录 + :param res_data: dict, 测试结果数据 + :param zero_type: int, 原点位置类型 + :param position_type: int, 位置表示方式类型 + :param show_img: bool, 是否本地显示结果图像 + :param save_img: bool, 是否保存结果图像 + :param save_dir: str, 结果图像保存目录 + :return: + """ + for item in res_data: + img_path = os.path.join(data_dir, item) + img = cv2.imread(img_path, flags=-1) + h, w = img.shape[:2] + x1, y1, x2, y2 = res_data[item] + if position_type == 1: + x1 = int(x1 * w) + y1 = int(y1 * h) + x2 = int(x2 * w) + y2 = int(y2 * h) + if zero_type == 1: + y1 = h - y1 + y2 = h - y2 + cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0, 255), 1) + if show_img: + cv2.imshow(item, img) + if save_img and save_dir: + save_path = os.path.join(save_dir, item) + cv2.imwrite(save_path, img) + if show_img: + cv2.waitKey(0) + + +def test(data_dir, zero_type, position_type, show_img=False, save_img=False, save_dir=None): + """ 测试入口 + :param data_dir: str, 测试数据目录 + :param zero_type: int, 原点位置类型 + :param position_type: int, 位置表示方式类型 + :param show_img: bool, 是否本地显示结果图像 + :param save_img: bool, 是否保存结果图像 + :param save_dir: str, 结果图像保存目录 + :return: + """ + res = batch_test(data_dir, zero_type=zero_type, position_type=position_type) + print('结果:', res) + res_data = res['image_extraction'] + save_res(data_dir, res_data, zero_type, position_type, show_img=show_img, save_img=save_img, save_dir=save_dir) + + +if __name__ == '__main__': + # 可通过 LQA_TEST_DATA_DIR / LQA_TEST_SAVE_DIR 指定目录 + _base = os.path.dirname(os.path.abspath(__file__)) + _data_dir = os.getenv('LQA_TEST_DATA_DIR', os.path.join(_base, 'test')) + _save_dir = os.getenv('LQA_TEST_SAVE_DIR', os.path.join(_base, 'test', 'result')) + test(_data_dir, 0, 0, show_img=False, save_img=True, save_dir=_save_dir) diff --git a/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_lqa.py b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_lqa.py new file mode 100644 index 0000000000000000000000000000000000000000..913b65d44f0141b5528db75320973709a526cace --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/lqa_service/tests/test_lqa.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +""" +# @file: test_lqa.py +# @desc: LQA 本地化文本异常检测服务测试用例 (基于 unittest), 提供 LqaTestCase 类: +# - setUp: 读取默认 (或指定) 测试数据目录下的 screenShot.png (截图) 和 +# v3_result.json (标准文本框/图像框标注), 可选读取历史对比图 +# (LQA_TEST_HISTORY_IMG) 用于半监督历史先验测试, 初始化 +# language/check_type/supervised 等请求参数 (默认均为全量检测) +# - test_lqa: 携带 project-method 请求头调用 /image/lqa_check/ 接口, +# 打印检测结果详情 (check_detail) 及耗时, 并将返回的 +# mark_img(检测标记图)/rect_img(标准框标注图) 本地弹窗展示, +# 同时保存为 lqa_mark_img.png / lqa_rect_img.png 便于人工核验 +# - tearDown: 关闭打开的图像/json文件句柄 +# +# 服务地址与测试数据路径均可通过环境变量覆盖: +# LQA_TEST_HOST / LQA_TEST_PORT / LQA_TEST_DATA_DIR / LQA_TEST_PROJECT / +# LQA_TEST_HISTORY_IMG +# +# 用法: python tests/test_lqa.py (或 python -m unittest tests.test_lqa) +""" +import json +import time +import base64 +import unittest +import requests +import cv2 +from common.tools import base64_to_mat + + +import os + +# 服务地址与测试数据路径均可通过环境变量覆盖: +# LQA_TEST_HOST / LQA_TEST_PORT / LQA_TEST_DATA_DIR +DEFAULT_DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test', '0') + + +class LqaTestCase(unittest.TestCase): + host = os.getenv("LQA_TEST_HOST", "127.0.0.1") + port = int(os.getenv("LQA_TEST_PORT", "8086")) + + def setUp(self): + data_dir = os.getenv("LQA_TEST_DATA_DIR", DEFAULT_DATA_DIR) + img_path = os.path.join(data_dir, "screenShot.png") + self.fd = open(img_path, "rb") + self.img_base64 = base64.b64encode(self.fd.read()).decode("ascii") + self.load_f = open(os.path.join(data_dir, "v3_result.json"), 'rb') + self.rect_locations = json.load(self.load_f) + self.supervised = None + self.language = None + self.check_type = None # 默认全部异常类型 + # 差异识别的历史图, 未配置时不启用 + history_img_path = os.getenv("LQA_TEST_HISTORY_IMG", "") + self.history_fd = None + self.history_img_base64 = None + if history_img_path and os.path.exists(history_img_path): + self.history_fd = open(history_img_path, "rb") + self.history_img_base64 = base64.b64encode(self.history_fd.read()).decode("ascii") + self.history_result = {} + + def test_lqa(self): + st = time.time() + path = "/image/lqa_check/" + body = { + "img_base64": self.img_base64, + "rect_locations": self.rect_locations, + "language": self.language, + "supervised": self.supervised, + "check_type": self.check_type, + "history_img_base64": self.history_img_base64, + "history_result": self.history_result, + } + url = f"http://{self.host}:{self.port}{path}" + print(url) + headers = {"project-method": f"{os.getenv('LQA_TEST_PROJECT', 'lqa')}_lqa"} + res = requests.post(url, json=body, headers=headers) + if res.status_code == 200: + res_dict = res.json() + if res_dict["success"]: + result = res_dict["result"] + mark_img = base64_to_mat(result["mark_img"]) + rect_img = base64_to_mat(result["rect_img"]) + print(result["check_detail"]) + print('耗时', time.time() - st) + if mark_img is not None: + cv2.namedWindow("mark_img", cv2.WINDOW_NORMAL) + cv2.imshow("mark_img", mark_img) + cv2.imwrite("lqa_mark_img.png", mark_img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) + if rect_img is not None: + cv2.namedWindow("rect_img", cv2.WINDOW_NORMAL) + cv2.imshow("rect_img", rect_img) + cv2.imwrite("lqa_rect_img.png", rect_img, [cv2.IMWRITE_PNG_COMPRESSION, 0]) + cv2.waitKey() + else: + print(res_dict["err_msg"]) + else: + print(res.status_code) + + def tearDown(self): + self.fd.close() + self.load_f.close() + if self.history_fd: + self.history_fd.close() + print("test end") + + +if __name__ == '__main__': + unittest.main() diff --git a/timi_hok_game_translator/LQA_WMP/server/.dockerignore b/timi_hok_game_translator/LQA_WMP/server/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..bc569922c9443699ca2cfad0da7d88380b8b2e79 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/.dockerignore @@ -0,0 +1,10 @@ +.venv +__pycache__ +*.pyc +*.log +.env +config/env.* +data +media +.idea +.vscode diff --git a/timi_hok_game_translator/LQA_WMP/server/.env.example b/timi_hok_game_translator/LQA_WMP/server/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..1c93be2f7d69873a77810ee2ade08041b6713f60 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/.env.example @@ -0,0 +1,29 @@ +# 复制为 server/.env 后按需修改 (也可以直接使用系统环境变量, 优先级更高) +DEBUG=true +APP_NAME=LQA +# 生产环境必须设置为随机字符串: python -c "import secrets;print(secrets.token_urlsafe(48))" +SECRET_KEY=change-me +ALLOWED_HOSTS=* + +# 数据目录 (日志、临时文件) 与上传文件目录 +APP_DATA_ROOT=./data/n0 +APP_MEDIA_ROOT=./data/media_root + +# MySQL 8 / Redis +MYSQL_URL=mysql://lqa:lqa_password@127.0.0.1:3306/lqa +REDIS_URL=rediscache://:redis_password@127.0.0.1:6379/1 +CELERY_BROKER_URL=redis://:redis_password@127.0.0.1:6379/2 +CELERY_BACKEND_URL=redis://:redis_password@127.0.0.1:6379/2 + +# 账号 +ALLOW_REGISTER=true +# HTTPS 部署时开启 +SESSION_COOKIE_SECURE=false + +# 平台对外访问地址 (缺陷中的截图链接、Webhook 变量 {{lqa_server}} 使用), 如 https://lqa.example.com +PUBLIC_URL= +# 截图 (/media/) 是否允许匿名访问; 使用禅道并希望在禅道中直接显示截图时开启 +MEDIA_PUBLIC=false + +# AI 识别服务地址 (lqa_service 默认监听 8086) +AI_BASE_URL=http://127.0.0.1:8086 diff --git a/timi_hok_game_translator/LQA_WMP/server/.gitignore b/timi_hok_game_translator/LQA_WMP/server/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f6e2801dbf2202a7bf3e16aefec5096eece385ab --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/.gitignore @@ -0,0 +1,20 @@ +__pycache__/ +*.py[cod] +*.log +.DS_Store +.env +config/env.* +# 注意: 必须带前导斜杠锚定到 server/ 根目录 +# 写成 data/ 会匹配任意层级的同名目录, 导致 Django app server/apps/data/ 被误排除 +/data/ +/media/ +.idea/ +.vscode/ +.venv/ + +# scripts/ 目录下只保留正式入库的脚本, 其余本地调试 /mock/ 验证脚本都不提交 +/scripts/*.py +!/scripts/__init__.py +!/scripts/smoke_test.py +!/scripts/test_bug_flow.py +!/scripts/test_bugtracker.py diff --git a/timi_hok_game_translator/LQA_WMP/server/.pylintrc b/timi_hok_game_translator/LQA_WMP/server/.pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..4c1924eef8f9a1dfa516ae4bb4b45f437432b5a3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/.pylintrc @@ -0,0 +1,57 @@ +[MASTER] +# 使用多进程加速 Pylint 检查, 设置为 0 时会自动检测可用的 CPU 核心数 +jobs=1 + + +[MESSAGES CONTROL] + +# 禁用指定 id 对应的消息/报告/分类或检查器 (此处设为 all, 即先禁用全部检查项, +# 再通过下方 enable 按需开启部分检查) +disable=all + +# 启用指定 id 对应的消息/报告/分类或检查器 (配合上方 disable=all, 仅开启以下列出的检查项) +enable=c-extension-no-member, + bad-indentation, + bare-except, + broad-except, + dangerous-default-value, + function-redefined, + len-as-condition, + line-too-long, + misplaced-future, + missing-final-newline, + mixed-line-endings, + multiple-imports, + multiple-statements, + singleton-comparison, + trailing-comma-tuple, + trailing-newlines, + trailing-whitespace, + unexpected-line-ending-format, + unused-import, + unused-variable, + wildcard-import, + wrong-import-order + + +[FORMAT] + +# 期望的换行符格式, 例如 empty (不限制任何换行符)、LF 或 CRLF +expected-line-ending-format=LF + +# 允许超出长度限制的行所匹配的正则表达式 (此处用于放行纯链接的注释行) +ignore-long-lines=^\s*(# )??$ + +# 单行代码允许的最大字符数 +max-line-length=120 + +# 单个模块 (文件) 允许的最大行数 +max-module-lines=2000 + + +[EXCEPTIONS] + +# 捕获时会触发警告的过于宽泛的异常类型, 默认值为 +# "BaseException, Exception" +overgeneral-exceptions=builtins.BaseException, + builtins.Exception \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/Dockerfile b/timi_hok_game_translator/LQA_WMP/server/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6c7122b47fd053197321d5b985d8cdf78070f641 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/Dockerfile @@ -0,0 +1,24 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + APP_DATA_ROOT=/data/n0 \ + APP_MEDIA_ROOT=/data/media_root + +# mysqlclient 编译依赖; opencv-headless 运行依赖 libglib2.0 +RUN apt-get update \ + && apt-get install -y --no-install-recommends gcc pkg-config default-libmysqlclient-dev libglib2.0-0 \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY requirements.txt . +ARG PIP_INDEX_URL=https://pypi.org/simple +RUN pip install -i ${PIP_INDEX_URL} -r requirements.txt + +COPY . . +RUN chmod +x docker-entrypoint.sh + +EXPOSE 8000 +ENTRYPOINT ["./docker-entrypoint.sh"] +CMD ["web"] diff --git a/timi_hok_game_translator/LQA_WMP/server/README.md b/timi_hok_game_translator/LQA_WMP/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dd54824bb081b6e58f5f8e7d521bd524380317ee --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/README.md @@ -0,0 +1,119 @@ +# LQA 后端服务 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +Python 3.12 + Django 5.1 + Celery 5, 数据库 MySQL 8, 缓存/会话/任务队列 Redis + +## 本地开发 + +```bash +cd server +python -m venv .venv +.venv/Scripts/activate # Linux/macOS: source .venv/bin/activate +pip install -r requirements.txt + +cp .env.example .env # 修改 MYSQL_URL / REDIS_URL 等 +python manage.py migrate +python manage.py init_data # 初始化系统模板: 缺陷类型、区域语言 +python manage.py init_admin --username admin --password 'Admin123456' + +python manage.py runserver 0.0.0.0:8000 +celery -A celery_app worker -l info -P solo # Windows 使用 -P solo +``` + +配置读取顺序: 系统环境变量 > `config/env.{APP_ENV}` (`APP_ENV` 默认 `dev`) > `.env`, 全部配置项见 `.env.example` + +## 管理命令 + +| 命令 | 说明 | +|---|---| +| `init_admin --username U --password P [--if-not-exists]` | 创建或重置超级管理员; 也可通过环境变量 `LQA_ADMIN_USERNAME` / `LQA_ADMIN_PASSWORD` 传入 | +| `init_data` | 初始化系统模板项目 (project_id=0) 的缺陷类型、区域语言, 可重复执行 | +| `update_access_token -u [-e <秒>]` | 为指定用户生成 access_token (默认 30 天有效), 用于还原端等 API 调用方 | + +## 目录 + +``` +apps/ + user/ 账号、登录/注册、项目角色、access_token + project/ 项目、项目配置 (缺陷类型/语言/图片还原/还原执行 Webhook/缺陷系统/提单配置) + job/ 还原任务、Webhook 触发 (runner.py)、回归 + image/ 截图上传与 AI 识别 + bug/ 缺陷提单与同步 + data/ 测试数据 + system/ 枚举 + lqa/ 健康检查、上传、管理命令 +libs/ + bugtracker/ 缺陷系统适配器: local (平台内记录) / bugzilla / zentao +scripts/ 冒烟测试、缺陷系统适配器测试 +``` + +## 认证 + +- 浏览器: `POST /api/user/login {username, password}` 登录后使用 Session Cookie; 请求头 `LQA-Authorization: web` +- API 调用方 (还原端等): 执行管理命令 `update_access_token` 生成 token; 或登录后先 `GET /api/ticket` 取一次性 ticket, + 再带请求头 `LQA-Ticket: ` 调用 `POST /api/user/access_token`, + 之后请求头带 `LQA-Authorization: ` (重新生成后旧 token 失效) +- 认证失败返回业务码 `1003` + +主要接口: + +| 接口 | 说明 | +|---|---| +| `GET /api/user/auth_config` | 是否开放注册 (免登录) | +| `POST /api/user/register` | 自助注册 (`ALLOW_REGISTER=true` 时可用) | +| `POST /api/user/login` / `POST /api/user/logout` | 登录 / 退出 | +| `POST /api/user/password` | 修改自己的密码 | +| `POST /api/user/reset_password` | 超管重置他人密码 | +| `GET /api/user/permission` | 当前用户可访问的项目及角色 | +| `POST /api/job/action` | `start` / `retry` 返回渲染好的 Webhook 请求; 浏览器调用成功后回调 `started`; `stop` 结束任务 | +| `GET /api/bug/tracker_meta` | 当前项目缺陷系统信息与提单下拉选项 | +| `POST /api/bug/tracker_test` | 测试缺陷系统连接 (项目管理员) | +| `GET /api/health` | 健康检查 (免登录) | + +## AI 识别服务 + +`POST {AI_BASE_URL}/image/lqa_check/`, 请求头 `project-method: <项目的 AI 识别项目名>_lqa` + +请求体: + +```json +{ + "img_base64": "当前截图 base64", + "history_img_base64": "差异识别时上一次识别成功的截图 base64,可为 null", + "rect_locations": [/* 还原端上报的文本控件位置 */], + "language": 2, + "history_result": null, + "check_type": ["1", "2-0"], + "no_trans_marks": [], + "error_trans_marks": [], + "ocr_detect": 0 +} +``` + +响应体: + +```json +{ + "success": true, + "err_msg": "", + "result": { + "mark_img": "标注后图片 base64", + "rect_img": "文本框图片 base64", + "check_detail": {} + } +} +``` + +`result.check_detail` 作为识别明细保存, 用于审核页展示、提单与下一次差异识别 (`history_result`) + +## 测试 + +```bash +# 缺陷系统适配器 (本地模拟 Bugzilla/ 禅道服务, 需要可用的 MySQL/Redis) +python scripts/test_bugtracker.py +# 提单/回归全流程 +python scripts/test_bug_flow.py +# 接口冒烟测试 (需要先启动服务并初始化超管) +python scripts/smoke_test.py http://127.0.0.1:8000 admin Admin123456 +``` diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f7ac3f8123737284b60ceb8613487c009bf261 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class BugConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.bug' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..395652682c2c5f487fa7a6b29d6306d5c3032039 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/migrations/0001_initial.py @@ -0,0 +1,55 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('job', '0001_initial'), + ('project', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Bug', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('image_id', models.IntegerField(default=0, verbose_name='image_id')), + ('bill_status', models.IntegerField(choices=[(0, '初始'), (1, '提bug单成功'), (2, '提bug单失败')], default=0, verbose_name='提单结果')), + ('bill_text', models.TextField(default='', verbose_name='提交bug返回的错误信息')), + ('regress_status', models.IntegerField(choices=[(1, '初始'), (2, '回归中'), (3, '回归成功'), (4, '回归失败')], default=1)), + ('regress_job_ids', models.JSONField(default=list, verbose_name='回归任务id')), + ('key_in_bug', models.TextField(default='', verbose_name='ai识别的结果')), + ('celery_task_id', models.CharField(default='', max_length=64, verbose_name='celery_task id')), + ('raw_image_path', models.CharField(default='', max_length=255, verbose_name='原始图片路径')), + ('ai_image_path', models.CharField(default='', max_length=255, verbose_name='AI识别返回的图片路径')), + ('tracker', models.CharField(choices=[('none', '平台内记录'), ('bugzilla', 'Bugzilla'), ('zentao', '禅道')], default='none', max_length=16, verbose_name='提交时使用的缺陷系统')), + ('external_id', models.CharField(default='', max_length=64, verbose_name='缺陷系统中的缺陷ID')), + ('external_url', models.CharField(default='', max_length=255, verbose_name='缺陷系统中的缺陷链接')), + ('status', models.CharField(default='open', max_length=32, verbose_name='缺陷状态(平台内记录模式使用)')), + ('comments', models.JSONField(default=list, verbose_name='处理记录')), + ('title', models.CharField(max_length=255, verbose_name='标题')), + ('reporter', models.CharField(default='', max_length=64, verbose_name='创建者人')), + ('current_owner', models.CharField(default='', max_length=255, verbose_name='处理人')), + ('priority', models.IntegerField(choices=[(0, '空'), (1, '紧急'), (2, '高'), (3, '中'), (4, '低'), (5, '无关紧要')], default=0, verbose_name='优先级')), + ('severity', models.IntegerField(choices=[(0, '空'), (1, '致命'), (2, '严重'), (3, '一般'), (4, '提示'), (5, '建议')], default=0, verbose_name='严重程度')), + ('version_report', models.CharField(default='', max_length=64, verbose_name='发现版本')), + ('version_fix', models.CharField(default='', max_length=64, verbose_name='修复版本')), + ('release_id', models.CharField(default='', max_length=64, verbose_name='发布计划')), + ('description', models.TextField(default='', verbose_name='描述')), + ('job', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='job.job')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_bug', + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/models.py new file mode 100644 index 0000000000000000000000000000000000000000..eff0e7ecce7a733c71015e894e3b977a07ac9045 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/models.py @@ -0,0 +1,48 @@ +from django.db import models + +from libs import BaseAttrModel +from libs.defs import (BugPriorityEnum, BugSeverityEnum, BugBillStatusEnum, BugRegressStatusEnum, + BugTrackerTypeEnum) +from apps.job.models import Job +from apps.project.models import Project + + +class Bug(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + job = models.ForeignKey(Job, on_delete=models.DO_NOTHING) + image_id = models.IntegerField(default=0, verbose_name='image_id') + + # 提单状态 + bill_status = models.IntegerField(choices=BugBillStatusEnum, default=BugBillStatusEnum.INIT, verbose_name='提单结果') + bill_text = models.TextField(default='', verbose_name='提交bug返回的错误信息') + # 回归状态 + regress_status = models.IntegerField(choices=BugRegressStatusEnum, default=BugRegressStatusEnum.INIT) + regress_job_ids = models.JSONField(default=list, verbose_name="回归任务id") + + key_in_bug = models.TextField(default='', verbose_name='ai识别的结果') + celery_task_id = models.CharField(max_length=64, default='', verbose_name='celery_task id') + + raw_image_path = models.CharField(max_length=255, default='', verbose_name='原始图片路径') + ai_image_path = models.CharField(max_length=255, default='', verbose_name='AI识别返回的图片路径') + + # 缺陷系统 + tracker = models.CharField(max_length=16, choices=BugTrackerTypeEnum, default=BugTrackerTypeEnum.NONE, + verbose_name='提交时使用的缺陷系统') + external_id = models.CharField(max_length=64, default='', verbose_name='缺陷系统中的缺陷ID') + external_url = models.CharField(max_length=255, default='', verbose_name='缺陷系统中的缺陷链接') + status = models.CharField(max_length=32, default='open', verbose_name='缺陷状态(平台内记录模式使用)') + comments = models.JSONField(default=list, verbose_name='处理记录') + + title = models.CharField(max_length=255, verbose_name='标题') + reporter = models.CharField(max_length=64, default='', verbose_name='创建者人') + current_owner = models.CharField(max_length=255, default='', verbose_name='处理人') + priority = models.IntegerField(choices=BugPriorityEnum, default=BugPriorityEnum.EMPTY, verbose_name='优先级') + severity = models.IntegerField(choices=BugSeverityEnum, default=BugSeverityEnum.EMPTY, verbose_name='严重程度') + version_report = models.CharField(max_length=64, default='', verbose_name='发现版本') + version_fix = models.CharField(max_length=64, default='', verbose_name='修复版本') + release_id = models.CharField(max_length=64, default='', verbose_name='发布计划') + description = models.TextField(default='', verbose_name='描述') + + class Meta: + db_table = 'lqa_bug' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..cb95d7a3b62c10d09de69cb546aa0db75d69c73b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/schemas.py @@ -0,0 +1,81 @@ +from typing import List, Annotated, Optional, Dict + +import orjson +from pydantic import BaseModel, Field, AliasChoices, BeforeValidator, AfterValidator + +from libs.defs import BugSeverityEnum, BugPriorityEnum, BugRegressStatusEnum, BugTrackerTypeEnum +from libs import util +from apps.project import service as proj_svr + + +class BugBuildInfoSchema(BaseModel): + image_id: int = Field(gt=0) + project_id: int = Field(gt=0) + bug_types: Annotated[List[int], BeforeValidator(util.make_item_array_validator()), AfterValidator(proj_svr.BugTypeValidator())] = Field(default_factory=list) + + +class BugListSchema(BaseModel): + job_id: int = Field(ge=1) + image_id: int = Field(default=None, ge=1) + title__contains: str = Field(default=None, alias='title') + info_type: int = Field(default=0) # 0:同步缺陷系统中的最新状态 1:只取平台数据库中的数据 + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2, le=100) + + +class BugCreateSchema(BaseModel): + project_id: int + image_id: int + job_id: int + title: str = Field(min_length=3, max_length=255) + description: str = Field(min_length=3) + version_report: str = Field(default='') + release_id: str = Field(default='') + version_fix: str = Field(default='') + severity: BugSeverityEnum = Field(default=BugSeverityEnum.EMPTY) + priority: BugPriorityEnum = Field(default=BugPriorityEnum.EMPTY) + reporter: str = Field(min_length=1) + current_owner: str = Field(default='') + raw_image_path: Annotated[str, BeforeValidator(util.make_img_url_validator())] = Field(min_length=3) + ai_image_path: Annotated[str, BeforeValidator(util.make_img_url_validator())] = Field(min_length=3) + key_in_bug: str = Field(default='{}') + # 自定义提单字段 {field_key: 选中的值},会原样附加到缺陷系统的创建请求中 + custom_fields: Optional[Dict[str, str]] = Field(default=None, description="自定义字段 {field_key: value}") + + +class BugBatchCreateSchema(BaseModel): + project_id: int = Field(gt=0) + job_id: int = Field(gt=0) + image_ids: List[int] = Field(min_length=1) + bug_types: Annotated[List[int], AfterValidator(proj_svr.BugTypeValidator())] + version_report: str = Field(default='', description="发现版本") + version_fix: str = Field(default='', description="修复版本") + release_id: str = Field(default='', description="发布计划") + severity: BugSeverityEnum = Field(default=BugSeverityEnum.EMPTY) + priority: BugPriorityEnum = Field(default=BugPriorityEnum.EMPTY) + reporter: str = Field(default='') + + +class BugTrackerTestSchema(BaseModel): + """测试缺陷系统连接(使用表单中尚未保存的配置)""" + project_id: int = Field(gt=0) + tracker_type: str = Field(default='none') + base_url: str = Field(default='') + username: str = Field(default='') + api_key: str = Field(default='') + product: str = Field(default='') + component: str = Field(default='') + extra: Annotated[dict, BeforeValidator(lambda v: orjson.loads(v) if isinstance(v, str) and v.strip() else (v or {}))] = Field(default_factory=dict) + + +class BugBatchUpdateSchema(BaseModel): + bug_ids: List[int] = Field(min_length=1) + regress_status: BugRegressStatusEnum = Field(validation_alias=AliasChoices('regress_status', 'status')) + + +class BugExportSchema(BaseModel): + """导出当前任务下的缺陷单为 Excel""" + job_id: int = Field(gt=0) + image_id: int = Field(default=0, ge=0) + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/service.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/service.py new file mode 100644 index 0000000000000000000000000000000000000000..af7fe95a366886c2777fff6fcdf34b45e94a56d3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/service.py @@ -0,0 +1,684 @@ +import os + +import orjson +from munch import munchify, Munch as AttrDict +from django.template.loader import render_to_string, TemplateDoesNotExist +from django.template.loader import get_template + +from .schemas import BugCreateSchema +from apps.project import service as proj_svr +from apps.data.models import Data +from apps.image.models import Image +from apps.job.models import Job +from apps.user.models import User +from apps.project.models import Module, Project +from apps.bug.models import Bug +from libs import TaskBase, lodash, storage, bugtracker +from libs.defs import BugBillStatusEnum, BugRegressStatusEnum +from libs.util import coordinate_trans, datetime_ms + + +class BugBuildBase(object): + image_fields = ('id', 'project_id', 'data_id', 'ai_bug_types', 'ai_check_detail', 'language', 'file_name', 'job_id', + 'size', 'rect_location') + data_fields = ('id', 'project_id', 'job_id', 'module_id', 'device', 'resource_version') + project_fields = ('id', 'code', 'name') + + BUG_NAMES = {'1': '漏译', '2': '超框', '3': '漏key', '4': '标准框重叠', '5': '错译', '7': '非标准框', + '8': '错译(规则)', '9': '行高百分比', '10': '字体太小'} + + def __init__(self, image, data, config_bill): + self.image = image + self.data = data + self.config_bill = config_bill + + @classmethod + def filter_check_detail(cls, check_detail, allow_bug_types_set=None): + """根据 allow_bug_types_set 过滤需要用到的 check_detail""" + if isinstance(check_detail, str): + check_detail = orjson.loads(check_detail) + detail = {} + if not allow_bug_types_set or len(allow_bug_types_set) == 0: + allow_bug_types_set = set(list(cls.BUG_NAMES.keys())) + else: + allow_bug_types_set = set([str(i) for i in allow_bug_types_set]) + for k, v in check_detail.items(): + if k in allow_bug_types_set: + detail[k] = v + return detail + + @classmethod + def query_db(cls, cate, pks, fields=None, mapping=True, attrify=True): + """bug build 查表时从这里查 精确返回字段""" + if len(pks) == 0: + return {} if mapping else [] + if cate == 'image': + model, fields_ = Image, fields if fields else cls.image_fields + elif cate == 'data': + model, fields_ = Data, fields if fields else cls.data_fields + elif cate == 'module': + model, fields_ = Module, {} if mapping else [] + elif cate == 'project': + model, fields_ = Project, fields if fields else cls.project_fields + else: + raise Exception(f'not supported cate: {cate}') + + datas = model.objects.filter(pk__in=pks).values(*fields_) + if mapping: + return {d_['id']: AttrDict(d_) if attrify else d_ for d_ in datas} + else: + return [AttrDict(d_) if attrify else d_ for d_ in datas] + + def build_current_owner(self, req_bug_types=None, default=''): + """ + bug 处理人 + :param req_bug_types: 实际提单时的bug_types + :param default: + :return: user_names + """ + image, config_bill, data = self.image, self.config_bill, self.data + + if config_bill is None: + return default + config_bill = munchify(config_bill) + if not (config_bill.bug_type_enable or config_bill.language_enable or config_bill.module_enable): # 如果全部关闭返回默认 + return default + user_name_set = set() + + ai_bug_types, language, module_id = image.ai_bug_types, image.language, data.module_id if data else 0 + if req_bug_types is None: + req_bug_types = ai_bug_types + + for bill_item in config_bill.rows: + if bill_item.enable: + if config_bill.bug_type_enable and bill_item.get('bug_type', 0) not in req_bug_types: + continue + if config_bill.language_enable and bill_item.get('language', 0) != language: + continue + if config_bill.module_enable and bill_item.get('module', 0) != module_id: + continue + user_name_set.update(bill_item.user_names) + if len(user_name_set) == 0: + return default + return ','.join(user_name_set) + + +class BugBuildComm(BugBuildBase): + """通用描述生成器。description_tpl 最终渲染后记得replace掉\n""" + + description_tpl = """ +

+【测试机型】:%s
+【分辨率】:%s
+【图片ID】:%s
+【图片名称】:%s
+【任务ID】:%s
+【发生时间】:%s
+【操作步骤】
+%s
+
+【预期结果】
+%s
+
+【实际结果】
+%s +

+ """ + + def __init__(self, image, data, config_bill): + super(BugBuildComm, self).__init__(image, data, config_bill) + + def build_title(self, use_check_detail, version_report=''): + parts = self.image.file_name.split('_') + region = parts[-2] if len(parts) >= 2 else '' + prefix = '-'.join([p for p in (version_report.split('-')[0], region) if p]) + text_str = self.build_title_raw(use_check_detail) + return f"【{prefix}】【LQA】-{text_str}" if prefix else f"【LQA】-{text_str}" + + def build_title_raw(self, use_check_detail): + '''"英/日/俄/法" "模块1" 漏译/漏key/标准框重叠 key:"" ''' + text_list = [] + data1 = use_check_detail.get('1', []) # 漏译 + data2 = use_check_detail.get('2', {}) # 超框 + data3 = use_check_detail.get('3', []) # 漏key + data4 = use_check_detail.get('4', []) # 标准框重叠 + # 漏译 + if len(data1) > 0: + text_list.append("漏译") + # 超框 + data20 = data2.get("0", []) # 文本超文本框 + data21 = data2.get("1", []) # 文本超图像框 + if len(data20) > 0: + text_list.append("文本超文本框") + if len(data21) > 0: + text_list.append("文本超图像框") + if len(data3) > 0: + text_list.append("漏key") + if len(data4) > 0: + text_list.append("标准框重叠") + # 解决bug标题超长导致提单失败,方案只给一个md5和bug类型 + if "--" in str(use_check_detail): + text_str = 'MD5:' + str(use_check_detail).split("--")[1].split(",")[0] + '等多处{}问题'.format(text_list) + else: + start_index = str(use_check_detail).find('[') + if start_index != -1: + text_str = str(use_check_detail)[start_index:start_index + 20] + '、'.join(text_list) + else: + text_str = str(use_check_detail)[:10] + '、'.join(text_list) + return text_str + + def build_description(self, check_rect_detail, allow_lf=True): + """buid_description""" + image, data = self.image, self.data + phone_type = data.device.get('phone_type', '') if data and data.device else '' + screen_w = data.device.get('screen_w', 0) if data and data.device else 0 + screen_h = data.device.get('screen_h', 0) if data and data.device else 0 + resolution = f'{screen_w}x{screen_h}' if screen_w and screen_h else '' + image_id, image_name, job_id = image.id, image.file_name, image.job_id + setp = '通过图像识别判断页面是否存在漏译,漏key,超框问题' + expected_results = "页面是不存在漏译,漏key,超框问题" + + bug_descs, bug_keys = self.build_bug_items(check_rect_detail) + actual_results = bug_descs + description = self.description_tpl % (phone_type, resolution, image_id, image_name, job_id, datetime_ms(), setp, + expected_results, actual_results) + return description.replace('\n', ''), bug_keys + + def _build_bug_item(self, bugs, topic=''): + key_desc_list, key_list = [], [] + for bug in bugs: + key, rect = (bug[0], bug[1]) if isinstance(bug[0], str) else (bug[1], bug[0]) + key_desc = f'页面中【{key}】存在 {topic} 问题' + key_list.append(key) + key_desc_list.append(key_desc) + return key_desc_list, key_list + + def build_bug_items(self, use_check_detail): + if len(use_check_detail) == 0: + return '', [] + bugs_item_1 = use_check_detail.get('1', []), '漏译' # 漏译 + bugs_item_20 = use_check_detail.get('2', {}).get("0", []), '文本超文本框' # 超框:文本超文本框 + bugs_item_21 = use_check_detail.get('2', {}).get("1", []), '文本超图像框' # 超框:文本超图像框 + bugs_item_3 = use_check_detail.get('3', []), '漏key' # 漏key + bugs_item_4 = use_check_detail.get('4', []), '标准框重叠' # 标准框重叠 + bug_items = (bugs_item_1, bugs_item_20, bugs_item_21, bugs_item_3, bugs_item_4) + rets = list(map(lambda item: self._build_bug_item(item[0], item[1]), bug_items)) + bug_keys = {'1': rets[0][1], '2': {'0': rets[1][1], '1': rets[2][1]}, '3': rets[3][1], '4': rets[4][1]} + description = '' + for i, desc in enumerate(rets[0][0] + rets[1][0] + rets[2][0] + rets[3][0] + rets[4][0]): + description += f'{i + 1}.{desc}
' + return description, bug_keys + + +class BugBuildTpl(BugBuildBase): + """ + 基于模板的描述生成器:模板位于 apps/bug/templates/spec2/<项目代号小写>/, + 包含 report.tpl / bug_info.tpl / test_env.tpl,可参考 spec2/normal 自定义。 + """ + + def __init__(self, image, data, config_bill, module, config_language, project_info): + super(BugBuildTpl, self).__init__(image, data, config_bill) + self.module = module + self.config_language = config_language + self.project_info = project_info + + self.title_pre = f'【{project_info["name"]}】#本地化#' + + def build_title(self, use_check_detail, version_report=''): + """构建title""" + text_str = self.build_title_raw(use_check_detail) + return f"{self.title_pre} {text_str}" + + def build_title_raw(self, use_check_detail): + """ + 构建title 动态部分 + example: "英/日/俄/法" "模块1" 漏译/漏key/标准框重叠 key:"" + need config_language,module,image,job + """ + language_text = '' + if self.config_language: + for config_lan in self.config_language: + if self.image.language == config_lan['value']: + language_text = config_lan.get('custom_label', '') or config_lan.get('label', '') + module_text = self.module.name if self.module else '' + bug_type_names = set() + bug_text_keys = set() + ret = self._build_bug_items(use_check_detail) + for bug_key_str in ret['infos']: + if bug_key_str == '2': + for sub_bug_key_str in ret['infos'][bug_key_str]: + infos = ret['infos'][bug_key_str][sub_bug_key_str] + if len(infos) > 0: + bug_type_names.add(self.BUG_NAMES['2']) + for info in infos: + text_key, _, _, _, _ = info + if text_key: + bug_text_keys.add(text_key) + else: + infos = ret['infos'][bug_key_str] + if len(infos) > 0: + bug_type_names.add(self.BUG_NAMES[bug_key_str]) + for info in infos: + text_key, _, _, _, _ = info + if text_key: + bug_text_keys.add(text_key) + + bug_type_name_text = '/'.join(bug_type_names) + bug_key_text = ','.join(bug_text_keys) + return f'"{language_text}" "{module_text}" {bug_type_name_text} key:"{bug_key_text}"'[:100] + + def build_description(self, use_check_detail, allow_lf=True): + """need image data""" + bug_info, bug_keys = self.make_bug_items_context(use_check_detail) + ctx = { + 'test_env': {'version': self.data.resource_version}, + 'bug_info': bug_info + } + content = self._render_to_string('report.tpl', ctx, allow_lf) + return content, bug_keys + + def _matched_rect_extern_info(self, rect): + """need image""" + text_key, parent_widget, text_str, source_string, widget_name = '', '', '', '', '' + image = self.image + if not (image and hasattr(image, 'size')): + return text_key, text_str, source_string, parent_widget, widget_name + rect_locations_dict = getattr(image, 'rect_locations_dict', None) + if not rect_locations_dict: + height = int(image.size.split(',')[1]) + rect_locations = orjson.loads(image.rect_location).get('text', []) + rect_locations_dict = {} + for rect_location_text in rect_locations: + _, rect_ = coordinate_trans(rect_location_text['corners'], height) + rect_location_text['rect'] = rect_ + rect_locations_dict[rect_location_text['rect']] = rect_location_text + setattr(image, 'rect_locations_dict', rect_locations_dict) + rect_location = image.rect_locations_dict.get(tuple(rect), None) + if rect_location: + text_key = rect_location.get('TextKey', '') + text_str = rect_location.get('textStr', '') + source_string = rect_location.get('SourceString', '') + parent_widget = rect_location.get('ParentWidget', '') + widget_name = rect_location.get('WidgetName', '') + return text_key, text_str, source_string, parent_widget, widget_name + + def _build_bug_item(self, bugs, bug_type): + """need image""" + infos, key_list = [], [] + + def __get_rect_extern_info(bug_): + key, rect = (bug_[0], bug_[1]) if isinstance(bug_[0], str) else (bug_[1], bug_[0]) + info = self._matched_rect_extern_info(rect) + key_list.append(key) + infos.append(info) + + for bug in bugs: + if bug_type == '4': + for bug1 in bug: + __get_rect_extern_info(bug1) + else: + __get_rect_extern_info(bug) + return infos, key_list + + def _build_bug_items(self, use_check_detail): + bugs_item_1 = use_check_detail.get('1', []), '1' # 漏译 + bugs_item_20 = use_check_detail.get('2', {}).get("0", []), '20' # 超框:文本超文本框 + bugs_item_21 = use_check_detail.get('2', {}).get("1", []), '21' # 超框:文本超图像框 + bugs_item_3 = use_check_detail.get('3', []), '3' # 漏key + bugs_item_4 = use_check_detail.get('4', []), '4' # 标准框重叠 + bugs_item_5 = use_check_detail.get('5', []), '5' # 错译 + bugs_item_7 = use_check_detail.get('7', []), '7' # 非标准框 + bugs_item_8 = use_check_detail.get('8', []), '8' # 错译(规则) + bugs_item_9 = use_check_detail.get('9', []), '9' # 行高百分比 + bugs_item_10 = use_check_detail.get('10', []), '10' # 字体太小 + bug_items = (bugs_item_1, bugs_item_20, bugs_item_21, bugs_item_3, bugs_item_4, bugs_item_5, bugs_item_7, + bugs_item_8, bugs_item_9, bugs_item_10) + rets = list(map(lambda item: self._build_bug_item(item[0], item[1]), bug_items)) + bug_keys = {'1': rets[0][1], '2': {'0': rets[1][1], '1': rets[2][1]}, '3': rets[3][1], '4': rets[4][1], + '5': rets[5][1], '7': rets[6][1], '8': rets[7][1], '9': rets[8][1], '10': rets[9][1]} + infos = {'1': rets[0][0], '2': {'0': rets[1][0], '1': rets[2][0]}, '3': rets[3][0], '4': rets[4][0], + '5': rets[5][0], '7': rets[6][0], '8': rets[7][0], '9': rets[8][0], '10': rets[9][0]} + return {'infos': infos, 'bug_keys': bug_keys} + + def build_bug_items(self, use_check_detail): + bug_info, bug_keys = self.make_bug_items_context(use_check_detail) + content = self._render_to_string('bug_info.tpl', {'bug_info': bug_info}, False) + return content, bug_keys + + def make_bug_items_context(self, use_check_detail): + context = {} + ret = self._build_bug_items(use_check_detail) + bug_keys, infos = ret['bug_keys'], ret['infos'] + all_infos = (infos['1'] + infos['2']['0'] + infos['2']['1'] + infos['3'] + infos['4'] + infos['5'] + infos['7'] + + infos['8'] + infos['9'] + infos['10']) + + context['bug_type_names'] = [self.BUG_NAMES[but_type_str] for but_type_str in use_check_detail] + items = ([], [], [], [], []) + distinct_dict = {} + for _, info in enumerate(all_infos): + # text_key, text_str, source_string, parent_widget, widget_names = info # 顺序不要改动 + if not info[1]: # 去空字符串 + continue + unin_key = f'{info[0]}_{info[1]}' + if unin_key in distinct_dict: # 去重 + continue + distinct_dict[unin_key] = 1 + for j, ele_str in enumerate(info): + items[j].append(ele_str) + context['text_keys'] = items[0] + context['text_strs'] = items[1] + context['source_strings'] = items[2] + context['parent_widgets'] = items[3] + context['widget_names'] = items[4] + return context, bug_keys + + def _render_to_string(self, tpl, ctx, allow_lf=True): + spec_name = self.project_info['code'].lower() + try: + content = render_to_string(f'spec2/{spec_name}/{tpl}', ctx) + except TemplateDoesNotExist: + content = render_to_string(f'spec2/normal/{tpl}', ctx) + if not allow_lf: + content = content.replace('\n', '') + return content + + +def has_custom_template(project_info) -> bool: + """项目是否在 templates/spec2// 下提供了自定义提单模板""" + if not project_info: + return False + try: + get_template(f'spec2/{project_info["code"].lower()}/report.tpl') + return True + except TemplateDoesNotExist: + return False + + +def make_builder(image, data, config_bill, project_info, module=None, config_language=None): + """有自定义模板的项目使用模板生成器,否则使用通用生成器""" + if has_custom_template(project_info): + if config_language is None: + config_language = proj_svr.ProjCfgService.get_language(project_info['id']) + return BugBuildTpl(image, data, config_bill, module, config_language, project_info) + return BugBuildComm(image, data, config_bill) + + +def _make_payload(bug: Bug, custom_fields) -> bugtracker.BugPayload: + return bugtracker.BugPayload( + lqa_bug_id=bug.id, + title=bug.title, + description=bug.description, + priority=int(bug.priority or 0), + severity=int(bug.severity or 0), + version_report=bug.version_report, + version_fix=bug.version_fix, + release_id=bug.release_id, + assignees=[n.strip() for n in (bug.current_owner or '').split(',') if n.strip()], + reporter=bug.reporter, + custom_fields=custom_fields or {}, + ) + + +class CreateBugTask(TaskBase): + """创建bug:先写入平台数据库,再提交到项目配置的缺陷系统。可前后台执行""" + def run(self): + self.logger.info(f'CreateBugTask.run ctx:{orjson.dumps(self.ctx).decode()}') + bug_create_body = BugCreateSchema.model_validate(self.ctx).model_dump(exclude_unset=True) + custom_fields = bug_create_body.pop('custom_fields', None) + project_id = bug_create_body['project_id'] + + try: + tracker = bugtracker.get_tracker(project_id) + except bugtracker.BugTrackerError as err: + self.logger.error(f'get_tracker project:{project_id} err: {err}') + return str(err), None + + bug_create_body['bill_status'] = BugBillStatusEnum.INIT + bug_create_body['tracker'] = tracker.type + bug = Bug.objects.create(**bug_create_body) + self.logger.info(f'[event.bug.add] bug_id:{bug.id} image_id:{bug.image_id} tracker:{tracker.type}') + + # 只上传还原截图(不上传检测结果图) + attachments = [storage.get_abs_path(bug.raw_image_path)] if bug.raw_image_path else [] + attachments = [p for p in attachments if os.path.exists(p)] + mapping = {'bill_text': ''} + try: + external_id = tracker.create_bug(_make_payload(bug, custom_fields), attachments) + mapping.update(external_id=external_id, external_url=tracker.bug_url(external_id), + bill_status=BugBillStatusEnum.SUCCESS) + except Exception as err: + self.logger.error(f'tracker create_bug bug_id:{bug.id} err: {err}', exc_info=err) + mapping.update(bill_status=BugBillStatusEnum.FAILED, bill_text=str(err)[:2000]) + Bug.update_db(bug.id, mapping) + self.logger.info(f'[event.tracker_bug.add] bug_id:{bug.id} external_id:{mapping.get("external_id")}') + return mapping['bill_text'], bug + + +def prepare_create_bug_task_ctx_by_custom(vmi): + """人工提单""" + return '', vmi.model_dump() + + +def _bug_build_info_auto(bug_body, req_bug_types_set, image, data, config_bill, staff, + project_info, config_language, module): + """自动提单 + return err_msg, bug_body + """ + # 兜底:图片未完成 AI 识别 / 抽帧失败 / AI 返回异常时,ai_check_detail 可能为空字符串或非法 JSON + # 直接 orjson.loads('') 会抛 "Input is a zero-length, empty document",前端只能看到英文异常, + # 这里转换成友好的中文错误,调用方会把该 image_id 放进 failed 列表并原样展示给用户。 + raw_detail = image.ai_check_detail or '' + if not raw_detail.strip(): + return '图片未完成 AI 识别或抽帧失败,无法提单', {'image_id': image.id} + try: + ai_check_detail = orjson.loads(raw_detail) + except (ValueError, orjson.JSONDecodeError) as err: + return f'图片 AI 识别结果不是合法 JSON,无法提单: {err}', {'image_id': image.id} + use_check_detail = BugBuildBase.filter_check_detail(ai_check_detail, req_bug_types_set) + if len(use_check_detail) == 0: + return f'use_check_detail is empty', {'image_id': image.id} + + builder = make_builder(image, data, config_bill, project_info, module, config_language) + title = builder.build_title(use_check_detail, bug_body.get('version_report', '')) + + current_owner = builder.build_current_owner(use_check_detail, staff) + description, bug_keys = builder.build_description(use_check_detail, False) + bug_body.update({ + 'project_id': image.project_id, + 'image_id': image.id, + 'title': title, + 'description': description, + 'current_owner': current_owner, + 'raw_image_path': image.file_path, + 'ai_image_path': image.ai_mark_img_path, + 'key_in_bug': orjson.dumps(bug_keys).decode() + }) + BugCreateSchema.model_validate(bug_body) + return '', bug_body + + +def prepare_create_bug_task_ctx_by_batch(vmi, images, data_dict, config_bill, staff, + project_info, config_language, module_dict): + """自动提单:批量提单""" + req_bug_types_set = set(vmi.bug_types) # 希望提单的bug类型 + bug_bodys = [] + for image_ in images: + try: + data = data_dict.get(image_.data_id, None) + if not data: + bug_bodys.append((f'not found data:{image_.data_id}', {'image_id': image_.id})) + continue + module = module_dict.get(data.module_id, None) + bug_body = vmi.model_dump(include={'job_id', 'version_report', 'release_id', + 'version_fix', 'severity', 'priority', 'reporter'}) + if bug_body['job_id'] == 0: + bug_body['job_id'] = image_.job_id + if not bug_body.get('reporter'): + bug_body['reporter'] = staff + bug_info = _bug_build_info_auto(bug_body, req_bug_types_set, image_, data, config_bill, staff, + project_info, config_language, module) + bug_bodys.append(bug_info) + except Exception as err: + bug_bodys.append((str(err), {'image_id': image_.id})) + return bug_bodys + + +def prepare_create_bug_task_ctx_by_ai_sign(image_id): + """自动提单:ai识别后提单 + return err_msg, bug_body + """ + image = Image.objects.filter(pk=image_id).first() + data = BugBuildBase.query_db('data', (image.data_id,)).get(image.data_id, None) + if not data: + return f'not fund data: {image.data_id}', {} + job = Job.objects.filter(pk=image.job_id).first() + user = User.objects.filter(pk=job.creator_id).values().first() + project_info = BugBuildBase.query_db('project', (image.project_id, )).get(image.project_id, None) + config_bill = proj_svr.ProjCfgService.get_bill(image.project_id) + + bug_body = lodash.pick(image, ['project_id', 'job_id']) + body2 = lodash.pick(job, ['version_report', 'release_id', 'version_fix', 'severity', 'priority']) + bug_body.update(body2) + bug_body['reporter'] = user['name'] # 由于ai识别提交接口无法知道用户是谁,所以使用job创建者替代 + + req_bug_types_set = set(job.bill_bug_types) + module = None + if has_custom_template(project_info) and data.module_id: + module = BugBuildBase.query_db('module', (data.module_id,)).get(data.module_id, None) + return _bug_build_info_auto(bug_body, req_bug_types_set, image, data, config_bill, user['name'], + project_info, None, module) + + +class UpdateBugByRegressedImageService(TaskBase): + """场景:bug回归任务,在编辑器还原完成后,上传图片,然后更新平台与缺陷系统中的缺陷状态""" + + def _get_open_bugs(self, tracker, job_id, image_id, req_bug_ids): + """获取到所有需要回归 且 未关闭的bug信息 [(local_bug_dict, TrackerBug)]""" + bugs = list(Bug.objects.filter(job_id=job_id, image_id=image_id, pk__in=req_bug_ids).values()) + if len(bugs) == 0: + self.logger.warning(f'_get_open_bugs empty, req_bug_ids:{req_bug_ids}') + return [] + valid_bugs = [] + for bug in bugs: + if bug['tracker'] != tracker.type or not bug['external_id']: + self.logger.warning(f'bug:{bug["id"]} tracker:{bug["tracker"]} external_id:{bug["external_id"]} ' + f'与当前缺陷系统({tracker.type})不一致或未成功提单,跳过') + Bug.update_db(bug['id'], {'regress_status': BugRegressStatusEnum.FAILED}) + continue + valid_bugs.append(bug) + tracker_bugs = tracker.get_bugs([b['external_id'] for b in valid_bugs]) + ret = [] + for bug in valid_bugs: + tracker_bug = tracker_bugs.get(bug['external_id']) + if tracker_bug and tracker_bug.is_open: + ret.append((bug, tracker_bug)) + return ret + + def run(self): + """ + 1.查找到父任务的image + 2.根据image找到关联的bug列表(一个image可以提交多个bug单) + 3.根据当前最新bug_types和bug的bug_types对比,是否关闭还是重新打开缺陷 + image_id: 当前还原任务的image_id + bug_ids: 编辑器调用上传图片时传入 + """ + image_id, bug_ids = self.ctx['image_id'], self.ctx['bug_ids'] + self.logger.info(f'UpdateBugByRegressedImageService.run image_id:{image_id} bug_ids:{bug_ids}') + + stats = [] + image = Image.objects.filter(pk=image_id).first() + job_info = Job.objects.filter(pk=image.job_id).values('id', 'parent_id').first() + job_id, job_parent_id = job_info['id'], job_info['parent_id'] + if job_parent_id == 0: + err_msg = f'job:{job_id} parend_id is 0' + self.logger.error(err_msg) + return 1, err_msg, stats + if not Job.objects.filter(pk=job_parent_id).exists(): + err_msg = f'job_parent:{job_parent_id} not exist' + self.logger.error(err_msg) + return 2, err_msg, stats + image_parent = Image.objects.filter(job_id=job_parent_id, data_id=image.data_id, language=image.language)\ + .first() + if image_parent is None: + err_msg = f'image_parent not found, job_id:{job_parent_id} data_id:{image.data_id}' + self.logger.error(err_msg) + return 3, err_msg, stats + + tracker = bugtracker.get_tracker(image.project_id) + open_bugs = self._get_open_bugs(tracker, job_parent_id, image_parent.id, bug_ids) + if len(open_bugs) == 0: + self.logger.warning(f'opened bugs is empty, update_db bug_ids:{bug_ids}') + Bug.objects.filter(pk__in=bug_ids, regress_status=BugRegressStatusEnum.RUNNING)\ + .update(regress_status=BugRegressStatusEnum.SUCCESS, updated_at=datetime_ms()) + return 0, 'opened bugs is empty', stats + + req_bug_types_set = set(image.ai_bug_types) + bugs_reopen = [] + bugs_closed = [] + for bug, tracker_bug in open_bugs: + key_in_bug = orjson.loads(bug['key_in_bug']) if bug['key_in_bug'] else {} + bug_types_set = set(map(int, key_in_bug.keys())) + merged_bug_types_set = req_bug_types_set.intersection(bug_types_set) + bug['tracker_bug'] = tracker_bug + if len(merged_bug_types_set) == 0: + bugs_closed.append(bug) + else: + bug['merged_bug_types_set'] = merged_bug_types_set + bugs_reopen.append(bug) + + self._update_bugs_closed(tracker, bugs_closed, stats) + + project_info = Project.objects.filter(pk=image.project_id).values().first() + self._update_bugs_reopen(tracker, bugs_reopen, image, project_info, stats) + + return 0, '', stats + + def _update_bugs_closed(self, tracker, bugs, stats): + for bug in bugs: + external_id = bug['external_id'] + try: + tracker.close_bug(external_id, '本地化工具回归验证通过,自动关闭') + Bug.update_db(bug['id'], {'regress_status': BugRegressStatusEnum.SUCCESS, 'status': 'closed'}) + stats.append(('close', bug['id'], external_id, 'suc')) + except Exception as err: + self.logger.error(f'_update_bugs_closed bug_id:{bug["id"]} err: {err}') + Bug.update_db(bug['id'], {'regress_status': BugRegressStatusEnum.FAILED}) + stats.append(('close', bug['id'], external_id, 'fail')) + + def _update_bugs_reopen(self, tracker, bugs, image, project_info, stats): + if len(bugs) == 0: + return + image_ids = list(map(lambda bug_: bug_['image_id'], bugs)) + image_old_map = BugBuildBase.query_db('image', image_ids) + + for bug in bugs: + external_id = bug['external_id'] + try: + self._update_bug_reopen(tracker, bug, image, project_info, image_old_map) + Bug.update_db(bug['id'], {'regress_status': BugRegressStatusEnum.SUCCESS, 'status': 'open'}) + stats.append(('reopen', bug['id'], external_id, 'suc')) + except Exception as err: + self.logger.error(f'_update_bugs_reopen bug_id:{bug["id"]} err: {err}') + Bug.update_db(bug['id'], {'regress_status': BugRegressStatusEnum.FAILED}) + stats.append(('reopen', bug['id'], external_id, 'fail')) + + def _update_bug_reopen(self, tracker, bug, image, project_info, image_old_map): + tracker_bug = bug['tracker_bug'] + version_report = bug['version_report'] + merged_bug_types_set = bug['merged_bug_types_set'] + + ai_check_detail = orjson.loads(image.ai_check_detail) + use_check_detail = BugBuildBase.filter_check_detail(ai_check_detail, merged_bug_types_set) + image_ = image_old_map.get(bug['image_id'], None) + if not image_: + raise Exception(f'not found old image:{bug["image_id"]}') + if has_custom_template(project_info): + description, _ = BugBuildTpl(image_, None, None, None, None, project_info).build_bug_items(use_check_detail) + else: + description, _ = BugBuildComm(image_, None, None).build_bug_items(use_check_detail) + + attachments = [storage.get_abs_path(image.ai_mark_img_path)] if image.ai_mark_img_path else [] + comment = f"

基于{version_report or '最新'}版本回归验证不通过

{description}" + # 优先指派给解决人,其次当前处理人 + assignee = tracker_bug.resolver or tracker_bug.assignee + tracker.reopen_bug(bug['external_id'], comment, attachments, assignee) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/tasks.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..d566dfa109e9ca8a970b0e5e4450eeae82097335 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/tasks.py @@ -0,0 +1,15 @@ +from celery.utils.log import get_task_logger + +from celery_app import app as celery_app +from .service import CreateBugTask + +logger = get_task_logger(__name__) + + +@celery_app.task(bind=True, ignore_result=True, queue='lqa_queue_bug') +def run_bug_create(self, ctx): + """启动任务""" + logger.info(f'run_bug_create start') + task = CreateBugTask(ctx, self, logger) + task.run() + logger.info(f'run_bug_create end') diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/bug_info.tpl b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/bug_info.tpl new file mode 100644 index 0000000000000000000000000000000000000000..27607fdc53fddac481cfdc9a344a4c7157d75467 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/bug_info.tpl @@ -0,0 +1,46 @@ +

【缺陷情况】

+
+

缺陷描述(必填): {{ bug_info.bug_type_names|join:"/" }}

+
+ +

修复建议:

+
+ +

中文文本内容(SourceString)(必填,文本缺失填”空“)

+ {% for source_string in bug_info.source_strings %} +

{{forloop.counter}}、{{source_string}}

+ {% endfor %} +
+ +

文本内容(textStr)(必填,文本缺失填”空“):

+ {% for text_str in bug_info.text_strs %} +

{{forloop.counter}}、{{text_str}}

+ {% endfor %} +
+ +

文本key(TextKey)(必填):

+ {% for text_key in bug_info.text_keys %} +

{{forloop.counter}}、{{text_key}}

+ {% endfor %} +
+ +

文本控件名(WidgetName)(必填):

+ {% for widget_name in bug_info.widget_names %} +

{{forloop.counter}}、{{widget_name}}

+ {% endfor %} +
+ +

【文本所处蓝图 ParentWidget】

+ {% for parent_widget in bug_info.parent_widgets %} +

{{forloop.counter}}、{{parent_widget}}

+ {% endfor %} +
+ +

复现步骤(选填):

+
+ +

缺陷详情(必填): +
+ 游戏界面截图 +

+
\ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/report.tpl b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/report.tpl new file mode 100644 index 0000000000000000000000000000000000000000..1d7b3500c4043b8d1c3520abafe130961a1f57b4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/report.tpl @@ -0,0 +1,2 @@ +{% include "./test_env.tpl" %} +{% include "./bug_info.tpl" %} \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/test_env.tpl b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/test_env.tpl new file mode 100644 index 0000000000000000000000000000000000000000..9093d2c63344e80cd3480a9b54cbf5dd1c86d49c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/templates/spec2/normal/test_env.tpl @@ -0,0 +1,5 @@ +

【测试环境】

+

测试机型(必填):PC

+

测试版本:{{test_env.version}}

+

服务器(必填):

+

帐号(必填):

\ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..79ce82c2918cbba4be7dae70211d9cd1e26e2d2e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/urls.py @@ -0,0 +1,15 @@ + +from django.urls import path + +from .views import * + +urlpatterns = [ + path('entity', BugView.as_view(), name='bug'), + path('list', BugListView.as_view(), name='bug-list'), + + path('build_info', view_bug_build_info, name='bug_build_info'), + path('tracker_meta', view_tracker_meta, name='tracker_meta'), + path('tracker_fields', view_tracker_fields, name='tracker_fields'), + path('tracker_test', view_tracker_test, name='tracker_test'), + path('export_excel', view_bug_export_excel, name='bug_export_excel'), +] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/bug/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/bug/views.py new file mode 100644 index 0000000000000000000000000000000000000000..2d69dd47bf5fa4a432900bd89248345b287167f5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/bug/views.py @@ -0,0 +1,343 @@ +import logging + +import orjson +from django.views.generic import View +from django.utils.decorators import method_decorator + +from libs import ApiResponse, PageView, lodash, bugtracker +from libs.util import time_ms +from libs.defs import ApiErrorEnum, RoleEnum +from libs.decorators import require_project_perm +from apps.image.models import Image +from apps.project.models import Project +from apps.project import service as proj_svr +from apps.bug.tasks import run_bug_create +from apps.bug.models import Bug +from apps.bug import service as bug_svr +from .schemas import * + +logger = logging.getLogger('bug_view') + +SECRET_MASK = '******' + + +def _project_id_param(request): + try: + return int(request.GET.get('project_id', 0)) + except ValueError: + return 0 + + +@require_project_perm() +def view_tracker_meta(request): + """当前项目缺陷系统信息及提单下拉选项 GET /api/bug/tracker_meta?project_id= """ + project_id = _project_id_param(request) + data = {'type': 'none', 'label': '', 'remote': False, 'enabled': True, + 'version_report_list': [], 'version_fix_list': [], 'release_id_list': [], 'error': ''} + try: + tracker = bugtracker.get_tracker(project_id) + data.update(type=tracker.type, label=tracker.label, remote=tracker.remote) + data.update(tracker.get_options()) + except bugtracker.BugTrackerError as err: + logger.warning(f'view_tracker_meta project:{project_id} err: {err}') + data['error'] = str(err) + return ApiResponse(data=data) + + +@require_project_perm() +def view_tracker_fields(request): + """缺陷系统中可作为“自定义提单字段”的字段及选项 GET /api/bug/tracker_fields?project_id= """ + project_id = _project_id_param(request) + try: + tracker = bugtracker.get_tracker(project_id) + return ApiResponse(data={'fields': tracker.get_fields(), 'type': tracker.type}) + except bugtracker.BugTrackerError as err: + return ApiResponse(ApiErrorEnum.ERROR, msg=str(err)) + + +@require_project_perm(RoleEnum.ADMIN) +def view_tracker_test(request): + """测试缺陷系统连接 POST /api/bug/tracker_test """ + vmi = BugTrackerTestSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + config = vmi.model_dump() + if config['api_key'] == SECRET_MASK: # 未修改密钥,使用已保存的 + saved = proj_svr.ProjCfgService.get_bug_tracker(vmi.project_id) or {} + config['api_key'] = saved.get('api_key', '') + try: + tracker = bugtracker.get_tracker(vmi.project_id, config) + return ApiResponse(msg=tracker.test_connection()) + except bugtracker.BugTrackerError as err: + return ApiResponse(ApiErrorEnum.ERROR, msg=str(err)) + + +@require_project_perm() +def view_bug_build_info(request): + """网页单个提单时,build提单内容 GET /api/bug/build_info """ + vmi = BugBuildInfoSchema.model_validate(request.GET.dict()) + image_id, project_id, bug_types = vmi.image_id, vmi.project_id, vmi.bug_types + + image = bug_svr.BugBuildBase.query_db('image', (image_id,)).get(image_id, None) + if not image or (image and image.project_id != project_id): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'未找到image_id:{image_id},请确认是否已删除') + + bug_types_set = set([str(bug_type_) for bug_type_ in bug_types]) + use_check_detail = bug_svr.BugBuildBase.filter_check_detail(image.ai_check_detail, bug_types_set) + if len(use_check_detail) == 0: + logger.warning(f'view_bug_build_info {len(image.ai_check_detail)} bug_types_set:{bug_types_set}') + return ApiResponse(ApiErrorEnum.ERROR, msg=f'没有有效的bug信息,请检查提单bug类型是否包含实际检测出的bug类型') + + project_info = bug_svr.BugBuildBase.query_db('project', (project_id,)).get(project_id, None) + + config_bill = proj_svr.ProjCfgService.get_bill(project_id) + if not config_bill: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'未找到项目提单project_id:{project_id},请完善提单配置') + + data = bug_svr.BugBuildBase.query_db('data', (image.data_id,)).get(image.data_id, None) + if not data: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'未找到data_id:{image.data_id},请确认是否已删除') + + version_report = '' + module = None + if bug_svr.has_custom_template(project_info): + module = bug_svr.BugBuildBase.query_db('module', (data.module_id,)).get(data.module_id, None) + version_report = data.resource_version + builder = bug_svr.make_builder(image, data, config_bill, project_info, module) + + description, bug_keys = builder.build_description(use_check_detail) + resp = { + 'title': builder.build_title_raw(use_check_detail), + 'description': description, + 'bug_keys': bug_keys, + 'current_owner': builder.build_current_owner(bug_types, default=request.user['name']), + 'title_pre': getattr(builder, 'title_pre', ''), + 'version_report': version_report + } + return ApiResponse(data=resp) + + +class BugView(View): + @method_decorator(require_project_perm()) + def post(self, request): + """提单个bug POST /api/bug/entity """ + vmi = BugCreateSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + image_id = vmi.image_id + + err, ctx = bug_svr.prepare_create_bug_task_ctx_by_custom(vmi) + if err: + return ApiResponse(ApiErrorEnum.ERROR, msg=err) + event = 'event.run_bug_create_0' + ctx['_event'] = event + try: + task = run_bug_create.apply_async((ctx,)) # 创建bug + logger.info(f'[{event}] task_id:{task.task_id} image_id:{image_id}') + return ApiResponse(data={'task': task.task_id}) + except Exception as err: + return ApiResponse(ApiErrorEnum.ERROR, msg=str(err)) + + +class BugListView(PageView): + Query_Fields = ('job_id', 'image_id', 'cur_id', 'title__contains') + Output_Fields = ('id', 'project_id', 'job_id', 'image_id', 'title', 'priority', 'severity', 'reporter', + 'current_owner', 'version_report', 'version_fix', 'release_id', 'created_at', 'updated_at', + 'tracker', 'external_id', 'external_url', 'status', 'bill_status', 'bill_text', + 'regress_status', 'regress_job_ids') + + def get(self, request): + """bug列表 GET /api/bug/list """ + vmi = BugListSchema.model_validate(request.GET.dict()) + + job_id, image_id, info_type, page, page_size = vmi.job_id, vmi.image_id, vmi.info_type, vmi.page, vmi.page_size + if not (job_id or image_id): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='job_id和image_id不能同时为空') + + param = self.make_query_params(vmi) + resp_data = {'list': [], 'total': 0, 'page': page, 'page_size': page_size} + t1 = time_ms() + total, bugs = self.page_query(Bug, param, page, page_size) + if info_type == 1 or len(bugs) == 0: + resp_data.update(total=total, list=bugs) + return ApiResponse(data=resp_data) + + project_id = bugs[0]['project_id'] + if not test_project_member(request.user, project_id): + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='没有该项目的权限') + + datas = [lodash.pick(bug, self.Output_Fields) for bug in bugs] + msg = '' + try: + tracker = bugtracker.get_tracker(project_id) + ids = [b['external_id'] for b in datas if b['tracker'] == tracker.type and b['external_id']] + tracker_bugs = tracker.get_bugs(ids) if ids else {} + for bug_ in datas: + bug_['tracker_status'] = '' + bug_['tracker_open'] = bug_['status'] != 'closed' + bug_['is_delete'] = 0 + if bug_['tracker'] != tracker.type or not bug_['external_id']: + continue + tracker_bug = tracker_bugs.get(bug_['external_id']) + if not tracker_bug: + bug_['is_delete'] = 1 # 缺陷系统中已不存在 + continue + bug_['tracker_status'] = tracker_bug.status + bug_['tracker_open'] = tracker_bug.is_open + if tracker_bug.assignee: + bug_['current_owner'] = tracker_bug.assignee + if tracker_bug.url: + bug_['external_url'] = tracker_bug.url + except bugtracker.BugTrackerError as err: + logger.warning(f'BugListView sync tracker err: {err}') + msg = f'同步缺陷系统状态失败: {err}' + resp_data.update(total=total, list=datas) + return ApiResponse(data=resp_data, msg=msg or f'cost:{time_ms() - t1}') + + @method_decorator(require_project_perm()) + def post(self, request): + """批量提交bug POST /api/bug/list """ + vmi = BugBatchCreateSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + image_ids, job_id = vmi.image_ids, vmi.job_id + + images = Image.objects.filter(pk__in=image_ids, job_id=job_id, project_id=vmi.project_id) + if len(images) != len(image_ids): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='存在无效的image_ids,请检查') + data_ids = list(map(lambda image_: image_.data_id, images)) + project_id = images[0].project_id + project_info = Project.objects.filter(pk=project_id).values().first() + if not project_info: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'未找到 project_info:{project_id}') + config_bill = proj_svr.ProjCfgService.get_bill(project_id) + data_dict = bug_svr.BugBuildBase.query_db('data', data_ids) + staff = request.user['name'] + + module_dict = {} + if bug_svr.has_custom_template(project_info): + module_ids = [0 if data_['module_id'] is None else data_['module_id'] for data_ in data_dict.values()] + module_dict = bug_svr.BugBuildBase.query_db('module', module_ids) + + stat = {'success': [], 'failed': []} + items = bug_svr.prepare_create_bug_task_ctx_by_batch(vmi, images, data_dict, config_bill, staff, + project_info, None, module_dict) + for err_msg, ctx in items: + if err_msg: + stat['failed'].append((ctx['image_id'], err_msg)) + else: + task = run_bug_create.apply_async((ctx,)) # 批量创建bug + logger.info(f'[event.run_bug_create] at:1 task_id:{task.task_id} image_id:{ctx["image_id"]}') + stat['success'].append(ctx['image_id']) + code = ApiErrorEnum.ERROR if len(stat['success']) == 0 else 0 + return ApiResponse(code, msg=f'提交失败 {stat}' if code else '', data=stat) + + def patch(self, request): + """批量更新 PATCH /api/bug/list """ + vmi = BugBatchUpdateSchema.model_validate(orjson.loads(request.body)) + project_ids = set(Bug.objects.filter(pk__in=vmi.bug_ids).values_list('project_id', flat=True)) + if not all(test_project_member(request.user, pid) for pid in project_ids): + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='没有该项目的权限') + count = Bug.update_db(vmi.bug_ids, {'regress_status': vmi.regress_status}) + return ApiResponse(data={'count': count}) + + +def test_project_member(user, project_id): + from libs.decorators import test_project_user_role_by_project_id + return test_project_user_role_by_project_id(user, project_id) + + +# -------- 枚举 → 中文显示(与前端 /api/system/enums 口径保持一致) -------- +_SEVERITY_LABELS = dict(BugSeverityEnum.choices) +_TRACKER_LABELS = dict(BugTrackerTypeEnum.choices) + + +def _calc_regress_text(bug: dict) -> str: + """与前端 bugs/crud.js human_local_bug_status 逻辑保持一致(后端拿不到 tracker 实时状态时,用 Bug.status 近似判定 closed)""" + regress_status = bug.get('regress_status') + is_closed = bug.get('status') == 'closed' + if regress_status == BugRegressStatusEnum.INIT: + return '无需回归' if is_closed else '等待回归' + if regress_status == BugRegressStatusEnum.RUNNING: + return '回归中' + if regress_status == BugRegressStatusEnum.SUCCESS: + return '回归成功' + if regress_status == BugRegressStatusEnum.FAILED: + return '回归失败' + return '' + + +@require_project_perm() +def view_bug_export_excel(request): + """导出当前任务下的缺陷单为 Excel GET /api/bug/export_excel?job_id=&image_id= """ + from io import BytesIO + from django.http import HttpResponse + from openpyxl import Workbook + from openpyxl.styles import Font, Alignment, PatternFill + from urllib.parse import quote + + try: + vmi = BugExportSchema.model_validate(request.GET.dict()) + qs = Bug.objects.filter(job_id=vmi.job_id) + if vmi.image_id: + qs = qs.filter(image_id=vmi.image_id) + bugs = list(qs.values('id', 'project_id', 'title', 'severity', 'tracker', 'current_owner', + 'regress_status', 'status', 'external_url')) + + if not bugs: + return ApiResponse(ApiErrorEnum.ERROR, msg='当前任务下没有可导出的缺陷单') + + # 权限校验:导出的缺陷必须都属于同一个项目,且用户是该项目成员 + project_id = bugs[0]['project_id'] + if not test_project_member(request.user, project_id): + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='没有该项目的权限') + + # 构造 Excel + wb = Workbook() + ws = wb.active + ws.title = '缺陷列表' + + headers = ['标题', '严重程度', '缺陷系统', '处理人', '回归状态'] + ws.append(headers) + + header_font = Font(bold=True, color='FFFFFFFF') + header_fill = PatternFill('solid', fgColor='FF409EFF') + header_align = Alignment(horizontal='center', vertical='center') + for cell in ws[1]: + cell.font = header_font + cell.fill = header_fill + cell.alignment = header_align + + link_font = Font(color='FF0066CC', underline='single') + center_align = Alignment(horizontal='center', vertical='center', wrap_text=True) + + for bug in bugs: + row_idx = ws.max_row + 1 + title_cell = ws.cell(row=row_idx, column=1, value=bug['title'] or '') + if bug.get('external_url'): + title_cell.hyperlink = bug['external_url'] + title_cell.font = link_font + ws.cell(row=row_idx, column=2, value=_SEVERITY_LABELS.get(bug['severity'], '')) + ws.cell(row=row_idx, column=3, value=_TRACKER_LABELS.get(bug['tracker'], bug['tracker'] or '')) + ws.cell(row=row_idx, column=4, value=bug['current_owner'] or '') + ws.cell(row=row_idx, column=5, value=_calc_regress_text(bug)) + for col in (2, 3, 4, 5): + ws.cell(row=row_idx, column=col).alignment = center_align + + # 列宽 + widths = [60, 12, 14, 16, 12] + for i, width in enumerate(widths, start=1): + ws.column_dimensions[chr(64 + i)].width = width + # 冻结表头 + ws.freeze_panes = 'A2' + + buf = BytesIO() + wb.save(buf) + buf.seek(0) + + filename = f'bugs_job{vmi.job_id}' + if vmi.image_id: + filename += f'_image{vmi.image_id}' + filename += '.xlsx' + resp = HttpResponse(buf.getvalue(), + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') + # RFC 5987 兼容中文文件名 + resp['Content-Disposition'] = f"attachment; filename={filename}; filename*=UTF-8''{quote(filename)}" + return resp + except Exception as err: + logger.exception(f'view_bug_export_excel err: {err}') + return ApiResponse(ApiErrorEnum.ERROR, msg=f'导出失败: {err}') diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..7223047787545f05ec19cc671fa1130d84eecd7f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class DataConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.data' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..1dda4875f390deb5574c023c9206b0aa22792637 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/migrations/0001_initial.py @@ -0,0 +1,58 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('project', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Data', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('job_id', models.BigIntegerField(default=0, verbose_name='任务id')), + ('name', models.TextField(default='', verbose_name='ui页面路径')), + ('resource_version', models.CharField(default='', max_length=100, verbose_name='资源版本')), + ('device', models.JSONField(default=dict, verbose_name='设备信息')), + ('file_path', models.CharField(default='', max_length=128, verbose_name='保存数据的文件路径')), + ('shot_img_path', models.CharField(default='', max_length=128, verbose_name='截图文件路径')), + ('reviewed', models.IntegerField(choices=[(0, '未审核(无审核记录)'), (1, '系统自动审核'), (2, '人工审核')], default=0, verbose_name='审核,0:未审核(无审核记录),1:系统自动审核,2:人工审核')), + ('module', models.ForeignKey(null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='project.module')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_data', + 'indexes': [models.Index(fields=['job_id'], name='idx_data_job')], + }, + ), + migrations.CreateModel( + name='ImagerResource', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('name', models.CharField(default='', max_length=255, verbose_name='图片名')), + ('resource_version', models.CharField(default='', max_length=255, verbose_name='资源版本')), + ('resources_path', models.CharField(default='', max_length=255, verbose_name='资源路径')), + ('md5', models.CharField(default='', max_length=100, verbose_name='md5')), + ('file_path', models.CharField(default='', max_length=255, verbose_name='图片存储路径')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_image_resource', + 'constraints': [models.UniqueConstraint(fields=('name', 'md5'), name='idx_unique_name_md5')], + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/models.py new file mode 100644 index 0000000000000000000000000000000000000000..0913f72ae9f24b6a8bf2a72abe5c1a2556a642a6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/models.py @@ -0,0 +1,43 @@ +from django.db import models + +from apps.project.models import Module, Project +from libs import BaseAttrModel +from libs.defs import ReviewedEnum + + +class Data(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + job_id = models.BigIntegerField(default=0, verbose_name='任务id') + module = models.ForeignKey(Module, null=True, on_delete=models.DO_NOTHING) + name = models.TextField(default='', verbose_name='ui页面路径') + resource_version = models.CharField(max_length=100, default='', verbose_name='资源版本') + device = models.JSONField(default=dict, verbose_name='设备信息') + file_path = models.CharField(max_length=128, default='', verbose_name='保存数据的文件路径') + shot_img_path = models.CharField(max_length=128, default='', verbose_name='截图文件路径') + reviewed = models.IntegerField(choices=ReviewedEnum, default=ReviewedEnum.EMPTY, + verbose_name='审核,0:未审核(无审核记录),1:系统自动审核,2:人工审核') + + class Meta: + # app_label = 'data' + db_table = 'lqa_data' + indexes = [ + models.Index(fields=["job_id"], name='idx_data_job') + ] + + +class ImagerResource(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=255, default='', verbose_name='图片名') + resource_version = models.CharField(max_length=255, default='', verbose_name='资源版本') + resources_path = models.CharField(max_length=255, default='', verbose_name='资源路径') + md5 = models.CharField(max_length=100, default='', verbose_name='md5') + file_path = models.CharField(max_length=255, default='', verbose_name='图片存储路径') + + class Meta: + # app_label = 'image_resources' + db_table = 'lqa_image_resource' + constraints = [ + models.UniqueConstraint(fields=['name', 'md5'], name='idx_unique_name_md5') + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..2a01344dda0a2e32d8e50433c7c0487c435c81cc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/schemas.py @@ -0,0 +1,55 @@ +from typing import List, Optional +import datetime + +from pydantic import BaseModel, Field, AliasPath +from libs.defs import ReviewedEnum + + +class DataListSchema(BaseModel): + project_id: int + id: int = Field(default=None, ge=0) + pk__gte: int = Field(default=None, ge=0) + pk__lte: int = Field(default=None, ge=0) + job_id: int = Field(default=None, ge=0) + name__contains: str = Field(default=None, alias='name') + reviewed: ReviewedEnum = Field(default=None) + resource_version: str = Field(default=None) + module_id: int = Field(default=None) + created_begin_at: datetime.datetime = Field(default=None, alias='begin_at') + created_end_at: datetime.datetime = Field(default=None, alias='end_at') + info_type: int = Field(default=0) # 0:简略信息 1:详细信息 + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2, le=100) + + +class DatasUpdateSchema(BaseModel): + ids: List[int] = Field(min_length=1) + resource_version: str = Field(default=None, min_length=2) + module_id: int = Field(default=None) + + +class DatasDeleteSchema(BaseModel): + ids: List[int] = Field(min_length=1) + + +class DataUpdateSchema(BaseModel): + id: int = Field(gt=0) + shot_img_path: str = Field(min_length=2, default=None) + resource_version: str = Field(default=None) + module_id: int = Field(default=None) + + +class ImageResCreateSchema(BaseModel): + project_id: int + name: str = Field(min_length=5) + resource_version: str = Field(description="资源版本") + resources_path: str = Field(default=None, description="资源路径") + upload_data: bytes = Field(default=None, description="图片文件base64数据") + # by_res_path: int = Field(default=0, description="是否通过资源路径处理, 0:否, 1:是") + + +class ImageResQuerySchema(BaseModel): + project_id: int + name: str + resource_version: str \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..607a870e8912509499db1ad6e2643792ef93fbe6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/urls.py @@ -0,0 +1,12 @@ + +from django.urls import path + +from .views import * + +urlpatterns = [ + path('entity', DataView.as_view(), name='data'), + path('list', DataListView.as_view(), name='data-list'), + path('resource_version/list', DataResourceVersionView.as_view(), name='data-resource-version-list'), + path('image_resource', ImagerResourceView.as_view(), name='image-resource'), + path('image_resource/merge', ImagerResourceMergeView.as_view(), name='image-resource-merge'), +] \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/data/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/data/views.py new file mode 100644 index 0000000000000000000000000000000000000000..93fbd5b69a4d8ce0a546f7e80215881a6c115470 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/data/views.py @@ -0,0 +1,371 @@ +import os +import gzip +import logging + +import orjson +from django.views.generic import View +from django.db import transaction, DatabaseError, IntegrityError +from django.db.models import Q +from django.http.response import HttpResponse +from django.forms.models import model_to_dict + +from apps.project.models import Project, Module +from apps.job.models import Job +from apps.image.models import DataReview, Image +from apps.data.models import Data, ImagerResource +from libs.defs import ApiErrorEnum, SwitchEnum +from libs import ApiResponse, PageView, cache, storage +from libs.util import md5, read_file_iter +from .schemas import * + +logger = logging.getLogger('data_view') + + +class DataListView(PageView): + Query_Fields = ('project_id', 'id', 'pk__gte', 'pk__lte', 'job_id', 'cur_id', 'name__contains', 'resource_version', + 'module_id', 'created_begin_at', 'created_end_at') + + def get(self, request): + vmi = DataListSchema.model_validate(request.GET.dict()) + + project_id, info_type = vmi.project_id, vmi.info_type + + if vmi.pk__gte is not None and vmi.pk__lte is not None and vmi.pk__gte > vmi.pk__lte: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='请检查ID范围') + + param = self.make_query_params(vmi) + page_by_where = self.page_by_where(param) + if vmi.reviewed is not None: + if vmi.reviewed == 0: + param['reviewed'] = 0 + else: + param['reviewed__gt'] = 0 + + # 当按任务筛选时,除了 Data.job_id = ? 的"原生"数据, + # 还需要把 Job.data_ids 里"外挂"的数据一并查出来(创建任务时勾选的其它任务数据) + if vmi.job_id is not None: + extra_data_ids = Job.objects.filter(pk=vmi.job_id).values_list('data_ids', flat=True).first() or [] + if len(extra_data_ids) > 0: + job_id_val = param.pop('job_id') + param = Q(**param) & (Q(job_id=job_id_val) | Q(pk__in=extra_data_ids)) + + total, datas = self.page_query(Data, param, vmi.page, vmi.page_size, page_by_where=page_by_where) + # 查询 image.file_path + data_ids = [o['id'] for o in datas] + data_image_map = {} + image_ids_set = set() + if len(data_ids) > 0: + drs = DataReview.objects.filter(project_id=project_id, data_id__in=data_ids).values('data_id', 'image_id') + for dr_ in drs: + data_image_map[dr_['data_id']] = dr_ + image_ids_set.add(dr_['image_id']) + image_dict = {p_['id']: p_ for p_ in Image.objects.filter(pk__in=image_ids_set).values('id', 'file_path', + 'updated_at')} + _block = {} + for data in datas: + if info_type == 0 and len(data['name']) > 400: # 太长就截取 + data['name'] = data['name'][:200] + ' ... ' + data['name'][len(data['name'])-200:] + image_id = data_image_map.get(data['id'], _block).get('image_id', 0) + image = image_dict.get(image_id) + data['revert_img_path'] = image['file_path'] + f'?_t={image["updated_at"]}' if image else '' + + return ApiResponse(data={'list': datas, 'total': total, 'page': vmi.page, 'page_size': vmi.page_size}) + + def patch(self, request): + obj = DatasUpdateSchema.model_validate(orjson.loads(request.body)) + ids, resource_version, module_id = obj.ids, obj.resource_version, obj.module_id + param = {} + if resource_version is not None: + param['resource_version'] = resource_version + if module_id: + param['module_id'] = module_id + if len(param) == 0: + return ApiResponse(ApiErrorEnum.ERROR, msg='resource_version和module_id不能同时为空') + # count = Data.objects.filter(pk__in=ids).count() + # if count != len(ids): + # return ApiResponse(ApiErrorEnum.ERROR, msg='存在无效ids,请刷新页面') + try: + Data.update_db(ids, param) + datas = Data.objects.filter(pk__in=ids).values() + if resource_version: + for data in datas: + cache.resource_version_cache.zadd(data['project_id'], {resource_version: data['id']}) + except Exception as err: + logger.error('DataView save err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'更新失败 err:{err}') + return ApiResponse(data={'list': datas}) + + def delete(self, request): + vmi = DatasDeleteSchema.model_validate(orjson.loads(request.body)) + ids = vmi.ids + + datas = Data.objects.filter(pk__in=ids).values('id', 'project_id') + if len(datas) != len(ids): + return ApiResponse(ApiErrorEnum.ERROR, msg='存在无效ids,请刷新页面') + if len(datas) == 0: + return ApiResponse(ApiErrorEnum.ERROR, msg='无有效数据') + + project_id = datas[0]['project_id'] + updated_num = 0 + try: + updated_num = Data.update_db(ids, {'is_delete': SwitchEnum.ON}) + if updated_num > 0: + cache.resource_version_cache.reset(project_id) + # 跟随Data数据库表做物理删除 + # for data_ in datas: + # data_id_, file_path = data_['id'], data_['file_path'] + # abs_path = storage.get_abs_path(file_path) + # storage.mv_to_temp(abs_path) + # logger.info(f"_delete_on_node id:{data_id_} file_path:{file_path}") + except Exception as err: + logger.error('delete data err:', exc_info=err) + if updated_num == 0: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'删除失败 err:{err}') + return ApiResponse(data={'ids': ids}) + + +class DataView(View): + content_types = ('json', 'gzip') + + def post(self, request): + """SDK调用 上传data""" + content_type = request.headers.get('content-type') + _, ext = content_type.split('/') + if ext not in self.content_types: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'body support {self.content_types}') + # todo 这里以后可以进一步优化一下减小内存开销:用form提交 需要存数据库的字段放field里,用不到的直接存文件 + try: + body = gzip.decompress(request.body) if ext == 'gzip' else request.body + body = orjson.loads(body) + project_id = int(body['project_id']) + job_id = int(body['job_id']) + data_dict = body['data'] + except Exception as err: + logger.error('decode err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'body解析出错 err: {str(err)}') + + name = (data_dict.get("name", '')).strip() + if len(name) == 0: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='name不能未空') + if not Job.objects.filter(pk=job_id, project_id=project_id).exists(): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'未找到job:{job_id}') + + resource_version = (data_dict.get("gameData", {}).get("resourceVersion", '')).strip() + device = {'phone_type': (data_dict.get("phoneType", '')).strip(), 'screen_w': 0, 'screen_h': 0} + device['screen_w'] = int(data_dict.get('sizeX', 0)) + device['screen_h'] = int(data_dict.get('sizeY', 0)) + # try: ## 不从里面拿数据了,减少内存开销 + # ui = orjson.loads(data_dict.get('uiJson')) + # device['screen_w'] = int(ui.get('screenWidth', 0)) + # device['screen_h'] = int(ui.get('screenHeight', 0)) + # except orjson.JSONDecodeError: + # pass + + try: + data = Data(project_id=project_id, job_id=job_id, name=name, resource_version=resource_version, + device=device) + tmp_data_file, _ = storage.write_temp_file(gzip.compress(orjson.dumps(data_dict), 1)) + with transaction.atomic(): + data.save() + abs_path, url_path = storage.gen_job_file_path(project_id, job_id, 'data', f"{data.id}_data.gzip") + storage.mv_file(tmp_data_file, abs_path) + data.file_path = url_path + data.save(update_fields=['file_path']) + if resource_version: + cache.resource_version_cache.zadd(project_id, {resource_version: data.id}) + except Exception as err: + logger.error('DataView save err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'创建失败 err:{err}') + logger.info(f'[event.data.add] user:{request.user["name"]} data_id:{data.id} file_path:{data.file_path}') + return ApiResponse(data={'data': model_to_dict(data)}) + + def patch(self, request): + body = orjson.loads(request.body) if request.content_type == 'application/json' else request.POST.dict() + vmi = DataUpdateSchema.model_validate(body) + data_id, shot_img_path, module_id = vmi.id, vmi.shot_img_path, vmi.module_id + + mapping = vmi.model_dump(exclude={'id'}, exclude_unset=True) + if len(mapping) == 0: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='没有可更新的参数') + + data = Data.objects.filter(pk=data_id).values('id', 'project_id', 'job_id', 'shot_img_path').first() + if not data: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'data: {data_id} 未找到') + + project_id, job_id = data['project_id'], data['job_id'] + + if module_id and not Module.objects.filter(pk=module_id, project_id=project_id).exists(): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'module_id: {module_id} 未找到') + + if shot_img_path and data['shot_img_path'] != shot_img_path: + _, file_ext = os.path.splitext(shot_img_path) + filen_name = f"{data['id']}_img{file_ext}" if file_ext else f"{data['id']}_img.jpeg" + abs_path, url_path = storage.gen_job_file_path(project_id, job_id, 'data', filen_name) + if data['shot_img_path']: # 删除旧文件 + abs_url_path_old = storage.get_abs_path(data['shot_img_path']) + storage.mv_to_temp(abs_url_path_old) + # 保存新文件 + tmp_abs_path_new = storage.get_abs_path(shot_img_path) + storage.mv_file(tmp_abs_path_new, abs_path) + mapping['shot_img_path'] = url_path + + Data.update_db(data_id, mapping) + return ApiResponse(msg='更新成功') + + + +class DataResourceVersionView(View): + def get(self, request): + project_id = request.GET.get('project_id', 0) + if not Project.objects.filter(pk=project_id).exists(): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'invalidate project_id:{project_id}') + items = cache.resource_version_cache.zrevrange(project_id, 0, -1) + items = [item.decode('utf-8') for item in items] + return ApiResponse(data={'list': items}) + + +class ImagerResourceView(View): + + def get(self, request): + """GET /api/image/image_resource """ + vmi = ImageResQuerySchema.model_validate(request.GET.dict()) + image_res = ImagerResource.objects.filter(**vmi.dict()).first() + + if not image_res: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='未找到image_res') + + file_path_abs = storage.get_abs_path(image_res.file_path) + if not os.path.exists(file_path_abs): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'image_res:{image_res.file_path} 不存在') + + response = HttpResponse(content=read_file_iter(file_path_abs)) + response['md5'] = image_res.md5 + return response + + def post(self, request): + """POST /api/image/image_resource """ + body = orjson.loads(request.body) if request.content_type == 'application/json' else request.POST.dict() + vmi = ImageResCreateSchema.model_validate(body) + project_id = vmi.project_id + + image_res = ImagerResource(**vmi.model_dump(exclude={'upload_data'}, exclude_unset=True)) + # 处理文件 + upload_data_bytes = None + if vmi.upload_data is not None: + # upload_data_bytes = base64.b64decode(vmi.upload_data) + upload_data_bytes = vmi.upload_data + image_res.md5 = md5(upload_data_bytes) + # 写临时文件 + tmp_abs_path, _ = storage.write_temp_file(upload_data_bytes) + try: + with transaction.atomic(): + image_res.save() + if upload_data_bytes: + # example /var/www/lqa/data/media/image_res/100/20240918/image_data_1024 + abs_path, url_path, _ = storage.gen_project_file_path(project_id, 'image_resource', f'img_res_{image_res.id}') + storage.mv_file(tmp_abs_path, abs_path) + image_res.file_path = url_path + image_res.save(update_fields=['file_path']) + except IntegrityError as err: + if err.args[0] == 1062: + obj = ImagerResource.objects.filter(name=image_res.name, md5=image_res.md5).first() + return ApiResponse(data={'image_res': model_to_dict(obj)}, msg='图片已存在') + else: + logger.error('ImageRes save err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg='创建失败') + except DatabaseError as err: + logger.error('ImageRes save err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg='创建失败') + return ApiResponse(data={'image_res': model_to_dict(image_res)}, msg='创建成功') + + +class ImagerResourceMergeView(View): + """根据SDK上传的image_resources信息,生成编辑器需要的json数据""" + + Type_Names = {"UnityEngine.UI.Image", "UnityEngine.UI.RawImage"} + + @classmethod + def _get_image_resource_names(cls, ui_list): + resource_names = [] + for ui_info in ui_list: + component_datas = ui_info['ComponentDatas'] + for component_data in component_datas: + if component_data['typeName'] in ["UnityEngine.UI.Image", "UnityEngine.UI.RawImage"]: + component_json = component_data.get('componentJson') + if not component_json: + continue + component_json = orjson.loads(component_json) + pic_data_name = component_json.get('picData') + if pic_data_name: + resource_names.append(pic_data_name) + return resource_names + + @classmethod + def merge(cls, data, all_ui_list): + names = cls._get_image_resource_names(all_ui_list) + project_id, resource_version = data.project_id, data.resource_version + img_res_list = ImagerResource.objects.filter(project_id=project_id, + resource_version=resource_version, name__in=names) + logger.info(f'image resource pre_merged: {[img_res.id for img_res in img_res_list]}') + img_res_dict = {img_res_list.name: img_res for img_res in img_res_list} + + suc_ids = [] + suc_file_path = [] + for ui_info in all_ui_list: + component_datas = ui_info['ComponentDatas'] + for component_data in component_datas: + try: + if component_data['typeName'] in cls.Type_Names: + component_json = component_data.get('componentJson') + if not component_json: + continue + component_json = orjson.loads(component_json) + pic_data_name = component_json['picData'] + img_res = img_res_dict.get(pic_data_name) + if img_res and img_res.file_path: + img_res_file_path_abs = storage.get_abs_path(img_res.file_path) + image_data = b''.join(bytes(chunk) for chunk in read_file_iter(img_res_file_path_abs)) + component_json['picData'] = list(image_data) + component_data['componentJson'] = orjson.dumps(component_json).decode() + suc_ids.append(img_res.id) + suc_file_path.append(img_res_file_path_abs) + except Exception as err: + logger.error('merge err:', exc_info=err) + + if len(suc_ids) > 0: + logger.info(f'image resource suc merged: {suc_ids}') + ImagerResource.update_db(suc_ids, {'is_delete': 1}) + for file_path_ in suc_file_path: + storage.mv_to_temp(file_path_) + + return all_ui_list + + def post(self, request): + project_id = request.POST.get('project_id', 0) + data_id = request.POST.get('data_id', 0) + + data = Data.objects.filter(pk=data_id, project_id=project_id).first() + if not data: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到数据data_id:{data_id}') + + file_path_abs = storage.get_abs_path(data.file_path) + if not os.path.exists(file_path_abs): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'数据文件不存在data_id:{data_id} {file_path_abs}') + + with open(file_path_abs, "rb") as fp: + content_raw = fp.read() + content = gzip.decompress(content_raw) + + content = orjson.loads(content) + ui_json_data = orjson.loads(content['uiJson']) + if ui_json_data: + all_ui_list = ui_json_data['allUIList'] + new_ui_list = self.merge(data, all_ui_list) + ui_json_data['allUIList'] = new_ui_list + content['uiJson'] = orjson.dumps(ui_json_data).decode() + content_raw = orjson.dumps(content).decode() + + tmp_file_path_abs, _ = storage.write_temp_file(gzip.compress(content_raw, 1)) + storage.mv_file(tmp_file_path_abs, file_path_abs) + + return ApiResponse(msg='数据合并成功') \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..20f5337f99c4e16326d63b7282976edd109bf566 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ImageConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.image' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..9a31404d1b7d739d9c452d05c601232ef130c4f2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/migrations/0001_initial.py @@ -0,0 +1,70 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('project', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='DataReview', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('data_id', models.BigIntegerField(default=0, verbose_name='data id')), + ('image_id', models.BigIntegerField(default=0, verbose_name='image id')), + ('rect_location', models.TextField(default='{}', verbose_name='文本框,图像框集合')), + ('check_rect_location', models.TextField(default='{}', verbose_name='审核后的文本框,图像框集合')), + ('dirty_rect_location', models.TextField(default='{}', verbose_name='删除的文本框,图像框集合')), + ('size', models.CharField(default='', max_length=64, verbose_name='图片尺寸')), + ('reviewer', models.CharField(default='', max_length=100, verbose_name='审核人')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_data_review', + }, + ), + migrations.CreateModel( + name='Image', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('job_id', models.BigIntegerField(default=0, verbose_name='任务id')), + ('data_id', models.BigIntegerField(default=0, verbose_name='data id')), + ('language', models.IntegerField(verbose_name='需要还原的语言')), + ('is_latest', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=1, verbose_name='是否最新')), + ('iteration', models.IntegerField(default=1, verbose_name='还原次数')), + ('rect_location', models.TextField(default='', verbose_name='文本框,图像框集合')), + ('file_name', models.CharField(default='', max_length=255, verbose_name='文件名称')), + ('file_path', models.CharField(default='', max_length=255, verbose_name='文件名称')), + ('size', models.CharField(default='', max_length=64, verbose_name='图片尺寸')), + ('ai_sign', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='是否需要识别图片,0不需要,1需要')), + ('ai_mark_img_path', models.CharField(default='', max_length=255, verbose_name='识别后标记结果图片')), + ('ai_rect_img_path', models.CharField(default='', max_length=255, verbose_name='识别后标记坐标图片debug使用')), + ('ai_overframe', models.IntegerField(default=0, verbose_name='是否超框,true代表超框,false代表没有超框')), + ('ai_check_detail', models.TextField(default='', verbose_name='图片识别返回的文本信息,全量识别时用到')), + ('ai_sign_suc', models.IntegerField(choices=[(0, '初始值'), (1, '识别成功'), (2, '识别失败')], default=0, verbose_name='识别阶段是否成功,0默认,1成功,2失败')), + ('ai_bug_types', models.JSONField(default=list, verbose_name='ai识别缺陷类型,1:漏译;2:超框;3:漏key;4:标准框重叠')), + ('err_msg', models.TextField(default='', verbose_name='错误信息')), + ('err_type', models.IntegerField(choices=[(0, '没有失败'), (1, '识别失败'), (2, '提单失败'), (3, '回归失败')], default=0, verbose_name='图像检测失败类型')), + ('will_review', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='当存在“标准框重叠”时需要人工审核')), + ('reviewed', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='是否已审核')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_image', + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/models.py new file mode 100644 index 0000000000000000000000000000000000000000..95c9a6509ae9071ad967e34d220cc7c1b6b3ef92 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/models.py @@ -0,0 +1,63 @@ +from django.db import models + +from libs.defs import SwitchEnum, ImageTaskErrorEnum, ImageAiSignErrorEnum +from apps.project.models import Project +from libs import BaseAttrModel + + +class Image(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + job_id = models.BigIntegerField(default=0, verbose_name='任务id') + + data_id = models.BigIntegerField(default=0, verbose_name='data id') + language = models.IntegerField(verbose_name='需要还原的语言') + is_latest = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.ON, verbose_name='是否最新') + iteration = models.IntegerField(default=1, verbose_name='还原次数') + rect_location = models.TextField(default='', verbose_name='文本框,图像框集合') + file_name = models.CharField(max_length=255, default='', verbose_name='文件名称') # like 98(job_id)-8821(data_id)-LAN_TW_CHT.png + file_path = models.CharField(max_length=255, default='', verbose_name='文件名称') + size = models.CharField(max_length=64, default='', verbose_name='图片尺寸') + + # ai 识别 + ai_sign = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='是否需要识别图片,0不需要,1需要') + ai_mark_img_path = models.CharField(max_length=255, default='', verbose_name='识别后标记结果图片') + ai_rect_img_path = models.CharField(max_length=255, default='', verbose_name='识别后标记坐标图片debug使用') + ai_overframe = models.IntegerField(default=0, verbose_name='是否超框,true代表超框,false代表没有超框') + ai_check_detail = models.TextField(default='', verbose_name='图片识别返回的文本信息,全量识别时用到') + ai_sign_suc = models.IntegerField(choices=ImageAiSignErrorEnum, default=ImageAiSignErrorEnum.ERR_NO, verbose_name='识别阶段是否成功,0默认,1成功,2失败') + ai_bug_types = models.JSONField(default=list, verbose_name='ai识别缺陷类型,1:漏译;2:超框;3:漏key;4:标准框重叠') + + err_msg = models.TextField(default='', verbose_name='错误信息') + err_type = models.IntegerField(choices=ImageTaskErrorEnum, default=ImageTaskErrorEnum.ERR_NO, verbose_name='图像检测失败类型') + + will_review = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='当存在“标准框重叠”时需要人工审核') + reviewed = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='是否已审核') # 跟will_review无关联 + + class Meta: + # app_label = 'image' + db_table = 'lqa_image' + # 索引以实际数据库中手动建立的为准 + # indexes = [ + # models.Index(fields=["job_id", "data_id"], name='idx_image_job_data') + # ] + # constraints = [ + # models.UniqueConstraint(fields=['job_id', 'data_id', 'language'], name='idx_unique_job_data_language') + # ] + + +class DataReview(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + data_id = models.BigIntegerField(default=0, verbose_name='data id') + image_id = models.BigIntegerField(default=0, verbose_name='image id') + rect_location = models.TextField(default='{}', verbose_name='文本框,图像框集合') + check_rect_location = models.TextField(default='{}', verbose_name='审核后的文本框,图像框集合') + dirty_rect_location = models.TextField(default='{}', verbose_name='删除的文本框,图像框集合') + size = models.CharField(max_length=64, default='', verbose_name='图片尺寸') + reviewer = models.CharField(default='', max_length=100, verbose_name='审核人') + + class Meta: + # app_label = 'data_review' + db_table = 'lqa_data_review' + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2c18363df6bf7defd98a373d0a04006267269e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/schemas.py @@ -0,0 +1,71 @@ +from typing import List, Annotated, Literal +import datetime + +from pydantic import BaseModel, Field, field_validator, BeforeValidator, AfterValidator, AliasChoices + +from libs import defs, lodash, util +from apps.project import service as proj_svr + + +class ImageListSchema(BaseModel): + job_id: int = Field(default=None, gt=0) + id: int = Field(default=None, gt=0) + pk__gte: int = Field(default=None, ge=0) + pk__lte: int = Field(default=None, ge=0) + data_id: int = Field(default=None, gt=0) + module_ids: Annotated[List[int], BeforeValidator(util.make_item_array_validator())] = Field(default=None, min_length=1) + file_name__contains: str = Field(default=None, alias='file_name') + err_type: int = Field(default=None) + will_review: int = Field(default=None) + languages: Annotated[List[int], BeforeValidator(util.make_item_array_validator())] = Field(default=None, min_length=1) + is_latest: int = Field(default=1) + ai_bug_types: Annotated[List[int], BeforeValidator(util.make_item_array_validator()), AfterValidator(proj_svr.BugTypeValidator())] = Field(default=None, alias='ai_bug_types') + reviewed: int = Field(default=None) + rect_location__contains: str = Field(default=None, min_length=1, alias='rect_location') + info_type: int = Field(default=0) # 0:简略信息 1:详细信息 + created_begin_at: datetime.datetime = Field(default=None) + created_end_at: datetime.datetime = Field(default=None) + updated_begin_at: datetime.datetime = Field(default=None) + updated_end_at: datetime.datetime = Field(default=None) + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2, le=100) + + + # @field_validator('languages', mode='before') # 指定解析的模型属性 + # @classmethod + # def valid_languages(cls, v: str): # 通过自定义类方法解析获取模型属性 + # if v.strip() == '': + # return [] + # return lodash.split(v, func=lambda i: int(i)) + +class ImageListUpdateSchema(BaseModel): + ids: List[int] = Field(min_length=1) + reviewed: Literal[0, 1] + +class ImageCreateSchema(BaseModel): + project_id: int + job_id: int + data_id: int + language: Annotated[int, BeforeValidator(proj_svr.LanguageValidator())] # 创建时验证语言有效性 + rect_locations: str + ai_sign: defs.SwitchEnum = Field(default=defs.SwitchEnum.OFF) + regression: defs.JobRegressionEnum = Field(default=defs.JobRegressionEnum.NORMAL) + bug_ids: Annotated[List[int], BeforeValidator(util.make_item_array_validator())] = Field(default=[]) + # 识别后是否自动提单(兼容旧版编辑器插件的参数名 create_bug_tapd) + create_bug: defs.SwitchEnum = Field(default=defs.SwitchEnum.OFF, + validation_alias=AliasChoices('create_bug', 'create_bug_tapd')) + discern: defs.JobDiscernEnum = Field(default=defs.JobDiscernEnum.FULL) + + +class ImageAiSignRequestSchema(BaseModel): + image_id: int = Field(default=None) + job_id: int = Field(default=None) + languages: Annotated[List[int], BeforeValidator(proj_svr.LanguageValidator())] = Field(default=None) + discern: defs.JobDiscernEnum = Field(default=defs.JobDiscernEnum.FULL) + + +class DataReviewPatchSchema(BaseModel): + id: int = Field(default=None, description="DataReview id") + check_rect_location: str = Field('{}', description="审核后的文本框,图像框集合 json") + dirty_rect_location: str = Field('{}', description="删除的文本框,图像框集合 json") \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/service.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/service.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a7cb9c68d2f8e3b69a000305ea739f524ce693 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/service.py @@ -0,0 +1,579 @@ +import os +import base64 +import time +import logging +from collections import defaultdict +from zlib import adler32 +import cv2 +import numpy as np +import copy + +import requests +import orjson +from munch import Munch as AttrDict +from django.db.models import Count + +import settings +from libs import TaskBase, util, lodash, storage +from libs.defs import ImageTaskErrorEnum, JobRegressionEnum, ImageAiSignErrorEnum, BugBillStatusEnum, JobDiscernEnum +from apps.job.models import Job +from apps.project.models import Project +from apps.project import service as proj_svr +from apps.image.models import Image, DataReview +from apps.bug import service as bug_svr +from apps.bug.models import Bug + +logger = logging.getLogger('img_svr') + + +def _size_to_wh(size): + if isinstance(size, str): + size = size.split(',') + return int(size[0]), int(size[1]) + + +class DataReviewService(object): + """利用DataReview清洗rect_location数据""" + + @classmethod + def rect_location_to_corners(cls, rect_location, size): + """ + 将文本框、图像框集合转换为前端需要的坐标格式 + :param rect_location: 文本框、图像框集合 + :param size: 图片尺寸 + :return: + """ + res = defaultdict(list) + if not rect_location: + return res + width, height = _size_to_wh(size) + rect_location_dict = orjson.loads(rect_location) if isinstance(rect_location, str) else rect_location + for k, v in rect_location_dict.items(): + for span in v: + corners = span["corners"] + if not util.judge_rectangle(corners): # 过滤掉非矩形 + continue + x1 = int(corners[1]["x"]) + y1 = int(height) - int(corners[1]["y"]) + x2 = int(corners[3]["x"]) + y2 = int(height) - int(corners[3]["y"]) + w = x2 - x1 + h = y2 - y1 + temp = {"key": str(adler32(orjson.dumps(corners))), "corners": [x1, y1, w, h]} + res[k].append(temp) + return res + + @classmethod + def data_clean(cls, rect_location, db_dirty): + """ + 数据清洗 + :param rect_location: 文本框,图像框集合 + :param db_dirty: 排除的文本框,图像框集合 + :return: + """ + cleaned = False + if not rect_location: + return rect_location, cleaned + db_dirty = orjson.loads(db_dirty) if isinstance(db_dirty, str) else db_dirty + clean_rect_location = defaultdict(list) + dirty_rect_location = defaultdict(list) + dirty_rect_location.update(db_dirty) + dirty_key = defaultdict(list) + for k, v in dirty_rect_location.items(): + for span in v: + dirty_key[k].append(span["key"]) + rect_location_dict = orjson.loads(rect_location) if isinstance(rect_location, str) else rect_location + for k, v in rect_location_dict.items(): + for span1 in v: + key = str(adler32(orjson.dumps(span1["corners"]))) + if key not in dirty_key[k]: + clean_rect_location[k].append(span1) + else: + cleaned = True + return orjson.dumps(clean_rect_location).decode(), cleaned + + @classmethod + def auto_review(cls, rect_location, size): + """ + 自动审核 + :param rect_location: 文本框,图像框集合 + :param size: 图片尺寸 + :return: + """ + if not rect_location: + return "{}", "{}", "{}" + clean_rect_location = defaultdict(list) + check_rect_location = defaultdict(list) + dirty_rect_location = defaultdict(list) + width, height = _size_to_wh(size) + rect_location_dict = orjson.loads(rect_location) if isinstance(rect_location, str) else rect_location + for k, v in rect_location_dict.items(): + for span_corners in v: + corners = span_corners["corners"] + x1 = int(corners[1]["x"]) + y1 = height - int(corners[1]["y"]) + x2 = int(corners[3]["x"]) + y2 = height - int(corners[3]["y"]) + w = x2 - x1 + h = y2 - y1 + span_rect = {"key": str(adler32(orjson.dumps(corners))), "corners": [x1, y1, w, h], "tag": "system"} + if min([x1, y1, x2, y2, w, h]) < 0 or max([x1, x2]) > width or max([y1, y2]) > height: + dirty_rect_location[k].append(span_rect) + continue + check_rect_location[k].append(span_rect) + clean_rect_location[k].append(span_corners) + return (orjson.dumps(clean_rect_location).decode(), + orjson.dumps(check_rect_location).decode(), + orjson.dumps(dirty_rect_location).decode()) + + +class SubmitAiImageSignTask(TaskBase): + """ + 场景:批量ai识别和重试时 可能会瞬间大量提交AiImageSignTask(预估10w级)。 + 在dev测试时100个提交差不多要800ms左右,所以这里将大批量提交做成异步任务 + """ + def __init__(self, ctx, request=None, logger=None): + super(SubmitAiImageSignTask, self).__init__(ctx, request, logger) + + def _run(self): + self.logger.info(f'AiImageSignSubmitTask.run ctx:{orjson.dumps(self.ctx).decode()}') + # 防止互相import冲突,放这里延迟import + from apps.image.tasks import run_ai_sign + param = self.ctx['param'] # 查询条件 + discern = self.ctx['discern'] + current_user = self.ctx['current_user'] + + stat = {'total': 0, 'success': 0} + fields = ['id', 'job_id', 'data_id', 'rect_location'] + size = 1000 + pk__gt = 0 + while True: + param['pk__gt'] = pk__gt + images = list(Image.objects.filter(**param).order_by('pk')[:size].values(*fields)) # QuerySet to list + + use_images = [] + for image in images: + stat['total'] += 1 + if image['rect_location'] == '': + continue + use_images.append(image) + + code, ctx_list = prepare_ai_sign_task_ctx_with_images(use_images, discern, current_user) + if code == 0: + self.logger.info(f'prepare_ai_sign_task_ctx_with_images code:{code} ctx_list_len:{len(ctx_list)}') + event = 'event.run_ai_sign_3' + for ctx in ctx_list: + ctx['_event'] = event + task = run_ai_sign.apply_async((ctx,)) # 接口图片识别 + self.logger.info(f'[{event}] user:{current_user["name"]} ' + f'task_id:{task.task_id} image_id:{ctx["image_id"]} discern:{discern}') + stat['success'] += 1 + else: + self.logger.warning(f'prepare_ai_sign_task_ctx_with_images code:{code}') + + # 控制循环变量 + if len(images) < size: + break + pk__gt = images[-1]['id'] + self.logger.info(f'stat: {stat}') + + def run(self): + try: + self._run() + except Exception as err: + self.logger.error(f'AiImageSignSubmitTask ctx:{self.ctx} run err:', exc_info=err) + + +class AiImageSignTask(TaskBase): + """识别任务分为3个阶段:1.识别阶段 2.自动提bug阶段 3.更新bug阶段""" + + Project_Methods = {} + + Language_Code_Dict = { + 10: 0, # 中文 + 8: 1, # 中文 (台湾) + 2: 2, # 英文 + 6: 3, # 日文 + 4: 4, # 泰文 + 5: 5, # 越南 + 3: 6, # 韩文 + 7: 7, # 俄文 + 9: 8, # 法文 + 11: 9, # 土耳其文 + 12: 10, # 德文 + 13: 11, # 西班牙文 + 14: 12, # 葡萄牙文(巴西) + 15: 13, # 印尼文 + 16: 14, # 阿拉伯文 + } + + def __init__(self, ctx, request=None, logger=None): + super(AiImageSignTask, self).__init__(ctx, request, logger) + + self.url = f"{settings.env('AI_BASE_URL')}/image/lqa_check/" + self.image = None + self.job = None + + self._check_type = None + + @property + def project_method(self): + project_id = self.image.project_id + val = self.Project_Methods.get(project_id, None) + if not val: + p = Project.objects.filter(pk=project_id).values('id', 'cvtest_project').first() + cvtest_project = p['cvtest_project'].strip() + if not cvtest_project: + raise Exception(f'project:{project_id} "cvtest_project" invalidate') + val = f"{cvtest_project}_lqa" + self.Project_Methods[project_id] = val # 运行时缓存 + return val + + @property + def check_type(self): + if self._check_type is None: + check_type_ = [] + sign_bug_types = self.job['sign_bug_types'] + if len(sign_bug_types) > 0: + for bug_type_ in sign_bug_types: + if bug_type_ == 2: + check_type_.extend(['2-0', '2-1']) + else: + check_type_.append(str(bug_type_)) + self._check_type = check_type_ + return self._check_type + + @property + def language_id(self): + return self.Language_Code_Dict.get(self.image.language, None) + + @classmethod + def _trans_marks(cls, project_id, sign_bug_types): + bug_type_dict = {} + sys_bug_type_dict = {} + + def _trans_marks(bug_type_): + nonlocal bug_type_dict + nonlocal sys_bug_type_dict + if bug_type_ not in sign_bug_types: + return '[]' + if len(sys_bug_type_dict) == 0: + sys_bug_type_dict = proj_svr.ProjCfgService.get_sys_bugtype(True) + if len(bug_type_dict) == 0: + bug_type_dict = proj_svr.ProjCfgService.get_bug_type(project_id, True) + trans_marks_ = bug_type_dict[bug_type_]['trans_marks'] + if len(orjson.loads(trans_marks_)) == 0: # 使用系统的 + trans_marks_ = sys_bug_type_dict[bug_type_]['trans_marks'] + return trans_marks_ + return _trans_marks(1), _trans_marks(5) + + @classmethod + def _base64_to_mat(cls, image_base64, gray=False): + """ + base64转ndarray + Args: + base64_img (str): + gray (bool): + Returns: + img (ndarray) + """ + if not image_base64: + return None + img_b64decode = base64.b64decode(image_base64) + img_array = np.frombuffer(img_b64decode, np.uint8) + img = cv2.imdecode(img_array, cv2.IMREAD_GRAYSCALE if gray else cv2.COLOR_BGR2RGB) + return img + + def _request_ai(self, rect_locations, file_path, old_file_path=None, image_check_detail=None, + discern=JobDiscernEnum.FULL): + """调用 AI 识别服务 POST {AI_BASE_URL}/image/lqa_check/,接口约定见 README「AI 识别服务」""" + # try: + # file_name_full = file_path.split("-")[2] + # language_code = file_name_full.split(".")[0] + # except Exception as e: + # language_code = '获取失败' + # language_id = self.language_code_dict.get(language_code, None) + # if language_id == 1: + # check_type = ['1', '2-0', '2-1', '4', '5', '6'] + # else: + # check_type = None + + file_path_abs = storage.get_abs_path(file_path) + self.logger.info(f'_request_ai file_path_abs:{file_path_abs} check_type:{self.check_type} language_id:{self.language_id}') + img_base64 = ''.join([part for part in util.base64_encode_file_iter(file_path_abs)]) + + img_base64_old = None + if discern: + if old_file_path: + abs_old_file_path = storage.get_abs_path(old_file_path) + if abs_old_file_path and os.path.exists(abs_old_file_path): + img_base64_old = ''.join([part for part in util.base64_encode_file_iter(abs_old_file_path)]) + else: + logger.warning(f'_request_ai old_file_path:{old_file_path} not exist') + if image_check_detail: + image_check_detail = orjson.loads(image_check_detail) + + rect_locations = orjson.loads(rect_locations) if isinstance(rect_locations, str) else rect_locations + no_trans_marks, err_trans_marks = self._trans_marks(self.image.project_id, self.job['sign_bug_types']) + body = { + "img_base64": img_base64, + "history_img_base64": img_base64_old, + "rect_locations": rect_locations, + "language": self.language_id, + "history_result": image_check_detail, + "check_type": self.check_type, + "no_trans_marks": no_trans_marks, + # 字段名须与 lqa_service handles/handle_lqa.py 读取的保持一致, + # 历史上误写为 err_trans_marks,导致项目自定义错译标记不生效 + "error_trans_marks": err_trans_marks, + "ocr_detect": self.job['ocr_detect'] + } + + self.logger.info(f'request_ai_server body: {self.language_id} {self.check_type} ' + f'{no_trans_marks} {err_trans_marks} {self.job["ocr_detect"]}') + + resp_obj = None + t1 = int(time.time() * 1000) + headers = {"project-method": self.project_method} + for idx in range(3): + try: + with requests.post(self.url, json=body, headers=headers, timeout=100) as resp: + resp.raise_for_status() + resp_obj = resp.json() + if resp_obj['err_msg'] != '': + break + except Exception as err: + if idx == 2: + raise err + t2 = int(time.time() * 1000) + self.logger.info(f'request_ai_server cost: {t2 - t1}ms') + mark_img_abs = '' + rect_img_abs = '' + # 保存识别后的图片 + if resp_obj: + if not resp_obj['success']: + raise Exception(f'request_ai_err: {orjson.dumps(resp_obj).decode()}') + mark_img = self._base64_to_mat(resp_obj['result']["mark_img"], False) + rect_img = self._base64_to_mat(resp_obj['result']["rect_img"], False) + # cv2.imwrite 不支持中文路径,这里使用 imencode + tofile,找不到路径会抛出异常FileNotFoundError + name_path, ext = os.path.splitext(file_path_abs) # /a/b/c/d.txt => ('/a/b/c/d', '.txt') + # file_ext = ".jpg" + mark_img_abs = fr"{name_path}-mark_img{ext}" + rect_img_abs = fr"{name_path}-rect_img{ext}" + os.remove(mark_img_abs) if os.path.exists(mark_img_abs) else 1 + os.remove(rect_img_abs) if os.path.exists(rect_img_abs) else 1 + cv2.imencode(ext, mark_img)[1].tofile(mark_img_abs) + self.logger.info(f'save mark_img_abs:{mark_img_abs}') + cv2.imencode(ext, rect_img)[1].tofile(rect_img_abs) + self.logger.info(f'save rect_img_abs:{rect_img_abs}') + return mark_img_abs, rect_img_abs, resp_obj + + def _get_last_ai_image(self, image): + """获取最近一次识别成功的结果""" + param = {'data_id': image.data_id, 'language': image.language, 'ai_sign_suc': ImageAiSignErrorEnum.ERR_SUC} + image_qs = Image.objects.filter(**param).order_by('-id').values('file_path', 'ai_mark_img_path', 'ai_check_detail') + for image_q in image_qs: + if image_q['ai_mark_img_path']: + return image_q['file_path'], image_q['ai_check_detail'] + return None, None + + def _run(self): + ctx_bak = copy.deepcopy(self.ctx) + if 'clean_rect_location' in ctx_bak: + del ctx_bak['clean_rect_location'] + self.logger.info(f'AiImageSignTask.run ctx_bak:{orjson.dumps(ctx_bak).decode()}') + image_id = self.ctx['image_id'] + clean_rect_location = self.ctx.get('clean_rect_location', None) # 没有说明没有dirty_rect_location,直接用image原始数据 + regression = self.ctx['regression'] + discern = self.ctx['discern'] + # 方案 B:以后端 job.bill_bug_types 为准,不信任编辑器插件/调用方传的 create_bug。 + # 规则:job 配了 bill_bug_types 且非回归 => 自动提单;否则不提。 + # 保留一个显式关闭的后门:ctx 显式传 create_bug=-1 时强制不提单(兼容特殊调试场景)。 + _ctx_create_bug = self.ctx.get('create_bug', self.ctx.get('create_bug_tapd', None)) + bug_ids = self.ctx.get('bug_ids', []) + + image = Image.objects.filter(pk=image_id).first() + if not image: + self.logger.error(f'image:{image_id} not exist') + return + self.image = image + job = Job.objects.filter(pk=image.job_id).values( + 'id', 'sign_bug_types', 'bill_bug_types', 'discern', 'ocr_detect').first() + if not job: + self.logger.error(f'job:{image.job_id} not exist') + return + self.job = job + if _ctx_create_bug == -1: + create_bug = 0 + self.logger.info(f'create_bug forced OFF by ctx(-1)') + else: + create_bug = 1 if job.get('bill_bug_types') and regression != JobRegressionEnum.REGRESSION else 0 + self.logger.info( + f'create_bug by job: ctx={_ctx_create_bug} bill_bug_types={job.get("bill_bug_types")} ' + f'regression={regression} -> create_bug={create_bug}') + if clean_rect_location is None: + clean_rect_location = image.rect_location + old_image_path, image_check_detail = None, None + if discern == JobDiscernEnum.DIFF: # 1.差异识别就需要传回旧信息 + old_image_path, image_check_detail = self._get_last_ai_image(image) + self.logger.info(f'discern:{discern} old_image_path:{old_image_path}') + + ai_rec_err = '' + try: + mark_img_abs, rect_img_abs, resp = self._request_ai(clean_rect_location, image.file_path, + old_file_path=old_image_path, + image_check_detail=image_check_detail, + discern=discern) + except Exception as err: + self.logger.error(f'_request_ai wrap err:', exc_info=err) + ai_rec_err = f'{str(err)} resp:{util.err_response_text(err)}' + mark_img_abs, rect_img_abs, resp = '', '', None + + if mark_img_abs and rect_img_abs: + ai_check_detail = resp['result']['check_detail'] + # check_detail 的键可能是带子类型的 "2-0"/"2-1",取主类型后去重 + _raw_types = [] + for bug_id in ai_check_detail.keys(): + try: + _raw_types.append(int(str(bug_id).split("-")[0])) + except (ValueError, TypeError): + continue + ai_bug_types = sorted(set(_raw_types)) + ai_overframe = int(resp["result"]["overframe"]) + will_review = 1 if ai_check_detail.get("4") else 0 # 当有“标准框重叠”时,需要人工审核 + Image.update_db(image_id, { + 'ai_mark_img_path': storage.get_url_path(mark_img_abs), + 'ai_rect_img_path': storage.get_url_path(rect_img_abs), + 'ai_check_detail': orjson.dumps(ai_check_detail).decode(), + 'ai_bug_types': ai_bug_types, + 'ai_overframe': ai_overframe, + 'will_review': will_review, + 'ai_sign_suc': ImageAiSignErrorEnum.ERR_SUC, + 'err_msg': '', + 'err_type': ImageTaskErrorEnum.ERR_NO + }) + + self.logger.info(f'create_bug:{create_bug}') + if create_bug: + self.create_bug(image_id) + + will_update_bug = True if regression == JobRegressionEnum.REGRESSION and len(bug_ids) > 0 else False + self.logger.warning(f'will_update_bug:{will_update_bug} regression:{regression} bug_ids_len:{len(bug_ids)}') + if will_update_bug : + self.update_bug(image_id, bug_ids) + else: + self.update_image_err_info(image_id, resp['err_msg'] if resp else ai_rec_err, + ImageTaskErrorEnum.ERR_AI_REC, ImageAiSignErrorEnum.ERR_FAIL) + + def run(self): + try: + self._run() + except Exception as err: + self.logger.error(f'run err:', exc_info=err) + self.update_image_err_info(self.ctx['image_id'], str(err), ImageTaskErrorEnum.ERR_AI_REC, + ImageAiSignErrorEnum.ERR_FAIL) + + def create_bug(self, image_id): + """自动提bug""" + self.logger.info(f'create_bug image_id:{image_id}') + try: + err_msg, ctx = bug_svr.prepare_create_bug_task_ctx_by_ai_sign(image_id) + if err_msg: + self.logger.error(f'create_bug build err:{err_msg}') + self.update_image_err_info(image_id, f'prepare_bug err: {err_msg}', ImageTaskErrorEnum.ERR_BUG_BILL) + else: + event = 'event.run_bug_create_2' + ctx['_event'] = event + self.logger.info(f'[{event}] image_id:{image_id}') + task = bug_svr.CreateBugTask(ctx, None, self.logger) # 图片识别后,自动提bug。因为图片识别任务本来就是后台任务,这里不用异步跑 + err, bug = task.run() + if err: + self.update_image_err_info(image_id, f'create_bug task err: {err}', ImageTaskErrorEnum.ERR_BUG_BILL) + except Exception as err: + self.logger.error(f'create_bug err:', exc_info=err) + self.update_image_err_info(image_id, f'create_bug err: {err}', ImageTaskErrorEnum.ERR_BUG_BILL) + + def update_bug(self, image_id, bug_ids): + """回归任务场景下,图片识别后处理:关闭或重新打开缺陷""" + self.logger.info(f'[event.run_update_bug] image_id:{image_id} bug_ids:{bug_ids}') + try: + svr = bug_svr.UpdateBugByRegressedImageService({'image_id': image_id, 'bug_ids': bug_ids}, self.request, self.logger) + code, err_msg, stats = svr.run() + self.logger.info(f'run_update_bug.return image_id:{image_id} bug_ids:{bug_ids} code:{code} msg:{err_msg} stats:{stats}') + if code != 0: + self.update_image_err_info(image_id, err_msg, ImageTaskErrorEnum.ERR_REGRESSION) + self.logger.info(f'update_bug image_id:{image_id} bug_ids:{bug_ids} finish') + except Exception as err: + self.logger.error(f'update_bug err:', exc_info=err) + self.update_image_err_info(image_id, f'update_bug err: {err}', ImageTaskErrorEnum.ERR_REGRESSION) + + def update_image_err_info(self, image_id, err_msg, err_type, ai_sign_suc=None): + mapping = {'err_msg': err_msg, 'err_type': err_type} + if ai_sign_suc is not None: + mapping['ai_sign_suc'] = ai_sign_suc + Image.update_db(image_id, mapping) + + +def prepare_ai_sign_task_ctx(review, image, ctx=None, trace=''): + """准备ai识别任务上下文参数""" + ctx['image_id'] = image.id + ctx['trace'] = trace + + if not ctx.get('clean_rect_location'): + if review and review.dirty_rect_location: + clean_rect_location, cleaned = DataReviewService.data_clean(image.rect_location, review.dirty_rect_location) + if cleaned: # 如果没有脏数据,不写入redis,减少内存消耗 + ctx['clean_rect_location'] = clean_rect_location + return ctx + + +def prepare_ai_sign_task_ctx_with_images(images, discern, current_user): + """ + 准备ai_sign任务的ctx + 场景1:单个、批量识别接口 + 场景2:重试job + """ + ctx_list = [] + if len(images) == 0: + return 1, ctx_list + data_ids = list(set(map(lambda img: img['data_id'], images))) + if len(data_ids) == 0: + return 2, ctx_list + # 查询 data_review + data_reviews = DataReview.query_batch({'data_id__in': data_ids}, fields=['id', 'data_id', 'dirty_rect_location']) + if len(data_reviews) == 0: + return 3, ctx_list + data_review_dict = lodash.key_by(data_reviews, 'data_id') + + for image_info in images: + data_review_ = data_review_dict.get(image_info['data_id']) + if not data_review_: + continue + ctx = prepare_ai_sign_task_ctx(AttrDict(data_review_), AttrDict(image_info), ctx={ + 'regression': JobRegressionEnum.NORMAL, + 'bug_ids': [], + 'discern': discern, + 'create_bug': 0, + 'staff_name': current_user['name'] + }, trace=f'ai_sign image_id:{image_info["id"]} job_id:{image_info["job_id"]}') + ctx_list.append(ctx) + return 0, ctx_list + + +def image_of_bug_num(pks, job_id): + param = {'image_id__in': pks, 'job_id': job_id, 'bill_status': BugBillStatusEnum.SUCCESS} + stats = list(Bug.objects.filter(**param).values('image_id').annotate(bug_num=Count('image_id'))) + if len(stats) < len(pks): + # 防止频繁查询Bug表。场景:有些image没有产生bug + delt_pks_set = set(pks) - set(map(lambda stat: stat['image_id'], stats)) + for pk_ in delt_pks_set: + stats.append({'image_id': pk_, 'bug_num': 0}) + return {st_['image_id']: st_ for st_ in stats} + + +# if __name__ == '__main__': +# rect_location1 = {"text":[{"corners":[{"x":949.7177124023438,"y":-89.23961639404297},{"x":915.7986450195313,"y":-56.17535400390625},{"x":1322.8271484375,"y":340.59588623046877},{"x":1356.74609375,"y":307.5316162109375}],"textStr":""},{"corners":[{"x":993.6756591796875,"y":161.15724182128907},{"x":959.756591796875,"y":194.22152709960938},{"x":1366.784912109375,"y":590.9927978515625},{"x":1400.7041015625,"y":557.928466796875}],"textStr":""},{"corners":[{"x":606.0126342773438,"y":-216.83648681640626},{"x":572.0936279296875,"y":-183.772216796875},{"x":979.1220092773438,"y":212.99900817871095},{"x":1013.0410766601563,"y":179.9347381591797}],"textStr":""},{"corners":[{"x":904.4332275390625,"y":173.6291046142578},{"x":870.51416015625,"y":206.6934051513672},{"x":1277.5426025390625,"y":603.464599609375},{"x":1311.46142578125,"y":570.400390625}],"textStr":""},{"corners":[{"x":512.9335327148438,"y":-207.24273681640626},{"x":479.0145263671875,"y":-174.178466796875},{"x":886.0428466796875,"y":222.59275817871095},{"x":919.9619140625,"y":189.5284881591797}],"textStr":""},{"corners":[{"x":653.3583984375,"y":23.007246017456056},{"x":619.4393310546875,"y":56.071510314941409},{"x":1026.4677734375,"y":452.8427429199219},{"x":1060.38671875,"y":419.7784423828125}],"textStr":""},{"corners":[{"x":748.9884033203125,"y":295.4697570800781},{"x":715.0694580078125,"y":328.53399658203127},{"x":1122.0977783203125,"y":725.3052978515625},{"x":1156.016845703125,"y":692.240966796875}],"textStr":""},{"corners":[{"x":342.121826171875,"y":-94.995849609375},{"x":308.2027893066406,"y":-61.93159103393555},{"x":715.231201171875,"y":334.8396301269531},{"x":749.1502685546875,"y":301.7753601074219}],"textStr":""},{"corners":[{"x":424.97674560546877,"y":65.21974182128906},{"x":391.0577087402344,"y":98.28400421142578},{"x":798.0860595703125,"y":495.0552673339844},{"x":832.005126953125,"y":461.990966796875}],"textStr":""},{"corners":[{"x":385.3042907714844,"y":323.2916259765625},{"x":351.38525390625,"y":356.35589599609377},{"x":758.4136352539063,"y":753.1270751953125},{"x":792.3327026367188,"y":720.0628051757813}],"textStr":""},{"corners":[{"x":20.6610107421875,"y":-30.717756271362306},{"x":-13.257980346679688,"y":2.346524238586426},{"x":393.7703857421875,"y":399.1177673339844},{"x":427.689453125,"y":366.053466796875}],"textStr":""},{"corners":[{"x":292.739501953125,"y":476.9834899902344},{"x":258.8204345703125,"y":510.0477600097656},{"x":665.848876953125,"y":906.8190307617188},{"x":699.767822265625,"y":873.7546997070313}],"textStr":""},{"corners":[{"x":-72.67318725585938,"y":121.05538177490235},{"x":-106.59217834472656,"y":154.11964416503907},{"x":300.43621826171877,"y":550.890869140625},{"x":334.355224609375,"y":517.8265991210938}],"textStr":""},{"corners":[{"x":-15.480880737304688,"y":274.3634948730469},{"x":-49.399871826171878,"y":307.427734375},{"x":357.62847900390627,"y":704.198974609375},{"x":391.54754638671877,"y":671.134765625}],"textStr":""},{"corners":[{"x":162.92251586914063,"y":-88.28025817871094},{"x":129.00347900390626,"y":-55.21599578857422},{"x":536.0318603515625,"y":341.5552673339844},{"x":569.950927734375,"y":308.490966796875}],"textStr":""},{"corners":[{"x":539.9736328125,"y":277.2416076660156},{"x":506.05462646484377,"y":310.305908203125},{"x":913.0829467773438,"y":707.0771484375},{"x":947.0020141601563,"y":674.0128784179688}],"textStr":""},{"corners":[{"x":845.1287231445313,"y":-89.23961639404297},{"x":811.209716796875,"y":-56.17535400390625},{"x":1218.238037109375,"y":340.59588623046877},{"x":1252.1571044921875,"y":307.5316162109375}],"textStr":""},{"corners":[{"x":418.9768981933594,"y":-118.980224609375},{"x":385.0578308105469,"y":-85.91596221923828},{"x":792.0862426757813,"y":310.8552551269531},{"x":826.0052490234375,"y":277.7909851074219}],"textStr":""},{"corners":[{"x":825.7823486328125,"y":273.40411376953127},{"x":791.86328125,"y":306.4683837890625},{"x":1198.8916015625,"y":703.2396240234375},{"x":1232.8106689453125,"y":670.17529296875}],"textStr":""},{"corners":[{"x":308.5308532714844,"y":160.1978759765625},{"x":274.61181640625,"y":193.26214599609376},{"x":681.64013671875,"y":590.0333862304688},{"x":715.5592041015625,"y":556.9691162109375}],"textStr":""},{"corners":[{"x":134.7803497314453,"y":192.8166046142578},{"x":100.86135864257813,"y":225.88088989257813},{"x":507.8897399902344,"y":622.6521606445313},{"x":541.8087768554688,"y":589.587890625}],"textStr":""},{"corners":[{"x":903.593017578125,"y":47.95001220703125},{"x":903.593017578125,"y":95.95623779296875},{"x":1109.4462890625,"y":95.95623779296875},{"x":1109.4462890625,"y":47.95001220703125}],"textStr":""},{"corners":[{"x":962.1188354492188,"y":99.42042541503906},{"x":962.1188354492188,"y":126.60833740234375},{"x":1051.41943359375,"y":126.60833740234375},{"x":1051.41943359375,"y":99.42042541503906}],"textStr":""},{"corners":[{"x":710.5418701171875,"y":48.42136764526367},{"x":710.5418701171875,"y":94.97811889648438},{"x":892.7023315429688,"y":94.97811889648438},{"x":892.7023315429688,"y":48.42136764526367}],"textStr":""},{"corners":[{"x":1031.261962890625,"y":560.4241943359375},{"x":1031.261962890625,"y":597.0425415039063},{"x":1158.2255859375,"y":597.0425415039063},{"x":1158.2255859375,"y":560.4241943359375}],"textStr":""},{"corners":[{"x":883.1456298828125,"y":559.56298828125},{"x":883.1456298828125,"y":595.8507080078125},{"x":1008.3408203125,"y":595.8507080078125},{"x":1008.3408203125,"y":559.56298828125}],"textStr":""},{"corners":[{"x":679.751220703125,"y":337.70001220703127},{"x":679.751220703125,"y":372.23748779296877},{"x":1170.5013427734375,"y":372.23748779296877},{"x":1170.5013427734375,"y":337.70001220703127}],"textStr":""},{"corners":[{"x":708.2402954101563,"y":387.07763671875},{"x":708.2402954101563,"y":425.74322509765627},{"x":1127.72021484375,"y":425.74322509765627},{"x":1127.72021484375,"y":387.07763671875}],"textStr":""},{"corners":[{"x":1012.8131103515625,"y":484.161865234375},{"x":1012.8131103515625,"y":507.6400146484375},{"x":1012.8131103515625,"y":507.6400146484375},{"x":1012.8131103515625,"y":484.161865234375}],"textStr":""},{"corners":[{"x":423.1435546875,"y":42.4984130859375},{"x":423.1435546875,"y":71.35640716552735},{"x":640.395263671875,"y":71.35640716552735},{"x":640.395263671875,"y":42.4984130859375}],"textStr":""},{"corners":[{"x":128.25592041015626,"y":47.820438385009769},{"x":128.25592041015626,"y":69.58753204345703},{"x":346.04364013671877,"y":69.58753204345703},{"x":346.04364013671877,"y":47.820438385009769}],"textStr":""}],"image":[{"corners":[{"x":623.9625244140625,"y":338.26190185546877},{"x":623.9625244140625,"y":589.2619018554688},{"x":1200.9625244140625,"y":589.2619018554688},{"x":1200.9625244140625,"y":338.26190185546877}],"textStr":""}]} +# items = DataReviewService.auto_review(orjson.dumps(rect_location1).decode('utf8'), (1280, 614)) +# for item in items: +# print(item) + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/tasks.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..29e43f43a7ffc5926e7fe7d13c211b9810aadb7b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/tasks.py @@ -0,0 +1,23 @@ +from celery.utils.log import get_task_logger +from celery_app import app as celery_app + +from .service import AiImageSignTask, SubmitAiImageSignTask + +logger = get_task_logger(__name__) + + +@celery_app.task(bind=True, ignore_result=True, queue='lqa_queue_ai_sign') +def run_ai_sign(self, ctx): + """启动任务""" + logger.info(f'run_ai_sign start') + svr = AiImageSignTask(ctx, self.request, logger) + svr.run() + logger.info(f'run_ai_sign end') + + +@celery_app.task(bind=True, ignore_result=True, queue='lqa_queue_submit_ai_sign') +def run_submit_ai_sign(self, ctx): + logger.info(f'run_submit_ai_sign start') + svr = SubmitAiImageSignTask(ctx, self.request, logger) + svr.run() + logger.info(f'run_submit_ai_sign end') diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..8e22c5b7c313dc8d8cad06f5eb797d0490e218f8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/urls.py @@ -0,0 +1,12 @@ + +from django.urls import path + +from .views import * + +urlpatterns = [ + path('entity', ImageView.as_view(), name='image'), + path('list', ImageListView.as_view(), name='image-list'), + path('ai_sign', ImageAiSignView.as_view(), name='image-ai-sign'), + path('data_review', DataReviewView.as_view(), name='data-review'), + # path('resource_version/list', ResourceVersionView.as_view(), name='resource-version-list') +] \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/image/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/image/views.py new file mode 100644 index 0000000000000000000000000000000000000000..c91cb099bec1f4cb6e1909f9ab6115100d204f23 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/image/views.py @@ -0,0 +1,449 @@ +import os +import logging +import time + +import orjson +from django.views.generic import View +from django.db import DatabaseError, transaction +from django.forms.models import model_to_dict +from django.db.models import Q +from PIL import Image as PImage + +import settings +from apps.bug.models import Bug +from apps.data.models import ReviewedEnum, Data +from apps.job.models import Job +from apps.image import service as img_svr +from apps.image.models import * +from apps.image.tasks import run_ai_sign, run_submit_ai_sign +from libs.defs import ApiErrorEnum, JobDiscernEnum +from libs import ApiResponse, PageView, cache, lodash, storage +from .schemas import * + +logger = logging.getLogger('img_view') + + +def _patch_image_info(image, image_bugs_stat, datas_stat=None): + if not datas_stat: + datas_stat = {} + stat = image_bugs_stat.get(image['id']) + image['bug_num'] = stat.get('bug_num', 0) if stat else 0 + image['shot_img_path'] = datas_stat.get(image['data_id'], {}).get('shot_img_path', '') + image['module_id'] = datas_stat.get(image['data_id'], {}).get('module_id', None) + return image + + +class ImageListView(PageView): + Query_Fields = ('id', 'pk__gte', 'pk__lte', 'cur_id', 'job_id', 'data_id', 'err_type', 'will_review', 'is_latest', + 'file_name__contains', 'created_begin_at', 'created_end_at', + 'updated_begin_at', 'updated_end_at', 'reviewed', 'rect_location__contains') + + def get(self, request): + """ + GET /api/image/list + """ + vmi = ImageListSchema.model_validate(request.GET.dict()) + info_type, page, page_size = vmi.info_type, vmi.page, vmi.page_size + + if vmi.pk__gte is not None and vmi.pk__lte is not None and vmi.pk__gte > vmi.pk__lte: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='请检查图片ID范围') + + param = self.make_query_params(vmi) + page_by_where = self.page_by_where(param) + if vmi.languages is not None: + param['language__in'] = vmi.languages + if vmi.data_id: # 多语种对比场景 + if vmi.job_id is None: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='data_id查询时需要job_id参数') + if 'id' in param: + del param['id'] + elif vmi.module_ids is not None: # 模块搜索 + if 'data_id' in param: + del param['data_id'] + param = Q(data_id__in=Data.objects.filter(module__in=vmi.module_ids)) & Q(**param) + if vmi.ai_bug_types and len(vmi.ai_bug_types) > 0: + if isinstance(param, dict): + param = Q(**param) + q = Q() + for ai_bug_type in vmi.ai_bug_types: + q |= Q(ai_bug_types__contains=ai_bug_type) + param &= q + if vmi.rect_location__contains and vmi.languages is None: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='检测文本查询时必须指定"区域语言"') + + fields = () + if info_type == 0: + fields = [field.name for field in Image._meta.fields] + fields.remove('rect_location') + fields.remove('ai_check_detail') + + total, images = self.page_query(Image, param, page, page_size, fields=fields, page_by_where=page_by_where) + + image_bugs_stat = {} + datas_stat = {} + if len(images) > 0: + image_ids = [] + data_ids = [] + img_keys = ('file_path', 'ai_mark_img_path', 'ai_rect_img_path') + for image_ in images: + image_ids.append(image_['id']) + data_ids.append(image_['data_id']) + for img_key in img_keys: + image_[img_key] = f"{image_[img_key]}?_t={image_['updated_at']}" if image_[img_key] else '' + image_bugs_stat = img_svr.image_of_bug_num(image_ids, images[0]['job_id']) + datas = Data.objects.filter(pk__in=data_ids).values('id', 'shot_img_path', 'module_id') + datas_stat = {data['id']: data for data in datas} + for image in images: + _patch_image_info(image, image_bugs_stat, datas_stat) + return ApiResponse(data={'list': images, 'total': total, 'page': vmi.page, 'page_size': vmi.page_size}) + + def patch(self, request): + vmi = ImageListUpdateSchema.model_validate(orjson.loads(request.body)) + body = vmi.model_dump(exclude_unset=True) + ids = body['ids'] + del body['ids'] + num = Image.update_db(ids, body) + return ApiResponse(data={'num': num}) + + +class ImageView(View): + + # 计算 同job data language 下的is_latest iteration属性的正确性 + LOCK_KEY_JOB_DATA_LAN_PREFIX = 'image_job_data_lan_latest_update' + + @classmethod + def _lock_key(cls, job_id, data_id, language): + return f'{cls.LOCK_KEY_JOB_DATA_LAN_PREFIX}:{job_id}_{data_id}_{language}' + + def get(self, request): + """ + GET /api/image/entity + """ + image_id = int(request.GET.get('image_id', 0)) + if not image_id: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='参数错误') + image = Image.objects.filter(pk=image_id).values().first() + if not image: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到image:{image_id}') + image_bugs_stat = img_svr.image_of_bug_num((image['id'], ), image['job_id']) + data = Data.objects.filter(pk=image['data_id']).values('id', 'shot_img_path', 'module_id').first() + datas_stat = {data['id']: data} if data else {} + _patch_image_info(image, image_bugs_stat, datas_stat) + return ApiResponse(data={'image': image}) + + def post(self, request): + """编辑器调用 上传图片 POST /api/image/entity""" + vmi = ImageCreateSchema.model_validate(request.POST.dict()) + + if len(request.FILES) == 0: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='未上传图片') + req_file = next(request.FILES.values()) + + if vmi.regression: + bug_ids = vmi.bug_ids + if len(bug_ids) == 0: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='回归任务,bug_id不运行未空') + bugs_cnt = Bug.objects.filter(pk__in=bug_ids).count() + if bugs_cnt != len(bug_ids): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='存在无效的 bug_id') + + project_id, data_id, job_id, rect_locations, ai_sign, language = (vmi.project_id, vmi.data_id, vmi.job_id, + vmi.rect_locations, vmi.ai_sign, vmi.language) + + # if not Data.objects.filter(job_id=job_id, pk=data_id).exists(): + # return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'job_id:{job_id} data_id:{data_id} dont match') + + if not Job.objects.filter(id=job_id, project_id=project_id).exists(): + return ApiResponse(ApiErrorEnum.ERROR, msg=f'job:{job_id} project_id:{project_id} 不合法') + + current_user = request.user + rect_locations_dict = orjson.loads(rect_locations) + file_name = req_file.name + + image_dr = Image.objects.filter(project_id=project_id, job_id=job_id, data_id=data_id).first() + data_review = DataReview.objects.filter(project_id=project_id, data_id=data_id).first() + data_review_new = None + + data_review_update = False + size_t = PImage.open(req_file).size + size_s = f"{size_t[0]},{size_t[1]}" + if ((data_review and data_review.image_id == 0) + or (image_dr and data_review and data_review.image_id == image_dr.id)): + rect_location_clean, rect_location_check, rect_location_dirty = ( + img_svr.DataReviewService.auto_review(rect_locations_dict, size_t)) + data_review.rect_location = rect_locations + data_review.check_rect_location = rect_location_check + data_review.dirty_rect_location = rect_location_dirty + data_review.size = size_s + data_review.reviewer = "system" + clean_rect_location = rect_location_clean + data_review_update = True + elif data_review and data_review.dirty_rect_location: + clean_rect_location, _ = img_svr.DataReviewService.data_clean(rect_locations, + data_review.dirty_rect_location) + else: + rect_location_clean, rect_location_check, rect_location_dirty = ( + img_svr.DataReviewService.auto_review(rect_locations_dict, size_t)) + review_params = { + "project_id": project_id, + "data_id": data_id, + "rect_location": rect_locations, + "check_rect_location": rect_location_check, + "dirty_rect_location": rect_location_dirty, + "size": size_s, + "reviewer": "system" + } + data_review_new = DataReview(**review_params) + clean_rect_location = rect_location_clean + # 处理文件 + abs_path, url_path = storage.gen_job_file_path(project_id, job_id, 'image', file_name) + req_file.seek(0) + tmp_abs_path, _ = storage.write_temp_file(req_file) + + image_info = { + 'project_id': project_id, + 'job_id': job_id, + 'data_id': data_id, + 'language': language, + 'rect_location': rect_locations, + 'file_name': file_name, + 'file_path': url_path, + 'ai_sign': ai_sign, + 'size': size_s + } + image = Image(**image_info) + + def _save_db(lock): + try: + ids = list(Image.objects.filter(job_id=job_id, data_id=data_id, language=language) + .values_list('id', flat=True)) + image.iteration = len(ids) + 1 # 这里为了计算iteration准确性 所以要加锁 + with transaction.atomic(): + if len(ids) > 0: + Image.update_db(ids, {'is_latest': SwitchEnum.OFF}) + image.save() + if data_review_new: + data_review_new.image_id = image.id + data_review_new.save() + Data.update_db(data_id, {'reviewed': ReviewedEnum.AUTO}) + elif data_review_update: + data_review.image_id = image.id + data_review.save() + Data.update_db(data_id, {'reviewed': ReviewedEnum.AUTO}) + storage.mv_file(tmp_abs_path, abs_path) + except DatabaseError as err: + logger.error('ImageView post err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg='创建失败 写数据库失败') + except Exception as err: + logger.error('ImageView post err1:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'创建失败 err:{str(err)}') + logger.info(f'[event.image.add] user:{current_user["name"]} id:{image.id}') + + lock_key = self._lock_key(job_id, data_id, language) + ok, save_db_response = cache.try_lock(lock_key, _save_db) + if not ok: + return ApiResponse(ApiErrorEnum.ERROR, msg='创建失败 获取锁失败') + if save_db_response: + return save_db_response + + task_id = '' + if vmi.ai_sign or vmi.create_bug or vmi.regression: + ctx = img_svr.prepare_ai_sign_task_ctx(data_review, image, ctx={ + 'clean_rect_location': clean_rect_location, + 'regression': vmi.regression, + 'bug_ids': vmi.bug_ids, + 'discern': vmi.discern, + 'create_bug': vmi.create_bug, + 'staff_name': current_user['name'] + }, trace=f'image_upload:{image.id}') + event = 'event.run_ai_sign_0' + ctx['_event'] = event + task = run_ai_sign.apply_async((ctx,)) # 编辑器上传图片 + task_id = task.task_id + logger.info(f'[{event}] user:{current_user["name"]} ' + f'task_id:{task.task_id} image_id:{image.id}') + image_info = model_to_dict(image) + del image_info['rect_location'] + return ApiResponse(data={'image': image_info, 'task_id': task_id}) + + def delete(self, request): + """ + DELETE /api/image/entity + """ + body = orjson.loads(request.body) + image_ids = body.get('image_ids', []) + image_id = int(body.get('image_id', '0')) + project_id = int(body.get('project_id', 0)) + if not project_id or (len(image_ids) == 0 and image_id == 0): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='参数错误') + if image_id: + image_ids = [image_id] + + imgs = Image.objects.filter(pk__in=image_ids).values() + if len(imgs) != len(image_ids): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='image_ids存在异常数据') + + errs = [] + use_imgs = [] + for img in imgs: + if project_id != img['project_id']: + errs.append((img["id"], f'image_id:{img["id"]} project_id:{project_id} 不匹配')) + continue + use_imgs.append(img) + + job_ids = list(Job.objects.filter(project_id=project_id).values_list('id', flat=True)) + + def _save_db(lock, img_info): + ts = [int(time.time() * 1000)] + with (transaction.atomic()): + ts.append(int(time.time() * 1000)) + image_id = img_info['id'] + images = Image.objects.filter(job_id=job_id, data_id=data_id, language=language, project_id=project_id + ).order_by('-iteration', '-id').values('id', 'is_latest') + if len(images) == 0: + return + ts.append(int(time.time() * 1000)) + # 计算 iteration 和 is_latest + max_iteration_of_image_id = 0 + all_image_ids_set = set() + for image_ in images: + if image_['id'] != image_id: + all_image_ids_set.add(image_['id']) + if max_iteration_of_image_id == 0: + max_iteration_of_image_id = image_['id'] + if len(all_image_ids_set) > 0: + all_image_ids_set.remove(max_iteration_of_image_id) + logger.info(f'delete image, set image_id:{all_image_ids_set} is_latest=0') + Image.update_db(all_image_ids_set, {'is_latest': 0}) + if max_iteration_of_image_id: + logger.info(f'delete image, set image_id:{max_iteration_of_image_id} is_latest=1') + Image.update_db(max_iteration_of_image_id, {'is_latest': 1}) + ts.append(int(time.time() * 1000)) + # 更新DataReview + data_review = DataReview.objects.filter(project_id=project_id, image_id=image_id).first() + if data_review: + ts.append(int(time.time() * 1000)) + rect_location = check_rect_location = dirty_rect_location = '{}' + image_id_ = 0 + size_ = '' + # 为了用上索引 这里查询用job_id__in=job_ids 替代 project_id=project_id + image_new = Image.objects.filter(job_id__in=job_ids, data_id=data_id).exclude(id=image_id)\ + .order_by('id').first() + if image_new: + ts.append(int(time.time() * 1000)) + image_id_ = image_new.id + size_ = image_new.size + ret = img_svr.DataReviewService.auto_review(image_new.rect_location, image_new.size) + ts.append(int(time.time() * 1000)) + rect_location = image_new.rect_location + check_rect_location = ret[1] + dirty_rect_location = ret[2] + logger.info( + f'delete image, update data_review:{data_review.id} with image:{image_new.id}') + else: + logger.info(f'delete image, update data_review:{data_review.id} empty') + data_review.rect_location = rect_location + data_review.check_rect_location = check_rect_location + data_review.dirty_rect_location = dirty_rect_location + data_review.reviewer = "system" + data_review.size = size_ + data_review.image_id = image_id_ + data_review.save() + Data.update_db(data_id, {'reviewed': ReviewedEnum.AUTO}) + logger.info(ts) + # 删除Image记录 + Image.objects.filter(pk=image_id).delete() + logger.info(f'delete image: {image_id}') + # 删除文件 + for field in ('file_path', 'ai_mark_img_path', 'ai_rect_img_path'): + field_path = img_info[field] + if field_path: + file_path_abs = storage.get_abs_path(field_path) + storage.mv_to_temp(file_path_abs) + logger.info(f'delete image {image_id} {project_id} {field_path}') + logger.info(f'[event.image.del] user:{current_user["name"]} image_id:{image_id}') + + current_user = request.user + for img_info_ in use_imgs: + try: + job_id, data_id, language = img_info_['job_id'], img_info_['data_id'], img_info_['language'] + lock_key = self._lock_key(job_id, data_id, language) + ok, _ = cache.try_lock(lock_key, _save_db, img_info_) + if not ok: + errs.append((img_info_['id'], '删除失败 获取锁失败')) + except Exception as err: + logger.error('DataView save err:', exc_info=err) + errs.append((img_info_['id'], str(err))) + + return ApiResponse(data={'errs': errs}) + + +class ImageAiSignView(View): + + def post(self, request): + """手动批量图片识别 POST /api/image/ai_sign""" + vmi = ImageAiSignRequestSchema.model_validate(orjson.loads(request.body)) + image_id, job_id, discern, languages = vmi.image_id, vmi.job_id, vmi.discern, vmi.languages + if not image_id and not job_id: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'job_id和image_id不能同时为空') + logger.info(f'image ai sign: image_id:{image_id} job_id:{job_id}') + + current_user = request.user + param = {} + if languages and len(languages) > 0: + param['language__in'] = languages + if image_id: + param['pk'] = image_id + else: + param.update({'job_id': job_id, 'is_latest': 1}) + ctx = {'param': param, 'current_user': current_user, 'discern': discern} + if image_id: # 单个任务,同步执行 + run_submit_ai_sign(ctx) + else: # 批量任务,异步执行 + run_submit_ai_sign.apply_async((ctx,)) + return ApiResponse(msg='提交成功') + + +class DataReviewView(View): + def get(self, request): + """GET /api/image/data_review """ + data_id = int(request.GET.get('data_id', 0)) + project_id = int(request.GET.get('project_id', 0)) + + if not data_id or not project_id: + return ApiResponse(ApiErrorEnum.ERROR_PARAM) + + dr = DataReview.objects.filter(project_id=project_id, data_id=data_id).first() + if not dr: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='数据无审核记录,请先还原图片') + dr = model_to_dict(dr) + rect_location = img_svr.DataReviewService.rect_location_to_corners(dr['rect_location'], dr['size']) + dr['rect_location'] = rect_location + return ApiResponse(data={'data_review': dr}) + + def patch(self, request): + """PATCH /api/image/data_review """ + vmi = DataReviewPatchSchema.model_validate(orjson.loads(request.body)) + try: + orjson.loads(vmi.check_rect_location) + orjson.loads(vmi.dirty_rect_location) + except Exception as err: + logger.error(f'data_review parse err: {err}') + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'rect_location 或 dirty_rect_location json解析失败') + + dr = DataReview.objects.filter(pk=vmi.id).values('id', 'data_id').first() + if not dr: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到 DataReview:{vmi.id}') + data_id = dr['data_id'] + if not Data.objects.filter(pk=data_id).exists(): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到 Data:{data_id}') + + staff = request.user['name'] + body = vmi.model_dump(exclude={'id'}, exclude_unset=True) + body['reviewer'] = staff + with transaction.atomic(): + DataReview.update_db(vmi.id, body) + Data.update_db(data_id, {'reviewed': ReviewedEnum.MANUAL}) + + return ApiResponse() + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee49d1d75d680e51fddf77263bc01eac4c54bec --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class JobConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.job' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..b154edebbdb71f1652bb4c668b0a4c406de433e3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/migrations/0001_initial.py @@ -0,0 +1,103 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('project', '0001_initial'), + ('user', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Job', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('name', models.CharField(max_length=64, verbose_name='任务名称')), + ('languages', models.JSONField(default=list, verbose_name='需要还原的语言')), + ('discern', models.IntegerField(choices=[(0, '全量识别'), (1, '差异识别')], default=1, verbose_name='识别类型')), + ('ocr_detect', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='是否ocr')), + ('status', models.IntegerField(choices=[(1, '未执行'), (2, '执行中'), (3, '执行失败'), (4, '执行成功'), (5, '执行完')], default=1, verbose_name='任务状态')), + ('parent_id', models.IntegerField(default=0, verbose_name='父任务id')), + ('regression_bug_ids', models.JSONField(default=list, verbose_name='需要回归bug的id')), + ('sign_bug_types', models.JSONField(default=list, verbose_name='识别bug类型')), + ('svn_url', models.CharField(default='', max_length=128)), + ('svn_version', models.CharField(default='', max_length=64)), + ('build_id', models.CharField(default='', max_length=128, verbose_name='外部构建ID/链接(Webhook 返回)')), + ('build_no', models.CharField(default='', max_length=64, verbose_name='外部构建编号')), + ('bill_bug_types', models.JSONField(default=list, verbose_name='提单bug类型')), + ('priority', models.IntegerField(choices=[(0, '空'), (1, '紧急'), (2, '高'), (3, '中'), (4, '低'), (5, '无关紧要')], default=5, verbose_name='优先级')), + ('severity', models.IntegerField(choices=[(0, '空'), (1, '致命'), (2, '严重'), (3, '一般'), (4, '提示'), (5, '建议')], default=4, verbose_name='严重程度')), + ('version_report', models.CharField(default='', max_length=32, verbose_name='发现版本')), + ('version_fix', models.CharField(default='', max_length=32, verbose_name='合入版本')), + ('release_id', models.CharField(default='', max_length=32, verbose_name='发布计划')), + ('plan_start_at', models.DateTimeField(blank=True, verbose_name='预约开始时间')), + ('plan_end_at', models.DateTimeField(blank=True, verbose_name='预约结束时间')), + ('exec_start_at', models.DateTimeField(blank=True, null=True, verbose_name='实际开始时间')), + ('exec_end_at', models.DateTimeField(blank=True, null=True, verbose_name='实际结束时间')), + ('remark', models.CharField(default='', max_length=255, verbose_name='备注')), + ('celery_task_id', models.CharField(default='', max_length=64, verbose_name='celery_task id')), + ('data_ids', models.JSONField(default=list, verbose_name='补充数据id')), + ('all_data_ids', models.JSONField(default=list, verbose_name='任务结束后填充')), + ('config_path99', models.CharField(default='', max_length=128, verbose_name='99配置表路径')), + ('reason', models.TextField(default='', verbose_name='任务失败原因')), + ('creator', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='user.user')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_job', + }, + ), + migrations.CreateModel( + name='JobDevice', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('job_id', models.BigIntegerField(verbose_name='job id')), + ('execute_pc', models.CharField(max_length=64, verbose_name='执行的机器')), + ('language', models.IntegerField(verbose_name='还原的语言')), + ('status', models.CharField(max_length=32, verbose_name='状态')), + ('editor_nums', models.IntegerField(verbose_name='编辑器数量')), + ], + options={ + 'db_table': 'lqa_job_device', + 'constraints': [models.UniqueConstraint(fields=('job_id', 'execute_pc', 'language'), name='idx__job_pc_language')], + }, + ), + migrations.CreateModel( + name='JobExtra', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('job_id', models.BigIntegerField(primary_key=True, serialize=False, verbose_name='job id')), + ('test_app_file_path', models.CharField(default='', max_length=128, verbose_name='测试app存储路径')), + ('test_case_file_path', models.CharField(default='', max_length=128, verbose_name='测试用例存储路径')), + ('proj_res_type', models.CharField(choices=[('git', 'Git'), ('svn', 'Svn'), ('p4', 'P4'), ('other', 'Other')], default='git', max_length=16, verbose_name='项目资源')), + ('proj_res_repo', models.CharField(default='', max_length=128, verbose_name='项目资源仓库')), + ('proj_res_br', models.CharField(default='', max_length=32, verbose_name='项目资源分支')), + ('proj_res_ver', models.CharField(default='', max_length=32, verbose_name='项目资源版本')), + ('proj_res_file_path', models.CharField(default='', max_length=64, verbose_name='项目资源其他')), + ('trans_res_type', models.CharField(choices=[('git', 'Git'), ('svn', 'Svn'), ('p4', 'P4'), ('other', 'Other')], default='git', max_length=16, verbose_name='翻译资源')), + ('trans_res_repo', models.CharField(default='', max_length=128, verbose_name='翻译资源仓库')), + ('trans_res_br', models.CharField(default='', max_length=32, verbose_name='翻译资源分支')), + ('trans_res_ver', models.CharField(default='', max_length=32, verbose_name='翻译资源版本')), + ('trans_res_file_path', models.CharField(default='', max_length=64, verbose_name='翻译资源其他')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_job_extra', + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/models.py new file mode 100644 index 0000000000000000000000000000000000000000..fec5adf8c6bddfa8934d53201874a05b19a8f46c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/models.py @@ -0,0 +1,83 @@ +from django.db import models + +from libs import BaseAttrModel +from libs.defs import (JobStatusEnum, BugPriorityEnum, BugSeverityEnum, SwitchEnum, JobDiscernEnum, + JobResTypeEnum) +from apps.project.models import Project +from apps.user.models import User + + +class Job(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + creator = models.ForeignKey(User, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=64, verbose_name='任务名称') + languages = models.JSONField(default=list, verbose_name='需要还原的语言') # 提交参数是数组,这里指定为数组 + discern = models.IntegerField(choices=JobDiscernEnum, default=JobDiscernEnum.DIFF, verbose_name='识别类型') + ocr_detect = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='是否ocr') + status = models.IntegerField(choices=JobStatusEnum, default=JobStatusEnum.UN_RUNNING, verbose_name='任务状态') + # 回归任务 + parent_id = models.IntegerField(default=0, verbose_name='父任务id') + regression_bug_ids = models.JSONField(default=list, verbose_name='需要回归bug的id') + sign_bug_types = models.JSONField(default=list, verbose_name='识别bug类型') # ai识别时用到 + # 还原执行(由前端调用项目配置的 Webhook 触发) + svn_url = models.CharField(max_length=128, default='') + svn_version = models.CharField(max_length=64, default='') + build_id = models.CharField(max_length=128, default='', verbose_name='外部构建ID/链接(Webhook 返回)') + build_no = models.CharField(max_length=64, default='', verbose_name='外部构建编号') + # 提单配置 + bill_bug_types = models.JSONField(default=list, verbose_name='提单bug类型') + priority = models.IntegerField(choices=BugPriorityEnum, default=BugPriorityEnum.INSIGNIFICANT, verbose_name='优先级') + severity = models.IntegerField(choices=BugSeverityEnum, default=BugSeverityEnum.PROMT, verbose_name='严重程度') + version_report = models.CharField(max_length=32, default='', verbose_name='发现版本') + version_fix = models.CharField(max_length=32, default='', verbose_name='合入版本') + release_id = models.CharField(max_length=32, default='', verbose_name='发布计划') + + plan_start_at = models.DateTimeField(blank=True, verbose_name='预约开始时间') + plan_end_at = models.DateTimeField(blank=True, verbose_name='预约结束时间') + exec_start_at = models.DateTimeField(blank=True, null=True, verbose_name='实际开始时间') + exec_end_at = models.DateTimeField(blank=True, null=True, verbose_name='实际结束时间') + remark = models.CharField(max_length=255, default='', verbose_name='备注') + + celery_task_id = models.CharField(max_length=64, default='', verbose_name='celery_task id') + data_ids = models.JSONField(default=list, verbose_name='补充数据id') + all_data_ids = models.JSONField(default=list, verbose_name='任务结束后填充') + config_path99 = models.CharField(max_length=128, default='', verbose_name='99配置表路径') + reason = models.TextField(default='', verbose_name='任务失败原因') + + class Meta: + # app_label = 'job' + db_table = 'lqa_job' + + +class JobExtra(BaseAttrModel): + job_id = models.BigIntegerField(primary_key=True, verbose_name='job id') + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + test_app_file_path = models.CharField(max_length=128, default='', verbose_name='测试app存储路径') + test_case_file_path = models.CharField(max_length=128, default='', verbose_name='测试用例存储路径') + proj_res_type = models.CharField(choices=JobResTypeEnum, default=JobResTypeEnum.GIT, max_length=16, verbose_name='项目资源') + proj_res_repo = models.CharField(max_length=128, default='', verbose_name='项目资源仓库') + proj_res_br = models.CharField(max_length=32, default='', verbose_name='项目资源分支') + proj_res_ver = models.CharField(max_length=32, default='', verbose_name='项目资源版本') + proj_res_file_path = models.CharField(max_length=64, default='', verbose_name='项目资源其他') + trans_res_type = models.CharField(choices=JobResTypeEnum, default=JobResTypeEnum.GIT, max_length=16, verbose_name='翻译资源') + trans_res_repo = models.CharField(max_length=128, default='', verbose_name='翻译资源仓库') + trans_res_br = models.CharField(max_length=32, default='', verbose_name='翻译资源分支') + trans_res_ver = models.CharField(max_length=32, default='', verbose_name='翻译资源版本') + trans_res_file_path = models.CharField(max_length=64, default='', verbose_name='翻译资源其他') + + class Meta: + db_table = 'lqa_job_extra' + + +class JobDevice(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + job_id = models.BigIntegerField(verbose_name='job id') + execute_pc = models.CharField(max_length=64, verbose_name='执行的机器') + language = models.IntegerField(verbose_name='还原的语言') + status = models.CharField(max_length=32, verbose_name='状态') + editor_nums = models.IntegerField(verbose_name='编辑器数量') + + class Meta: + db_table = 'lqa_job_device' + constraints = [models.UniqueConstraint(fields=['job_id', 'execute_pc', 'language'], name='idx__job_pc_language')] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/runner.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..254a25007ab6ade5b62fa0a19f3efc9a7fe978e5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/runner.py @@ -0,0 +1,136 @@ +""" +还原任务执行:前端调用 Webhook 触发外部执行器(Jenkins / GitLab CI / 自建服务等) + +流程: + 1. 前端点击“开始/重试” -> POST /api/job/action {action: start|retry} + 后端校验任务状态,按项目配置渲染出 Webhook 请求(url/method/headers/body)返回给前端 + 2. 前端浏览器直接请求 Webhook(目标服务需允许 LQA 域名跨域) + 3. 请求成功后前端 -> POST /api/job/action {action: started, regression, build_id} + 后端把任务置为“执行中” + 4. 执行器(Unity 编辑器等)按原有接口拉取数据、上传截图: + GET /api/job/datas、POST /api/image/entity、POST /api/job/device + +模板变量: url / headers / body 中可以使用 {{变量名}},见 runner_variables() + body 中某个字符串值恰好等于 "{{变量名}}" 时,替换为变量的原始类型(数字/数组) +""" +import re +from urllib.parse import quote + +import orjson + +import settings +from apps.project import service as proj_svr +from apps.project.models import Project +from libs import defs + +_VAR_PATTERN = re.compile(r'\{\{\s*([a-zA-Z0-9_]+)\s*\}\}') + +# 平台标准 code -> UE 还原插件 code 的反向映射 +# 平台内部统一使用 ISO 国家码(如 LAN_KO_KR), 但 UE 还原插件 ConfigManager.cpp +# 的 LanguageMap 认的是另一套命名(如 LAN_KO_KO)。 +# 触发 Webhook 直接把平台 code 拼到 UE 命令行 -Language= 参数时, 需要先翻译一次。 +# 该映射由 LanguageValidator._UE_LANGUAGE_CODE_ALIASES 反转而来, 两边保持同步。 +_WMP_TO_UE_LANGUAGE_CODE = { + v: k for k, v in proj_svr.LanguageValidator._UE_LANGUAGE_CODE_ALIASES.items() +} + + +class RunnerConfigError(Exception): + pass + + +def _to_ue_lang(code): + """平台 code -> UE 还原插件 code; 不在映射表的保持原值""" + return _WMP_TO_UE_LANGUAGE_CODE.get(code, code) + + +def runner_variables(job, regression, runner_cfg) -> dict: + """可在 Webhook 模板中使用的变量""" + project = Project.objects.filter(pk=job.project_id).values('id', 'code', 'name').first() or {} + img_revert_cfg = list(proj_svr.ProjCfgService.get_img_revert(job.project_id)) + language_path = img_revert_cfg[0].get('root_path', '') if img_revert_cfg else '' + sys_languages = proj_svr.ProjCfgService.get_sys_language(True) + language_names = [sys_languages[lan]['name'] for lan in job.languages if lan in sys_languages] + create_bug = 1 if job.bill_bug_types and regression != defs.JobRegressionEnum.REGRESSION else 0 + # job.languages 存的是语言数字 ID (如 [6, 3, 2]), sys_languages[id]['name'] 是平台标准 code (如 'LAN_KO_KR'), + # 再经 _to_ue_lang 反向翻译为 UE 还原插件认识的 code (如 'LAN_KO_KO') + ue_language_values = [_to_ue_lang(name) for name in language_names] + return { + 'job_id': job.id, + 'job_name': job.name, + 'parent_job_id': job.parent_id, + 'project_id': job.project_id, + 'project_code': project.get('code', ''), + 'project_name': project.get('name', ''), + 'languages': ','.join(language_names), + 'language_values': list(job.languages), + # UE 还原插件专用的语言编码(已按 LanguageValidator._UE_LANGUAGE_CODE_ALIASES 反向翻译) + # Webhook 直接拉起 UE 时, 命令行 -Language= 必须用这个值, 否则插件 ConfigManager 无法识别。 + 'ue_language_values': ue_language_values, + 'ue_languages': ','.join(ue_language_values), + 'regression': int(regression), + 'discern': int(job.discern), + 'create_bug': create_bug, + 'svn_url': job.svn_url, + 'svn_version': job.svn_version, + 'language_path': language_path, + 'editor_path': runner_cfg.get('editor_path', ''), + 'editor_version': runner_cfg.get('editor_version', ''), + 'lqa_server': (getattr(settings, 'PUBLIC_URL', '') or '').rstrip('/'), + } + + +def _render_str(text, variables, url_encode=False): + def _sub(m): + key = m.group(1) + if key not in variables: + return m.group(0) + val = variables[key] + val = ','.join(map(str, val)) if isinstance(val, (list, tuple)) else str(val) + return quote(val, safe='') if url_encode else val + return _VAR_PATTERN.sub(_sub, text) + + +def _render_obj(obj, variables): + if isinstance(obj, dict): + return {k: _render_obj(v, variables) for k, v in obj.items()} + if isinstance(obj, list): + return [_render_obj(v, variables) for v in obj] + if isinstance(obj, str): + m = _VAR_PATTERN.fullmatch(obj.strip()) + if m and m.group(1) in variables: + return variables[m.group(1)] + return _render_str(obj, variables) + return obj + + +def build_trigger(job, regression) -> dict: + """渲染 Webhook 请求,供前端直接发起""" + runner_cfg = proj_svr.ProjCfgService.get_runner(job.project_id) + if not runner_cfg: + raise RunnerConfigError('请先在“项目设置 > 基础配置 > 还原执行”中配置 Webhook 地址') + variables = runner_variables(job, regression, runner_cfg) + + try: + headers = orjson.loads(runner_cfg['webhook_headers'] or '{}') + except orjson.JSONDecodeError: + raise RunnerConfigError('Webhook 请求头不是合法的 JSON') + headers = {str(k): _render_str(str(v), variables) for k, v in headers.items()} + + method = (runner_cfg['webhook_method'] or 'POST').upper() + body = None + if method != 'GET': + tpl = (runner_cfg['webhook_body'] or '').strip() + try: + body = _render_obj(orjson.loads(tpl), variables) if tpl else variables + except orjson.JSONDecodeError: + raise RunnerConfigError('Webhook 请求体模板不是合法的 JSON') + headers.setdefault('Content-Type', 'application/json') + + return { + 'url': _render_str(runner_cfg['webhook_url'].strip(), variables, url_encode=True), + 'method': method, + 'headers': headers, + 'body': body, + 'variables': variables, + } diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..b3cf65655ffb00ecb8913c5cab77175099f8d915 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/schemas.py @@ -0,0 +1,101 @@ +from typing import List, Optional, Annotated, Literal +import datetime + +from pydantic import BaseModel, Field, BeforeValidator + +from libs import defs, util +from apps.project import service as proj_svr + + +class JobListSchema(BaseModel): + project_id: int + id: int = Field(default=None, ge=0) + name__icontains: str = Field(default=None, alias='name') + module_id: int = Field(default=None) + language: Annotated[int, BeforeValidator(proj_svr.LanguageValidator())] = Field(default=None) + status: defs.JobStatusEnum = Field(default=None) + is_parent: int = Field(default=None) + creator_id: int = Field(default=None) + created_begin_at: datetime.datetime = Field(default=None, alias='begin_at') + created_end_at: datetime.datetime = Field(default=None, alias='end_at') + children: int = Field(default=0) # 是否查询子任务 + info_type: int = Field(default=0) # 0:简略信息 1:详细信息 + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2, le=100) + + +class JobSchema(BaseModel): + id: int = Field(default=None) + project_id: int + discern: defs.JobDiscernEnum + ocr_detect: defs.SwitchEnum = Field(default=defs.SwitchEnum.OFF) + name: str = Field(min_length=2) + languages: Annotated[List[int], BeforeValidator(proj_svr.LanguageValidator())] = Field(min_length=1) + plan_start_at: datetime.datetime + plan_end_at: datetime.datetime + data_ids: List[int] = Field(default_factory=list) + sign_bug_types: Annotated[List[int], BeforeValidator(proj_svr.BugTypeValidator())] = Field(default=None) + bill_bug_types: Annotated[List[int], BeforeValidator(proj_svr.BugTypeValidator())] = Field(default=None) + priority: defs.BugPriorityEnum = Field(default=None) + severity: defs.BugSeverityEnum = Field(default=None) + version_report: str = Field(default=None) + version_fix: str = Field(default=None) + release_id: str = Field(default=None) + svn_url: str = Field(default='') + svn_version: str = Field(default='') + + +class JobExtraSchema(BaseModel): + test_app_file_path: Annotated[str, BeforeValidator(lambda v: v or '')] = Field(default='') + test_case_file_path: Annotated[str, BeforeValidator(lambda v: v or '')] = Field(default='') + proj_res_type: defs.JobResTypeEnum = Field(default=defs.JobResTypeEnum.GIT) + proj_res_repo: str = Field(default='') + proj_res_br: str = Field(default='') + proj_res_ver: str = Field(default='') + proj_res_file_path: Annotated[str, BeforeValidator(lambda v: v or '')] = Field(default='') + trans_res_type: defs.JobResTypeEnum = Field(default=defs.JobResTypeEnum.GIT) + trans_res_repo: str = Field(default='') + trans_res_br: str = Field(default='') + trans_res_ver: str = Field(default='') + trans_res_file_path: Annotated[str, BeforeValidator(lambda v: v or '')] = Field(default='') + + +class JobGetSchema(BaseModel): + job_id: int = Field(gt=0) + progress: defs.SwitchEnum = Field(default=defs.SwitchEnum.OFF) + fields: Annotated[List[str], BeforeValidator(util.make_item_array_validator(item_class=str))] = Field(default_factory=lambda: []) + mappings: Literal['0', '1'] = Field(default='0') + + +class JobBugRegressSchema(BaseModel): + bug_ids: List[int] = Field(min_length=1) + discern: defs.JobDiscernEnum + + +class JobDatasSchema(BaseModel): + job_id: int + regression: defs.JobRegressionEnum = Field(default=defs.JobRegressionEnum.NORMAL) + language: Annotated[int, BeforeValidator(proj_svr.LanguageValidator())] = Field(default=None) + count: int = Field(default=10, gt=0) # 一次获取个数 + minID: int = Field(default=0, ge=0) # 最小id + module_ids: Annotated[List[int], BeforeValidator(util.make_item_array_validator())] = ( + Field(default_factory=lambda: [], min_length=1)) + iteration: int = Field(default=1, ge=0) # 迭代次数 + use_cache: int = Field(default=1, ge=0) + + +class JobDeviceCreateSchema(BaseModel): + job_id: int = Field(ge=1) + execute_pc: str = Field(min_length=1) + language: Annotated[int, BeforeValidator(proj_svr.LanguageValidator())] = Field(gt=0) + status: str = Field(min_length=1) + editor_nums: int = Field(ge=0) + + +class JobActionSchema(BaseModel): + action: Literal['start', 'stop', 'retry', 'started'] + job_id: int = Field(gt=0) + # 以下仅 action=started 时使用 + regression: defs.JobRegressionEnum = Field(default=defs.JobRegressionEnum.NORMAL) + build_id: str = Field(default='', description='Webhook 返回的外部构建ID/链接') diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/service.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/service.py new file mode 100644 index 0000000000000000000000000000000000000000..106979dfbcc45b4b1bc160bb1667399d5923d0f4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/service.py @@ -0,0 +1,472 @@ +import datetime +import os +import time +import logging +import threading +import itertools +from typing import List, Union + +import orjson +from munch import Munch as AttrDict +from django.db import transaction, DatabaseError +from django.db.models import Count, Q + +from apps.project import service as proj_svr +from apps.project.models import Project +from apps.data.models import Data +from apps.job.models import Job, JobExtra +from apps.image.models import Image +from apps.bug.models import Bug +from libs import defs, cache, lodash, util, storage +from libs.decorators import test_project_user_role_by_project_id + +logger = logging.getLogger('job_svr') + + +def _query_image_data_ids(param_, language_=None, module_ids_=(), counter_=False, seq_=None, iteration=0): + """如果查询没有指定language_ 可能会出现重复data_id 这是预期之中""" + logger.info(f'_query_image_data_ids seq:{seq_} p:{param_} lan:{language_} m:{module_ids_} c:{counter_} ' + f'i:{iteration}') + if iteration > 0 and 'is_latest' in param_: + del param_['is_latest'] + qs_ = Image.objects.filter(**param_) + if iteration: + qs_ = qs_.filter(iteration=iteration) + if language_: + qs_ = qs_.filter(language=language_) + if len(module_ids_) > 0: + qs_ = qs_.filter(data_id__in=Data.objects.filter(module__in=module_ids_)) + return qs_.count() if counter_ else list(qs_.values_list('data_id', flat=True)) + + +def job_of_data_ids(job_dict_or_id, action, language=None, module_ids=(), counter=False, seq=None, + iteration=0) -> Union[List, int]: + """ + 获取任务的data id !!!如果 job_dict_or_id 是dict 检查是否包含 id,data_ids,parent_id + action = 1 # 获取任务所有的data_id,当是回归任务时不查Data表,因为不跟job_id绑定 + action = 2 # 场景 已经还原的data id + action = 3 # 场景 编辑器获取未还原的data id + action = 4 # 场景 任务详情计算任务进度时获取已经还原成功的 data id + """ + if seq is None: + seq = next(util.seq_generator) + + if isinstance(job_dict_or_id, int): + job_dict = None + job_id = job_dict_or_id + else: + job_dict = job_dict_or_id + job_id = job_dict['id'] + + logger.info(f'job_of_data_ids seq:{seq} act:{action} job:{job_id} lan:{language} m:{module_ids} c:{counter} ' + f'i:{iteration}') + + if action == 1: # all + if not job_dict: + job_dict = Job.objects.filter(pk=job_id).values('data_ids', 'parent_id').first() # 补充数据id + data_ids = job_dict['data_ids'] + if job_dict['parent_id'] != 0: # 回归任务,不需要跑跟job_id绑定的data + if len(data_ids) > 0 and len(module_ids) > 0: + # 这里的data_ids可能不是同一job下的 + qs = Data.objects.filter(pk__in=data_ids, module__in=module_ids) + return qs.count() if counter else list(qs.values_list('id', flat=True)) + return len(data_ids) if counter else data_ids + else: # 非回归任务 + param = Q(job_id=job_id) + if len(data_ids) > 0: + param |= Q(pk__in=data_ids) + qs = Data.objects.filter(param) + if len(module_ids) > 0: + qs = qs.filter(module__in=module_ids) + return qs.count() if counter else list(qs.values_list('id', flat=True)) + elif action == 2: # imaged + param = {'job_id': job_id, 'is_latest': defs.SwitchEnum.ON} + return _query_image_data_ids(param, language, module_ids, counter, seq, iteration) + elif action == 3: # unimaged + all_data_ids = job_of_data_ids(job_dict_or_id, 1, language, module_ids, counter, seq, iteration) + imaged_data_ids = job_of_data_ids(job_dict_or_id, 2, language, module_ids, counter, seq, iteration) + if counter: + return all_data_ids - imaged_data_ids + return list(set(all_data_ids) - set(imaged_data_ids)) + elif action == 4: # imaged and ai_sign + param = {'job_id': job_id, 'is_latest': defs.SwitchEnum.ON, 'ai_sign_suc__gt': 0} + return _query_image_data_ids(param, language, module_ids, counter, seq, iteration) + + +class JobOfDataIdsQuery(object): + """查询任务相关的data ids,利用缓存""" + + def __init__(self, job_id): + self.job_id = job_id + """ + cache_datas + { + id: {id: id, module_id: module_id}, + } + """ + self._cache_datas = {} + self._cache_bd_datas = {} + """cache_of_images + {image_id: { + id: id, + is_latest: is_latest, + ai_sign_suc: ai_sign_suc, + language: language, + module: module, + iteration: iteration + } + } + """ + self._cache_of_images = {} + + self._updated_at = 0 + self.EXPIRE = 60 + self.DELTA_CNT = self.EXPIRE * 8 + + self.lock = threading.Lock() + + def _update_cache_data(self, job_id): + """查询全量数据""" + now = time.time() + if now - self._updated_at < self.EXPIRE: + return + + job_dict = Job.objects.filter(pk=job_id).values('data_ids', 'parent_id').first() + _cache_bd_datas = dict() + if len(job_dict['data_ids']) > 0: + datas_ = Data.objects.filter(id__in=job_dict['data_ids']).values('id', 'module_id') + _cache_bd_datas = {data_['id']: data_ for data_ in datas_} + + datas_ = Data.objects.filter(job_id=job_id).values('id', 'module_id') + _cache_datas = {data_['id']: data_ for data_ in datas_} + + images_ = Image.objects.filter(job_id=job_id).values('id', 'is_latest', 'ai_sign_suc', 'language', 'iteration', + 'data_id') + _cache_of_images = {image_['id']: image_ for image_ in images_} + + self._cache_bd_datas = _cache_bd_datas + self._cache_datas = _cache_datas + self._cache_of_images = _cache_of_images + + self._updated_at = now + + logger.info(f'_update_cache_data job_id: {job_id} datas:{len(_cache_datas)} bd_datas:{len(_cache_bd_datas)} ' + f'images:{len(_cache_of_images)}') + + def get_cache_data(self): + """获取全量数据""" + if time.time() - self._updated_at > self.EXPIRE: + with self.lock: + self._update_cache_data(self.job_id) + return self._cache_datas, self._cache_bd_datas, self._cache_of_images + + def query_delta_data(self, job_id): + """查询增量数据""" + datas_ = Data.objects.filter(job_id=job_id).values('id', 'module_id').order_by('-id')[:self.DELTA_CNT] + images_ = Image.objects.filter(job_id=job_id).values('id', 'is_latest', 'ai_sign_suc', 'language', 'data_id', + 'iteration').order_by('-id')[:self.DELTA_CNT] + return datas_, images_ + + def _image_of_data_ids(self, data_tpl, where, counter=False, seq=None): + """如果查询没有指定language_ 可能会出现重复data_id 这是预期之中""" + is_latest = where['is_latest'] + ai_sign_suc__gt = where.get('ai_sign_suc__gt', None) + language = where['language'] + module_ids = where['module_ids'] + iteration = where['iteration'] + images, delta_images = data_tpl[3].values(), data_tpl[4] + + logger.info(f'_image_of_data_ids seq:{seq} counter:{counter} where:{where}') + + data_ids_set = set() + for image_ in itertools.chain(images, delta_images): + if ai_sign_suc__gt is not None and image_['ai_sign_suc'] <= ai_sign_suc__gt: + continue + if language and language != image_['language']: + continue + if iteration and iteration != image_['iteration']: + continue + if iteration == 0 and is_latest != image_['is_latest']: + continue + data_ids_set.add(image_['data_id']) + + if len(data_ids_set) > 0 and len(module_ids) > 0: + data_ids_set1 = set(Data.objects.filter(job_id=self.job_id, module__in=module_ids) + .values_list('id', flat=True)) + return len(data_ids_set & data_ids_set1) if counter else (data_ids_set & data_ids_set1) + + return len(data_ids_set) if counter else data_ids_set + + def _job_of_data_ids(self, data_tpl, job_dict, action, language=None, module_ids=(), counter=False, + seq=None, iteration=0) -> Union[set, int]: + job_id = job_dict['id'] + + if seq is None: + seq = next(util.seq_generator) + + logger.info(f'_job_of_data_ids seq:{seq} act:{action} job:{job_id} lan:{language} m:{module_ids} c:{counter} ' + f'i:{iteration}') + + if action == 1: # all + datas, bd_datas, delta_datas = data_tpl[0].values(), data_tpl[1].values(), data_tpl[2] + if job_dict['parent_id'] != 0: # 回归任务,不需要跑跟job_id绑定的data + if len(module_ids) > 0: + module_ids_set = set(module_ids) + data_ids_set = {data_['id'] for data_ in bd_datas if data_['module_id'] in module_ids_set} + else: + data_ids_set = {data_['id'] for data_ in bd_datas} + return len(data_ids_set) if counter else data_ids_set + else: # 非回归任务 + if len(module_ids) > 0: + module_ids_set = set(module_ids) + data_ids_set = {data_['id'] for data_ in + itertools.chain(datas, bd_datas, delta_datas) + if data_['module_id'] in module_ids_set} + else: + data_ids_set = {data_['id'] for data_ in itertools.chain(datas, bd_datas, delta_datas)} + return len(data_ids_set) if counter else data_ids_set + + elif action == 2: # imaged + where = { + 'is_latest': defs.SwitchEnum.ON, + 'language': language, + 'module_ids': module_ids, + 'iteration': iteration + } + return self._image_of_data_ids(data_tpl, where, counter, seq) + + elif action == 3: # unimaged + all_data_ids_set = self._job_of_data_ids(data_tpl, job_dict, 1, language, module_ids, counter, seq, + iteration) + imaged_data_ids_set = self._job_of_data_ids(data_tpl, job_dict, 2, language, module_ids, counter, seq, + iteration) + if counter: + return all_data_ids_set - imaged_data_ids_set + return all_data_ids_set - imaged_data_ids_set + + elif action == 4: # imaged and ai_sign + where = { + 'is_latest': defs.SwitchEnum.ON, + 'ai_sign_suc__gt': 0, + 'language': language, + 'module_ids': module_ids, + 'iteration': iteration + } + return self._image_of_data_ids(data_tpl, where, counter, seq) + + def job_of_data_ids(self, job_dict_or_id, action, language=None, module_ids=(), counter=False, + seq=None, iteration=0) -> Union[List, int]: + """获取任务的data ids""" + job_dict, job_id = (None, job_dict_or_id) if isinstance(job_dict_or_id, int) \ + else (job_dict_or_id, job_dict_or_id['id']) + + if not job_dict: + job_dict = Job.objects.filter(pk=job_id).values('data_ids', 'parent_id').first() # 补充数据id + + datas, bd_datas, images = self.get_cache_data() + + delta_datas, delta_images = self.query_delta_data(job_id) + + data_tpl = (datas, bd_datas, delta_datas, images, delta_images) + + return self._job_of_data_ids(data_tpl, job_dict, action, language, module_ids, counter, seq, iteration) + + +class JobOfDataIdsQueryManager(object): + """按job管理查询器""" + def __init__(self): + self.querys = {} + self.lock = threading.Lock() + + def get_query(self, job_id) -> JobOfDataIdsQuery: + """ get_query """ + if job_id in self.querys: + return self.querys[job_id] + + with self.lock: + if job_id not in self.querys: + self.querys[job_id] = JobOfDataIdsQuery(job_id) + + return self.querys[job_id] + + +_job_of_data_ids_query_manager = JobOfDataIdsQueryManager() + + +def job_of_data_ids_query(job_id): + """按job获取查询器""" + return _job_of_data_ids_query_manager.get_query(job_id) + + +def update_job_extra_files(job_extra, job_extra_old=None): + """处理文件更新""" + file_cates = ('test_app', 'test_case', 'proj_res', 'trans_res') + if job_extra_old is None: + job_extra_old = AttrDict({f'{cate}_file_path': '' for cate in file_cates}) + project_id = job_extra.project_id + job_id = job_extra.job_id + update_fields = {} + for cate in file_cates: + field = f'{cate}_file_path' + url_path_new = getattr(job_extra, field, '') + url_path_old = getattr(job_extra_old, field, '') + if url_path_new == '' or url_path_new == url_path_old: + continue + _, file_ext = os.path.splitext(url_path_new) + file_name = f'{job_id}-{cate}{file_ext}' if file_ext else f'{job_id}-{cate}.zip' + abs_path_new, url_path = storage.gen_job_file_path(project_id, job_id, 'comm', file_name) + if url_path_old: + abs_url_path_old = storage.get_abs_path(url_path_old) + if os.path.exists(abs_url_path_old): + storage.mv_to_temp(abs_url_path_old) + tmp_abs_path_new = storage.get_abs_path(url_path_new) # 如果有更新,url_path_new还是临时路径 + storage.mv_file(tmp_abs_path_new, abs_path_new) # 将临时路径移到正式路径 + update_fields[field] = url_path + if len(update_fields) > 0: + JobExtra.update_db(job_id, update_fields) + + +def create_job_by_custom(vmi, vmi_extra, user): + """普通创建job""" + project = Project.objects.filter(pk=vmi.project_id).values('id', 'cvtest_project').first() + if not project or project['cvtest_project'].strip() == '': + return '项目未配置“AI识别项目名”,请联系超级管理员在“项目管理”中完善', None + + if not proj_svr.ProjCfgService.get_runner(vmi.project_id): + return '请先通过路径 “项目设置 > 基础配置 > 还原执行” 配置 Webhook', None + + job_body = vmi.model_dump(exclude={'id'}, exclude_unset=True) + job_body['creator_id'] = user['id'] + job = Job(**job_body) + + job_extra_body = vmi_extra.model_dump(exclude_unset=True) + job_extra_body['project_id'] = vmi.project_id + job_extra = JobExtra(**job_extra_body) + with transaction.atomic(): + job.save() + job_extra.job_id = job.id + job_extra.save() + update_job_extra_files(job_extra, None) + logger.info(f'[event.job.add] at:0 user:{user["name"]} job_id:{job.id}') + return '', job + + +def create_job_by_regress_bugs(vmi, vmi_extra, user): + """通过bug回归创建任务""" + bug_ids = list(set(vmi.bug_ids)) + bugs = Bug.objects.filter(pk__in=bug_ids) + if len(bugs) != len(bug_ids): + return '存在无效 bug_ids', None + + project_id = bugs[0].project_id + if not test_project_user_role_by_project_id(user, project_id): + return f'没有项目权限 project_id:{project_id}', None + + if not proj_svr.ProjCfgService.get_runner(project_id): + return '请先通过路径 “项目设置 > 基础配置 > 还原执行” 配置 Webhook', None + + image_ids_set = set() + for bug_ in bugs: + # 正在回归的bug不再回归 + if bug_.regress_status != defs.BugRegressStatusEnum.RUNNING: + image_ids_set.add(bug_.image_id) + + if len(image_ids_set) == 0: + return '无有效的image_ids', None + + images = Image.objects.filter(pk__in=image_ids_set).values('id', 'job_id', 'project_id', 'data_id') # image 可能已经被删除 + + job_ids_set = set() + project_ids_set = set() + use_image_ids_set = set() + data_ids_set = set() + for image_ in images: + project_ids_set.add(image_['project_id']) + job_ids_set.add(image_['job_id']) + use_image_ids_set.add(image_['id']) + data_ids_set.add(image_['data_id']) + + if len(job_ids_set) == 0: + return '无满足条件的任务id', None + if len(job_ids_set) != 1: + return '回归的bug任务id必须相同', None + if len(project_ids_set) != 1: + return '回归的bug项目必须相同', None + + use_data_ids_set = set(Data.objects.filter(pk__in=data_ids_set).values_list('id', flat=True)) + + use_bugs = [] + use_bug_ids = [] + for _bug in bugs: + if _bug.image_id in use_image_ids_set: # image 可能已经被删除所以要过滤一次 + use_bugs.append(_bug) + use_bug_ids.append(_bug.id) + if len(use_bugs) == 0: + return '无满足条件的bug_ids', None + + job_id = job_ids_set.pop() + job = Job.objects.filter(pk=job_id).first() + if not job: + return f'未找到原始任务,job_id:{job_id}', None + if job.parent_id: + return f'不允许在回归任务上再次回归,请在原始任务上回归,job_id:{job_id}', None + + fields = lodash.pick(job, ['project_id', 'languages', 'bill_bug_types', + 'plan_start_at', 'plan_end_at', + 'priority', 'severity', 'version_report', 'version_fix', 'release_id', 'config_path99']) + fields.update({ + 'discern': vmi.discern, + 'creator_id': user['id'], + 'name': job.name + "-回归", + 'parent_id': job_id, + 'regression_bug_ids': use_bug_ids, + 'data_ids': list(use_data_ids_set), + 'svn_url': '', + 'svn_version': '', + }) + + updated_at = util.datetime_ms() + job_regress = Job(**fields) + job_extra_body = vmi_extra.model_dump(exclude_unset=True) + job_extra_body['project_id'] = project_id + job_extra = JobExtra(**job_extra_body) + with transaction.atomic(): + job_regress.save() + job_extra.job_id = job_regress.id + job_extra.save() + bugs_ = [] + for bug_ in use_bugs: + bug_.regress_status = defs.BugRegressStatusEnum.RUNNING + bug_.regress_job_ids.append(job_regress.id) + bug_.updated_at = updated_at + bugs_.append(bug_) + if len(bugs_) > 0: + Bug.objects.bulk_update(bugs_, ('regress_status', 'regress_job_ids', 'updated_at')) + update_job_extra_files(job_extra, None) + logger.info(f'[event.job.add] at:1 user:{user["name"]} job_id:{job.id} job_regress:{job_regress.id}') + return '', job_regress + + +def job_of_regress_num(job_ids, project_id): + param = {'parent_id__in': job_ids, 'project_id': project_id} + rows = Job.objects.filter(**param).values('id', 'parent_id') + stat = {} + for row in rows: + job = stat.get(row['parent_id'], {'id': row['parent_id'], 'children': []}) + job['children'].append(row['id']) + stat[row['parent_id']] = job + if len(job_ids) != len(rows): + delt_pk_set = set(job_ids) - set(stat.keys()) + for pk in delt_pk_set: + stat[pk] = {'id': pk, 'children': []} + return stat + + +def job_of_bug_num(job_ids, project_id): + param = {'job_id__in': job_ids, 'project_id': project_id} + stats = list(Bug.objects.filter(**param).values('job_id').annotate(bug_num=Count('job_id'))) + if len(stats) != len(job_ids): + delt_pks_set = set(job_ids) - set(map(lambda stat: stat['job_id'], stats)) + for pk_ in delt_pks_set: + stats.append({'job_id': pk_, 'bug_num': 0}) + return {st_['job_id']: st_ for st_ in stats} diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..73e594f2a66d908490d2a7f727ad4c81154e3453 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/urls.py @@ -0,0 +1,15 @@ + +from django.urls import path + +from .views import * + +urlpatterns = [ + path('list', JobListView.as_view(), name='job-list'), + path('entity', JobView.as_view(), name='job'), + path('bug_regress', JobBugRegressView.as_view(), name='job-bug-gegress'), + # path('retry', JobRetryView.as_view(), name='job-retry'), + path('datas', JobDatasView.as_view(), name='job-datas'), + path('device', JobDeviceView.as_view(), name='job-device'), + path('action', JobActionView.as_view(), name='job-action'), + path('progress', view_job_progress, name='job-progress') +] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/job/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/job/views.py new file mode 100644 index 0000000000000000000000000000000000000000..efa6285bb1e6765a8287fa8ca8f74fb43e96c23d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/job/views.py @@ -0,0 +1,374 @@ +import logging + +import orjson +from django.forms.models import model_to_dict +from django.views.generic import View +from django.utils.decorators import method_decorator +from munch import Munch as AttrDict + +from apps.image.models import Image +from apps.image import service as img_svr +from apps.image import tasks as img_task +from apps.data.models import Data +from apps.job.models import * +from apps.job import service as job_svr +from apps.job import runner +from apps.project import service as proj_svr +from libs import ApiResponse, PageView, cache, lodash, util +from libs.decorators import require_project_perm, test_project_user_role_by_project_id +from libs.defs import ApiErrorEnum, JobRegressionEnum, JobStatusEnum +from .schemas import * + +logger = logging.getLogger('job_view') + + +class JobListView(PageView): + fields_simple = ('id', 'project_id', 'creator_id', 'name', 'languages', 'status', 'reason', 'created_at', + 'updated_at', 'parent_id', 'plan_start_at', 'plan_end_at') + + Query_Fields = ('cur_id', 'project_id', 'id', 'name__icontains', 'status', 'creator_id', + 'created_begin_at', 'created_end_at') + + def get(self, request): + vmi = JobListSchema.model_validate(request.GET.dict()) + + project_id, info_type, page, page_size = vmi.project_id, vmi.info_type, vmi.page, vmi.page_size + is_parent = vmi.is_parent + + param = self.make_query_params(vmi) + if vmi.language: + param['languages__contains'] = vmi.language + if 'id' in param: + job_info = Job.objects.filter(pk=param['id']).values('id', 'parent_id').first() + if job_info is None: + # 指定 id 的任务不存在,直接返回空列表,避免后续 None 下标访问报错 + return ApiResponse(data={'list': [], 'total': 0, 'page': page, 'page_size': page_size}) + if is_parent is not None: + if is_parent > 0 and job_info['parent_id'] == 0: # 搜子级 + del param['id'] + param['parent_id'] = job_info['id'] + elif is_parent == 0 and job_info['parent_id'] > 0: # 搜父级 + param['id'] = job_info['parent_id'] + else: + if is_parent is not None: # 筛选是否回归数据 + if is_parent == 0: + param['parent_id'] = 0 + else: + param['parent_id__gt'] = 0 + fields = self.fields_simple if info_type == 0 else () + + total, jobs = self.page_query(Job, param, page, page_size, fields=fields) + all_job_ids = list(map(lambda x: x['id'], jobs)) + + # 统计回归任务数 {job_id: {job_id, children:[]}} + job_regress_stat = job_svr.job_of_regress_num(all_job_ids, project_id) + # 统计缺陷数 {job_id: {job_id, bug_num}} + job_bugs_stat = job_svr.job_of_bug_num(all_job_ids, project_id) + + if 'id' in param and total == 1 and all_job_ids and param['id'] == all_job_ids[0]: # id 查询时返回children信息 + children = Job.objects.filter(parent_id=param['id']).values(*fields).order_by('-id') + jobs[0]['children'] = children + all_job_ids.extend(list(map(lambda x: x['id'], children))) + + job_ext_info_stat = {} if info_type == 0 else \ + {o_['job_id']: o_ for o_ in JobExtra.objects.filter(pk__in=all_job_ids).values()} + + for job_ in jobs: + _job_id = job_['id'] + job_ext_info = job_ext_info_stat.get(_job_id, {}) + job_.update(job_ext_info) + job_['regress_num'] = len(job_regress_stat[_job_id]['children']) if _job_id in job_regress_stat else 0 + job_['bug_num'] = job_bugs_stat[_job_id]['bug_num'] if _job_id in job_bugs_stat else 0 + + return ApiResponse(data={'list': jobs, 'total': total, 'page': page, 'page_size': page_size}) + + +class JobView(View): + + @method_decorator(require_project_perm()) + def post(self, request): + """创建普通Job""" + body_json = getattr(request, 'body_json', None) or orjson.loads(request.body) + vmi = JobSchema.model_validate(body_json) + vmi_extra = JobExtraSchema.model_validate(body_json) + vmi.plan_start_at = util.datetime_ms(vmi.plan_start_at) + vmi.plan_end_at = util.datetime_ms(vmi.plan_end_at) + + # if vmi.plan_start_at < datetime.datetime.now() or vmi.plan_start_at > vmi.plan_end_at: + # return ApiResponse(ApiErrorEnum.ERROR, msg='存在无效时间,请检查') + if vmi_extra.trans_res_repo == '' and vmi_extra.trans_res_file_path: + return ApiResponse(ApiErrorEnum.ERROR, msg='译文资源不能为空') + + err_msg, job = job_svr.create_job_by_custom(vmi, vmi_extra, request.user) + if err_msg: + return ApiResponse(ApiErrorEnum.ERROR, msg=err_msg) + return ApiResponse(data={'job': model_to_dict(job)}) + + @method_decorator(require_project_perm()) + def patch(self, request): + """修改job信息""" + body_json = getattr(request, 'body_json', None) or orjson.loads(request.body) + vmi = JobSchema.model_validate(body_json) + vmi_extra = JobExtraSchema.model_validate(body_json) + vmi.plan_start_at = util.datetime_ms(vmi.plan_start_at) + vmi.plan_end_at = util.datetime_ms(vmi.plan_end_at) + job_id = vmi.id + if not Job.objects.filter(pk=job_id, project_id=vmi.project_id).exists(): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到job:{job_id}') + + job_info = vmi.model_dump(exclude={'id', 'project_id'}, exclude_unset=True) + if len(job_info) > 0: # 更新job信息 + Job.update_db(job_id, job_info) + + job_extra_info = vmi_extra.model_dump(exclude_unset=True) + if len(job_extra_info) > 0: + job_extra_old = JobExtra.objects.filter(pk=job_id).first() + if not job_extra_old: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'未找到job_extra:{job_id}') + JobExtra.update_db(job_id, job_extra_info) # 更新job_extra信息 + job_extra_info['job_id'] = job_id + job_extra_info['project_id'] = vmi.project_id + job_svr.update_job_extra_files(AttrDict(job_extra_info), job_extra_old) # 更新job_extra管理文件信息 + return ApiResponse(msg='提交成功') + + def get(self, request): + """任务详情 编辑器也有调用""" + vmi = JobGetSchema.model_validate(request.GET.dict()) + job_id, progress, fields, mappings = vmi.job_id, vmi.progress, vmi.fields, vmi.mappings + + job_info = Job.objects.filter(pk=job_id).values().first() + if job_info is None: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到job:{job_id}') + job_info_bak = job_info + + job_ext_info = JobExtra.objects.filter(pk=job_id).values().first() + if job_ext_info is None: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到job_extra:{job_id}') + job_ext_info.update(job_info) + job_info = job_ext_info + + if progress: + all_count = len(job_svr.job_of_data_ids(job_info_bak, 1)) + ai_signed_count = len(job_svr.job_of_data_ids(job_info_bak, 4)) + job_info['progress_rate'] = f'{ai_signed_count}/{all_count}' + job_info['all_count'] = all_count + job_info['ai_signed_count'] = ai_signed_count + + if len(fields) > 0: + job_info = lodash.pick(job_info, fields) + data = {'job': job_info} + + if mappings == '1': + _fields = ('name', 'value', 'label') + data['mappings'] = { + 'language': [lodash.pick(o_, _fields) for o_ in proj_svr.ProjCfgService.get_sys_language()], + 'bug_type': [lodash.pick(o_, _fields) for o_ in proj_svr.ProjCfgService.get_sys_bugtype()], + 'status': [lodash.pick(o_, _fields) for o_ in util.choices_to_python(JobStatusEnum)] + } + return ApiResponse(data=data) + + +class JobActionView(View): + """ + 任务启/停/重试(还原任务由前端调用 Webhook 触发,见 apps/job/runner.py) + start 未执行的任务:返回渲染后的 Webhook 请求,前端负责发起 + retry 重试:重新提交未完成识别的图片,并返回 Webhook 请求 + started 前端调用 Webhook 成功后回调:任务置为执行中 + stop 结束任务 + """ + + def _lock_key(self, job_id): + return f'action_job:{job_id}' + + def _check_no_ai_mark_image(self, request, job): + """检查ai_mark_img_path为空的Image并提交ai_sign任务""" + images = Image.objects.filter(job_id=job.id, is_latest=1, ai_mark_img_path='').values() + if len(images) == 0: + return + + empty_location_list = [] + for image_ in images: + if image_['rect_location'] == '': + empty_location_list.append(image_['id']) + if len(empty_location_list) > 0: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'有数据文本框集合为空请检查,image_ids: {empty_location_list}') + logger.info(f'_check_no_ai_mark_image images_len:{len(images)}') + + current_user = request.user + discern = job.discern + code, ctx_list = img_svr.prepare_ai_sign_task_ctx_with_images(images, discern, current_user) + if code == 0: + logger.info(f'prepare_ai_sign_task_ctx_with_images2 code:{code} ctx_list_len:{len(ctx_list)}') + event = 'event.run_ai_sign_2' + for ctx in ctx_list: + ctx['_event'] = event + task = img_task.run_ai_sign.apply_async((ctx,)) # 接口图片识别 + logger.info(f'[{event}] user:{current_user["name"]} ' + f'task_id:{task.task_id} image_id:{ctx["image_id"]} discern:{discern}') + else: + logger.warning(f'prepare_ai_sign_task_ctx_with_images2 code:{code}') + + @staticmethod + def _trigger_response(job, regression, msg): + try: + trigger = runner.build_trigger(job, regression) + except runner.RunnerConfigError as err: + return ApiResponse(ApiErrorEnum.ERROR, msg=str(err)) + return ApiResponse(msg=msg, data={'job_id': job.id, 'regression': int(regression), 'trigger': trigger}) + + def start_job(self, request, job): + if job.status != JobStatusEnum.UN_RUNNING: + return ApiResponse(ApiErrorEnum.ERROR, msg='任务已运行过,请重试任务') + regression = JobRegressionEnum.REGRESSION if job.parent_id else JobRegressionEnum.NORMAL + return self._trigger_response(job, regression, '请求已生成,正在调用 Webhook') + + def retry_job(self, request, job): + def _retry_job(lock): + api_response_ = self._check_no_ai_mark_image(request, job) + if api_response_: + return api_response_ + return self._trigger_response(job, JobRegressionEnum.RETRY, '请求已生成,正在调用 Webhook') + + locked, api_response = cache.try_lock(self._lock_key(job.id), _retry_job, timeout=30) + return api_response if locked else ApiResponse(ApiErrorEnum.ERROR, msg='lock fail, 请稍后再试') + + def started_job(self, request, job, vmi): + """Webhook 调用成功:设置任务状态为执行中""" + def _started(lock): + if vmi.regression != JobRegressionEnum.RETRY and \ + Job.objects.filter(pk=job.id).values_list('status', flat=True).first() != JobStatusEnum.UN_RUNNING: + return ApiResponse(ApiErrorEnum.ERROR, msg='任务已运行过,请重试任务') + mapping = {'status': JobStatusEnum.RUNNING, 'build_id': vmi.build_id[:128], 'build_no': '', + 'reason': '', 'exec_start_at': util.datetime_ms(), 'exec_end_at': None} + Job.update_db(job.id, mapping) + logger.info(f'[event.job.started] user:{request.user["name"]} job_id:{job.id} ' + f'regression:{vmi.regression} build_id:{vmi.build_id}') + return ApiResponse(msg='成功开启任务') + + locked, api_response = cache.try_lock(self._lock_key(job.id), _started, timeout=30) + return api_response if locked else ApiResponse(ApiErrorEnum.ERROR, msg='lock fail, 请稍后再试') + + def stop_job(self, request, job): + """只需要改变任务状态""" + def _stop_job(lock): + Job.update_db(job.id, {'status': JobStatusEnum.COMPLETED, 'exec_end_at': util.datetime_ms()}) + return ApiResponse(msg=f"成功关闭任务") + + locked, api_response = cache.try_lock(self._lock_key(job.id), _stop_job, timeout=30) + return api_response if locked else ApiResponse(ApiErrorEnum.ERROR, msg='lock fail, 请稍后再试') + + def post(self, request): + vmi = JobActionSchema.model_validate(orjson.loads(request.body)) + action, job_id = vmi.action, vmi.job_id + + job = Job.objects.filter(pk=job_id).first() + if not job: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'未找到job:{job_id}') + if not test_project_user_role_by_project_id(request.user, job.project_id): + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='没有该项目的权限') + + logger.info(f'[event.job.action] user:{request.user["name"]} action:{action} job_id:{job_id}') + + if action == 'start': + return self.start_job(request, job) + elif action == 'retry': + return self.retry_job(request, job) + elif action == 'started': + return self.started_job(request, job, vmi) + elif action == 'stop': + return self.stop_job(request, job) + + +class JobBugRegressView(View): + def post(self, request): + """创建bug回归任务(创建后由前端调用 /api/job/action start 触发执行)""" + body = orjson.loads(request.body) + vmi = JobBugRegressSchema.model_validate(body) + vmi_extra = JobExtraSchema.model_validate(body) + + err_msg, job = job_svr.create_job_by_regress_bugs(vmi, vmi_extra, request.user) + if err_msg: + return ApiResponse(ApiErrorEnum.ERROR, msg=err_msg) + return ApiResponse(data={'job': model_to_dict(job)}) + + +class JobDatasView(View): + def get(self, request): + """编辑器调用 获取任务datas""" + vmi = JobDatasSchema.model_validate(request.GET.dict()) + job_id, regression, language, count, min_id = vmi.job_id, vmi.regression, vmi.language, vmi.count, vmi.minID + module_ids, iteration, use_cache = vmi.module_ids, vmi.iteration, vmi.use_cache + + job = Job.objects.filter(pk=job_id).values('id', 'languages', 'parent_id', 'regression_bug_ids', 'data_ids').first() + if not job: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='f未找到job:{job_id}') + if language is not None and language not in job['languages']: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'非法的language: {language}') + + if use_cache: + data_ids = job_svr.job_of_data_ids_query(job_id).job_of_data_ids(job, 3, language, module_ids, + iteration=iteration) + else: + data_ids = job_svr.job_of_data_ids(job, 3, language, module_ids, iteration=iteration) + order_data_ids = sorted(data_ids) + ret_data_ids = [] + if min_id > 0: + for data_id in order_data_ids: + if len(ret_data_ids) >= count: + break + if data_id > min_id: + ret_data_ids.append(data_id) + else: + ret_data_ids = order_data_ids[:count] + datas = Data.query_batch_by_pks(ret_data_ids, ('id', 'file_path', 'module_id')) + data = {'bug_ids': [], 'datas': datas} + if regression == JobRegressionEnum.REGRESSION: # 回归时获取的数据 + data['bug_ids'] = job['regression_bug_ids'] + return ApiResponse(data=data) + + +class JobDeviceView(View): + """这个view主要处理 编辑器还原情况上报 """ + def post(self, request): + vmi = JobDeviceCreateSchema.model_validate(orjson.loads(request.body)) + job_id, execute_pc, language = vmi.job_id, vmi.execute_pc, vmi.language + + job_dev = JobDevice.objects.filter(job_id=job_id, execute_pc=execute_pc, language=language).values('id').first() + if job_dev: # 更新 + mapping = vmi.model_dump(exclude_unset=True) + JobDevice.update_db(job_dev['id'], mapping) + else: # 创建 + JobDevice(**vmi.model_dump(exclude_unset=True)).save() + return ApiResponse() + + def get(self, request): + job_id = int(request.GET.get('job_id', 0)) + jds = JobDevice.objects.filter(job_id=job_id).order_by('updated_at').values() + proj_svr.patch_language_code(jds) + return ApiResponse(data={'list': jds}) + + +def view_job_progress(request): + job_id = int(request.GET.get('job_id', 0)) + + job = Job.objects.filter(pk=job_id).values('id', 'languages', 'data_ids', 'parent_id').first() + if not job: + return ApiResponse(ApiErrorEnum.NOT_EXIST, f'job:{job_id}不存在') + + all_data_count = job_svr.job_of_data_ids(job, 1, counter=True) + all_imaged_count = job_svr.job_of_data_ids(job, 2, counter=True) + + languges = [] + + for language in job['languages']: + imaged_count = job_svr.job_of_data_ids(job, 2, language, counter=True) + languges.append({ + 'language': language, + 'imaged_count': imaged_count, + 'imaged_count_per': f'{int(imaged_count / all_data_count * 100) if all_data_count > 0 else 0}%' + }) + return ApiResponse(data={ + 'all_data_count': all_data_count, + 'all_imaged_count': all_imaged_count, + 'languges': languges + }) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5abf88ea76864a8d7252a828acb8978b21a5bddb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/__init__.py @@ -0,0 +1,3 @@ +from celery_app import app as celery_app + +__all__ = ('celery_app',) \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_admin.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..40b1ade6274493d0d65c354969a9b0c8aba5bdb4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_admin.py @@ -0,0 +1,45 @@ +""" +创建/重置超级管理员 + +python manage.py init_admin --username admin --password 'Admin@123456' + 也可通过环境变量 LQA_ADMIN_USERNAME / LQA_ADMIN_PASSWORD 传入(便于容器启动时自动初始化) + --if-not-exists 已存在任意超级管理员时跳过 +""" +import os + +from django.core.management.base import BaseCommand, CommandError +from pydantic import TypeAdapter, ValidationError + +from apps.user.models import User +from apps.user.schemas import Password, Username +from libs.defs import SwitchEnum, UserStatusEnum + + +class Command(BaseCommand): + help = '创建或重置超级管理员账号' + + def add_arguments(self, parser): + parser.add_argument('--username', default=os.environ.get('LQA_ADMIN_USERNAME', 'admin')) + parser.add_argument('--password', default=os.environ.get('LQA_ADMIN_PASSWORD', '')) + parser.add_argument('--if-not-exists', action='store_true', help='已存在超级管理员时跳过') + + def handle(self, *args, **options): + if options['if_not_exists'] and User.objects.filter(is_admin=SwitchEnum.ON).exists(): + self.stdout.write('已存在超级管理员,跳过') + return + try: + username = TypeAdapter(Username).validate_python(options['username']) + password = TypeAdapter(Password).validate_python(options['password']) + except ValidationError as err: + raise CommandError(f'参数不合法: {err.errors()[0]["msg"]}') + + user = User.objects2.filter(name=username).first() + created = user is None + if created: + user = User(name=username, name_zh=username) + user.is_delete = 0 + user.is_admin = SwitchEnum.ON + user.status = UserStatusEnum.ACTIVE + user.set_password(password) + user.save() + self.stdout.write(self.style.SUCCESS(f'超级管理员 {username} {"已创建" if created else "密码已重置"}')) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_data.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_data.py new file mode 100644 index 0000000000000000000000000000000000000000..475f9087d9b9db05c924e790f805735d6ded180b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/init_data.py @@ -0,0 +1,81 @@ +""" +初始化系统数据(可重复执行): + - 系统模板项目(id=0),存放系统级的缺陷类型、区域语言,新建项目时会复制这些配置 + - 默认缺陷类型、区域语言 + +python manage.py init_data +""" +from django.core.management.base import BaseCommand +from django.db import transaction + +from apps.project.models import Project, ProjectConfigBugType, ProjectConfigLanguage +from apps.system.models import SystemLanguage +from libs.defs import QCC_PROJECT_ID, ProjectTypeEnum, ProjectPhaseEnum, GameTypeEnum + +# (value, name, label) value 与 AI 识别服务约定的缺陷类型编号一致 +DEFAULT_BUG_TYPES = ( + (1, 'MISS_TRANS', '漏译'), + (2, 'OVERFLOW', '超框'), + (3, 'MISS_KEY', '漏key'), + (4, 'OVERLAP', '标准框重叠'), + (5, 'ERR_TRANS', '错译'), + (7, 'NON_STANDARD_FRAME', '非标准框'), + (8, 'ERR_TRANS_RULE', '错译(规则)'), + (9, 'LINE_HEIGHT', '行高百分比'), + (10, 'FONT_TOO_SMALL', '字体太小'), +) + +# (value, code, label) 其中 2/4/5/6/8/10 与 AI 识别服务的语言编码映射一致(见 apps/image/service.py) +DEFAULT_LANGUAGES = ( + (2, 'LAN_EN_US', '英语'), + (3, 'LAN_KO_KR', '韩语'), + (4, 'LAN_TH_TH', '泰语'), + (5, 'LAN_VI_VN', '越南语'), + (6, 'LAN_JA_JP', '日语'), + (7, 'LAN_RU_RU', '俄语'), + (8, 'LAN_ZH_TW', '繁体中文'), + (9, 'LAN_FR_FR', '法语'), + (10, 'LAN_ZH_CN', '简体中文'), + (11, 'LAN_TR_TR', '土耳其语'), + (12, 'LAN_DE_DE', '德语'), + (13, 'LAN_ES_ES', '西班牙语'), + (14, 'LAN_PT_BR', '葡萄牙语'), + (15, 'LAN_ID_ID', '印尼语'), + (16, 'LAN_AR_SA', '阿拉伯语'), +) + + +class Command(BaseCommand): + help = '初始化系统模板项目、默认缺陷类型和区域语言' + + def _ensure_template_project(self): + if Project.objects2.filter(pk=QCC_PROJECT_ID).exists(): + return False + # 需要 libs.db_mysql 后端(允许 id=0 且启用 NO_AUTO_VALUE_ON_ZERO) + Project.objects.create(id=QCC_PROJECT_ID, code='__system__', name='系统模板', + project_type=ProjectTypeEnum.PLATFORM, project_phase=ProjectPhaseEnum.ONLINE, + game_type=str(GameTypeEnum.MOBILE_GAME.value)) + if not Project.objects2.filter(pk=QCC_PROJECT_ID).exists(): + raise RuntimeError('系统模板项目 id=0 创建失败,请确认使用的是 libs.db_mysql 数据库后端') + return True + + @transaction.atomic + def handle(self, *args, **options): + created = self._ensure_template_project() + self.stdout.write(f'系统模板项目(id={QCC_PROJECT_ID}): {"已创建" if created else "已存在"}') + + n = 0 + for value, name, label in DEFAULT_BUG_TYPES: + _, c = ProjectConfigBugType.objects.get_or_create( + project_id=QCC_PROJECT_ID, value=value, defaults={'name': name, 'label': label, 'trans_marks': '[]'}) + n += int(c) + self.stdout.write(f'缺陷类型: 新增 {n} 条') + + n = 0 + for value, code, label in DEFAULT_LANGUAGES: + _, c = ProjectConfigLanguage.objects.get_or_create( + project_id=QCC_PROJECT_ID, value=value, defaults={'name': code, 'label': label}) + SystemLanguage.objects.get_or_create(id=value, defaults={'language': label, 'language_code': code}) + n += int(c) + self.stdout.write(f'区域语言: 新增 {n} 条') + self.stdout.write(self.style.SUCCESS('初始化完成')) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/update_access_token.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/update_access_token.py new file mode 100644 index 0000000000000000000000000000000000000000..93cb530617c50730fcdc494b89f05e7ba8c6ce8f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/management/commands/update_access_token.py @@ -0,0 +1,16 @@ +from django.core.management.base import BaseCommand + +from apps.user import service as user_svr + + +class Command(BaseCommand): + + def add_arguments(self, parser): + parser.add_argument("-u", "--uid", type=int, required=True, help="请输入uid") + parser.add_argument("-e", "--exp", type=int, default=864000*30, help="请输入过期时间单位秒,默认30天") + + def handle(self, *args, **options): + uid = options['uid'] + exp = options['exp'] + access_token = user_svr.update_user_access_token(uid, exp) + print(f'==> uid:{uid}, exp:{exp} access_token:{access_token}') diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/middleware.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1206f047e521fe2a573efcf58b6226d96946b4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/middleware.py @@ -0,0 +1,185 @@ +import logging + +import orjson +from django.utils.deprecation import MiddlewareMixin +from pydantic import ValidationError + +from libs.util import md5, time_ms, get_client_ip +from libs import ApiResponse, lodash, cache +from libs.defs import ApiErrorEnum, Minute_5 +from settings import NODE_NAME + +logger = logging.getLogger('lqa_ware') +logger_access = logging.getLogger('access') + + +# 参数校验错误中,字段英文名 -> 中文标签 的映射。 +# 没有命中的字段会直接显示英文名(不会导致出错),后续按需补充即可。 +FIELD_LABELS = { + 'name': '英文名', + 'name_zh': '中文名', + 'username': '用户名', + 'password': '密码', + 'old_password': '原密码', + 'new_password': '新密码', + 'email': '邮箱', + 'department': '部门', + 'roles': '角色', + 'role': '角色', + 'project_id': '项目', + 'status': '状态', + 'is_admin': '管理员', + 'id': 'ID', + 'code': '项目代号', + 'game_type': '游戏类型', + 'page': '页码', + 'page_size': '每页条数', +} + + +# 常见正则校验失败时的人类可读规则说明。key 是字段英文名(loc 最后一段), +# 命中后会替换掉通用的“格式不正确”提示。 +# 说明文案需和 schemas 里的 Field.description / xxx_HELP 常量保持一致。 +PATTERN_HELP = { + 'name': '需以字母开头,3~32 位,只能包含字母、数字、下划线、点、中划线', + 'username': '需以字母开头,3~32 位,只能包含字母、数字、下划线、点、中划线', + 'email': '邮箱格式不正确(例如:name@example.com)', +} + + +def _field_key(loc): + """取 loc 路径的最后一段字段名,用于查 PATTERN_HELP。""" + if not loc: + return '' + for item in reversed(loc): + if not isinstance(item, int): + return str(item) + return '' + + +def _loc_to_label(loc): + """把 pydantic 的 loc 路径(元组/列表)转成中文/英文字段标签。""" + if not loc: + return '参数' + parts = [] + for item in loc: + if isinstance(item, int): + parts.append(f'[{item}]') + else: + parts.append(FIELD_LABELS.get(str(item), str(item))) + return '.'.join(parts).replace('.[', '[') + + +def _format_validation_error(exc): + """把 pydantic ValidationError 转成人类可读的中文清单。""" + messages = [] + for err in exc.errors(): + err_type = err.get('type', '') + loc = err.get('loc', ()) + msg = err.get('msg', '') + ctx = err.get('ctx', {}) or {} + label = _loc_to_label(loc) + + if err_type == 'missing': + text = f'{label} 不能为空' + elif err_type == 'string_too_short': + min_len = ctx.get('min_length') + text = f'{label} 长度不能少于 {min_len} 个字符' if min_len is not None else f'{label} 长度过短' + elif err_type == 'string_too_long': + max_len = ctx.get('max_length') + text = f'{label} 长度不能超过 {max_len} 个字符' if max_len is not None else f'{label} 长度过长' + elif err_type == 'string_pattern_mismatch': + help_text = PATTERN_HELP.get(_field_key(loc)) + text = f'{label} 格式不正确,{help_text}' if help_text else f'{label} 格式不正确' + elif err_type in ('int_parsing', 'float_parsing', 'int_type', 'float_type'): + text = f'{label} 必须是数字' + elif err_type in ('bool_parsing', 'bool_type'): + text = f'{label} 必须是布尔值' + elif err_type in ('greater_than', 'greater_than_equal'): + limit = ctx.get('gt', ctx.get('ge')) + text = f'{label} 必须大于 {limit}' if err_type == 'greater_than' else f'{label} 必须不小于 {limit}' + elif err_type in ('less_than', 'less_than_equal'): + limit = ctx.get('lt', ctx.get('le')) + text = f'{label} 必须小于 {limit}' if err_type == 'less_than' else f'{label} 必须不大于 {limit}' + elif err_type == 'enum': + text = f'{label} 不在允许的取值范围内' + elif err_type.startswith('value_error'): + # 业务校验器自己 raise ValueError('xxx') 时,pydantic 会在 msg 前加 'Value error, ' + clean_msg = msg.replace('Value error, ', '') if msg else '' + text = f'{label} {clean_msg}' if clean_msg else f'{label} 校验失败' + elif err_type.startswith('type_error'): + text = f'{label} 类型错误' + else: + # 兜底:显示原始英文 msg,避免丢失信息 + text = f'{label} {msg}' if msg else f'{label} 校验失败' + messages.append(text) + return '参数校验失败:' + ';'.join(messages) + + +class DistinctBodyMiddleware(MiddlewareMixin): + + def process_request(self, request): + if request.method == 'POST': + ens = md5(request.body) + client = cache.get_redis_client() + if not client.set(f'lqa:body:{ens}', time_ms(), nx=True, ex=Minute_5+10): + return ApiResponse(ApiErrorEnum.ERROR, msg='可能短时间内重复提交') + + +class ExceptionMiddleware(MiddlewareMixin): + + def process_request(self, request): + ip = getattr(request, 'client_ip', None) + if not ip: + err, ip = get_client_ip(request) + if err: + logger.error(f'get_client_ip err:{err}') + request.client_ip = ip + + def process_exception(self, request, exception): + logger.exception(f'request method:{request.method} path: {request.path}', exc_info=exception) + + if isinstance(exception, ValidationError): + # 开发排查用:仍把完整的原始错误结构打到日志 + errs = list(map(lambda o: lodash.pick(o, ('type', 'loc', 'msg')), exception.errors())) + logger.warning(f'ValidationError detail: {orjson.dumps(errs).decode("utf-8")}') + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=_format_validation_error(exception)) + + return ApiResponse(ApiErrorEnum.ERROR, msg=f'接口错误 {exception}') + + def process_response(self, request, response): + if isinstance(response, ApiResponse) and response.data['code'] != 0: + logger.warning(f'ApiError {request.client_ip} {request.method} {request.path} {response}') + + response['Lqa-Node'] = NODE_NAME + + headers = request.headers + proxy_node = headers.get('proxy-node') + if proxy_node: + proxy_headers = { + 'proxy-node': proxy_node, + 'proxy-target-node': headers.get('proxy-target-node', ''), + 'proxy-node-trace': headers.get('proxy-node-trace', ''), + 'proxy-url': headers.get('proxy-url', '') + } + logger.info(f'[event.proxy_node.response] {orjson.dumps(proxy_headers).decode()}') + + return response + + +class AccessLogMiddleware(MiddlewareMixin): + def process_request(self, request): + request.__req_at = time_ms() + ip = getattr(request, 'client_ip', None) + if not ip: + err, ip = get_client_ip(request) + if err: + logger.error(f'get_client_ip err:{err}') + request.client_ip = ip + + def process_response(self, request, response): + cost = time_ms() - request.__req_at + content = getattr(response, 'content', None) + size = '-' if content is None else len(content) + logger_access.info(f'"{request.method} {request.get_full_path()}" {response.status_code} {size} {cost} "{request.client_ip}"') + return response diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..8f756f9595d9844c122a5014844913f1e55a9d49 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/urls.py @@ -0,0 +1,12 @@ +from django.urls import path + +from .views import * + +urlpatterns = [ + path('', IndexView.as_view(), name='index'), + path('api/health', view_health, name='health'), + path('api/ticket', TicketView.as_view(), name='ticket'), + path('api/disk_usage', DiskUsageView.as_view(), name='disk_usage'), + path('api/upload_file', view_upload_file, name='upload_file'), + path('api/test', view_test) +] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/lqa/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/views.py new file mode 100644 index 0000000000000000000000000000000000000000..c72e7025257a11e5fdae092bfc92d6ada02b46b3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/lqa/views.py @@ -0,0 +1,96 @@ +import os +import logging +import time +import uuid +import threading +import shutil + +from django.http import HttpResponse +from django.views.generic import View + +import settings +from libs import ApiResponse, cache, storage, util +from libs.defs import Minute_5, ApiErrorEnum + +logger = logging.getLogger('lqa_view') + + +class IndexView(View): + def get(self, request): + return HttpResponse(f"Index") + + +def view_health(request): + """健康检查(免登录)""" + return ApiResponse(data={'status': 'ok'}) + + +class TicketView(View): + """可以考虑使用 django-ratelimit 限速""" + def get(self, request): + uuid_str = uuid.uuid1() + cache.ticket_cache.set(uuid_str, int(time.time()) + Minute_5) + return ApiResponse(data={'ticket': uuid_str}) + + +class DiskUsageView(View): + """磁盘使用情况""" + def get(self, request): + total, used, free = shutil.disk_usage(settings.APP_MEDIA_ROOT) + return ApiResponse(data={'total': total, 'used': used, 'free': free}) + + # #下面统计正式文件大小 实测太慢了 放弃使用 + # default_stat = {'total': 0, 'used': 0, 'free': 0, 'expire_at': 0} + # stat = cache.comm_cahce.get('disk', json=True) + # if stat and util.time_ms() < stat['expire_at']: # 使用缓存数据 有效期一天 + # return ApiResponse(data=stat) + # else: + # # redis锁:判断是否计算任务正在执行 + # lqa_lock_disk_stat_key = 'lqa_lock_disk_stat' + # ok = cache.get_redis_client().set(lqa_lock_disk_stat_key, 1, nx=True, xx=False, ex=Minute_5*3) + # if not ok: + # return ApiResponse(data=default_stat) + # + # def _disk_stat(): + # total_size = 0 + # file_count = 0 + # for dirpath, dirnames, filenames in os.walk(settings.APP_MEDIA_ROOT): + # for filename in filenames: + # filepath = os.path.join(dirpath, filename) + # try: + # total_size += os.path.getsize(filepath) # 获取文件大小并累加 + # file_count += 1 + # except OSError as e: + # logger.error(f"cant access file:{filepath}. err: {e}") + # total, used, free = shutil.disk_usage(settings.APP_MEDIA_ROOT) + # expire_at = util.time_ms() + 86400000 + # stat_ = {'total': total, 'used': used, 'free': free, 'app_used': total_size, + # 'file_count': file_count, 'expire_at': expire_at} + # cache.comm_cahce.set('disk', stat_, json=True, timeout=86400 + 1200) + # cache.get_redis_client().delete(lqa_lock_disk_stat_key) # 执行完 删掉key + # logger.info(f'disk_stat end') + # + # thread = threading.Thread(target=_disk_stat) + # thread.daemon = False + # thread.start() + # logger.info(f'disk_stat start thread: {thread}') + # + # return ApiResponse(data=default_stat) + + +def view_upload_file(request): + if len(request.FILES) == 0: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='未上传文件') + req_file = next(request.FILES.values()) + file_name = req_file.name + _, file_extension = os.path.splitext(file_name) + tmp_abs_path, url_path = storage.write_temp_file(req_file, ext=file_extension if file_extension else '') + logger.info(f'upload file_name:{file_name} url_path:{url_path}') + return ApiResponse(data={'file_name': file_name, 'file_path': url_path}) + + +def view_test(request): + num = request.GET.get('num', 0) + delay = int(request.GET.get('delay', 10)) + logger.info(int(time.time()*1000)) + return ApiResponse(data={"num": num, "delay": delay}) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..8c36ea84c12ec5e060627ce20b619f67e7b372b3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ProjectConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.project' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..0c80323fc7ae429b06dbf5274260ae91886bdcd7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0001_initial.py @@ -0,0 +1,199 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Project', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('code', models.CharField(max_length=100, unique=True, verbose_name='项目代号')), + ('name', models.CharField(max_length=100, verbose_name='项目名称')), + ('img', models.CharField(default='', max_length=255, verbose_name='项目图标')), + ('project_type', models.IntegerField(choices=[(1, '平台级'), (2, '项目级')], verbose_name='项目类型')), + ('project_phase', models.IntegerField(choices=[(1, '上线运营'), (2, '下线'), (3, '研发期'), (4, '保密')], verbose_name='项目阶段')), + ('game_type', models.IntegerField(choices=[(1, '手游'), (2, '端游'), (3, '页游'), (4, 'app'), (5, '小游戏')], verbose_name='游戏类型')), + ('team', models.CharField(default='', max_length=100, verbose_name='所属团队')), + ('cvtest_project', models.CharField(default='', max_length=32, verbose_name='AI识别项目名')), + ('test_manager', models.CharField(default='', max_length=100, verbose_name='测试经理')), + ], + options={ + 'db_table': 'lqa_project', + }, + ), + migrations.CreateModel( + name='Module', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('name', models.CharField(max_length=100, verbose_name='模块名字')), + ('show_name', models.CharField(max_length=100, verbose_name='模块show名字')), + ('sub_module', models.CharField(default='', max_length=100, verbose_name='子模块')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_module', + }, + ), + migrations.CreateModel( + name='ProjectConfigBugBillMethod', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('bug_type_enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='bug_type_enable')), + ('language_enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='language_enable')), + ('module_enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='module_enable')), + ('description_template', models.TextField(default='', verbose_name='缺陷描述模板')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_bugbill_method', + }, + ), + migrations.CreateModel( + name='ProjectConfigBugBillUser', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=1, verbose_name='enable')), + ('bug_type', models.IntegerField(default=0, verbose_name='bug_type')), + ('language', models.IntegerField(default=0, verbose_name='language')), + ('module', models.IntegerField(default=0, verbose_name='module')), + ('user_names', models.JSONField(default=list, verbose_name='user_names')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_bugbill_user', + }, + ), + migrations.CreateModel( + name='ProjectConfigBugTracker', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('tracker_type', models.CharField(choices=[('none', '平台内记录'), ('bugzilla', 'Bugzilla'), ('zentao', '禅道')], default='none', max_length=16, verbose_name='缺陷系统类型')), + ('base_url', models.CharField(default='', max_length=255, verbose_name='缺陷系统地址')), + ('username', models.CharField(default='', max_length=128, verbose_name='账号(禅道)')), + ('api_key', models.CharField(default='', max_length=255, verbose_name='API Key(Bugzilla)/ 密码(禅道)')), + ('product', models.CharField(default='', max_length=128, verbose_name='产品名称(Bugzilla)/ 产品ID(禅道)')), + ('component', models.CharField(default='', max_length=128, verbose_name='组件(Bugzilla)')), + ('extra', models.JSONField(default=dict, verbose_name='高级配置(JSON)')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_bugtracker', + }, + ), + migrations.CreateModel( + name='ProjectConfigBugType', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('name', models.CharField(max_length=32, verbose_name='name')), + ('label', models.CharField(max_length=32, verbose_name='label')), + ('value', models.IntegerField(verbose_name='value')), + ('enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=1, verbose_name='enable')), + ('trans_marks', models.CharField(default='[]', max_length=1024, verbose_name='trans_marks')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_bugtype', + }, + ), + migrations.CreateModel( + name='ProjectConfigCustomField', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('field_name', models.CharField(max_length=64, verbose_name='字段显示名称')), + ('field_key', models.CharField(max_length=64, verbose_name='缺陷系统字段名')), + ('options', models.JSONField(default=list, verbose_name='下拉选项列表')), + ('enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=1, verbose_name='enable')), + ('sort_order', models.IntegerField(default=0, verbose_name='排序')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_custom_field', + }, + ), + migrations.CreateModel( + name='ProjectConfigImgRevert', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('root_path', models.CharField(max_length=128, verbose_name='root_path')), + ('key', models.CharField(max_length=32, verbose_name='key')), + ('text', models.CharField(max_length=32, verbose_name='text')), + ('lang_path', models.TextField(default='', verbose_name='lang_path')), + ('no_trans_text', models.CharField(max_length=128, verbose_name='no_trans_text')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_imgrevert', + }, + ), + migrations.CreateModel( + name='ProjectConfigLanguage', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('name', models.CharField(max_length=32, verbose_name='name')), + ('label', models.CharField(max_length=32, verbose_name='label')), + ('custom_label', models.CharField(default='', max_length=32, verbose_name='custom_label')), + ('value', models.IntegerField(verbose_name='value')), + ('enable', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=1, verbose_name='enable')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_language', + }, + ), + migrations.CreateModel( + name='ProjectConfigOther', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('webhook_url', models.CharField(default='', max_length=512, verbose_name='Webhook地址')), + ('webhook_method', models.CharField(default='POST', max_length=8, verbose_name='请求方法')), + ('webhook_headers', models.TextField(default='{}', verbose_name='请求头(JSON)')), + ('webhook_body', models.TextField(default='', verbose_name='请求体模板(JSON),为空时发送全部变量')), + ('editor_path', models.CharField(default='', max_length=128, verbose_name='编辑器路径')), + ('editor_version', models.CharField(default='', max_length=32, verbose_name='编辑器版本')), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project')), + ], + options={ + 'db_table': 'lqa_project_config_other', + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0002_alter_project_game_type.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0002_alter_project_game_type.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe53fb72a95dbcef0b0f5c9a088888f9a18d283 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/0002_alter_project_game_type.py @@ -0,0 +1,18 @@ +# Generated by Django 5.1.1 on 2026-10-10 14:29 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('project', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='project', + name='game_type', + field=models.CharField(default='', max_length=32, verbose_name='游戏类型'), + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/models.py new file mode 100644 index 0000000000000000000000000000000000000000..25dc2cbfdecf5e7bcc0c6cf349cb85fdfea30910 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/models.py @@ -0,0 +1,174 @@ +from django.db import models +import datetime + +from libs.defs import ProjectTypeEnum, ProjectPhaseEnum, GameTypeEnum, SwitchEnum, BugTrackerTypeEnum +from libs import BaseAttrModel, BaseModel + + +class Project(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + code = models.CharField(max_length=100, unique=True, verbose_name='项目代号') + name = models.CharField(max_length=100, verbose_name='项目名称') + img = models.CharField(default='', max_length=255, verbose_name='项目图标') + project_type = models.IntegerField(choices=ProjectTypeEnum, verbose_name='项目类型') + project_phase = models.IntegerField(choices=ProjectPhaseEnum, verbose_name='项目阶段') + # 游戏类型支持多选,以逗号分隔存储(如 '1,3';取值见 GameTypeEnum) + game_type = models.CharField(default='', max_length=32, verbose_name='游戏类型') + team = models.CharField(default='', max_length=100, verbose_name='所属团队') + # AI 识别服务中的项目标识,请求时以 "{cvtest_project}_lqa" 作为 project-method + cvtest_project = models.CharField(default='', max_length=32, verbose_name='AI识别项目名') + test_manager = models.CharField(default='', max_length=100, verbose_name='测试经理') + + class Meta: + # app_label = 'project' + db_table = 'lqa_project' + + +# class ProjectConfig(BaseModel): +# """用来存储项目的一些开关配置(不需要元素搜索,否则单独建表)""" +# id = models.BigAutoField(primary_key=True) +# project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) +# cate = models.IntegerField(choices=ProjectConfigCateEnum) +# # content内容规格,参考./schemas.py中的ProjectConfig相关的Schema +# content = models.JSONField(default=dict, verbose_name='配置json') +# +# created_at = models.DateTimeField(auto_now_add=True) +# updated_at = models.DateTimeField(auto_now=True) +# +# class Meta: +# # app_label = 'project_config' +# db_table = 'lqa_project_config' +# constraints = [models.UniqueConstraint(fields=['project_id', 'cate'], name='idx__project_id__cate')] + + +class Module(BaseAttrModel): + """项目配置:模块""" + id = models.BigAutoField(primary_key=True) + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=100, verbose_name='模块名字') + show_name = models.CharField(max_length=100, verbose_name='模块show名字') + sub_module = models.CharField(default='', max_length=100, verbose_name='子模块') + + class Meta: + # app_label = 'module' + db_table = 'lqa_module' + + + +class ProjectConfigBugType(BaseAttrModel): + """项目配置:缺陷类型""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=32, verbose_name='name') + label = models.CharField(max_length=32, verbose_name='label') + value = models.IntegerField(verbose_name='value') + enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.ON, verbose_name='enable') + trans_marks = models.CharField(max_length=1024, default='[]', verbose_name='trans_marks') # json数组 + + class Meta: + db_table = 'lqa_project_config_bugtype' + + +class ProjectConfigLanguage(BaseAttrModel): + """项目配置:语言""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + name = models.CharField(max_length=32, verbose_name='name') + label = models.CharField(max_length=32, verbose_name='label') + custom_label = models.CharField(max_length=32, default='', verbose_name='custom_label') + value = models.IntegerField(verbose_name='value') + enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.ON, verbose_name='enable') + + class Meta: + db_table = 'lqa_project_config_language' + + +class ProjectConfigImgRevert(BaseAttrModel): + """项目配置:图片还原""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + root_path = models.CharField(max_length=128, verbose_name='root_path') + key = models.CharField(max_length=32, verbose_name='key') + text = models.CharField(max_length=32, verbose_name='text') + lang_path = models.TextField(default='', verbose_name='lang_path') + no_trans_text = models.CharField(max_length=128, verbose_name='no_trans_text') + + class Meta: + db_table = 'lqa_project_config_imgrevert' + + +class ProjectConfigBugBillMethod(BaseAttrModel): + """项目配置:提单分配方式""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + bug_type_enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='bug_type_enable') + language_enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='language_enable') + module_enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='module_enable') + # [新增] 缺陷描述模板,支持HTML格式和变量替换({image_id}、{image_name}、{job_id}、{create_time}) + description_template = models.TextField(default='', verbose_name='缺陷描述模板') + + class Meta: + db_table = 'lqa_project_config_bugbill_method' + + +class ProjectConfigBugBillUser(BaseAttrModel): + """项目配置:提单处理人""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.ON, verbose_name='enable') + bug_type = models.IntegerField(default=0, verbose_name='bug_type') + language = models.IntegerField(default=0, verbose_name='language') + module = models.IntegerField(default=0, verbose_name='module') + user_names = models.JSONField(default=list, verbose_name="user_names") + + class Meta: + db_table = 'lqa_project_config_bugbill_user' + + +class ProjectConfigOther(BaseAttrModel): + """ + 项目配置:还原执行(Webhook) + 还原任务由前端浏览器直接调用 Webhook 触发(Jenkins / GitLab CI / 自建服务等), + url / headers / body 支持 {{变量}} 占位符,变量列表见 apps.job.service.runner_variables + """ + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + webhook_url = models.CharField(max_length=512, default='', verbose_name='Webhook地址') + webhook_method = models.CharField(max_length=8, default='POST', verbose_name='请求方法') + webhook_headers = models.TextField(default='{}', verbose_name='请求头(JSON)') + webhook_body = models.TextField(default='', verbose_name='请求体模板(JSON),为空时发送全部变量') + editor_path = models.CharField(max_length=128, default='', verbose_name='编辑器路径') + editor_version = models.CharField(max_length=32, default='', verbose_name='编辑器版本') + + class Meta: + db_table = 'lqa_project_config_other' + + +class ProjectConfigBugTracker(BaseAttrModel): + """项目配置:缺陷系统(每个项目一条)""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + tracker_type = models.CharField(max_length=16, choices=BugTrackerTypeEnum, default=BugTrackerTypeEnum.NONE, + verbose_name='缺陷系统类型') + base_url = models.CharField(max_length=255, default='', verbose_name='缺陷系统地址') + username = models.CharField(max_length=128, default='', verbose_name='账号(禅道)') + api_key = models.CharField(max_length=255, default='', verbose_name='API Key(Bugzilla)/ 密码(禅道)') + product = models.CharField(max_length=128, default='', verbose_name='产品名称(Bugzilla)/ 产品ID(禅道)') + component = models.CharField(max_length=128, default='', verbose_name='组件(Bugzilla)') + extra = models.JSONField(default=dict, verbose_name='高级配置(JSON)') + + class Meta: + db_table = 'lqa_project_config_bugtracker' + + +class ProjectConfigCustomField(BaseAttrModel): + """项目配置:自定义提单字段 + 用于在提单界面动态添加自定义下拉选择框,字段值会原样提交到缺陷系统对应字段。 + - field_name: 显示在提单弹窗中的标题 + - field_key: 缺陷系统中的字段名(如 Bugzilla 的 cf_xxx、禅道的 type/os) + - options: 下拉选项列表(可从缺陷系统拉取,也可手动编辑) + - enable: 是否启用该字段 + - sort_order: 排序顺序 + """ + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING) + field_name = models.CharField(max_length=64, verbose_name='字段显示名称') + field_key = models.CharField(max_length=64, verbose_name='缺陷系统字段名') + options = models.JSONField(default=list, verbose_name='下拉选项列表') + enable = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.ON, verbose_name='enable') + sort_order = models.IntegerField(default=0, verbose_name='排序') + + class Meta: + db_table = 'lqa_project_config_custom_field' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..4c423633a4abf5460782603018459d65c5c7a508 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/schemas.py @@ -0,0 +1,220 @@ +import datetime +from typing import List, Optional, Union, Any, Annotated, Literal + +import orjson +from pydantic import BaseModel, Field, BeforeValidator, field_validator, AfterValidator + +from libs import util +from libs.defs import ProjectTypeEnum, ProjectPhaseEnum, GameTypeEnum, SwitchEnum, BugTrackerTypeEnum +from apps.project import service as proj_svr + + +def make_game_type_validator(): + """游戏类型(多选)统一校验:接受数组 / 逗号字符串 / 单个值,输出逗号分隔字符串(如 '1,3')""" + + def _validate(value): + if value is None or value == '': + return '' + items = value if isinstance(value, (list, tuple, set)) else str(value).split(',') + result = [] + for item in items: + if item is None or item == '': + continue + try: + num = int(item) + except (TypeError, ValueError): + raise ValueError(f'非法的游戏类型: {item}') + if num not in GameTypeEnum.values: + raise ValueError(f'非法的游戏类型: {num}') + if str(num) not in result: + result.append(str(num)) + return ','.join(result) + + return _validate + + +def split_game_type(value): + """把库中逗号分隔的游戏类型转成 int 数组,供接口返回(如 '1,3' -> [1, 3])""" + if not value: + return [] + return [int(v) for v in str(value).split(',') if v != ''] + + +def make_game_type_search_validator(): + """搜索参数:接受数组 / 逗号串 / 单值,统一输出逗号分隔字符串(如 '1,2'),非法项直接忽略""" + + def _validate(value): + if value is None or value == '': + return None + items = value if isinstance(value, (list, tuple, set)) else str(value).split(',') + result = [] + for item in items: + if item is None or item == '': + continue + try: + num = int(item) + except (TypeError, ValueError): + continue + if num not in GameTypeEnum.values: + continue + if str(num) not in result: + result.append(str(num)) + return ','.join(result) if result else None + + return _validate + + +class ProjectSchema(BaseModel): + project_id: int = Field(default=0) + code: str = Field(min_length=2, max_length=100, pattern=r'^[A-Za-z0-9_\-]+$') + name: str = Field(min_length=1, max_length=100) + img: str = Field(default='') + project_type: ProjectTypeEnum + project_phase: ProjectPhaseEnum + game_type: Annotated[str, BeforeValidator(make_game_type_validator())] = Field(default='') + team: str = Field(default='', max_length=100) + cvtest_project: str = Field(default='', max_length=32) + test_manager: str = Field(default='') + + +class ProjectListSchema(BaseModel): + project_id: int = Field(default=None) + team__icontains: str = Field(default=None, alias='team') + name__icontains: str = Field(default=None, alias='name') + project_type: int = Field(default=None) + game_type: Annotated[str, BeforeValidator(make_game_type_search_validator())] = Field( + default=None, alias='game_type') + project_phase: int = Field(default=None) + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2) + + +class ProjectModuleCreateSchema(BaseModel): + id: int = 0 + project_id: int + name: str = Field(min_length=2) + show_name: str = Field(min_length=2) + sub_module: str = Field(default='') + + +class ProjectModuleListSchema(BaseModel): + project_id: int + all: SwitchEnum = Field(default=SwitchEnum.OFF) + name__icontains: str = Field(default=None, alias='name') + show_name__icontains: str = Field(default=None, alias='show_name') + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2) + + +class ProjectConfigBugTypeSchema(BaseModel): + id: int = Field(default=0) + project_id: int = Field(ge=0) + name: str = Field(min_length=2) + label: str = Field(min_length=2) + value: int = Field(gt=0) + enable: int = Literal[0, 1] + trans_marks: Annotated[List, BeforeValidator(util.make_json_validator()), AfterValidator(lambda v: orjson.dumps(v).decode())] = Field(default_factory=lambda: []) + + +class ProjectConfigLanguageSchema(BaseModel): + id: int = Field(default=0) + project_id: int = Field(ge=0) + name: str = Field(min_length=2) + label: str = Field(min_length=2) + custom_label: str = Field(default='') + value: int = Field(gt=0) + enable: int = Literal[0, 1] + + +class ProjectConfigImgRevertSchema(BaseModel): + """项目配置:图片还原""" + id: int = Field(default=0) + project_id: int = Field(ge=0) + root_path: str = Field(default='') + key: str = Field(default='') + text: str = Field(default='') + lang_path: str = Field(default='') + no_trans_text: str = Field(default='') + + +class ProjectConfigBugBillMethodSchema(BaseModel): + """项目配置:提单""" + id: int = Field(default=0) + project_id: int = Field(ge=0) + bug_type_enable: int = Literal[0, 1] + language_enable: int = Literal[0, 1] + module_enable: int = Literal[0, 1] + description_template: str = Field(default='') + + +class ProjectConfigBugBillUserSchema(BaseModel): + """项目配置:提单""" + id: int = Field(default=0) + project_id: int = Field(ge=0) + enable: int = Literal[0, 1] + bug_type: Annotated[int, BeforeValidator(proj_svr.BugTypeValidator(True))] + language: Annotated[int, BeforeValidator(proj_svr.LanguageValidator(True))] + module: int = Field(ge=0) + user_names: List[str] + + +def _json_text_validator(expect_type, allow_empty=False): + def validator(v): + if v is None: + return '' if allow_empty else orjson.dumps(expect_type()).decode() + if isinstance(v, (dict, list)): + v = orjson.dumps(v).decode() + v = v.strip() + if allow_empty and v == '': + return v + try: + parsed = orjson.loads(v) + except orjson.JSONDecodeError: + raise ValueError('不是合法的 JSON') + if not isinstance(parsed, expect_type): + raise ValueError(f'必须是 JSON {"对象" if expect_type is dict else "数组"}') + return v + return validator + + +class ProjectConfigOtherSchema(BaseModel): + """项目配置:还原执行(Webhook)""" + id: int = Field(default=0) + project_id: int = Field(gt=0) + webhook_url: str = Field(default='', max_length=512, pattern=r'^(https?://.*)?$') + webhook_method: Literal['POST', 'GET', 'PUT'] = Field(default='POST') + webhook_headers: Annotated[str, BeforeValidator(_json_text_validator(dict))] = Field(default='{}') + webhook_body: Annotated[str, BeforeValidator(_json_text_validator((dict, list), True))] = Field(default='') + editor_path: str = Field(default='', max_length=128) + editor_version: str = Field(default='', max_length=32) + + +class ProjectConfigBugTrackerSchema(BaseModel): + """项目配置:缺陷系统""" + id: int = Field(default=0) + project_id: int = Field(gt=0) + tracker_type: BugTrackerTypeEnum = Field(default=BugTrackerTypeEnum.NONE) + base_url: str = Field(default='', max_length=255, pattern=r'^(https?://.*)?$') + username: str = Field(default='', max_length=128) + api_key: str = Field(default='', max_length=255) + product: str = Field(default='', max_length=128) + component: str = Field(default='', max_length=128) + extra: Annotated[dict, BeforeValidator(lambda v: orjson.loads(v) if isinstance(v, str) and v.strip() else (v or {}))] = Field(default_factory=dict) + + +class ProjectConfigDelSchema(BaseModel): + project_id: int = Field(gt=0) + ids: List[int] = Field(min_length=1) + + +class ProjectConfigCustomFieldSchema(BaseModel): + """项目配置:自定义提单字段""" + id: int = Field(default=0) + project_id: int = Field(ge=0) + field_name: str = Field(min_length=1) + field_key: str = Field(min_length=1) + options: List[str] = Field(default_factory=list) + enable: int = Literal[0, 1] + sort_order: int = Field(default=0) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/service.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/service.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab4cb310e38c044749709a94f50e457354286bc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/service.py @@ -0,0 +1,244 @@ +from functools import partialmethod +from typing import Union + +from django.db.models import Q, QuerySet + +from apps.user.models import UserProjectRelationship +from apps.project.models import * +from libs.base import ExpireData +from libs.defs import QCC_PROJECT_ID + + +Project_Config_Model_Map = { + 'BugType': ProjectConfigBugType, + 'Language': ProjectConfigLanguage, + 'ImgRevert': ProjectConfigImgRevert, + 'BugBillMethod': ProjectConfigBugBillMethod, + 'BugBillUser': ProjectConfigBugBillUser, + 'Other': ProjectConfigOther, # 还原执行(Webhook) + 'BugTracker': ProjectConfigBugTracker, # 缺陷系统 + 'CustomField': ProjectConfigCustomField, # 自定义提单字段 +} + +# 每个项目只有一条记录的配置 +Project_Single_Config_Models = (ProjectConfigBugBillMethod, ProjectConfigOther, ProjectConfigBugTracker) + + +class _SysLanguage(ExpireData): + def query_db(self): + return list(ProjCfgService.get_language(QCC_PROJECT_ID)) + + +class _SysBugType(ExpireData): + def query_db(self): + return list(ProjCfgService.get_bug_type(QCC_PROJECT_ID)) + + +class ProjCfgService(object): + _sys_language = _SysLanguage() + _sys_bugtype = _SysBugType() + + @classmethod + def get_config(cls, cate, project_id) -> QuerySet: + model = Project_Config_Model_Map[cate] + return model.objects.filter(project_id=project_id).values() + + @classmethod + def get_bill(cls, project_id) -> Union[dict, None]: + cfg = cls.get_bill_method(project_id).first() + if not cfg: + return None + cfg['rows'] = list(cls.get_bill_user(project_id)) + return cfg + + @classmethod + def get_runner(cls, project_id, validate=True) -> Union[dict, None]: + """还原执行(Webhook)配置;validate=True 时未配置 webhook_url 返回 None""" + cfg = cls.get_config('Other', project_id).first() + if not cfg: + return None + if validate and not cfg['webhook_url'].strip(): + return None + return cfg + + @classmethod + def get_bug_tracker(cls, project_id) -> Union[dict, None]: + """缺陷系统配置,未配置时返回 None(等同于平台内记录)""" + return cls.get_config('BugTracker', project_id).first() + + @classmethod + def get_sys_language(cls, mapping=False) -> Union[dict, list]: + return {o['value']: o for o in cls._sys_language.data} if mapping else cls._sys_language.data + + @classmethod + def get_sys_bugtype(cls, mapping=False) -> Union[dict, list]: + return {o['value']: o for o in cls._sys_bugtype.data} if mapping else cls._sys_bugtype.data + + @classmethod + def get_bug_type(cls, project_id, mapping=False) -> Union[dict, list]: + rows = list(cls.get_config('BugType', project_id)) + if mapping: + return {r_['value']: r_ for r_ in rows} + return rows + + @classmethod + def get_language(cls, project_id, mapping=False) -> Union[dict, list]: + rows = list(cls.get_config('Language', project_id)) + if mapping: + return {r_['value']: r_ for r_ in rows} + return rows + + get_img_revert = partialmethod(get_config, 'ImgRevert') + get_bill_user = partialmethod(get_config, 'BugBillUser') + get_bill_method = partialmethod(get_config, 'BugBillMethod') + + +def update_user_project_roles(uid, project_id, project_roles): + """更新用户项目的角色信息 增删改 """ + param = {'user_id': uid} + if project_id: + param['project_id'] = project_id + ships = UserProjectRelationship.objects.filter(**param) + req_ships_set = set(map(lambda pr_: (pr_[0], uid, pr_[1]), project_roles)) + all_ships_set = set(map(lambda ship_: (ship_.project_id, ship_.user_id, ship_.role), ships)) + del_ships_set = all_ships_set - req_ships_set + add_ships_set = req_ships_set - all_ships_set + updated_project_ids = set() + if len(del_ships_set): # 删除的角色 + qs = Q() + for ship in del_ships_set: + qs |= Q(project_id=ship[0], user_id=ship[1], role=ship[2]) + updated_project_ids.add(ship[0]) + UserProjectRelationship.objects.filter(qs).delete() + if len(add_ships_set): # 新增的角色 + add_ships = [] + for ship in add_ships_set: + add_ships.append(UserProjectRelationship(project_id=ship[0], user_id=ship[1], role=ship[2])) + updated_project_ids.add(ship[0]) + UserProjectRelationship.objects.bulk_create(add_ships) + return updated_project_ids + + +def update_ship_and_project_cfg_by_delete_user(uid): + """ + 删除用户时 角色和提单配置处理 + """ + ships = UserProjectRelationship.objects.filter(user_id=uid) + project_ids = set() + for ship in ships: + project_ids.add(ship.project_id) + ships.delete() + return project_ids + + +def project_of_members(project_ids): + """ + { + "project_id": project_id, + "members": [ + user_id_str: [1, 2, 3] + ] + } + :param project_ids: project_id or project_ids + :return: dict or list[dict] + """ + + is_int = isinstance(project_ids, int) + project_ids_ = [project_ids] if is_int else project_ids + projects = {} + for ship_row in UserProjectRelationship.objects.filter(project_id__in=project_ids_).values(): + project_id = ship_row['project_id'] + user_id_str = str(ship_row['user_id']) + role = ship_row['role'] + project = projects.get(project_id, {'project_id': project_id, 'members': {}}) + roles = project['members'].get(user_id_str, []) + roles.append(role) + project['members'][user_id_str] = roles + projects[project_id] = project + datas = list(projects.values()) + return (datas[0] if len(datas) > 0 else None) if is_int else datas + + +class BugTypeValidator(ExpireData): + + def __init__(self, allow_zero=False): + super(BugTypeValidator, self).__init__() + self.allow_zero = allow_zero + + def query_db(self): + data = {} + for row in ProjCfgService.get_sys_bugtype(): + data[row['value']] = row['value'] + data[row['name']] = row['value'] + return data + + def _validate_bug_type(self, v, allow_zero=True): + """v bug_type_code or bug_type_value""" + try: + v = int(v) + except: + pass + if allow_zero and v == 0: + return 0 + + v_ = self.data.get(v, None) + if v_ is None: + raise ValueError(f'Invalid value: {v}') + return v_ + + def __call__(self, v, info): + """ + v is List[value or name] or value or name + """ + if isinstance(v, list) or isinstance(v, tuple): + return [self._validate_bug_type(v_, self.allow_zero) for v_ in v] + else: + return self._validate_bug_type(v, self.allow_zero) + + +class LanguageValidator(BugTypeValidator): + # UE 编辑器侧使用的语言代码到 WMP 标准代码的别名映射 + # 当 UE 通过 /api/job/datas /api/image/entity 等接口传入 UE 侧命名 + # (见 UE_LQARestore_Plugin/Plugins/LQARestore/.../ConfigManager.cpp InitializeLanguageMap) + # 时, 自动翻译为 lqa_system_language 表里的标准 code, 避免误报 "Invalid language" + _UE_LANGUAGE_CODE_ALIASES = { + 'LAN_EU_EN': 'LAN_EN_US', # 英语 + 'LAN_EU_DE': 'LAN_DE_DE', # 德语 + 'LAN_FR_FR': 'LAN_FR_FR', # 法语 + 'LAN_RU_RU': 'LAN_RU_RU', # 俄语 + 'LAN_JP_JP': 'LAN_JA_JP', # 日语 + 'LAN_KO_KO': 'LAN_KO_KR', # 韩语 + 'LAN_CHT_CHT': 'LAN_ZH_TW', # 繁体中文 + 'LAN_AR_AR': 'LAN_AR_SA', # 阿拉伯语 + 'LAN_ES_LT': 'LAN_ES_ES', # 西班牙语 + 'LAN_PT_BR': 'LAN_PT_BR', # 巴西葡萄牙语 + 'LAN_TR_TR': 'LAN_TR_TR', # 土耳其语 + 'LAN_TH_TH': 'LAN_TH_TH', # 泰语 + 'LAN_ID_ID': 'LAN_ID_ID', # 印尼语 + 'LAN_CHS_CHS': 'LAN_ZH_CN', # 简体中文 + } + + def __init__(self, allow_zero=False): + super(LanguageValidator, self).__init__(allow_zero) + + def query_db(self): + data = {} + for row in ProjCfgService.get_sys_language(): + data[row['value']] = row['value'] + data[row['name']] = row['value'] + return data + + def _validate_bug_type(self, v, allow_zero=True): + # 若传入的是 UE 侧别名, 先翻译为 WMP 标准代码再走原校验 + if isinstance(v, str) and v in self._UE_LANGUAGE_CODE_ALIASES: + v = self._UE_LANGUAGE_CODE_ALIASES[v] + return super(LanguageValidator, self)._validate_bug_type(v, allow_zero) + + +def patch_language_code(val: Union[int, list]): + language_codes = ProjCfgService.get_sys_language(True) + if isinstance(val, int): + return language_codes[val]['name'] + else: + for v_ in val: + v_['language_code'] = language_codes[v_['language']]['name'] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..69a963a174d9fbf83189422672532038c2b8fe68 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/urls.py @@ -0,0 +1,15 @@ + +from django.urls import path + +from .views import * + +urlpatterns = [ + path('config', ProjectConfigView.as_view(), name='project-config'), + + path('module', ProjectModuleView.as_view(), name='project-module'), + path('module/list', ProjectModuleListView.as_view(), name='project-module-list'), + + path('entity', ProjectView.as_view(), name='project'), + path('roles', ProjectRolesView.as_view(), name='project-roles'), + path('list', ProjectListView.as_view(), name='project-list'), +] \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/project/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/project/views.py new file mode 100644 index 0000000000000000000000000000000000000000..1b1b7aa2c4e6bcd73dbd0cdbb6cfe238fb4bac3f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/project/views.py @@ -0,0 +1,350 @@ +import logging + +from django.db import transaction +from django.db.models import Q +from django.views.generic import View +from django.forms.models import model_to_dict +from django.utils.decorators import method_decorator +import orjson + +from apps.project.models import * +from apps.project import service as proj_svr +from libs.util import choices_to_python +from libs.decorators import require_super_admin, require_project_perm, test_project_user_role_by_project_id +from libs import ApiResponse, PageView, lodash +from libs.defs import ApiErrorEnum, RoleEnum, QCC_PROJECT_ID +from .schemas import * + +logger = logging.getLogger('proj_view') + + +def _project_dict(project): + """项目信息序列化:游戏类型统一转成数组返回(多选)""" + data_ = model_to_dict(project) + data_['game_type'] = split_game_type(data_.get('game_type')) + return data_ + + +class ProjectView(View): + def get(self, request): + """获取项目信息""" + project_id = int(request.GET.get('project_id', 0)) + if not project_id: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='非法的project_id') + project_info = Project.objects.filter(pk=project_id).values().first() + if not project_info: + return ApiResponse(ApiErrorEnum.NOT_EXIST) + project_info['game_type'] = split_game_type(project_info.get('game_type')) + return ApiResponse(data={'project': project_info}) + + @method_decorator(require_super_admin) + def post(self, request, *args, **kwargs): + """创建项目""" + vmi = ProjectSchema.model_validate(orjson.loads(request.body)) + + if Project.objects.filter(code=vmi.code).exists(): + return ApiResponse(ApiErrorEnum.ERROR, msg=f'项目名"{vmi.code}"已存在,请换一个项目名') + + fields1 = ('name', 'label', 'value', 'enable', 'trans_marks') + proj_cfg_bugtypes = list(ProjectConfigBugType.objects.filter(project_id=QCC_PROJECT_ID).values(*fields1)) + fields2 = ('name', 'label', 'custom_label', 'value', 'enable') + proj_cfg_languages = list(ProjectConfigLanguage.objects.filter(project_id=QCC_PROJECT_ID).values(*fields2)) + proj_cfg_bugtypes_, proj_cfg_languages_ = [], [] + + project = Project(**vmi.model_dump(exclude={'project_id'}, exclude_unset=True)) + with transaction.atomic(): + project.save() + # 初始化项目配置 + for proj_cfg_bugtype in proj_cfg_bugtypes: + proj_cfg_bugtype['project_id'] = project.id + proj_cfg_bugtype['trans_marks'] = '[]' + proj_cfg_bugtypes_.append(ProjectConfigBugType(**proj_cfg_bugtype)) + for proj_cfg_language in proj_cfg_languages: + proj_cfg_language['project_id'] = project.id + proj_cfg_languages_.append(ProjectConfigLanguage(**proj_cfg_language)) + ProjectConfigBugType.objects.bulk_create(proj_cfg_bugtypes_) + ProjectConfigLanguage.objects.bulk_create(proj_cfg_languages_) + ProjectConfigOther.objects.get_or_create(project_id=project.id) + ProjectConfigBugTracker.objects.get_or_create(project_id=project.id) + ProjectConfigBugBillMethod.objects.get_or_create(project_id=project.id) + logger.info(f'[event.project.add] user:{request.user["name"]} id:{project.id}') + return ApiResponse(data={'project': _project_dict(project)}) + + @method_decorator(require_super_admin) + def patch(self, request, *args, **kwargs): + """修改项目信息""" + vmi = ProjectSchema.model_validate(orjson.loads(request.body)) + + project_id = vmi.project_id + project = Project.objects.filter(pk=project_id).first() + if not project: + return ApiResponse(ApiErrorEnum.NOT_EXIST) + + mapping = vmi.model_dump(exclude={'project_id', 'code'}, exclude_unset=True) + for k, v in mapping.items(): + setattr(project, k, v) + project.save(update_fields=list(mapping.keys())) + + logger.info(f'[event.project.update] user:{request.user["name"]} body:{orjson.dumps(mapping).decode()}') + return ApiResponse(data={'project': _project_dict(project)}) + + +class ProjectListView(PageView): + Query_Fields = ('cur_id', 'team__icontains', 'name__icontains', 'project_type', + 'project_phase') + + def get(self, request): + """查询项目列表""" + vmi = ProjectListSchema.model_validate(request.GET.dict()) + + param = {} + if vmi.project_id is not None and vmi.project_id > 0: + param['id'] = vmi.project_id + else: + param = self.make_query_params(vmi) + param['pk__gt'] = QCC_PROJECT_ID # 不展示系统模板项目 + # 游戏类型多选:数据库里以逗号分隔存储(如 "1,3"),用正则精确匹配每个值,再 OR 合并 + if vmi.game_type: + q_game = Q() + for item in vmi.game_type.split(','): + item = item.strip() + if not item: + continue + # (^|,) 和 (,|$) 保证匹配的是完整值而不是子串,避免 "1" 命中 "10,20" + q_game |= Q(game_type__regex=rf'(^|,){item}(,|$)') + if q_game.children: + # param 是 dict:合并时转成 Q(**param) & q_game + param = Q(**param) & q_game + + total, datas = self.page_query(Project, param, vmi.page, vmi.page_size) + + # 游戏类型以数组返回(多选),便于前端直接绑定多选组件 + for data_ in datas: + data_['game_type'] = split_game_type(data_.get('game_type')) + + return ApiResponse(data={'list': datas, 'total': total, 'page': vmi.page, 'page_size': vmi.page_size}) + + +class ProjectRolesView(View): + def get(self, request): + """获取项目角色信息""" + project_id = int(request.GET.get('project_id', 0)) + qs = Project.objects.exclude(pk=QCC_PROJECT_ID) if project_id == 0 else Project.objects.filter(pk=project_id) + project_infos = {p_['id']: p_ for p_ in qs.values('id', 'name')} + data_list = [] + roles_arr = choices_to_python(RoleEnum) + for project_id_, project_info in project_infos.items(): + children = list(map(lambda role: ({ + 'label': role['label'], + 'value': f'{project_id_}_{role["value"]}', + 'cell_roles': f'{project_info["name"]}/{role["label"]}' + }), roles_arr)) + data_list.append({ + 'project_id': project_id_, + 'label': project_info['name'], + 'value': project_info['name'], + 'children': children + }) + return ApiResponse(data={'list': data_list}) + + +class ProjectConfigView(View): + + Project_Config_Schema_Map = { + 'BugType': ProjectConfigBugTypeSchema, + 'Language': ProjectConfigLanguageSchema, + 'ImgRevert': ProjectConfigImgRevertSchema, + 'BugBillMethod': ProjectConfigBugBillMethodSchema, + 'BugBillUser': ProjectConfigBugBillUserSchema, + 'Other': ProjectConfigOtherSchema, + 'BugTracker': ProjectConfigBugTrackerSchema, + 'CustomField': ProjectConfigCustomFieldSchema, + } + + # 返回给前端时需要隐藏的敏感字段 {cate: (fields)} + Secret_Fields = {'BugTracker': ('api_key',)} + SECRET_MASK = '******' + + def get(self, request): + project_id = int(request.GET.get('project_id', 0)) + cate = request.GET.get('cate', '').strip() + is_editor = int(request.GET.get('editor', 0)) + + model = proj_svr.Project_Config_Model_Map.get(cate, None) + if not model: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'非法的cate:{cate}') + # 系统模板(project_id=0)的语言/缺陷类型对所有登录用户可读,其它项目配置需要项目成员权限 + if project_id != QCC_PROJECT_ID and not test_project_user_role_by_project_id(request.user, project_id): + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='没有该项目的权限') + + if cate == 'ImgRevert' and is_editor: # 编辑器 获取还原配置 + return self.get_img_revert_cfg_by_editor(request, project_id) + + datas = list(model.objects.filter(project_id=project_id).order_by('-pk').values()) + if cate == 'ImgRevert': + for data in datas: + data['lang_path'] = orjson.loads(data['lang_path']) + if cate == 'BugType': + datas = sorted(datas, key=lambda obj_: obj_['value']) + for field in self.Secret_Fields.get(cate, ()): + for data in datas: + data[field] = self.SECRET_MASK if data.get(field) else '' + return ApiResponse(data={'list': datas}) + + def get_img_revert_cfg_by_editor(self, request, project_id): + """编辑器 获取还原配置 + # class ImageRSBase(BaseModel): + # 项目图像还原配置信息 + # id: int = Field(Required, description="项目id") + # name: str = Field(Required, description="项目名", alias="project_name") + # root_path: str = Field(None, description="根文件夹路径") + # text: str = Field(None, description="描述文本的标题") + # key: str = Field(None, description="唯一id名称") + # DN_translation: str = Field(None, description="不需要翻译的标识标题") + # unity_path: str = Field(None, description="不需要翻译的标识标题") + """ + project = Project.objects.filter(pk=project_id).values().first() + if not project: + return ApiResponse(ApiErrorEnum.ERROR, msg='项目信息不存在') + img_revert_cfg = proj_svr.ProjCfgService.get_img_revert(project_id).first() + if not img_revert_cfg: + return ApiResponse(ApiErrorEnum.ERROR, msg='图片还原配置不存在,请先配置再使用') + runner_cfg = proj_svr.ProjCfgService.get_runner(project_id, validate=False) or {} + data = { + 'project_id': project['id'], + 'name': project['code'], + 'text': img_revert_cfg['text'], + 'key': img_revert_cfg['key'], + 'root_path': img_revert_cfg['root_path'], + 'DN_translation': img_revert_cfg['no_trans_text'], + 'unity_path': runner_cfg.get('editor_path', ''), + } + for row in orjson.loads(img_revert_cfg['lang_path']): + data[row['code_raw']] = row + return ApiResponse(data=data) + + def _check_param(self, request): + cate = request.GET.get('cate', '').strip() + schema = self.Project_Config_Schema_Map.get(cate, None) + model = proj_svr.Project_Config_Model_Map.get(cate, None) + if not (schema and model): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'非法的cate:{cate}'), None, None + vmi = schema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + return None, vmi, model + + def _drop_masked_secrets(self, cate, param): + """前端回传的掩码表示“未修改”,不覆盖数据库中的密钥""" + for field in self.Secret_Fields.get(cate, ()): + if param.get(field) == self.SECRET_MASK: + del param[field] + return param + + @method_decorator(require_project_perm(RoleEnum.ADMIN)) + def post(self, request): + response, vmi, model = self._check_param(request) + if response: + return response + cate = request.GET.get('cate', '').strip() + param = self._drop_masked_secrets(cate, vmi.model_dump(exclude_unset=True, exclude={'id'})) + if model in proj_svr.Project_Single_Config_Models: + obj, created = model.objects.get_or_create(project_id=param['project_id'], defaults=param) + if not created: + model.update_db(obj.id, mapping=lodash.omit(param, ('project_id',), False)) + else: + obj = model.objects.create(**param) + # 返回新建/更新后的完整对象(含 id),便于前端把草稿行转为已持久化状态,避免因全量刷新丢失其他草稿 + config = model.objects.filter(pk=obj.id).values().first() + for field in self.Secret_Fields.get(cate, ()): + if config: + config[field] = self.SECRET_MASK if config.get(field) else '' + return ApiResponse(msg='创建成功', data={'config': config}) + + @method_decorator(require_project_perm(RoleEnum.ADMIN)) + def patch(self, request): + response, vmi, model = self._check_param(request) + if response: + return response + cate = request.GET.get('cate', '').strip() + pk = vmi.id + param = self._drop_masked_secrets(cate, vmi.model_dump(exclude_unset=True, exclude={'id', 'project_id'})) + # 单条配置用 project_id 定位 + if model in proj_svr.Project_Single_Config_Models: + obj, _ = model.objects.get_or_create(project_id=vmi.project_id) + pk = obj.id + elif not model.objects.filter(pk=pk, project_id=vmi.project_id).exists(): + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'配置不存在 id:{pk}') + model.update_db(pk, mapping=param) + config = model.objects.filter(pk=pk).values().first() + for field in self.Secret_Fields.get(cate, ()): + config[field] = self.SECRET_MASK if config.get(field) else '' + return ApiResponse(msg='更新成功', data={'config': config}) + + @method_decorator(require_project_perm(RoleEnum.ADMIN)) + def delete(self, request): + cate = request.GET.get('cate', '').strip() + model = proj_svr.Project_Config_Model_Map.get(cate, None) + if not model: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg=f'非法的cate:{cate}') + vmi = ProjectConfigDelSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + model.objects.filter(pk__in=vmi.ids, project_id=vmi.project_id).delete() + return ApiResponse(msg='删除成功') + + +class ProjectModuleView(View): + @method_decorator(require_project_perm()) + def post(self, request): + """创建项目模块""" + vmi = ProjectModuleCreateSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + obj_dict = vmi.model_dump(exclude={'id'}, exclude_unset=True) + module = Module(**obj_dict) + module.save() + logger.info(f'[event.project_module.add] user:{request.user["name"]} module_id:{module.id}') + return ApiResponse(data={'module': model_to_dict(module)}) + + @method_decorator(require_project_perm()) + def patch(self, request, *args, **kwargs): + """修改项目模块""" + vmi = ProjectModuleCreateSchema.model_validate(getattr(request, 'body_json', None) or orjson.loads(request.body)) + obj_dict = vmi.model_dump(exclude={'id', 'project_id'}, exclude_unset=True) + if len(obj_dict) == 0: + return ApiResponse(ApiErrorEnum.ERROR, msg='无有效参数') + + module_id = vmi.id + module = Module.objects.filter(pk=module_id).first() + if not module: + return ApiResponse(ApiErrorEnum.NOT_EXIST) + for k, v in obj_dict.items(): + setattr(module, k, v) + module.save() + logger.info(f'[event.project_module.update] user:{request.user["name"]} body:{orjson.dumps(vmi.model_dump()).decode()}') + return ApiResponse(data={'module': model_to_dict(module)}) + + @method_decorator(require_project_perm()) + def delete(self, request, *args, **kwargs): + """删除模块""" + body = getattr(request, 'body_json', None) or orjson.loads(request.body) + module_id = int(body.get('module_id', 0)) + project_id = int(body.get('project_id', 0)) + mapping = {'id': module_id, 'project_id': project_id, 'is_delete': 1} + num = Module.update_db(module_id, mapping) + logger.info(f'[event.project_module.del] user:{request.user["name"]} module_id:{module_id}') + return ApiResponse(data={'num': num}) + + +class ProjectModuleListView(PageView): + Query_Fields = ('project_id', 'cur_id', 'name__icontains', 'show_name__icontains') + + def get(self, request): + """获取模块列表""" + vmi = ProjectModuleListSchema.model_validate(request.GET.dict()) + project_id, page, page_size = vmi.project_id, vmi.page, vmi.page_size + + if vmi.all: # 返回所有模块 + modules_dict = {o_['id']: o_ for o_ in Module.objects.filter(project_id=project_id).values()} + modules = sorted(modules_dict.values(), key=lambda obj: obj['id'], reverse=True) + return ApiResponse( + data={'modules': modules, 'total': len(modules), 'page': page, 'page_size': page_size}) + # 分页查询 + param = self.make_query_params(vmi) + total, datas = self.page_query(Module, param, page, page_size) + return ApiResponse(data={'list': datas, 'total': total, 'page': page, 'page_size': page_size}) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/api.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/api.py new file mode 100644 index 0000000000000000000000000000000000000000..406881eff72c3698fa69f540ce80c30b28443fdb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/api.py @@ -0,0 +1,34 @@ +from libs.util import time_ms +from apps.system.models import SystemLanguage + + +_system_languages_value_map = {} +_system_languages_code_map = {} +_expire_at = 0 + + +def get_system_language_config(): + global _system_languages_value_map + global _system_languages_code_map + global _expire_at + if time_ms() > _expire_at: + query_info = SystemLanguage.objects.filter(is_delete=0).values() + __system_languages_value_map = {item['id']: {'value': item['id'], 'name': item['language_code'], 'label': item['language']} + for item in query_info} + _system_languages_value_map = __system_languages_value_map + __system_languages_code_map = {item['language_code']: {'value': item['id'], 'name': item['language_code'], 'label': item['language']} + for item in query_info} + _system_languages_code_map = __system_languages_code_map + _expire_at = time_ms() + 120 + return _system_languages_value_map + + +def get_language_by_code(language_code): + get_system_language_config() + return _system_languages_code_map.get(language_code, None) + + +def get_language_by_value(language_value): + get_system_language_config() + return _system_languages_value_map.get(language_value, None) + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e1e5525512699306bc3f45f0f4d0bb301b433e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class SystemConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.system' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..43bd41458fa1b4c7e97a1ab9879bed0d0c4ae2cd --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/migrations/0001_initial.py @@ -0,0 +1,26 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='SystemLanguage', + fields=[ + ('id', models.IntegerField(primary_key=True, serialize=False)), + ('language', models.CharField(max_length=45, verbose_name='语言')), + ('language_code', models.CharField(max_length=45, verbose_name='语言编码')), + ('is_delete', models.IntegerField(default=0, verbose_name='逻辑删除')), + ], + options={ + 'db_table': 'lqa_system_language', + }, + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/models.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3fd6499724e0b0bea07d3291da8f89367a841d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/models.py @@ -0,0 +1,10 @@ +from django.db import models + +class SystemLanguage(models.Model): + id = models.IntegerField(primary_key=True) + language = models.CharField(max_length=45, verbose_name='语言') + language_code = models.CharField(max_length=45, verbose_name='语言编码') + is_delete = models.IntegerField(default=0, verbose_name='逻辑删除') + + class Meta: + db_table = 'lqa_system_language' diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..350975aa9887d7df30d012040e2f8ac4fb4221ed --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/urls.py @@ -0,0 +1,8 @@ + +from django.urls import path + +from . import views + +urlpatterns = [ + path('enums/', views.EnumsView.as_view(), name='enum_cate') +] \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/system/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/system/views.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cc36ffb2a69cab4bbf243fb3075608ebce748f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/system/views.py @@ -0,0 +1,35 @@ +from django.views.generic import View + +from libs.util import choices_to_python +from libs import ApiResponse, defs, lodash +from apps.project import service as proj_svr + +class EnumsView(View): + CATE_MAP = { + 'role': choices_to_python(defs.RoleEnum), + 'project_type': choices_to_python(defs.ProjectTypeEnum), + 'game_type': choices_to_python(defs.GameTypeEnum), + 'user_status': choices_to_python(defs.UserStatusEnum), + 'bug_tracker': choices_to_python(defs.BugTrackerTypeEnum), + 'project_phase': choices_to_python(defs.ProjectPhaseEnum), + 'job_status': choices_to_python(defs.JobStatusEnum), + 'bug_priority': choices_to_python(defs.BugPriorityEnum), + 'bug_severity': choices_to_python(defs.BugSeverityEnum), + 'bug_status': choices_to_python(defs.BugRegressStatusEnum) + } + + Field1 = ('id', 'name', 'label', 'value', 'enable') + Field2 = ('id', 'name', 'label', 'value', 'trans_marks') + + def get(self, request, cate): + cate = cate.strip() + if cate == 'language': + arrs = [lodash.pick(obj, self.Field1) for obj in proj_svr.ProjCfgService.get_sys_language()] + elif cate == 'bug_type': + arrs = [lodash.pick(obj, self.Field2) for obj in proj_svr.ProjCfgService.get_sys_bugtype()] + arrs = sorted(arrs, key=lambda obj_: obj_['value']) + else: + arrs = self.CATE_MAP.get(cate, None) + if arrs is None: + return ApiResponse(defs.ApiErrorEnum.NOT_EXIST) + return ApiResponse(data={'list': arrs}) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/apps.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..dff1f83411eda001affd7aaca3fcd9b89ba542aa --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + +class UserConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'apps.user' + diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/middleware.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..17e465cb22512bcc7734e21e9b503166a5aaf420 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/middleware.py @@ -0,0 +1,69 @@ +import time +import re +import logging + +from django.utils.deprecation import MiddlewareMixin + +import settings +from apps.user.models import User +from libs.util import decode_jwt +from libs import ApiResponse +from libs.defs import ApiErrorEnum, UserStatusEnum + +logger = logging.getLogger('user_ware') + +# 免登录接口 +_exclude_paths = ( + r'^/api/user/(login|register|auth_config)$', + r'^/api/health$', +) +if settings.MEDIA_PUBLIC: # 截图允许匿名访问(禅道内嵌截图需要) + _exclude_paths += (r'^/media/', ) +_re_exclude_paths = list(map(lambda p: re.compile(p), _exclude_paths)) + +# request.user 中不携带的字段 +_user_fields = [f.name for f in User._meta.concrete_fields if f.name != 'password'] + + +class AuthRequiredMiddleware(MiddlewareMixin): + """ + 检查用户登录 + - 浏览器:Session(/api/user/login 登录后写入 login_uid) + - API 调用:请求头 LQA-Authorization: ,通过 /api/user/access_token 获取 + """ + def process_request(self, request): + if any(map(lambda reg: reg.match(request.path), _re_exclude_paths)): + return + + uid = None + access_token = request.headers.get('LQA-Authorization', 'web') + if access_token in ('web', ''): + access_token = None + if access_token is not None: + code, body = decode_jwt(access_token, settings.SECRET_KEY) + if code != 0: + logger.error(f'decode_jwt code:{code} err:{body}') + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg=f'认证失败,access_token验证失败:{code}') + if time.time() - int(body['exp']) > 0: + logger.error(f' access_token expire uid:{body["uid"]}') + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg=f'认证失败,access_token已过期') + uid = body['uid'] + + if not uid: + uid = request.session.get('login_uid', None) + + if not uid: + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg='未登录或登录已过期') + + user = User.objects.filter(pk=int(uid)).values(*_user_fields).first() + if not user: + request.session.flush() + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg='认证失败,用户不存在') + if user['status'] != UserStatusEnum.ACTIVE: + request.session.flush() + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg='账号已被禁用,请联系管理员') + + if access_token is not None and access_token != user['access_token']: + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg='认证失败,非法的access_token') + + request.user = user diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/migrations/0001_initial.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/migrations/0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..a719fd261a25d26a8b1cbdb12c91ff37c252451e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/migrations/0001_initial.py @@ -0,0 +1,61 @@ +# Generated by Django 5.1.1 on 2026-10-08 11:00 + +import django.db.models.deletion +import libs.util +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('project', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('is_delete', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='逻辑删除')), + ('created_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('updated_at', models.DateTimeField(default=libs.util.datetime_ms)), + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('name', models.CharField(max_length=100, unique=True, verbose_name='登录用户名')), + ('name_zh', models.CharField(default='', max_length=100, verbose_name='显示名称')), + ('email', models.CharField(default='', max_length=128, verbose_name='邮箱')), + ('department', models.CharField(default='', max_length=100, verbose_name='部门')), + ('password', models.CharField(default='', max_length=128, verbose_name='密码哈希')), + ('status', models.IntegerField(choices=[(0, '禁用'), (1, '正常')], default=1, verbose_name='状态')), + ('is_admin', models.IntegerField(choices=[(0, '关闭'), (1, '开启')], default=0, verbose_name='是否超级管理员')), + ('last_login_at', models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')), + ('access_token', models.CharField(default='', max_length=255)), + ], + options={ + 'db_table': 'lqa_user', + }, + ), + migrations.CreateModel( + name='UserProjectRelationship', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('role', models.IntegerField(choices=[(1, '项目管理员'), (2, '测试人员'), (3, '开发人员')], verbose_name='角色')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('project', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='project.project', verbose_name='项目')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='user.user', verbose_name='用户')), + ], + options={ + 'db_table': 'lqa_user_project_relationship', + }, + ), + migrations.AddField( + model_name='user', + name='projects', + field=models.ManyToManyField(related_name='users', through='user.UserProjectRelationship', to='project.project'), + ), + migrations.AddConstraint( + model_name='userprojectrelationship', + constraint=models.UniqueConstraint(fields=('project_id', 'user_id', 'role'), name='idx__project_id__user_id__role'), + ), + ] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/migrations/__init__.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/models.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/models.py new file mode 100644 index 0000000000000000000000000000000000000000..07c3b0d8b158a160f544895d0d840115c55ef6ef --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/models.py @@ -0,0 +1,47 @@ +from django.contrib.auth.hashers import make_password, check_password +from django.db import models + +from apps.project.models import Project +from libs.defs import SwitchEnum, RoleEnum, UserStatusEnum +from libs import BaseAttrModel, BaseModel + + +class User(BaseAttrModel): + id = models.BigAutoField(primary_key=True) + name = models.CharField(max_length=100, unique=True, verbose_name='登录用户名') + name_zh = models.CharField(max_length=100, default='', verbose_name='显示名称') + email = models.CharField(max_length=128, default='', verbose_name='邮箱') + department = models.CharField(max_length=100, default='', verbose_name='部门') + password = models.CharField(max_length=128, default='', verbose_name='密码哈希') + status = models.IntegerField(choices=UserStatusEnum, default=UserStatusEnum.ACTIVE, verbose_name='状态') + is_admin = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='是否超级管理员') + last_login_at = models.DateTimeField(null=True, blank=True, verbose_name='最后登录时间') + projects = models.ManyToManyField(Project, through='UserProjectRelationship', related_name='users') + access_token = models.CharField(max_length=255, default='') + + # 不允许通过接口返回的敏感字段 + SENSITIVE_FIELDS = ('password', 'access_token') + + def set_password(self, raw_password): + self.password = make_password(raw_password) + + def check_password(self, raw_password): + return bool(self.password) and check_password(raw_password, self.password) + + class Meta: + db_table = 'lqa_user' + + +class UserProjectRelationship(BaseModel): + """角色 用户关系表""" + project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, verbose_name='项目') + user = models.ForeignKey('User', on_delete=models.DO_NOTHING, verbose_name='用户') + role = models.IntegerField(choices=RoleEnum, verbose_name='角色') + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + db_table = 'lqa_user_project_relationship' + constraints = [models.UniqueConstraint(fields=['project_id', 'user_id', 'role'], + name='idx__project_id__user_id__role')] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/schemas.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e6e0b8e05beacecbfca9a07cb824b34ca4f50b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/schemas.py @@ -0,0 +1,98 @@ +import re +from typing import List, Annotated + +from pydantic import BaseModel, Field, BeforeValidator, AfterValidator + +from libs.defs import SwitchEnum, RoleEnum, UserStatusEnum + +USERNAME_PATTERN = r'^[A-Za-z][A-Za-z0-9_.\-]{2,31}$' +USERNAME_HELP = '用户名需以字母开头,3~32位,只能包含字母、数字、下划线、点、中划线' + + +def validate_password(v: str) -> str: + if not (8 <= len(v) <= 64): + raise ValueError('密码长度需为 8~64 位') + if not (re.search(r'[A-Za-z]', v) and re.search(r'\d', v)): + raise ValueError('密码需同时包含字母和数字') + return v + + +Password = Annotated[str, AfterValidator(validate_password)] +Username = Annotated[str, BeforeValidator(lambda v: v.strip() if isinstance(v, str) else v), + Field(pattern=USERNAME_PATTERN, description=USERNAME_HELP)] + + +class UserListSchema(BaseModel): + name__icontains: str = Field(default="", alias="name") + name_zh__icontains: str = Field(default="", alias="name_zh") + department__icontains: str = Field(default="", alias="department") + status: UserStatusEnum = Field(default=None) + project_id: int = Field(default=None) + is_admin: SwitchEnum = Field(default=None) + info_type: int = Field(default=0) # 0:用户简略信息; 1:用户详细信息; 2:用户详细信息(带项目角色信息) + cur_id: int = Field(default=None) + page: int = Field(default=1, ge=1) + page_size: int = Field(default=20, ge=2) + + +def make_project_roles_validator(): + def validator(project_roles, info): + if project_roles is None: + return project_roles + arr = [] + for project_role in project_roles: + project_id, role = project_role.split('_') + arr.append((int(project_id), int(role))) + return arr + return validator + + +class LoginSchema(BaseModel): + username: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=1, max_length=128) + + +class RegisterSchema(BaseModel): + username: Username + password: Password + name_zh: str = Field(default='', max_length=100) + email: str = Field(default='', max_length=128, pattern=r'^([^@\s]+@[^@\s]+\.[^@\s]+)?$') + + +class PasswordChangeSchema(BaseModel): + old_password: str = Field(min_length=1) + new_password: Password + + +class PasswordResetSchema(BaseModel): + id: int = Field(gt=0) + new_password: Password + + +class UserCreateSchema(BaseModel): + name: Username + # 管理员添加用户时允许不传密码;view 层会使用系统默认密码(见 DEFAULT_NEW_USER_PASSWORD) + password: Password = None + name_zh: str = Field(default='', max_length=100) + email: str = Field(default='', max_length=128, pattern=r'^([^@\s]+@[^@\s]+\.[^@\s]+)?$') + department: str = Field(default='', max_length=100) + project_id: int = Field(default=None) # 非super admin需要,要不然可能越权操作其他项目 + roles: Annotated[List[tuple[int, RoleEnum]], BeforeValidator(make_project_roles_validator())] = Field(default_factory=list) + + +class UserPatchSchema(BaseModel): + id: int + is_admin: SwitchEnum = Field(default=None) + status: UserStatusEnum = Field(default=None) + name_zh: str = Field(default=None, max_length=100) + email: str = Field(default=None, max_length=128, pattern=r'^([^@\s]+@[^@\s]+\.[^@\s]+)?$') + department: str = Field(default=None, max_length=100) + project_id: int = Field(default=None) # 非super admin需要,要不然可能越权操作其他项目 + roles: Annotated[List[tuple[int, RoleEnum]], BeforeValidator(make_project_roles_validator())] = Field(default=None) + + +class ProfilePatchSchema(BaseModel): + """用户修改自己的资料""" + name_zh: str = Field(default=None, max_length=100) + email: str = Field(default=None, max_length=128, pattern=r'^([^@\s]+@[^@\s]+\.[^@\s]+)?$') + department: str = Field(default=None, max_length=100) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/service.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/service.py new file mode 100644 index 0000000000000000000000000000000000000000..1688c444b389cb5929470f9a09f5b970522d9217 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/service.py @@ -0,0 +1,48 @@ +import time + +import settings +from libs import cache +from libs.util import encode_jwt, datetime_ms +from apps.user.models import User + +LOGIN_MAX_FAILS = 5 # 连续失败次数上限 +LOGIN_LOCK_SECONDS = 15 * 60 # 达到上限后锁定时长 + + +def update_user_access_token(uid, exp=86400 * 30): + """更新用户access_token""" + payload = { + 'uid': uid, + 'exp': int(time.time()) + exp + } + jwt_str = encode_jwt(payload, settings.SECRET_KEY) + num = User.update_db(uid, {'access_token': jwt_str}) + if num == 0: + raise Exception(f'update_user_access_token uid: {uid} invalidate') + return jwt_str + + +def _fail_key(username, ip): + return f'{cache.BASE_KEY}login_fail:{username.lower()}:{ip}' + + +def login_locked(username, ip) -> bool: + count = cache.get_redis_client().get(_fail_key(username, ip)) + return int(count or 0) >= LOGIN_MAX_FAILS + + +def login_failed(username, ip): + client = cache.get_redis_client() + key = _fail_key(username, ip) + count = client.incr(key) + if count == 1: + client.expire(key, LOGIN_LOCK_SECONDS) + return LOGIN_MAX_FAILS - int(count) + + +def login_succeeded(request, user: User): + cache.get_redis_client().delete(_fail_key(user.name, getattr(request, 'client_ip', ''))) + request.session.cycle_key() # 防止会话固定攻击 + request.session['login_uid'] = user.id + request.session['login_at'] = int(time.time()) + User.update_db(user.id, {'last_login_at': datetime_ms()}, auto_updated_at=False) diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/urls.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..6bc217ff7da435bc646f75350e1635e4e51c8578 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/urls.py @@ -0,0 +1,20 @@ + +from django.urls import path +from .views import * + +urlpatterns = [ + path('auth_config', view_auth_config, name='auth-config'), + path('login', UserLoginView.as_view(), name='login'), + path('register', UserRegisterView.as_view(), name='register'), + path('logout', UserLogoutView.as_view(), name='logout'), + path('password', UserPasswordView.as_view(), name='password'), + path('reset_password', view_reset_password, name='reset-password'), + path('profile', UserProfileView.as_view(), name='profile'), + + path('entity', UserView.as_view(), name='users'), + path('list', UserListView.as_view(), name='user-list'), + + path('permission', user_permission_view, name='user-permission'), + + path('access_token', UserToken.as_view(), name='access-token') +] diff --git a/timi_hok_game_translator/LQA_WMP/server/apps/user/views.py b/timi_hok_game_translator/LQA_WMP/server/apps/user/views.py new file mode 100644 index 0000000000000000000000000000000000000000..3856882e8b4193d8d4fef5450aa7a3e8e44cf591 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/apps/user/views.py @@ -0,0 +1,412 @@ +from typing import List, Tuple +import logging + +from django.views.generic import View +from django.db import transaction +from django.utils.decorators import method_decorator +import orjson + +import settings +from apps.project.models import Project +from apps.project import service as proj_svr +from apps.user import service as user_svr +from apps.user.models import User, UserProjectRelationship +from libs.decorators import * +from libs import ApiResponse, PageView, lodash +from libs.defs import ApiErrorEnum, RoleEnum, UserStatusEnum, SwitchEnum +from .schemas import * + +logger = logging.getLogger('user_view') + +# 管理员添加用户时,若未指定密码则使用该默认密码(需符合 Password 规则:8~64位、字母+数字) +DEFAULT_NEW_USER_PASSWORD = 'Lqa@123456' + + +def view_auth_config(request): + """登录页需要的公开配置(免登录) GET /api/user/auth_config""" + return ApiResponse(data={'allow_register': settings.ALLOW_REGISTER, 'app_name': settings.APP_NAME}) + + +class UserLoginView(View): + """账号密码登录(免登录) POST /api/user/login {username, password}""" + + def post(self, request): + vmi = LoginSchema.model_validate(orjson.loads(request.body or b'{}')) + username, ip = vmi.username.strip(), getattr(request, 'client_ip', '') + if user_svr.login_locked(username, ip): + return ApiResponse(ApiErrorEnum.ERROR_AUTH, + msg=f'登录失败次数过多,请 {user_svr.LOGIN_LOCK_SECONDS // 60} 分钟后再试') + user = User.objects.filter(name=username).first() + if not user or not user.check_password(vmi.password): + left = user_svr.login_failed(username, ip) + logger.warning(f'[event.user.login_fail] name:{username} ip:{ip}') + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg=f'用户名或密码错误{f",还可尝试 {left} 次" if left > 0 else ""}') + if user.status != UserStatusEnum.ACTIVE: + return ApiResponse(ApiErrorEnum.ERROR_AUTH, msg='账号已被禁用,请联系管理员') + user_svr.login_succeeded(request, user) + logger.info(f'[event.user.login] uid:{user.id} name:{user.name} ip:{ip}') + return ApiResponse(data={'user': {'id': user.id, 'name': user.name, 'name_zh': user.name_zh, + 'is_admin': user.is_admin}}) + + +class UserRegisterView(View): + """自助注册(免登录) POST /api/user/register;注册后需由管理员分配项目角色才能使用业务功能""" + + def post(self, request): + if not settings.ALLOW_REGISTER: + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='系统未开放注册,请联系管理员创建账号') + vmi = RegisterSchema.model_validate(orjson.loads(request.body or b'{}')) + if User.objects2.filter(name=vmi.username).exists(): + return ApiResponse(ApiErrorEnum.ERROR, msg='用户名已存在') + user = User(name=vmi.username, name_zh=vmi.name_zh or vmi.username, email=vmi.email) + user.set_password(vmi.password) + user.save() + logger.info(f'[event.user.register] uid:{user.id} name:{user.name} ip:{getattr(request, "client_ip", "")}') + return ApiResponse(msg='注册成功,请登录') + + +class UserLogoutView(View): + def post(self, request): + request.session.flush() + return ApiResponse(msg='已退出登录') + + get = post + + +class UserPasswordView(View): + """修改自己的密码 POST /api/user/password {old_password, new_password}""" + + def post(self, request): + vmi = PasswordChangeSchema.model_validate(orjson.loads(request.body)) + user = User.objects.filter(pk=request.user['id']).first() + if not user.check_password(vmi.old_password): + return ApiResponse(ApiErrorEnum.ERROR, msg='原密码错误') + user.set_password(vmi.new_password) + user.save(update_fields=['password', 'updated_at']) + request.session.cycle_key() # 更换当前会话ID,保留登录态 + logger.info(f'[event.user.password] uid:{user.id}') + return ApiResponse(msg='密码已修改') + + +@require_super_admin +def view_reset_password(request): + """超级管理员重置用户密码 POST /api/user/reset_password {id, new_password}""" + vmi = PasswordResetSchema.model_validate(orjson.loads(request.body)) + user = User.objects.filter(pk=vmi.id).first() + if not user: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='用户不存在') + user.set_password(vmi.new_password) + user.save(update_fields=['password', 'updated_at']) + logger.info(f'[event.user.reset_password] by:{request.user["name"]} uid:{user.id}') + return ApiResponse(msg='密码已重置') + + +class UserProfileView(View): + """修改自己的资料 PATCH /api/user/profile""" + + def patch(self, request): + vmi = ProfilePatchSchema.model_validate(orjson.loads(request.body)) + mapping = vmi.model_dump(exclude_unset=True, exclude_none=True) + if mapping: + User.update_db(request.user['id'], mapping) + return ApiResponse(msg='已保存') + + +def _patch_user_infos(user_infos, include=None, exclude=None): + if exclude is None: + exclude = User.SENSITIVE_FIELDS + if isinstance(user_infos, List) or isinstance(user_infos, Tuple): + ret = [] + for user_info_ in user_infos: + if include: + user_info_ = lodash.pick(user_info_, include) + user_info_ = lodash.omit(user_info_, exclude, False) + ret.append(user_info_) + return ret + else: + user_info_ = lodash.omit(user_infos, exclude, False) + if include: + user_info_ = lodash.pick(user_infos, include) + return user_info_ + + +def _patch_user_project_roles(user_infos, user_of_project_roles, project_dict): + for user_info in user_infos: + user_info['projects'] = [] + user_info['roles'] = [] + uid = user_info['id'] + project_roles = user_of_project_roles.get(uid, {}) + for project_id, roles in project_roles.items(): + project_info = project_dict.get(project_id) + if project_info: + user_info['roles'].extend(list(map(lambda role: f'{project_info["id"]}_{role}', roles))) + user_info['projects'].append({'id': project_info['id'], 'code': project_info['code'], + 'name': project_info['name'], 'roles': roles}) + + +def _query_user_of_project_roles(ship_param_): + """{user_id1: {project_id1: [role1, role2]} }""" + ships = UserProjectRelationship.objects.filter(**ship_param_).values() + user_of_project_roles_ = {} + project_ids_set_ = set() + for ship in ships: + projects_dict = user_of_project_roles_.get(ship['user_id'], {}) + roles = projects_dict.get(ship['project_id'], []) + roles.append(ship['role']) + projects_dict[ship['project_id']] = roles + user_of_project_roles_[ship['user_id']] = projects_dict + project_ids_set_.add(ship['project_id']) + return user_of_project_roles_, project_ids_set_ + + +class UserListView(PageView): + Query_Fields = ('cur_id', 'name__icontains', 'name_zh__icontains', 'department__icontains', 'status') + + def get(self, request): + vmi = UserListSchema.model_validate(request.GET.dict()) + page, page_size, project_id, is_admin, info_type = vmi.page, vmi.page_size, vmi.project_id, vmi.is_admin, vmi.info_type + + user_param = self.make_query_params(vmi) + + ship_param = {} + if project_id is not None: + ship_param['project_id'] = project_id + + # is_admin 筛选:以"该用户在筛选范围内是否担任过 ADMIN"做二分,避免同一用户同时命中"是/否" + # 先按 project_id 过滤查到范围内担任 ADMIN 的 user_id 集合 + admin_user_ids = None + if is_admin is not None: + admin_ship_param = dict(ship_param) + admin_ship_param['role'] = RoleEnum.ADMIN + admin_user_ids = set( + UserProjectRelationship.objects.filter(**admin_ship_param).values_list('user_id', flat=True) + ) + if is_admin == 1 and not admin_user_ids: + return ApiResponse(data={'list': [], 'total': 0, 'page': page, 'page_size': page_size}, msg='empty') + + # 按 project_id 查该项目下的所有相关用户关系(用于后续 role 展示 & 范围限制) + user_of_project_roles = {} + project_ids_set = set() + if len(ship_param) > 0: + user_of_project_roles, project_ids_set = _query_user_of_project_roles(ship_param) + if len(user_of_project_roles) == 0: + return ApiResponse(data={'list': [], 'total': 0, 'page': page, 'page_size': page_size}, msg='empty') + + # 组装 user_param['id__in']:按 project_id 范围 ∩ is_admin 二分规则 + if is_admin == 1: + # 查管理员:必须在 admin_user_ids 内;若还有 project 范围,则取交集 + allowed_ids = admin_user_ids + if user_of_project_roles: + allowed_ids = allowed_ids & set(user_of_project_roles.keys()) + if not allowed_ids: + return ApiResponse(data={'list': [], 'total': 0, 'page': page, 'page_size': page_size}, msg='empty') + user_param['id__in'] = list(allowed_ids) + elif is_admin == 0: + # 查非管理员:从"候选集合"中排除 admin_user_ids + if user_of_project_roles: + allowed_ids = set(user_of_project_roles.keys()) - admin_user_ids + else: + # 未指定项目:从全站用户中排除 admin_user_ids + allowed_ids = set(User.objects.values_list('id', flat=True)) - admin_user_ids + if not allowed_ids: + return ApiResponse(data={'list': [], 'total': 0, 'page': page, 'page_size': page_size}, msg='empty') + user_param['id__in'] = list(allowed_ids) + elif user_of_project_roles: + # 没有 is_admin 筛选但有 project 范围 + user_param['id__in'] = list(user_of_project_roles.keys()) + + total, user_infos = self.page_query(User, user_param, page, page_size) + if len(user_infos) == 0: + return ApiResponse(data={'list': [], 'total': total, 'page': page, 'page_size': page_size}) + + if info_type == 0: # info + user_infos = _patch_user_infos(user_infos) + return ApiResponse(data={'list': user_infos, 'total': total, 'page': page, 'page_size': page_size}) + elif info_type == 1: # simple info + user_infos = _patch_user_infos(user_infos, include=('id', 'name', 'name_zh')) + return ApiResponse(data={'list': user_infos, 'total': total, 'page': page, 'page_size': page_size}) + else: + if len(ship_param) == 0: + ship_param['user_id__in'] = list(map(lambda user_info_: user_info_['id'],user_infos)) + user_of_project_roles, project_ids_set = _query_user_of_project_roles(ship_param) + user_infos = _patch_user_infos(user_infos) + project_dict = {p_['id']: p_ for p_ in Project.objects.filter(pk__in=project_ids_set).values()} + _patch_user_project_roles(user_infos, user_of_project_roles, project_dict) + + return ApiResponse(data={'list': user_infos, 'total': total, 'page': page, 'page_size': page_size}) + + +class UserView(View): + + @classmethod + def _check_permission(cls, current_user, project_id, roles, update_is_admin): + ERROR_PERMISSION = ApiErrorEnum.ERROR_PERMISSION + is_super = test_super_admin(current_user) + if is_super: + return True, None + # 不是super_admin 不能修改用户的is_admin属性 + if update_is_admin: + return False, ApiResponse(ERROR_PERMISSION, msg='update_is_admin, 需要超管权限') + # 不是super_admin 需要 project_id + if not project_id: + return False, ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='请指定项目') + if not test_project_user_role_by_project_id(current_user, project_id, {RoleEnum.ADMIN}): + return False, ApiResponse(ERROR_PERMISSION, msg='需要项目管理员权限') + # 不是super_admin 只能同时操作project_id一个项目且是管理员 + project_ids_set = set(map(lambda role: role[0], roles or [])) + if len(project_ids_set) > 1: + return False, ApiResponse(ERROR_PERMISSION, msg='多项目修改, 需要超管权限') + elif len(project_ids_set) == 1 and project_id not in project_ids_set: + return False, ApiResponse(ERROR_PERMISSION, msg='跨项目修改, 需要超管权限') + return True, None + + def post(self, request): + """管理员创建用户(超管,或项目管理员为本项目创建成员)""" + vr = UserCreateSchema.model_validate(orjson.loads(request.body)) + name, roles, project_id = vr.name, vr.roles, vr.project_id + current_user = request.user + + ok, api_response = self._check_permission(current_user, project_id, roles, False) + if not ok: + return api_response + + user = User.objects2.filter(name=name).first() # 可能之前被删除了,重新加回来 + if user and user.is_delete == 0: + return ApiResponse(ApiErrorEnum.ERROR, msg=f'用户 {name} 已存在') + if not user: + user = User(name=name) + user.is_delete = 0 + user.status = UserStatusEnum.ACTIVE + user.name_zh = vr.name_zh or name + user.email = vr.email + user.department = vr.department + # 管理员添加用户时允许不传密码,此时使用系统默认密码 + user.set_password(vr.password or DEFAULT_NEW_USER_PASSWORD) + try: + with transaction.atomic(): + user.save() + if roles: + proj_svr.update_user_project_roles(user.id, project_id, roles) + except Exception as err: + logger.error('UserProjectRelationship bulk_create err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'创建失败 err:{err}') + user_info = _patch_user_infos(User.objects.filter(pk=user.id).values().first()) + logger.info(f'[event.user.add] user:{current_user["name"]} name:{name} roles:{roles}') + return ApiResponse(data={'user': user_info}) + + def patch(self, request, *args, **kwargs): + vr = UserPatchSchema.model_validate(orjson.loads(request.body)) + roles, is_admin, project_id = vr.roles, vr.is_admin, vr.project_id + uid = vr.id + current_user = request.user + + user_info = User.objects.filter(pk=uid).values().first() + if not user_info: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='用户数据不存在') + # 只保留真正发生变化的资料字段(前端编辑表单会把未修改的字段一并提交) + profile = {k: v for k, v in vr.model_dump(include={'name_zh', 'email', 'department', 'status'}, + exclude_none=True).items() if user_info.get(k) != v} + if roles is None and is_admin is None and not profile: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='没有需要修改的内容') + + update_is_admin = True if is_admin is not None and is_admin != user_info['is_admin'] else False + # 修改资料/禁用账号属于超管操作 + ok, api_response = self._check_permission(current_user, project_id, roles, update_is_admin or bool(profile)) + if not ok: + return api_response + if uid == current_user['id'] and (is_admin == SwitchEnum.OFF or profile.get('status') == UserStatusEnum.DISABLED): + return ApiResponse(ApiErrorEnum.ERROR, msg='不能取消自己的超管权限或禁用自己') + + try: + with transaction.atomic(): + mapping = dict(profile) + if update_is_admin: + mapping['is_admin'] = is_admin + if mapping: + User.update_db(uid, mapping) + if roles is not None: + proj_svr.update_user_project_roles(uid, project_id, roles) + except Exception as err: + logger.error('UserProjectRelationship bulk_create err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'修改失败 err:{err}') + logger.info(f'[event.user.update] user:{request.user["name"]} body:{orjson.dumps(vr.model_dump()).decode()}') + return ApiResponse() + + def get(self, request): + uid = int(request.GET.get('id', request.user['id'])) + info_type = int(request.GET.get('info_type', 1)) + + user_info = User.objects.filter(pk=uid).values().first() + if not user_info: + return ApiResponse(ApiErrorEnum.NOT_EXIST, msg='用户不存在') + + # 本人可以看到自己的 access_token,密码哈希任何情况下都不返回 + exclude = ('password',) if user_info['id'] == request.user['id'] else User.SENSITIVE_FIELDS + user_info = _patch_user_infos(user_info, exclude=exclude) + + if info_type == 1: + user_of_project_roles, project_ids_set = _query_user_of_project_roles({'user_id': uid}) + project_dict = {p_['id']: p_ for p_ in Project.objects.filter(pk__in=project_ids_set).values()} + + _patch_user_project_roles((user_info,), user_of_project_roles, project_dict) + + return ApiResponse(data={'user': user_info}) + + @method_decorator(require_super_admin) + def delete(self, request): + body = orjson.loads(request.body) if request.content_type == 'application/json' else request.POST.dict() + uid = int(body.get('id', 0)) + if not uid: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg=f'非法用户id:{uid}') + if uid == request.user['id']: + return ApiResponse(ApiErrorEnum.ERROR, msg='不能删除自己') + user = User.objects.filter(pk=uid).first() + if not user: + return ApiResponse(ApiErrorEnum.NOT_EXIST) + try: + with transaction.atomic(): + proj_svr.update_ship_and_project_cfg_by_delete_user(uid) + user.is_delete = 1 + user.access_token = '' + user.save(update_fields=['is_delete', 'access_token']) + except Exception as err: + logger.error('use delete err:', exc_info=err) + return ApiResponse(ApiErrorEnum.ERROR, msg=f'删除失败 err:{err}') + logger.info(f'[event.user.del] user:{request.user["name"]} body:{orjson.dumps(body).decode()}') + return ApiResponse() + + +def user_permission_view(request): + user = request.user + projects = [] + project_ids_set = set() + ships = UserProjectRelationship.objects.filter(user_id=user['id']) + ships_dict = {} + for ship in ships: + roles = ships_dict.get(ship.project_id, []) + roles.append(f'{ship.project_id}_{ship.role}') + ships_dict[ship.project_id] = roles + project_ids_set.add(ship.project_id) + + user = _patch_user_infos(user, include=('id', 'is_admin', 'name', 'name_zh')) + + qs = None + if user['is_admin']: + qs = Project.objects.all().exclude(pk=0) + elif len(project_ids_set) > 0: + qs = Project.objects.filter(id__in=project_ids_set).exclude(pk=0) + if qs: + projects = qs.values('id', 'code', 'name') + for p in projects: + p['roles'] = ships_dict.get(p['id'], []) + return ApiResponse(data={'user': user, 'projects': projects}) + + +class UserToken(View): + + @method_decorator(require_ticket) + def post(self, request): + uid = request.user['id'] + jwt_str = user_svr.update_user_access_token(uid) + logger.info(f'[event.access_token] user:{request.user["name"]}') + return ApiResponse(data={'access_token': jwt_str}) diff --git a/timi_hok_game_translator/LQA_WMP/server/celery_app.py b/timi_hok_game_translator/LQA_WMP/server/celery_app.py new file mode 100644 index 0000000000000000000000000000000000000000..b0316a791a0b30180727cae279b960759b2d1923 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/celery_app.py @@ -0,0 +1,10 @@ +import os + +from celery import Celery + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') + +app = Celery('lqa') +app.config_from_object('django.conf:settings', namespace='CELERY') + +app.autodiscover_tasks() diff --git a/timi_hok_game_translator/LQA_WMP/server/celery_worker_debug.py b/timi_hok_game_translator/LQA_WMP/server/celery_worker_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..f52cedbc73a00e89415776017e24136883ef382b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/celery_worker_debug.py @@ -0,0 +1,7 @@ +""" +本地调试 Celery worker (便于在 IDE 中断点调试): + python celery_worker_debug.py -A celery_app worker -l INFO --pool threads -c 2 +""" +from celery.__main__ import main + +main() diff --git a/timi_hok_game_translator/LQA_WMP/server/docker-entrypoint.sh b/timi_hok_game_translator/LQA_WMP/server/docker-entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..a58b776a27a040371c899d00a88b4d63e95a6401 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/docker-entrypoint.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# 用法: docker-entrypoint.sh web | worker | <任意命令> +set -e + +case "$1" in + web) + python manage.py migrate --noinput + python manage.py init_data + if [ -n "$LQA_ADMIN_PASSWORD" ]; then + python manage.py init_admin --if-not-exists + fi + exec gunicorn wsgi:application \ + --bind 0.0.0.0:8000 \ + --workers "${GUNICORN_WORKERS:-4}" \ + --timeout "${GUNICORN_TIMEOUT:-120}" \ + --access-logfile - + ;; + worker) + exec celery -A celery_app worker -l info \ + --concurrency "${CELERY_CONCURRENCY:-4}" \ + -Q "${CELERY_QUEUES:-celery,lqa_queue_ai_sign,lqa_queue_submit_ai_sign,lqa_queue_bug}" + ;; + *) + exec "$@" + ;; +esac diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/__init__.py b/timi_hok_game_translator/LQA_WMP/server/libs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44f3b07c21646f668e437f46694cc4bb76ec2ffa --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/__init__.py @@ -0,0 +1,3 @@ +from .base import * +from .response import * +from . import lodash \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/base.py b/timi_hok_game_translator/LQA_WMP/server/libs/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a08be3cd8a427c94d5e984deade366cd608c6b38 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/base.py @@ -0,0 +1,226 @@ +from typing import Tuple, List, Set +from abc import ABC, abstractmethod +import logging +import datetime + +from django.db import models, transaction +from django.views.generic import View + +from libs.defs import SwitchEnum +from libs.util import time_ms, datetime_ms + +logger = logging.getLogger('base') + +class BaseManager(models.Manager): + def get_queryset(self): + return super().get_queryset().filter(is_delete=SwitchEnum.OFF) + + +class BaseModel(models.Model): + @classmethod + def query_batch(cls, params, exclude_params=None, fields=None, size=600, asc=True, loop=1000): + """大批量查询""" + if exclude_params is None: + exclude_params = {} + if fields is None: + fields = ['id'] + rows = [] + cur_id = 0 if asc else 100000000 + order_key = 'id' + for _ in range(loop): + if asc: # 升序 + params['id__gt'] = cur_id + else: + params['id__lt'] = cur_id + order_key = '-d' + query_set = cls.objects.filter(**params).exclude(**exclude_params) + rows_ = query_set.order_by(order_key)[:size].values(*fields) + rows.extend(rows_) + if len(rows_) < size: + return rows + cur_id = rows[-1]['id'] + return rows + + @classmethod + def query_batch_by_pks(cls, pks, fields=None, step=500, reverse=False): + """ + 当 pks 数量比较多的场景 + reverse False 升序 True 降序 + """ + if not fields: + fields = [] + cur = 0 + order_pks = sorted(pks, reverse=reverse) + pks_ = order_pks[cur: cur + step] + datas = [] + while len(pks_) > 0: + rows = cls.objects.filter(pk__in=pks_).values(*fields) + datas.extend(list(rows)) + cur += step + pks_ = order_pks[cur: cur + step] + return datas + + @classmethod + def update_db_and_cache(cls, pks, mapping=None, cache_update=None, atomic=False, auto_updated_at=True): + """更新数据库同时删除缓存""" + if not pks or mapping is None or len(mapping) == 0: + return 0, [] + if not (isinstance(pks, Tuple) or isinstance(pks, List) or isinstance(pks, Set)): + pks = (pks,) + if auto_updated_at and 'updated_at' not in mapping: + mapping['updated_at'] = datetime_ms() + + def _update_db_and_cache(): + num = cls.objects.filter(pk__in=pks).update(**mapping) + ret = [] + if cache_update: + # 在事务内应该更新缓存, 而不是删除缓存 + if callable(cache_update): + cache_func_name = cache_update.__name__ + ret = cache_update(pks) + else: + cache_func_name = cache_update.hmget.__name__ + ret = cache_update.hmget(pks, refresh=True) + logger.info(f'update_query_and_cache model:{cls._meta.model_name} {cache_func_name}:{pks} rows:{num}') + else: + logger.info(f'update_query model:{cls._meta.model_name} rows:{num}') + return num, ret + + if atomic: + with transaction.atomic(): + return _update_db_and_cache() + else: + return _update_db_and_cache() + + @classmethod + def update_db(cls, pks, mapping=None, auto_updated_at=True): + """ + cls.objects.filter(pk__in=pks).update(**mapping) 方法是直接转为 SQL 语句的, 这是一种用于直接更新的批量操作, + 它并不会调用模型的 save() 方法, 或发射 pre_save 或 post_save 信号 (调用 save() 会触发信号), 或使用 auto_now 字段选项 + 若想保存 QuerySet 中的每项, 并确保调用了每个实例的 save() 方法, 你并不需要任何特殊的函数来处理此问题, 迭代它们, + 并调用它们的 save() 方法 + 所以再这里 统一更新 updated_at + """ + if not pks or mapping is None or len(mapping) == 0: + return 0 + if not (isinstance(pks, Tuple) or isinstance(pks, List) or isinstance(pks, Set)): + pks = (pks,) + if auto_updated_at and 'updated_at' not in mapping: + mapping['updated_at'] = datetime_ms() + return cls.objects.filter(pk__in=pks).update(**mapping) + + class Meta: + abstract = True + + +class BaseAttrModel(BaseModel): + is_delete = models.IntegerField(choices=SwitchEnum, default=SwitchEnum.OFF, verbose_name='逻辑删除') + created_at = models.DateTimeField(default=datetime_ms) + updated_at = models.DateTimeField(default=datetime_ms) + + objects = BaseManager() + objects2 = models.Manager() + + class Meta: + abstract = True + + +class PageView(View): + + BEGIN_AT = '_begin_at' + END_AT = '_end_at' + Pk_Conditions = {'pk__lt': 1, 'pk__lte': 1, 'pk__gt': 1, 'pk__gte': 1} + + Query_Fields = None + + def make_query_params(self, vmi, query_fields=None): + if not query_fields: + query_fields = self.Query_Fields + if not query_fields: + raise Exception('need query fields') + has_pk_condition = False + params = {} + for field in query_fields: + val = getattr(vmi, field) + if val is not None: + if field.endswith('contains') and len(val) == 0: + continue + if field in self.Pk_Conditions: # 防止和本身的 pk 查询冲突 + has_pk_condition = True + if 'pk_lt' in params: + del params['pk_lt'] + if field == 'cur_id' and not has_pk_condition: # 防止和本身的 pk 查询冲突 + params['pk__lt'] = vmi.cur_id + elif field.endswith(self.BEGIN_AT): + params[f'{field[:len(field) - len(self.BEGIN_AT)]}_at__gte'] = val + elif field.endswith(self.END_AT): + params[f'{field[:len(field) - len(self.END_AT)]}_at__lt'] = val + else: + params[field] = val + logger.debug(f'make_query_params: {params}') + return params + + def page_query(self, module, param, page=1, page_size=20, order_key='-id', return_id=False, fields=(), + page_by_where=None): + """ + param dict or Q() + """ + if isinstance(param, dict): + total = module.objects.filter(**param).count() + else: + total = module.objects.filter(param).count() + + if total == 0: + return 0, [] + + if page_by_where is None: + page_by_where = self.page_by_where(param) + + def _db_query(only_id_): + if isinstance(param, dict): + qs = module.objects.filter(**param).order_by(order_key) + else: + qs = module.objects.filter(param).order_by(order_key) + qs = qs.values_list('id', flat=True) if only_id_ else qs.values(*fields) + if page_by_where: # 用 where + id 分页 + return qs[:page_size] + else: # 用 offset + limit 分页 + return qs[(page - 1) * page_size:page * page_size] + + return total, list(_db_query(return_id)) + + @classmethod + def page_by_where(cls, param: dict): + return False # 强制使用 page 分页 + if param is None: + return False + return True if any([k_ in param for k_ in cls.Pk_Conditions]) else False + + +class TaskBase(ABC): + def __init__(self, ctx, request= None, logger=None): + self.ctx = ctx + self.request = request + self.logger = logger + + @abstractmethod + def run(self): + pass + + +class ExpireData(ABC): + def __init__(self, default_data=None, expire_time=60): + self.expire_time = expire_time * 1000 + self.expire_at = 0 + self._data = default_data or {} + + @abstractmethod + def query_db(self): + pass + + @property + def data(self): + if time_ms() > self.expire_at: + self._data = self.query_db() + self.expire_at = time_ms() + self.expire_time + return self._data diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/__init__.py b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..255d97d6159fdf79d7c35743ebef5dfcd01541b9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/__init__.py @@ -0,0 +1,41 @@ +""" +缺陷系统适配层 + +用法: + from libs import bugtracker + tracker = bugtracker.get_tracker(project_id) + external_id = tracker.create_bug(payload, [abs_img_path]) +""" +from typing import Optional + +from .base import BugTracker, BugTrackerError, BugPayload, TrackerBug, html_to_text + +TRACKER_TYPES = ( + ('none', '平台内记录'), + ('bugzilla', 'Bugzilla'), + ('zentao', '禅道'), +) + + +def _tracker_class(tracker_type): + if tracker_type == 'bugzilla': + from .bugzilla import BugzillaTracker + return BugzillaTracker + if tracker_type == 'zentao': + from .zentao import ZentaoTracker + return ZentaoTracker + from .local import LocalTracker + return LocalTracker + + +def get_tracker(project_id: int, config: Optional[dict] = None) -> BugTracker: + """ + 获取项目当前配置的缺陷系统客户端 + :param project_id: 项目ID + :param config: 不传则读取项目配置 ProjectConfigBugTracker (用于 “测试连接” 时传入未保存的配置) + 配置不完整时抛出 BugTrackerError + """ + if config is None: + from apps.project.service import ProjCfgService + config = ProjCfgService.get_bug_tracker(project_id) or {} + return _tracker_class(config.get('tracker_type') or 'none')(project_id, config) diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/base.py b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/base.py new file mode 100644 index 0000000000000000000000000000000000000000..cf02073563441b420e968ebf6f85ccd0f60751af --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/base.py @@ -0,0 +1,196 @@ +""" +缺陷系统适配层: 抽象接口 + +每个项目在 “项目设置 > 基础配置 > 缺陷系统” 中选择一种缺陷系统: + - none 仅在平台内记录 (不对接外部系统) + - bugzilla Bugzilla 5.x REST API + - zentao 禅道开源版 RESTful API v1 +""" +import html +import logging +import re +from abc import ABC, abstractmethod +from dataclasses import dataclass, field, asdict +from typing import Dict, List, Optional + +import requests + +logger = logging.getLogger('bugtracker') + + +class BugTrackerError(Exception): + """调用外部缺陷系统失败""" + + +@dataclass +class TrackerBug: + """统一的缺陷信息结构""" + id: str + title: str = '' + status: str = '' + is_open: bool = True + assignee: str = '' + resolver: str = '' + reporter: str = '' + priority: str = '' + severity: str = '' + url: str = '' + extra: dict = field(default_factory=dict) + + def to_dict(self): + return asdict(self) + + +@dataclass +class BugPayload: + """提交缺陷时的统一参数 (与具体缺陷系统无关)""" + lqa_bug_id: int + title: str + description: str # HTML + priority: int = 0 # libs.defs.BugPriorityEnum + severity: int = 0 # libs.defs.BugSeverityEnum + version_report: str = '' # 发现版本 + version_fix: str = '' # 修复版本/里程碑 + release_id: str = '' # 发布计划 + assignees: List[str] = field(default_factory=list) # LQA 用户名 + reporter: str = '' + custom_fields: Dict[str, str] = field(default_factory=dict) + + +def html_to_text(content: str) -> str: + """把提单描述 (HTML) 转换为纯文本, 供不支持富文本的缺陷系统使用""" + if not content: + return '' + text = re.sub(r'(?i)', '\n', content) + text = re.sub(r'(?i)', '\n', text) + text = re.sub(r'(?i)]*src=["\']([^"\']+)["\'][^>]*>', r'[\1]', text) + text = re.sub(r'<[^>]+>', '', text) + text = html.unescape(text) + text = re.sub(r'\n{3,}', '\n\n', text) + return text.strip() + + +class BugTracker(ABC): + type: str = '' + label: str = '' + #: 是否对接外部系统 (none 为 False) + remote: bool = True + + def __init__(self, project_id: int, config: Optional[dict] = None): + self.project_id = project_id + self.config = config or {} + self.extra = self.config.get('extra') or {} + self.base_url = (self.config.get('base_url') or '').rstrip('/') + self.timeout = int(self.extra.get('timeout', 20)) + + # ---------------------------------------------------------------- HTTP + def _http(self, method, url, expect_json=True, **kwargs): + kwargs.setdefault('timeout', self.timeout) + try: + resp = requests.request(method, url, **kwargs) + except requests.Timeout as err: + raise BugTrackerError(f'{self.label} 请求超时 (>{self.timeout}s): 请检查「系统地址」是否可达, 或在高级配置中调大 timeout') from err + except requests.ConnectionError as err: + raise BugTrackerError(f'{self.label} 无法连接到服务器: 请检查「系统地址」是否正确、网络是否通畅 ({err.__class__.__name__})') from err + except requests.RequestException as err: + raise BugTrackerError(f'{self.label} 请求失败: {err}') from err + if resp.status_code >= 400: + raise BugTrackerError(self._format_http_error(resp)) + if not expect_json: + return resp + try: + return resp.json() + except ValueError as err: + raise BugTrackerError(self._format_non_json_error(resp)) from err + + # 返回了 HTML / 纯文本等非 JSON 内容时, 给出更友好的说明 + def _format_non_json_error(self, resp): + content_type = (resp.headers.get('Content-Type') or '').lower() + body = (resp.text or '').strip() + snippet = body[:120].replace('\n', ' ').replace('\r', ' ') + looks_like_html = 'html' in content_type or body[:15].lower().lstrip().startswith(('=400 的错误: 按常见状态给出中文说明 + def _format_http_error(self, resp): + status = resp.status_code + body = (resp.text or '').strip() + content_type = (resp.headers.get('Content-Type') or '').lower() + # 尝试从 JSON 响应里提取错误信息; 非 JSON 时截取前 200 字符 + detail = '' + if 'json' in content_type: + try: + data = resp.json() + if isinstance(data, dict): + detail = str(data.get('message') or data.get('error') or data.get('msg') or '').strip() + if not detail: + detail = body[:200] + except ValueError: + detail = body[:200] + else: + detail = body[:200].replace('\n', ' ').replace('\r', ' ') + status_hint = { + 400: '请求参数有误', + 401: '认证失败 (账号/密码或 API Key 不正确)', + 403: '权限不足 (当前账号无该操作权限)', + 404: '资源不存在 (请检查「产品ID」「组件」或「系统地址」是否正确)', + 405: '方法不允许 (接口路径可能错误)', + 500: '对方服务内部错误', + 502: '对方服务网关错误', + 503: '对方服务不可用', + 504: '对方服务网关超时', + }.get(status, '') + prefix = f'{self.label} HTTP {status}' + if status_hint: + prefix = f'{prefix}({status_hint})' + return f'{prefix}: {detail}' if detail else prefix + + # ---------------------------------------------------------------- 接口 + @abstractmethod + def create_bug(self, payload: BugPayload, attachments: List[str]) -> str: + """创建缺陷, 返回外部缺陷ID; attachments 为截图绝对路径""" + + @abstractmethod + def get_bugs(self, bug_ids: List[str]) -> Dict[str, TrackerBug]: + """批量查询缺陷, 返回 {外部ID: TrackerBug}, 不存在的ID不返回""" + + @abstractmethod + def close_bug(self, bug_id: str, comment: str): + """回归通过: 关闭缺陷""" + + @abstractmethod + def reopen_bug(self, bug_id: str, comment: str, attachments: List[str], assignee: str = ''): + """回归不通过: 重新打开缺陷并附上新截图""" + + def bug_url(self, bug_id: str) -> str: + return '' + + def get_options(self) -> dict: + """提单下拉选项 (发现版本/修复版本/发布计划)""" + return {'version_report_list': [], 'version_fix_list': [], 'release_id_list': []} + + def get_fields(self) -> List[dict]: + """可配置为 “自定义提单字段” 的外部字段 [{key, label, options:[{value,label}]}]""" + return [] + + def test_connection(self) -> str: + """连通性测试, 成功返回说明文字, 失败抛 BugTrackerError""" + return 'ok' + + # ---------------------------------------------------------------- 工具 + @staticmethod + def _options(items): + return [{'value': str(v), 'label': str(l)} for v, l in items] + + def _map_value(self, key, value, default_map): + """优先使用项目配置 extra.{key} 中的映射""" + mapping = {**default_map, **{int(k): v for k, v in (self.extra.get(key) or {}).items()}} + return mapping.get(int(value or 0)) diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/bugzilla.py b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/bugzilla.py new file mode 100644 index 0000000000000000000000000000000000000000..22a94c85457e791fd0b8946cd79dae085c953190 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/bugzilla.py @@ -0,0 +1,190 @@ +""" +Bugzilla 5.x REST API 适配 +文档: https://bugzilla.readthedocs.io/en/5.0/api/index.html + +项目配置: + base_url Bugzilla 地址, 如 https://bugzilla.example.com + api_key 用户偏好设置 > API Keys 中生成的 Key + product 产品名称 (必填) + component 组件名称 (必填) + extra 可选 JSON: + default_version 未选择 “发现版本” 时使用的版本, 默认 unspecified + op_sys / platform 默认 All + close_status 回归通过时的目标状态, 默认 RESOLVED + close_resolution 默认 FIXED + reopen_status 回归失败时的目标状态, 默认 CONFIRMED (Bugzilla 4.0+ 默认工作流) + priority_map {"1": "Highest", ...} 覆盖 LQA 优先级 -> Bugzilla 优先级映射 + severity_map {"1": "critical", ...} 覆盖 LQA 严重程度 -> Bugzilla 严重程度映射 + assignee_field email(默认, 使用LQA用户邮箱) / name (直接使用LQA用户名) +""" +import base64 +import mimetypes +import os +from typing import Dict, List + +from .base import BugTracker, BugTrackerError, BugPayload, TrackerBug, html_to_text + +PRIORITY_MAP = {1: 'Highest', 2: 'High', 3: 'Normal', 4: 'Low', 5: 'Lowest'} +SEVERITY_MAP = {1: 'critical', 2: 'major', 3: 'normal', 4: 'minor', 5: 'enhancement'} + +# 自定义提单字段中可选的标准字段 +_STANDARD_FIELDS = ('priority', 'bug_severity', 'op_sys', 'rep_platform', 'keywords', 'version', + 'target_milestone', 'component') + + +class BugzillaTracker(BugTracker): + type = 'bugzilla' + label = 'Bugzilla' + + def __init__(self, project_id, config=None): + super().__init__(project_id, config) + self.api_key = self.config.get('api_key', '') + self.product = self.config.get('product', '') + self.component = self.config.get('component', '') + if not (self.base_url and self.api_key and self.product): + raise BugTrackerError('Bugzilla 配置不完整:需要地址、API Key、产品') + + def _req(self, method, path, **kwargs): + headers = kwargs.pop('headers', {}) + headers['X-BUGZILLA-API-KEY'] = self.api_key + headers.setdefault('Accept', 'application/json') + data = self._http(method, f'{self.base_url}/rest/{path.lstrip("/")}', headers=headers, **kwargs) + if isinstance(data, dict) and data.get('error'): + raise BugTrackerError(f'Bugzilla 错误 {data.get("code")}: {data.get("message")}') + return data + + # ------------------------------------------------------------------ 账号 + def _account(self, name: str) -> str: + if not name: + return '' + if self.extra.get('assignee_field', 'email') != 'email' or '@' in name: + return name + from apps.user.models import User + email = User.objects.filter(name=name).values_list('email', flat=True).first() + return email or name + + # ------------------------------------------------------------------ 接口 + def create_bug(self, payload: BugPayload, attachments: List[str]) -> str: + body = { + 'product': self.product, + 'component': self.component, + 'summary': payload.title[:255], + 'version': payload.version_report or self.extra.get('default_version', 'unspecified'), + 'description': html_to_text(payload.description), + 'op_sys': self.extra.get('op_sys', 'All'), + 'platform': self.extra.get('platform', 'All'), + } + if payload.priority: + body['priority'] = self._map_value('priority_map', payload.priority, PRIORITY_MAP) + if payload.severity: + body['severity'] = self._map_value('severity_map', payload.severity, SEVERITY_MAP) + if payload.version_fix: + body['target_milestone'] = payload.version_fix + accounts = [self._account(n) for n in payload.assignees if n] + if accounts: + body['assigned_to'] = accounts[0] + if len(accounts) > 1: + body['cc'] = accounts[1:] + for key, value in (payload.custom_fields or {}).items(): + body[key] = value + + data = self._req('POST', 'bug', json=body) + bug_id = str(data.get('id', '')) + if not bug_id: + raise BugTrackerError(f'Bugzilla 未返回缺陷ID: {data}') + for path in attachments: + self._upload(bug_id, path, '还原截图') + return bug_id + + def _upload(self, bug_id, abs_path, summary, comment=''): + if not abs_path or not os.path.exists(abs_path): + return + with open(abs_path, 'rb') as fp: + content = base64.b64encode(fp.read()).decode() + body = { + 'ids': [int(bug_id)], + 'data': content, + 'file_name': os.path.basename(abs_path), + 'summary': summary, + 'content_type': mimetypes.guess_type(abs_path)[0] or 'image/png', + } + if comment: + body['comment'] = comment + self._req('POST', f'bug/{bug_id}/attachment', json=body) + + def get_bugs(self, bug_ids: List[str]) -> Dict[str, TrackerBug]: + ids = [str(i) for i in bug_ids if i] + if not ids: + return {} + fields = 'id,summary,status,resolution,is_open,assigned_to,creator,priority,severity' + data = self._req('GET', 'bug', params={'id': ','.join(ids), 'include_fields': fields}) + ret = {} + for bug in data.get('bugs', []): + bid = str(bug['id']) + status = bug.get('status', '') + if bug.get('resolution'): + status = f"{status}/{bug['resolution']}" + ret[bid] = TrackerBug( + id=bid, title=bug.get('summary', ''), status=status, is_open=bool(bug.get('is_open', True)), + assignee=bug.get('assigned_to', ''), reporter=bug.get('creator', ''), + priority=bug.get('priority', ''), severity=bug.get('severity', ''), url=self.bug_url(bid), + ) + return ret + + def close_bug(self, bug_id: str, comment: str): + self._req('PUT', f'bug/{bug_id}', json={ + 'status': self.extra.get('close_status', 'RESOLVED'), + 'resolution': self.extra.get('close_resolution', 'FIXED'), + 'comment': {'body': comment}, + }) + + def reopen_bug(self, bug_id: str, comment: str, attachments: List[str], assignee: str = ''): + text = html_to_text(comment) + bug = self.get_bugs([bug_id]).get(str(bug_id)) + if bug and bug.is_open and not bug.status.startswith('RESOLVED'): + # 缺陷仍处于打开状态 (开发尚未处理), 只追加评论 + self._req('POST', f'bug/{bug_id}/comment', json={'comment': text}) + else: + body = {'status': self.extra.get('reopen_status', 'CONFIRMED'), 'comment': {'body': text}} + if assignee: + body['assigned_to'] = self._account(assignee) + self._req('PUT', f'bug/{bug_id}', json=body) + for path in attachments: + self._upload(bug_id, path, '回归截图') + + def bug_url(self, bug_id: str) -> str: + return f'{self.base_url}/show_bug.cgi?id={bug_id}' if bug_id else '' + + def get_options(self) -> dict: + data = self._req('GET', 'product', params={'names': self.product, + 'include_fields': 'name,versions,milestones'}) + products = data.get('products', []) + if not products: + raise BugTrackerError(f'Bugzilla 中不存在产品: {self.product}') + product = products[0] + versions = [v['name'] for v in product.get('versions', []) if v.get('is_active', True)] + milestones = [m['name'] for m in product.get('milestones', []) if m.get('is_active', True)] + return { + 'version_report_list': self._options((v, v) for v in versions), + 'version_fix_list': self._options((m, m) for m in milestones), + 'release_id_list': [], + } + + def get_fields(self) -> List[dict]: + data = self._req('GET', 'field/bug') + fields = [] + for f in data.get('fields', []): + name = f.get('name', '') + if not (f.get('is_custom') or name in _STANDARD_FIELDS): + continue + options = [{'value': v['name'], 'label': v['name']} for v in (f.get('values') or []) if v.get('name')] + fields.append({'key': name, 'label': f.get('display_name') or name, 'options': options}) + return fields + + def test_connection(self) -> str: + self.get_options() # 校验 API Key 与产品 + try: + who = self._req('GET', 'whoami') # 部分 5.0.x 版本不支持, 失败不影响 + return f"连接成功, 当前账号: {who.get('name') or who.get('real_name') or '-'}" + except BugTrackerError: + return '连接成功' diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/local.py b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/local.py new file mode 100644 index 0000000000000000000000000000000000000000..76d46a03b1d2eecb9f2ca236b20d029d60fc3c70 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/local.py @@ -0,0 +1,51 @@ +"""不对接外部系统: 缺陷只记录在 LQA 平台内 (lqa_bug 表)""" +from typing import Dict, List + +from libs.util import datetime_ms +from .base import BugTracker, BugPayload, TrackerBug + +STATUS_OPEN = 'open' +STATUS_CLOSED = 'closed' + + +class LocalTracker(BugTracker): + type = 'none' + label = '平台内记录' + remote = False + + @staticmethod + def _model(): + from apps.bug.models import Bug + return Bug + + def _append_comment(self, bug_id, text, status=None): + Bug = self._model() + bug = Bug.objects.filter(pk=int(bug_id)).first() + if not bug: + return + comments = list(bug.comments or []) + comments.append({'at': datetime_ms().strftime('%Y-%m-%d %H:%M:%S'), 'text': text}) + mapping = {'comments': comments} + if status: + mapping['status'] = status + Bug.update_db(bug.id, mapping) + + def create_bug(self, payload: BugPayload, attachments: List[str]) -> str: + return str(payload.lqa_bug_id) + + def get_bugs(self, bug_ids: List[str]) -> Dict[str, TrackerBug]: + Bug = self._model() + pks = [int(i) for i in bug_ids if str(i).isdigit()] + ret = {} + for row in Bug.objects.filter(pk__in=pks).values('id', 'title', 'status', 'current_owner', 'reporter'): + ret[str(row['id'])] = TrackerBug( + id=str(row['id']), title=row['title'], status=row['status'], + is_open=row['status'] != STATUS_CLOSED, assignee=row['current_owner'], reporter=row['reporter'], + ) + return ret + + def close_bug(self, bug_id: str, comment: str): + self._append_comment(bug_id, comment, STATUS_CLOSED) + + def reopen_bug(self, bug_id: str, comment: str, attachments: List[str], assignee: str = ''): + self._append_comment(bug_id, comment, STATUS_OPEN) diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/zentao.py b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/zentao.py new file mode 100644 index 0000000000000000000000000000000000000000..80cb3118581ba026c4aacb74150c24e1855a33a0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/bugtracker/zentao.py @@ -0,0 +1,205 @@ +""" +禅道 (ZenTao) 开源版 RESTful API v1 适配 +文档: https://www.zentao.net/book/api/setting-369.html + +项目配置: + base_url 禅道地址, 如 http://zentao.example.com (不含 /api.php) + username API 账号 (需要 Bug 模块的创建/解决/关闭/激活权限, 并关闭 “首次登录强制修改密码”) + api_key 该账号的密码 + product 产品 ID (数字) + extra 可选 JSON: + bug_type Bug 类型, 默认 others (codeerror/config/install/security/performance/standard/automation/designdefect/others) + default_build 未选择 “发现版本” 时的影响版本, 默认 trunk (主干) + project_id 禅道项目 ID, 填写后可拉取该项目的版本列表作为 “发现版本” 选项 + execution_id 禅道执行 ID (可选, 创建 Bug 时关联) + priority_map / severity_map 覆盖 LQA -> 禅道 优先级(1~4)/严重程度(1~4)映射 + +说明: 禅道 v1 API 未提供附件上传接口, 截图会以 形式嵌入重现步骤中, + 需要在 .env 中配置 PUBLIC_URL, 且禅道用户的浏览器能访问 LQA 的 /media/ 路径 +""" +from typing import Dict, List + +import settings +from libs import cache, storage +from libs.util import md5 +from .base import BugTracker, BugTrackerError, BugPayload, TrackerBug + +PRIORITY_MAP = {1: 1, 2: 2, 3: 3, 4: 4, 5: 4} +SEVERITY_MAP = {1: 1, 2: 2, 3: 3, 4: 4, 5: 4} +BUG_TYPES = (('codeerror', '代码错误'), ('config', '配置相关'), ('install', '安装部署'), ('security', '安全相关'), + ('performance', '性能问题'), ('standard', '标准规范'), ('automation', '测试脚本'), + ('designdefect', '设计缺陷'), ('others', '其他')) +TOKEN_TTL = 60 * 20 + + +def _account(user) -> str: + """禅道返回的用户字段可能是对象 {account, realname} 也可能是字符串""" + if isinstance(user, dict): + return user.get('account', '') or '' + return user or '' + + +class ZentaoTracker(BugTracker): + type = 'zentao' + label = '禅道' + + def __init__(self, project_id, config=None): + super().__init__(project_id, config) + self.account = self.config.get('username', '') + self.password = self.config.get('api_key', '') + self.product = str(self.config.get('product', '')).strip() + if not (self.base_url and self.account and self.password and self.product): + raise BugTrackerError('禅道配置不完整: 需要地址、账号、密码、产品ID') + self.api = f'{self.base_url}/api.php/v1' + self._token_key = f'zentao_token:{md5(f"{self.base_url}|{self.account}")}' + + # ------------------------------------------------------------------ token + def _token(self, refresh=False): + client = cache.get_redis_client() + key = f'{cache.BASE_KEY}{self._token_key}' + if not refresh: + token = client.get(key) + if token: + return token.decode() if isinstance(token, bytes) else token + data = self._http('POST', f'{self.api}/tokens', json={'account': self.account, 'password': self.password}) + token = data.get('token') + if not token: + raise BugTrackerError(f'禅道获取 Token 失败: {data}') + client.set(key, token, ex=TOKEN_TTL) + return token + + def _req(self, method, path, retry=True, **kwargs): + headers = kwargs.pop('headers', {}) + headers['Token'] = self._token() + try: + data = self._http(method, f'{self.api}/{path.lstrip("/")}', headers=headers, **kwargs) + except BugTrackerError as err: + if retry and 'HTTP 401' in str(err): + self._token(refresh=True) + return self._req(method, path, retry=False, **kwargs) + raise + if isinstance(data, dict) and data.get('error'): + raise BugTrackerError(f'禅道错误: {data.get("error")}') + return data + + # ------------------------------------------------------------------ 工具 + @staticmethod + def _img_html(abs_paths): + public_url = (getattr(settings, 'PUBLIC_URL', '') or '').rstrip('/') + parts = [] + for path in abs_paths: + if not path: + continue + url_path = storage.get_url_path(path) + if public_url: + parts.append(f'

screenshot

') + else: + parts.append(f'

截图: {url_path} (未配置 PUBLIC_URL, 无法内嵌图片)

') + return ''.join(parts) + + def _builds(self, value): + return [value or self.extra.get('default_build', 'trunk')] + + # ------------------------------------------------------------------ 接口 + def create_bug(self, payload: BugPayload, attachments: List[str]) -> str: + body = { + 'title': payload.title[:255], + 'severity': self._map_value('severity_map', payload.severity or 3, SEVERITY_MAP), + 'pri': self._map_value('priority_map', payload.priority or 3, PRIORITY_MAP), + 'type': self.extra.get('bug_type', 'others'), + 'openedBuild': self._builds(payload.version_report), + 'steps': payload.description + self._img_html(attachments), + } + if payload.assignees: + body['assignedTo'] = payload.assignees[0] + if self.extra.get('execution_id'): + body['execution'] = int(self.extra['execution_id']) + if payload.release_id: + body['plan'] = payload.release_id + for key, value in (payload.custom_fields or {}).items(): + body[key] = value + data = self._req('POST', f'products/{self.product}/bugs', json=body) + bug_id = str(data.get('id', '')) + if not bug_id: + raise BugTrackerError(f'禅道未返回缺陷 ID: {data}') + return bug_id + + def _get_bug(self, bug_id): + try: + return self._req('GET', f'bugs/{bug_id}') + except BugTrackerError as err: + if 'HTTP 404' in str(err): + return None + raise + + def get_bugs(self, bug_ids: List[str]) -> Dict[str, TrackerBug]: + ret = {} + for bug_id in [str(i) for i in bug_ids if i]: + bug = self._get_bug(bug_id) + if not bug or bug.get('deleted') in (True, 1, '1'): + continue + status = bug.get('status', '') + ret[bug_id] = TrackerBug( + id=bug_id, title=bug.get('title', ''), status=status, is_open=status != 'closed', + assignee=_account(bug.get('assignedTo')), resolver=_account(bug.get('resolvedBy')), + reporter=_account(bug.get('openedBy')), priority=str(bug.get('pri', '')), + severity=str(bug.get('severity', '')), url=self.bug_url(bug_id), + ) + return ret + + def close_bug(self, bug_id: str, comment: str): + bug = self._get_bug(bug_id) + if not bug: + raise BugTrackerError(f'禅道缺陷不存在: {bug_id}') + if bug.get('status') == 'closed': + return + if bug.get('status') == 'active': # 禅道只能关闭 “已解决” 的缺陷 + self._req('POST', f'bugs/{bug_id}/resolve', json={ + 'resolution': 'fixed', 'resolvedBuild': self.extra.get('default_build', 'trunk'), 'comment': comment}) + self._req('POST', f'bugs/{bug_id}/close', json={'comment': comment}) + + def reopen_bug(self, bug_id: str, comment: str, attachments: List[str], assignee: str = ''): + bug = self._get_bug(bug_id) + if not bug: + raise BugTrackerError(f'禅道缺陷不存在: {bug_id}') + if bug.get('status') == 'active': # 仍处于激活状态, 无需重新激活 + return + body = {'comment': comment + self._img_html(attachments), + 'openedBuild': self._builds('')} + target = assignee or _account(bug.get('resolvedBy')) or _account(bug.get('assignedTo')) + if target: + body['assignedTo'] = target + self._req('POST', f'bugs/{bug_id}/active', json=body) + + def bug_url(self, bug_id: str) -> str: + return f'{self.base_url}/bug-view-{bug_id}.html' if bug_id else '' + + def get_options(self) -> dict: + builds = [('trunk', '主干')] + if self.extra.get('project_id'): + data = self._req('GET', f'projects/{self.extra["project_id"]}/builds') + builds += [(b['id'], b.get('name', b['id'])) for b in data.get('builds', [])] + plans = [] + try: + data = self._req('GET', f'products/{self.product}/plans') + plans = [(p['id'], p.get('title', p['id'])) for p in data.get('plans', [])] + except BugTrackerError: + pass + return { + 'version_report_list': self._options(builds), + 'version_fix_list': [], + 'release_id_list': self._options(plans), + } + + def get_fields(self) -> List[dict]: + return [ + {'key': 'type', 'label': 'Bug类型', 'options': self._options(BUG_TYPES)}, + {'key': 'os', 'label': '操作系统', 'options': []}, + {'key': 'browser', 'label': '浏览器', 'options': []}, + {'key': 'keywords', 'label': '关键词', 'options': []}, + ] + + def test_connection(self) -> str: + self._token(refresh=True) + product = self._req('GET', f'products/{self.product}') + return f"连接成功, 产品: {product.get('name', self.product)}" diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/cache.py b/timi_hok_game_translator/LQA_WMP/server/libs/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..cc6ec6b724a0db30d474ae1b7df30d6402d0bf89 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/cache.py @@ -0,0 +1,452 @@ +import random +import time +import logging +import traceback +from typing import List +from zlib import compress as zcompress, decompress as zdecompress, error as ZLIB_ERROR + +import orjson +from orjson import loads as json_loads, dumps as json_dumps, JSONDecodeError +from django.core.cache import cache +from django.db.models import Count, Max +from munch import Munch as AttrDict + +from settings import COMPRESS +from apps.bug.models import Bug +from apps.project.models import Project, Module +from apps.data.models import Data +from apps.user.models import User, UserProjectRelationship +from apps.job.models import Job, JobExtra +from apps.image.models import Image +from libs.defs import Minute_5, BugBillStatusEnum + +logger = logging.getLogger('cache') + + +def _json_loads_zlib(bjson, compress): + if compress and COMPRESS: # 可能旧缓存还是 json 的 + try: + return json_loads(zdecompress(bjson)) + except ZLIB_ERROR: + return json_loads(bjson) + else: + try: + return json_loads(bjson) + except JSONDecodeError: + return json_loads(zdecompress(bjson)) + + +def _json_dumps_zlib(obj, compress): + return zcompress(json_dumps(obj)) if compress and COMPRESS else json_dumps(obj) + + +def get_redis_client(): + return cache._cache.get_client() + + +BASE_KEY = "lqa_" + + +class ConnectBase(object): + @property + def client(self): + return cache._cache.get_client() + + +class TableBase(ConnectBase): + def __init__(self, modal, name, expire=Minute_5, compress=False ): + self.name = name + self.modal = modal + self.expire = expire + self.compress = compress + + self.db_name = f'{BASE_KEY}{self.name}' + + def _field(self, obj): + return obj['id'] + def _index_pk(self, pk_): + return f'{self.db_name}:{pk_}' + def _index_obj(self, obj): + return f'{self.db_name}:{self._field(obj)}' + + def _query_db(self, pks, **kwargs): + if len(pks) == 0: + return [] + return list(self.modal.objects.filter(pk__in=pks).values()) + + def mset(self, objs, expire=None): + if len(objs) == 0: + return + client = self.client + mapping = {self._index_obj(o): _json_dumps_zlib(o, self.compress) for o in objs} + client.mset(mapping) + + expire_ = expire if expire else self.expire + pipe = client.pipeline() + for key in mapping.keys(): + pipe.expire(key, expire_ + random.randint(1, 10)) + pipe.execute() + + def hget(self, pk, default=None, refresh=False, attrify=False, **kwargs): + objs = self.hmget([pk], refresh=refresh, attrify=attrify, **kwargs) + return default if len(objs) == 0 else objs[0] + + def hmget(self, pks: List = None, refresh=False, mapping=False, attrify=False, ** kwargs): + if len(pks) == 0: + return {} if mapping else [] + pks = list(pks) if isinstance(pks, set) else list(set(pks)) + if refresh: + objs = self._query_db(pks, **kwargs) + self.mset(objs) + else: + b_jsons = self.client.mget(map(self._index_pk, pks)) + quey_db_pks = [] + objs = [] + for idx, bjson in enumerate(b_jsons): + if bjson is None: + quey_db_pks.append(pks[idx]) + continue + objs.append(_json_loads_zlib(bjson, self.compress and COMPRESS)) + objs_delt = self._query_db(quey_db_pks, **kwargs) + for obj in objs_delt: + objs.append(obj) + self.mset(objs_delt) + if attrify: + objs = list(map(lambda o: AttrDict(o), objs)) + if mapping: + return {self._field(obj): obj for obj in objs} + return objs + + def hdel(self, *pks): + self.client.delete(*list(map(self._index_pk, pks))) + + + +class CommBase(ConnectBase): + def __init__(self, name='comm'): + self.prefix = f'{BASE_KEY}{name}' + + def key(self, name): + return f'{self.prefix}:{name}' + + def set(self, name, val, json=False, timeout=Minute_5): + if json: + val = orjson.dumps(val) + self.client.set(self.key(name), val, ex=timeout) + + def get(self, name, default=None, json=False): + val = self.client.get(self.key(name)) + if val is None: + return default + return orjson.loads(val) if json else val + + def delete(self, name): + self.client.delete(self.key(name)) + + +class UserHash(TableBase): pass +class ProjectHash(TableBase): pass +class DataHash(TableBase): pass +class JobHash(TableBase): pass +class JobExtraHash(TableBase): pass +class ImageHash(TableBase): pass +class BugHash(TableBase): pass + + +class JobRegressNumHash(TableBase): + def _query_db(self, pks, **kwargs): + if len(pks) == 0: + return [] + param = {'parent_id__in': pks} + if 'project_id' in kwargs: + param['project_id'] = kwargs['project_id'] + rows = self.modal.objects.filter(**param).values('id', 'parent_id') + stat = {} + for row in rows: + job = stat.get(row['parent_id'], {'id': row['parent_id'], 'children': []}) + job['children'].append(row['id']) + stat[row['parent_id']] = job + if len(pks) != len(rows): # 防止频繁查询 Job 表, 场景: 查询不到时, 补充默认值 + delt_pk_set = set(pks) - set(stat.keys()) + for pk in delt_pk_set: + stat[pk] = {'id': pk, 'children': []} + return list(stat.values()) + + +class JobBugNumHash(TableBase): + def _gen(self, pk): + return {'job_id': pk, 'bug_num': 0} + + def _query_db(self, pks, **kwargs): + param = {'job_id__in': pks} + if 'project_id' in kwargs: + param['project_id'] = kwargs['project_id'] + stats = list(self.modal.objects.filter(**param).values('job_id').annotate(bug_num=Count('job_id'))) + if len(stats) == len(pks): + return stats + # 防止频繁查询 Bug 表, 场景: 有些 job 没有产生 bug + delt_pks_set = set(pks) - set(map(lambda stat: stat['job_id'], stats)) + for pk_ in delt_pks_set: + stats.append(self._gen(pk_)) + return stats + + + def _field(self, obj): + return obj['job_id'] + +class ImageBugNumHash(TableBase): + def _gen(self, pk): + return {'image_id': pk, 'bug_num': 0} + + def _query_db(self, pks, **kwargs): + param = {'image_id__in': pks, 'bill_status': BugBillStatusEnum.SUCCESS} + if 'job_id' in kwargs: + param['job_id'] = kwargs['job_id'] + stats = list(self.modal.objects.filter(**param).values('image_id').annotate(bug_num=Count('image_id'))) + if len(stats) == len(pks): + return stats + # 防止频繁查询 Bug 表, 场景: 有些 image 没有产生 bug + delt_pks_set = set(pks) - set(map(lambda stat: stat['image_id'], stats)) + for pk_ in delt_pks_set: + stats.append(self._gen(pk_)) + return stats + + def _field(self, obj): + return obj['image_id'] + + +class ProjectUserHash(TableBase): + """ + { + "project_id": project_id, + "members": [ + user_id_str: [1, 2, 3] + ] + } + """ + def _query_db(self, project_ids): + if len(project_ids) == 0: + return [] + projects = {} + for ship_row in self.modal.objects.filter(project_id__in=project_ids).values(): + project_id = ship_row['project_id'] + user_id = ship_row['user_id'] + user_id_str = str(user_id) + role = ship_row['role'] + project = projects.get(project_id, {'project_id': project_id, 'members': {}}) + roles = project['members'].get(user_id_str, []) + roles.append(role) + project['members'][user_id_str] = roles + projects[project_id] = project + return list(projects.values()) + + def _field(self, obj): + return obj['project_id'] + + +class ModuleHash(TableBase): + + wrap_id = '_projectid_' + def _field(self, obj): + return obj[self.wrap_id] + + def _query_db(self, project_ids, **kwargs): + rows = self.modal.objects.filter(project_id__in=project_ids).values() + wrap_rows = {} + for row in rows: + wrap_row = wrap_rows.get(row['project_id'], {self.wrap_id: row['project_id']}) + wrap_row[str(row['id'])] = row + wrap_rows[row['project_id']] = wrap_row + return wrap_rows.values() + + def hget(self, pk, default=None, refresh=False, attrify=False, **kwargs): + val = super().hget(pk, default=default, refresh=refresh, attrify=attrify, **kwargs) + if val: + del val[self.wrap_id] + return val + + +user_cache = UserHash(User, 'users') +project_cache = ProjectHash(Project, 'projects') +project_module_cache = ModuleHash(Module, 'project_module', compress=True) +project_user_cache = ProjectUserHash(UserProjectRelationship, 'project_users') +data_cache = DataHash(Data, 'datas', Minute_5 * 2, compress=True) +job_cache = JobHash(Job, 'jobs') +job_ext_cache = JobExtraHash(JobExtra, 'job_extra') +job_regress_num_cache = JobRegressNumHash(Job, 'job_regress_num') +job_bug_num_cache = JobBugNumHash(Bug, 'bug_num') +image_cache = ImageHash(Image, 'images', compress=True) +image_bug_num_cache = ImageBugNumHash(Bug, 'image_bug_num') +bug_cache = BugHash(Bug, 'bugs') + + +class ResourceVersionZSet(ConnectBase): + KEY_RESOURCE_VERSION = f'{BASE_KEY}resource_versions' + + def _index_pk(self, project_id): + return f'{self.KEY_RESOURCE_VERSION}:{project_id}' + + def _query_db(self, project_id): + # return Data.objects.filter(project_id=project_id).exclude(resource_version='')\ + # .values_list('id', 'resource_version')[:1000] + return Data.objects.filter(project_id=project_id).exclude(resource_version='')\ + .values('resource_version').annotate(id=Max('id')).values_list('id', 'resource_version') + + def reset(self, project_id): + qset = self._query_db(project_id) + mapping = {version: id_ for id_, version in qset} + index_pk = self._index_pk(project_id) + self.client.delete(index_pk) + self._zadd(project_id, mapping) + self.client.expire(index_pk, Minute_5 + 50) + + def _zadd(self, project_id, mapping): + if len(mapping) == 0: + return + self.client.zadd(self._index_pk(project_id), mapping) + + def zadd(self, project_id, mapping): + if self.client.exists(self._index_pk(project_id)): + self._zadd(project_id, mapping) + else: + self.reset(project_id) + + def zrem(self, *value): + self.client.zrem(*value) + + def zrevrange(self, project_id, start, end): + items = self.client.zrevrange(self._index_pk(project_id), start, end) + if len(items) == 0: + if self.client.exists(self._index_pk(project_id)): + return items + self.reset(project_id) + items = self.client.zrevrange(self._index_pk(project_id), start, end) + return items + +resource_version_cache = ResourceVersionZSet() + +ticket_cache = CommBase('ticket') + +comm_cahce = CommBase() + +class Lock(ConnectBase): + def __init__(self, key, flag='', timeout=Minute_5, raise_err=False): + self.timeout = timeout + self.flag = flag + self._key = key + self.refresh_at = 0 + self.raise_err = raise_err + + self.current_val_str = None + self.pre_val_str = None + + def __str__(self): + return f'' + + @property + def key(self): + return f'{BASE_KEY}lock:{self._key}' + + def _encode_val(self): + validate_at = int(time.time()) + self.timeout + return f'{validate_at}:{self.flag}' + + def _decode_val(self, val): + idx = val.find(':') + return int(val[:idx]), val[idx+1:] + + def _require(self, ex, nx=False, xx=False): + val = self._encode_val() + # NX: 仅在键不存在时设置; XX: 仅在键存在时设置; EX: 设置键的过期时间, 单位: 秒 + ok = self.client.set(self.key, val, nx=nx, xx=xx, ex=ex) + if ok: + self.current_val_str = val + return ok + + def acquire(self, timeout=None): + """ + 获取锁: 场景 1.如果锁key不存在, 则占用; 场景2: 如果锁key存在但超时, 则占用 + :param timeout: + :return: + """ + _timeout = timeout if timeout else self.timeout + by = 0 + ok = self._require(_timeout, nx=True) + if not ok: + r_val_b = self.client.get(self.key) + if r_val_b: + r_val_str = r_val_b.decode('utf-8') + r_validate_at, flag = self._decode_val(r_val_str) + if time.time() > r_validate_at: # 锁超时 强行占用 + self.client.delete(self.key) + by = 1 + ok = self._require(_timeout, nx=True) + if ok: + self.pre_val_str = r_val_str + else: + by = 2 + ok = self._require(_timeout, nx=True) + logger.warning(f'[lock_acquire] {self} by:{by} ok:{ok}') + return ok + + def release(self): + self.client.delete(self.key) + logger.warning(f'[lock_release] {self}') + + def validate(self, val): + r_validate_at, flag = self._decode_val(val) + if self.flag != flag: + return 1 + elif time.time() > r_validate_at: + return 2 + return 0 + + def refresh(self, timeout=None, interval=30): + now_at = int(time.time()) + if now_at - self.refresh_at < interval: + return True + _timeout = timeout if timeout else self.timeout + r_val_b = self.client.get(self.key) + ok = False + by = 0 + if r_val_b: + r_val_str = r_val_b.decode('utf8') + code = self.validate(r_val_str) + if code == 0: + ok = self._require(_timeout, xx=True) + by = 1 + else: + ok = False + by = 2 + logger.warning(f'[lock_refresh] {self} validate:{code} reason:{r_val_str}') + if ok: + self.refresh_at = now_at + logger.debug(f'[lock_refresh] {self} by:{by} ok:{ok}') + else: + logger.warning(f'[lock_refresh] {self} by:{by} ok:{ok}') + return ok + + def __enter__(self): + return self if self.acquire() else None + + def __exit__(self, exc_type, exc_val, exc_tb): + if exc_val: + logger.error(f'[lock_error]: {exc_type} {exc_val} {"".join(traceback.format_tb(exc_tb))}') + self.release() + if exc_val and self.raise_err: + return False + else: + return True + + +def try_lock(key, func, *args, flag='', timeout=15, raise_err=True, num=3, delay=0.1): + """重试 lock""" + for idx in range(num): + with Lock(key, flag, timeout, raise_err) as lock: + if not lock: + if idx == num - 1: + return False, None + logger.warning(f'try_lock {key} fail, idx:{idx}') + time.sleep(delay) + continue + return True, func(lock, *args) diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/db_mysql/__init__.py b/timi_hok_game_translator/LQA_WMP/server/libs/db_mysql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/db_mysql/base.py b/timi_hok_game_translator/LQA_WMP/server/libs/db_mysql/base.py new file mode 100644 index 0000000000000000000000000000000000000000..b5eecc553f4e79de5ecd083ea164ef5693c8461b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/db_mysql/base.py @@ -0,0 +1,22 @@ +""" +MySQL 数据库后端 (在 Django 官方后端基础上) 允许主键/外键值为 0 + +系统模板项目使用 id=0 (libs.defs.QCC_PROJECT_ID), 其下的缺陷类型、语言配置的 project_id 为 0, +Django 官方 MySQL 后端会拒绝 0 作为 AutoField 的值, 这里放开该限制, +并在连接上启用 NO_AUTO_VALUE_ON_ZERO, 使显式写入的 0 不会被当作 “生成下一个自增ID” +""" +from django.db.backends.mysql import base, operations + + +class DatabaseOperations(operations.DatabaseOperations): + def validate_autopk_value(self, value): + return value + + +class DatabaseWrapper(base.DatabaseWrapper): + ops_class = DatabaseOperations + + def init_connection_state(self): + super().init_connection_state() + with self.cursor() as cursor: + cursor.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',NO_AUTO_VALUE_ON_ZERO')") diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/decorators.py b/timi_hok_game_translator/LQA_WMP/server/libs/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..db5f45901f7c267578c4d3a3c35687af4e8c1b9c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/decorators.py @@ -0,0 +1,124 @@ +import time +import functools +import logging + +import orjson + +from apps.project import service as proj_svr +from libs import ApiResponse, cache +from libs.defs import ApiErrorEnum, RoleEnum + +logger = logging.getLogger(__name__) + +DEFAULT_CHECK_PROJECT_ROLES = (RoleEnum.ADMIN, RoleEnum.DEVELOP, RoleEnum.TEST) + +def _validate_ticket(ticket): + expire_at = cache.ticket_cache.get(ticket, 0) + validate = int(time.time()) < int(expire_at) + if validate: + cache.ticket_cache.delete(ticket) + return validate + + +def require_ticket(func): + """验证 ticket""" + @functools.wraps(func) + def _inner(request, *args, **kwargs): + ticket = request.headers.get('LQA-Ticket', None) + if not ticket: + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='ticket require') + if not _validate_ticket(ticket): + return ApiResponse(ApiErrorEnum.ERROR_PARAM, msg='ticket invalidate') + + return func(request, *args, **kwargs) + return _inner + + +def test_super_admin(user_info): + return True if user_info['is_admin'] else False + + +def require_super_admin(func): + """检查超级管理员 装饰器""" + @functools.wraps(func) + def _inner(request, *args, **kwargs): + if test_super_admin(request.user): + return func(request, *args, **kwargs) + else: + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg='需要超管权限') + return _inner + + +def test_project_user_role(user_info, project_users, roles, allow_super=True): + """ + :param user_info: + :param project_users: + :param roles: + :param allow_super: + :return: bool + """ + if allow_super and test_super_admin(user_info): + return True + if isinstance(roles, set): + roles_set = roles + elif isinstance(roles, tuple) or isinstance(roles, list): + roles_set = set(roles) + else: + roles_set = {roles} + has_roles = project_users['members'].get(str(user_info['id']), []) + return True if len(roles_set.intersection(set(has_roles))) > 0 else False + + +def test_project_user_role_by_project_id(user_info, project_id, roles=DEFAULT_CHECK_PROJECT_ROLES, allow_super=True): + if allow_super and test_super_admin(user_info): + return True + project_users = proj_svr.project_of_members(project_id) + if not project_users: + logger.error(f'test_project_user_role_by_project_id invalidate project:{project_id}') + return False + return test_project_user_role(user_info, project_users, roles, allow_super) + + +def test_project_user_role_by_project_ids(user_info, project_ids, check_roles, allow_super=True): + if allow_super and test_super_admin(user_info): + return True + project_ids_set = project_ids if isinstance(project_ids, set) else set(project_ids) + project_users = proj_svr.project_of_members(project_ids_set) + if len(project_ids_set) != len(project_users): + logger.error(f'test_project_user_role_by_project_ids invalidate projects:{project_ids_set}') + return False + return all(map(lambda item: test_project_user_role(user_info, item, check_roles, allow_super), project_users)) + + +def require_project_perm(roles=DEFAULT_CHECK_PROJECT_ROLES, allow_super=True): + """装饰器: 检查用户在项目中的角色""" + def decorator(func): + @functools.wraps(func) + def _inner(request, *args, **kwargs): + key = 'project_id' + project_id = int(request.GET.get(key, 0)) or int(request.POST.get(key, 0)) or int(request.headers.get(key, 0)) + if not project_id and request.method != 'GET' and request.content_type == 'application/json': + try: + body_json = orjson.loads(request.body) + project_id = int(body_json.get(key, 0)) + request.body_json = body_json # 标记一下, 不用重复 json 解析了 + except Exception as err: + pass + code = '' + if allow_super and test_super_admin(request.user): + return func(request, *args, **kwargs) + if project_id: + project_users = proj_svr.project_of_members(project_id) + if project_users: + if test_project_user_role(request.user, project_users, roles, allow_super): + return func(request, *args, **kwargs) + else: + code = f'test_project_user_role failed, roles:{roles} allow_super:{allow_super}' + else: + code = f'no project_of_members:{project_id}' + else: + code = 'no project id' + err_msg = f'require_project_perm uid: {request.user["id"]} msg: {code}' + return ApiResponse(ApiErrorEnum.ERROR_PERMISSION, msg=err_msg) + return _inner + return decorator diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/defs.py b/timi_hok_game_translator/LQA_WMP/server/libs/defs.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1bcaab763c685b0b6c128513d33cec83908b52 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/defs.py @@ -0,0 +1,161 @@ +from django.db import models +import datetime + +Minute_5 = 60 * 5 + +MAX_ID = 900000000 + + +class ProjectTypeEnum(models.IntegerChoices): + PLATFORM = 1, '平台级' + PROJECT = 2, '项目级' + + +class ProjectPhaseEnum(models.IntegerChoices): + ONLINE = 1, '上线运营' + OFFLINE = 2, '下线' + DEV = 3, '研发期' + SECRECY = 4, '保密' + + +class GameTypeEnum(models.IntegerChoices): + MOBILE_GAME = 1, '手游' + PC_GAME = 2, '端游' + WEB_GAME = 3, '页游' + APP = 4, 'app' + MINI_GAME = 5, '小游戏' + + +class UserStatusEnum(models.IntegerChoices): + DISABLED = 0, '禁用' + ACTIVE = 1, '正常' + + +class BugTrackerTypeEnum(models.TextChoices): + NONE = 'none', '平台内记录' + BUGZILLA = 'bugzilla', 'Bugzilla' + ZENTAO = 'zentao', '禅道' + + +class RoleEnum(models.IntegerChoices): + ADMIN = 1, '项目管理员' + TEST = 2, '测试人员' + DEVELOP = 3, '开发人员' + + +# class BugTypeEnum(models.IntegerChoices): +# MISS_TRANS = 1, "漏译" +# OVERFLOW = 2, "超框" +# MISS_KEY = 3, "漏Key" +# OVERLAP = 4, "标准框重叠" +# ERR_TRANS = 5, "错译" + + +class ProjectConfigCateEnum(models.IntegerChoices): + BUG_TYPE = 1, "缺陷类型" + LANGUAGE = 2, "区域语言" + IMG_REVERT = 3, "图片还原" + RUNNER = 4, "还原执行(Webhook)" + BILL = 5, "提单" + BUG_TRACKER = 6, "缺陷系统" + + +class SwitchEnum(models.IntegerChoices): + OFF = 0, '关闭' + ON = 1, '开启' + + +class JobRegressionEnum(models.IntegerChoices): + """任务类型标识 0:正常生成图片,1:回归任务生成图片,2:正常生成图片重试任务""" + NORMAL = 0, '正常生成图片' + REGRESSION = 1, '回归任务生成图片' + RETRY = 2, '正常生成图片重试任务' + +class JobDiscernEnum(models.IntegerChoices): + FULL = 0, '全量识别' + DIFF = 1, '差异识别' + +class JobStatusEnum(models.IntegerChoices): + UN_RUNNING = 1, '未执行' + RUNNING = 2, '执行中' + FAILED = 3, '执行失败' + SUCCESS = 4, '执行成功' + COMPLETED = 5, '执行完' + +class JobResTypeEnum(models.TextChoices): + GIT = 'git' + SVN = 'svn' + P4 = 'p4' + OTHER = 'other' + +class BugPriorityEnum(models.IntegerChoices): + """平台内的优先级, 提交到缺陷系统时由适配器映射为对应系统的取值""" + EMPTY = 0, '空' + URGENT = 1, '紧急' + HIGH = 2, '高' + MEDIUM = 3, '中' + LOW = 4, '低' + INSIGNIFICANT = 5, '无关紧要' + + +class BugSeverityEnum(models.IntegerChoices): + """平台内的严重程度, 提交到缺陷系统时由适配器映射为对应系统的取值""" + EMPTY = 0, '空' + FATAL = 1, '致命' + SERIOUS = 2, '严重' + NORMAL = 3, '一般' + PROMT = 4, '提示' + ADVICE = 5, '建议' + + +class BugBillStatusEnum(models.IntegerChoices): + INIT = 0, '初始' + SUCCESS = 1, '提bug单成功' + FAILED = 2, '提bug单失败' + + +class BugRegressStatusEnum(models.IntegerChoices): + INIT = 1, '初始' + RUNNING = 2, '回归中' + SUCCESS = 3, '回归成功' + FAILED = 4, '回归失败' + + +class ImageTaskErrorEnum(models.IntegerChoices): + ERR_NO = 0, '没有失败' + ERR_AI_REC = 1, '识别失败' + ERR_BUG_BILL = 2, '提单失败' + ERR_REGRESSION = 3, '回归失败' + +class ImageAiSignErrorEnum(models.IntegerChoices): + ERR_NO = 0, '初始值' + ERR_SUC = 1, '识别成功' + ERR_FAIL = 2, '识别失败' + + +class SystemCateEnum(models.IntegerChoices): + ROLE = 1, 'roles' + BUG_TYPE = 2, 'bugtypes' + LANGUAGE = 3, 'languages' + + +class ReviewedEnum(models.IntegerChoices): + EMPTY = 0, '未审核(无审核记录)' + AUTO = 1, '系统自动审核' + MANUAL = 2, '人工审核' + + +class ApiErrorEnum(models.IntegerChoices): + ERROR = 1000, '接口错误' + ERROR_PARAM = 1001, '参数错误' + ERROR_AUTH = 1003, '认证失败' + NOT_EXIST = 1004, '数据不存在' + ERROR_NEED_UPDATE = 1005, '数据版本错误' + ERROR_PERMISSION = 1006, '没有权限' + + +LO_TIME_DELTA = datetime.timedelta(hours=8) +LO_ZONE = datetime.timezone(LO_TIME_DELTA) + +# 系统模板项目id: 存放系统级缺陷类型、语言配置, 新建项目时以此为模板复制 +QCC_PROJECT_ID = 0 diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/lodash.py b/timi_hok_game_translator/LQA_WMP/server/libs/lodash.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7a9c7eb7038f1b41931971a332c4c286e43d50 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/lodash.py @@ -0,0 +1,89 @@ +""" +参考 https://www.lodashjs.com/ +""" + +from __future__ import annotations + +import copy +from typing import List, Tuple, Callable + +__all__ = ['split', 'pick', 'key_by', 'omit'] + + +class LodashError(Exception): + pass + + +def split(content, sep=',', func=None): + """ '1, 2, 3' => [1, 2, 3] """ + content = content.strip() + if not content: + return [] + items = content.split(sep) + if func: + return list(map(func, items)) + return items + + +def pick(obj, keys: List[str] or Tuple[str]): + """ + obj = { 'a': 1, 'b': '2', 'c': 3 } + pick(obj, ['a', 'c']); + // => { 'a': 1, 'c': 3 } + """ + if len(keys) == 0: + return {} + if isinstance(obj, dict): # dict + return {key: obj[key] for key in keys} + else: # obj + return {key: getattr(obj, key) for key in keys} + + +def omit(obj_dict: dict, keys: List[str] or Tuple[str], deep=True): + """ + { 'a': 1, 'b': '2', 'c': 3, 'd': [1, 2, 3] } + omit(obj, ('a', 'c')) + => {'b': '2', 'd': [1, 2, 3]} + """ + copy_func = copy.deepcopy if deep else copy.copy + if len(keys) == 0: + return copy_func(obj_dict) + all_keys_set = set(obj_dict.keys()) + keys_set = set(keys) + delta_keys_set = all_keys_set - keys_set + return {key: copy_func(obj_dict[key]) for key in delta_keys_set} + + + +def key_by(arr, key: str or Callable): + """ + array = [{ 'dir': 'left', 'code': 97 }, { 'dir': 'right', 'code': 100 }] + key_by(array, lambda o: chr(o['code'])) + // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + key_by(array, 'dir'); + // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + """ + if len(arr) == 0: + return {} + if callable(key): + return {key(obj): obj for obj in arr} + else: + if isinstance(arr[0], dict): + return {obj[key]: obj for obj in arr} + else: + return {getattr(obj, key): obj for obj in arr} + + + + +if __name__ == '__main__': + print(pick({'a': 1, 'b': '2', 'c': 3}, ('a', 'c'))) + + array = [{'dir': 'left', 'code': 97}, {'dir': 'right', 'code': 100}] + obj = { 'a': 1, 'b': '2', 'c': 3, 'd': [1, 2, 3] } + print(key_by(array, lambda o: chr(o['code']))) + print(key_by(array, 'dir')) + obj1 = omit(obj, ('a', 'c')) + obj1['d'].append(4) + print(obj1) + print(obj) \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/response.py b/timi_hok_game_translator/LQA_WMP/server/libs/response.py new file mode 100644 index 0000000000000000000000000000000000000000..35f3da484f526ea9148da5c1e1ee510dfd1eab83 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/response.py @@ -0,0 +1,116 @@ +import datetime +import decimal +import uuid +import json + +from django.utils.timezone import is_aware +from django.utils.duration import duration_iso_string +from django.utils.functional import Promise +from django.http.response import JsonResponse, HttpResponse +from django.core.serializers.json import DjangoJSONEncoder +from django.db.models.query import QuerySet +from django.db.models import Choices +import orjson + + +def _default_api_data(code, data, msg, api_err: Choices = None): + if data is None: + data = {} + if api_err: + resp = {'code': api_err.value, 'data': data, 'msg': api_err.label } + if code: + resp['code'] = code + if msg: + resp['msg'] = msg + return resp + return {'code': code, 'data': data, 'msg': msg} + + +class ApiResponseBase(HttpResponse): + def __init__(self, api_err: Choices = None, data=None, code=0, msg='', dump=True, **kwargs): + self.data = _default_api_data(code, data, msg, api_err) + kwargs.setdefault("content_type", "application/json") + # 业务错误统一返回 HTTP 500; 认证失败 (1003) 返回 401, 前端据此跳转登录页 + kwargs.setdefault("status", 200 if self.data['code'] == 0 else (401 if self.data['code'] == 1003 else 500)) + data_s = self.json() if dump else '' + self._dumped = dump + super().__init__(data_s, **kwargs) + + def dump(self, force=False): + """dump content""" + if self._dumped and not force: + return self + self.content = self.json() + self._dumped = True + return self + + def raw(self): + """raw data""" + return self.data + + def __str__(self): + return f"code:{self.data['code']}, msg:{self.data['msg']}" + + +class ApiJsonResponse(ApiResponseBase): + def __init__(self, api_err: Choices = None, data=None, code=0, msg='', dump=True, + encoder=None, json_dumps_params=None, **kwargs): + self.encoder = encoder + self.json_dumps_params = json_dumps_params + super().__init__(api_err, data, code, msg, dump, **kwargs) + + def json(self, encoder=DjangoJSONEncoder, json_dumps_params=None): + """ + :param encoder: + :param json_dumps_params: + :return: str + """ + json_dumps_params_ = json_dumps_params or self.json_dumps_params or {} + encoder_ = encoder or self.encoder + return json.dumps(self.data, cls=encoder_, **json_dumps_params_) + + +class ApiOrjsonResponse(ApiResponseBase): + def __init__(self, api_err: Choices = None, data=None, code=0, msg='', dump=True, json_dumps_params=None, **kwargs): + self.json_dumps_params = json_dumps_params or {} + super().__init__(api_err, data, code, msg, dump, **kwargs) + + def json(self, json_dumps_params=None): + """ + :param json_dumps_params: + :return: bytes + """ + json_dumps_params_ = json_dumps_params or self.json_dumps_params or {} + return orjson.dumps(self.data, default=self._encode_default, option=orjson.OPT_PASSTHROUGH_DATETIME, + **json_dumps_params_) + + @classmethod + def _encode_default(cls, o): + if isinstance(o, QuerySet): + return tuple(o) + elif isinstance(o, datetime.datetime): + r = o.isoformat() + if o.microsecond: + r = r[:23] + r[26:] + if r.endswith("+00:00"): + r = r.removesuffix("+00:00") + "Z" + return r + elif isinstance(o, datetime.date): + return o.isoformat() + elif isinstance(o, datetime.time): + if is_aware(o): + raise ValueError("JSON can't represent timezone-aware times.") + r = o.isoformat() + if o.microsecond: + r = r[:12] + return r + elif isinstance(o, datetime.timedelta): + return duration_iso_string(o) + elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): + return str(o) + elif hasattr(o, '__iter__'): + return tuple(item for item in o) + raise TypeError + + +ApiResponse = ApiOrjsonResponse diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/storage.py b/timi_hok_game_translator/LQA_WMP/server/libs/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..14aedd651b9fe8cfd7290fa235de5ed99406ba8c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/storage.py @@ -0,0 +1,92 @@ +import os +import logging +import uuid +import datetime + +import settings + +from libs.util import write_file, mv_file_safe, read_file_iter + +logger = logging.getLogger('storage') + + +APP_MEDIA_ROOT = settings.APP_MEDIA_ROOT + +os.makedirs(os.path.join(APP_MEDIA_ROOT, 'media/temp'), exist_ok=True) + +def path_join(pre_path, *args, check_slash=True): + if check_slash: + args = list(map(lambda arg: arg[1:] if arg[0] == '/' else arg, args)) + full_path = os.path.join(pre_path, *args) + if os.sep == '\\': + full_path = full_path.replace('\\', '/') + return full_path + + +def get_url_path(abs_path): + url_path = abs_path.replace(APP_MEDIA_ROOT, '') + if url_path[0] != '/': + url_path = '/' + url_path + return url_path + + +def get_abs_path(relative_path): + return path_join(APP_MEDIA_ROOT, relative_path) + + +def gen_tmp_file_path(): + url_path = path_join('/', 'media', 'temp', f'{str(uuid.uuid4())}.tmp') + return get_abs_path(url_path), url_path + + +def gen_project_file_path(project_id, media_type, file_name): + """media_type: image_resource, comm """ + if media_type not in ('image_resource', 'comm'): + raise Exception('Unsupported project media type') + month = datetime.date.today().strftime('%Y%m') + url_path = path_join('/', 'media', media_type, month, str(project_id), file_name) + return get_abs_path(url_path), url_path + + +def gen_job_file_path(project_id, job_id, media_type, file_name): + """media_type: 'data', 'image', 'comm' """ + if media_type not in ('data', 'image', 'comm'): + raise Exception('Unsupported job media type') + month = datetime.date.today().strftime('%Y%m') + url_path = path_join('/', 'media', media_type, month, str(project_id), str(job_id), file_name) + return get_abs_path(url_path), url_path + + +def write_temp_file(buffer_or_fp, chunk_size=1024 * 64, ext=''): + abs_path, url_path = gen_tmp_file_path() + if ext: + url_path += ext + abs_path += ext + return write_file(buffer_or_fp, abs_path, chunk_size), url_path + + +def mv_file(src, dest): + mv_file_safe(src, dest) + logger.info(f'mv_file src:{src} dest:{dest}') + return src, dest + + +def mv_to_temp(src, strict=False): + if not os.path.exists(src) and not strict: + logger.warning(f'mv_to_temp src:{src} file not exist') + return + _, src_file_name = os.path.split(src) + dest_abs_path, url_path = gen_tmp_file_path() + dest_path, dest_file_name = os.path.split(dest_abs_path) + dest = os.path.join(dest_path, f'{src_file_name}.{dest_file_name}') + mv_file_safe(src, dest) + logger.info(f'mv_to_temp src:{src} dest:{dest}') + return src, dest + + +def read_file(abs_path): + return b''.join(bytes(chunk) for chunk in read_file_iter(abs_path)) + + +def read_url_file(url_path): + return read_file(get_abs_path(url_path)) diff --git a/timi_hok_game_translator/LQA_WMP/server/libs/util.py b/timi_hok_game_translator/LQA_WMP/server/libs/util.py new file mode 100644 index 0000000000000000000000000000000000000000..acac9d92ac2a9ba5a639be186a833dc2230cdfef --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/libs/util.py @@ -0,0 +1,309 @@ +import os +import time +import datetime +import hashlib +from functools import partial +from io import BytesIO +import base64 + +import orjson +from PIL import Image +from django.db.models import Choices +from django.core.files.base import File +from requests import request, JSONDecodeError, HTTPError, URLRequired, TooManyRedirects +import jwt + + +def time_ms(): + return int(time.time() * 1000) + + +def datetime_ms(dt=None, del_tz=True): + """ + dt: datetime + tz: 去除dt的tzinfo信息, 因为settings.USE_TZ一般设置为False, 表示django处理datetime对时区无感知, 如果dt带有tzinfo, 存db时会报错 + + 由于django在json序列化时只保留了datetime毫秒的前3位, 所以为了后端和前端使用一致, 生成时间转换一下 + 这个方法目的是保留毫秒的前3位 2024-12-06T15:37:30.540123 => 2024-12-06T15:37:30.540000 + """ + if dt and del_tz and dt.tzinfo: + dt = dt.replace(tzinfo=None) + if not dt: + dt = datetime.datetime.now() + return dt.replace(microsecond=int(dt.microsecond / 1000) * 1000) + + +def str_to_ms(ts, format='%Y-%m-%d %H:%M:%S'): + """%Y-%m-%d %H:%M:%S to ms""" + dt = datetime.datetime.strptime(ts, format) + return int(dt.timestamp() * 1000) + + +def ms_to_str(ms): + return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ms / 1000)) + + +class open_file_safe(object): + + def __init__(self, filepath, mode='r'): + self.filepath = filepath + self.mode = mode + self.fp = None + + def __enter__(self): + parent_dir = os.path.dirname(self.filepath) + if not os.path.exists(parent_dir): + os.makedirs(parent_dir, exist_ok=True) + self.fp = open(self.filepath, self.mode) + return self.fp + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.fp and not self.fp.closed: + self.fp.close() + + +def mv_file_safe(src, dest): + if os.path.isfile(dest): + os.remove(dest) + p_path = os.path.dirname(dest) + if not os.path.isdir(p_path): + os.makedirs(p_path) + os.rename(src, dest) + + +def write_file(buffer_or_fp, file_path=None, chunk_size=1024 * 64): + with open(file_path, 'wb') as fp: + if isinstance(buffer_or_fp, File): + for chunk in buffer_or_fp.chunks(chunk_size): + fp.write(chunk) + else: + for i in range(0, len(buffer_or_fp), chunk_size): + fp.write(buffer_or_fp[i:i + chunk_size]) + return file_path + + +def read_file_iter(filepath, chunk_size=1024 * 64): + with open(filepath, 'rb') as fp: + for chunk in iter(partial(fp.read, chunk_size), b''): + yield chunk + + +def choices_to_python(obj: Choices): + return tuple( + map(lambda item: {'value': item[0], 'name': item[1], 'label': item[2]}, zip(obj.values, obj.names, obj.labels))) + + +def md5(content): + md5_hash = hashlib.md5() + md5_hash.update(content.encode('utf-8') if isinstance(content, str) else content) + return md5_hash.hexdigest() + + +def encode_jwt(payload, secret_key): + return jwt.encode(payload, secret_key, algorithm='HS256') + + +def decode_jwt(token, secret_key): + try: + return 0, jwt.decode(token, secret_key, algorithms=["HS256"]) + except jwt.ExpiredSignatureError as err: + return 1, '签名已过期' + except jwt.InvalidTokenError as err: + return 2, '非法的Token' + except Exception: + return 3, '未知' + + +def judge_rectangle(corners): + """判断是否是标准文本框 + :param corners: dict, 位置信息 + :param height: int, 图像高度 + :return: 判断是否是标准矩形框 + """ + x1 = int(corners[0]["x"]) + y1 = int(corners[0]["y"]) + x2 = int(corners[1]["x"]) + y2 = int(corners[1]["y"]) + x3 = int(corners[2]["x"]) + y3 = int(corners[2]["y"]) + x4 = int(corners[3]["x"]) + y4 = int(corners[3]["y"]) + if x1 != x2 or x3 != x4 or y1 != y4 or y2 != y3: + return False + return True + + +def coordinate_trans(corners, height): + """坐标变换, 将左下角为原点的坐标点转换为左上角为原点的坐标点, 如果是标准矩形用 (x,y,w,h) 表示, 如果非标准矩形用转换后的坐标点表示 + :param corners: dict, 位置信息 + :param height: int, 图像高度 + :param is_rectangle: bool, 默认标准文本框, 返回思维向量, 否则保持原4个点坐标 + :return: 转化后的位置坐标 (x1, y1, x2, y2) + """ + is_rectangle = judge_rectangle(corners) + + if is_rectangle: + x1 = int(corners[1]["x"]) + y1 = height - int(corners[1]["y"]) + x2 = int(corners[3]["x"]) + y2 = height - int(corners[3]["y"]) + trans_location = (x1, y1, x2, y2) # x, y, w, h + else: + x1 = int(corners[0]["x"]) + y1 = height - int(corners[0]["y"]) + x2 = int(corners[1]["x"]) + y2 = height - int(corners[1]["y"]) + x3 = int(corners[2]["x"]) + y3 = height - int(corners[2]["y"]) + x4 = int(corners[3]["x"]) + y4 = height - int(corners[3]["y"]) + trans_location = (x1, y1, x2, y2, x3, y3, x4, y4) + return is_rectangle, trans_location + + +def err_response_text(err): + return (err.response.text if err.response is not None else '') if hasattr(err, 'response') else str(err) + + +def retry_request(method, url, params=None, data=None, json=None, headers=None, timeout=15, + retry=2, resp_json=True, **kwargs): + for idx in range(retry): + try: + with request(method, url, params=params, data=data, json=json, headers=headers, + timeout=timeout, allow_redirects=False, **kwargs) as resp: + resp.raise_for_status() + return None, resp.json() if resp_json else resp + except (JSONDecodeError, HTTPError, URLRequired, TooManyRedirects) as err: + return err, None + except Exception as err: + if idx == retry - 1: + return err, None + + +def compress_image_ify(file_path_abs, limit=1024 * 1024 * 5): + st = os.stat(file_path_abs) + if st.st_size > limit: # 大于 5MB 压缩 + img_io = BytesIO() + quality = int(1.0 * limit / st.st_size * 100) - 10 + if quality <= 0: + quality = 10 + with Image.open(file_path_abs) as fp: + fp.save(img_io, format="JPEG", optimize=True, quality=quality) + img_io.seek(0) + return img_io, quality + return None, 0 + + +def make_enum_validator(enum_cls): + def validator(v, info): + return enum_cls[v] if v.startswith('LAN') or v == 'DEFAULT' else enum_cls(int(v)) + return validator + + +def make_item_array_validator(sep=',', item_class=int): + def validator(v, info): + ret = [] + v = v.strip() + if not v: + return ret + items = v.split(sep) + for item in items: + ret.append(item_class(item.strip())) + return ret + return validator + + +def _seq_generator(): + """简单生成序列, 注意不是线程安全的""" + start = 1000 + num = start + while True: + yield num + num += 1 + if num > 100000: + num = start + + +seq_generator = _seq_generator() + + +def get_client_ip(request) -> tuple[Exception, str]: + try: + # 获取真实client_ip + x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') + ip = x_forwarded_for.split(',')[0] if x_forwarded_for else request.META.get('REMOTE_ADDR') + return None, ip + except Exception as err: + return err, '' + + +def base64_encode_file_iter(file_path, chunk_size=1024*96, encode='utf-8'): + """ + 对文件内容流式编码, 减少内存开销 + file_path 文件名 + chunk_size 为了保持和整体编码一致 只能使用3的倍数 切记 + """ + if chunk_size % 3 != 0: + raise Exception('chunk_size must be a multiple of 3') + for chunk in read_file_iter(file_path, chunk_size): + yield base64.b64encode(chunk).decode(encode) + + +def make_json_validator(): + def validator(v, info): + try: + return orjson.loads(v) + except: + raise ValueError('json parse error') + return validator + +def make_img_url_validator(): + def validator(v, info): + idx = v.find('?') + return v[:idx] if idx != -1 else v + return validator + + +if __name__ == '__main__': + pass + # ret = decode_jwt( + # 'xxxxxxxxxxxx') + # print(ret) + # t = time_ms() + # print(t) + # ts = ms_to_str(t) + # print(ts) + # print(str_to_ms(ts)) + + # now = datetime.datetime.now() + # print(f'1: {now}') + # + # from django.core.serializers.json import DjangoJSONEncoder + # import json + # + # data = {"abc": now, "dt": datetime.date.today(), "tm": datetime.time(), + # "content": "metaclass 是 Python 面向对象里最难理解, 也是最难使用的魔术代码, " + # "正常情况下, 你不会碰到需要使用 metaclass 的情况, 所以, 以下内容看不懂也没关系, 因为基本上你不会用到"} + # + # data1 = json.dumps(data, cls=DjangoJSONEncoder) + # print(f'json: {data1}') + # + # data2 = (orjson.dumps(data)).decode('utf-8') + # print(f'orjson: {data2}') + # + # data3 = (orjson.dumps(data, default=ApiResponse._encode_default, option=orjson.OPT_PASSTHROUGH_DATETIME)).decode('utf-8') + # print(f'orjson1: {data3}') + # t1 = time.time() + # for i in range(10000): + # json.dumps(data, cls=DjangoJSONEncoder) + # t2 = time.time() + # for i in range(10000): + # (orjson.dumps(data, default=ApiResponse._encode_default, option=orjson.OPT_PASSTHROUGH_DATETIME)) + # t3 = time.time() + # print((t2 - t1) * 1000) + # print((t3 - t2) * 1000) + + # payload = { 'uid': 2, 'exp': int(time.time()) + 86400 } + # jwt_str = encode_jwt(payload) + # print(jwt_str) + # print(md5(jwt_str)) diff --git a/timi_hok_game_translator/LQA_WMP/server/manage.py b/timi_hok_game_translator/LQA_WMP/server/manage.py new file mode 100644 index 0000000000000000000000000000000000000000..f15f2204a9852ae75af70217940daa844f04668f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/manage.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +"""Django 项目的命令行管理工具, 用于执行各类管理任务 +(如启动开发服务器 runserver、数据库迁移 migrate/makemigrations、 +创建超级用户 createsuperuser 等) +""" +import os +import sys + + +def main(): + """执行管理任务""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/timi_hok_game_translator/LQA_WMP/server/pyproject.toml b/timi_hok_game_translator/LQA_WMP/server/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..5814e24fe6637ebf493ebc420c991ff70f72fce5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/pyproject.toml @@ -0,0 +1,29 @@ +[tool.poetry] +name = "lqa-server" +version = "1.0.0" +description = "LQA 本地化质量检测平台 - 后端服务" +authors = ["LQA Contributors"] +license = "Apache-2.0" +readme = "README.md" +package-mode = false + +[tool.poetry.dependencies] +python = "^3.12" +django = "^5.1.1" +mysqlclient = "^2.2.4" +django-environ = "^0.11.2" +orjson = "^3.10.7" +redis = "^5.0.8" +requests = "^2.32.3" +pydantic = "^2.9.1" +celery = "^5.4.0" +munch = "^4.0.0" +pyjwt = "^2.9.0" +pillow = "^10.4.0" +opencv-python-headless = "^4.10.0.84" +gunicorn = "^23.0.0" + + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/timi_hok_game_translator/LQA_WMP/server/requirements.txt b/timi_hok_game_translator/LQA_WMP/server/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..db4cf0dbb8c6112cf25911c1c1bea0206f1b6c68 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/requirements.txt @@ -0,0 +1,14 @@ +Django==5.1.1 +mysqlclient==2.2.4 +django-environ==0.11.2 +orjson==3.10.7 +redis==5.0.8 +requests==2.32.3 +pydantic==2.9.1 +celery==5.4.0 +munch==4.0.0 +PyJWT==2.9.0 +pillow==10.4.0 +opencv-python-headless==4.10.0.84 +gunicorn==23.0.0 +openpyxl==3.1.5 diff --git a/timi_hok_game_translator/LQA_WMP/server/scripts/__init__.py b/timi_hok_game_translator/LQA_WMP/server/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/LQA_WMP/server/scripts/smoke_test.py b/timi_hok_game_translator/LQA_WMP/server/scripts/smoke_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1dac6ecf383fed629638e8a24055f102c72bef --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/scripts/smoke_test.py @@ -0,0 +1,175 @@ +""" +后端接口冒烟测试 (不依赖外部系统) +用法: + python scripts/smoke_test.py http://127.0.0.1:8000 admin Admin123456 +会在库中创建以 smoke_ 开头的测试项目与用户 +""" +import sys +import time +import uuid + +import requests + +BASE = sys.argv[1].rstrip('/') if len(sys.argv) > 1 else 'http://127.0.0.1:8000' +ADMIN, ADMIN_PWD = (sys.argv[2], sys.argv[3]) if len(sys.argv) > 3 else ('admin', 'Admin123456') + +_passed = 0 + + +def check(cond, title, resp=None): + global _passed + if not cond: + detail = f' -> HTTP {resp.status_code} {resp.text[:300]}' if resp is not None else '' + print(f'[FAIL] {title}{detail}') + sys.exit(1) + _passed += 1 + print(f'[ OK ] {title}') + + +def api(s, method, path, **kw): + return s.request(method, BASE + path, timeout=20, **kw) + + +def main(): + suffix = uuid.uuid4().hex[:6] + anon = requests.Session() + + r = api(anon, 'GET', '/api/user/entity') + check(r.status_code == 401 and r.json()['code'] == 1003, '未登录访问返回 401/1003', r) + + r = api(anon, 'POST', '/api/user/login', json={'username': ADMIN, 'password': 'wrong-pass1'}) + check(r.json()['code'] == 1003 and '还可尝试' in r.json()['msg'], '错误密码登录被拒绝并提示剩余次数', r) + + admin = requests.Session() + r = api(admin, 'POST', '/api/user/login', json={'username': ADMIN, 'password': ADMIN_PWD}) + check(r.json()['code'] == 0, '超级管理员登录', r) + r = api(admin, 'GET', '/api/user/entity') + user = r.json()['data']['user'] + check(user['is_admin'] == 1 and 'password' not in user, '获取当前用户 (不返回密码哈希)', r) + + # ---- 注册 + username = f'smoke_{suffix}' + r = api(anon, 'POST', '/api/user/register', json={'username': username, 'password': '123'}) + check(r.json()['code'] == 1001, '弱密码注册被拒绝', r) + r = api(anon, 'POST', '/api/user/register', json={'username': username, 'password': 'Smoke12345', 'name_zh': '冒烟'}) + check(r.json()['code'] == 0, '自助注册', r) + r = api(anon, 'POST', '/api/user/register', json={'username': username, 'password': 'Smoke12345'}) + check(r.json()['code'] != 0, '重复用户名注册被拒绝', r) + + member = requests.Session() + r = api(member, 'POST', '/api/user/login', json={'username': username, 'password': 'Smoke12345'}) + check(r.json()['code'] == 0, '新用户登录', r) + r = api(member, 'GET', '/api/user/permission') + check(r.json()['data']['projects'] == [], '新注册用户没有任何项目 (需管理员分配)', r) + + # ---- 项目 + code = f'smoke_{suffix}' + r = api(admin, 'POST', '/api/project/entity', json={ + 'code': code, 'name': f'冒烟项目{suffix}', 'project_type': 2, 'project_phase': 3, 'game_type': 1, + 'team': 'QA', 'cvtest_project': 'demo'}) + check(r.json()['code'] == 0, '创建项目', r) + project_id = r.json()['data']['project']['id'] + + r = api(member, 'GET', f'/api/project/config?project_id={project_id}&cate=BugTracker') + check(r.json()['code'] == 1006, '非项目成员不能读取项目配置', r) + + r = api(admin, 'GET', '/api/user/list', params={'name': username, 'info_type': 0}) + uid = r.json()['data']['list'][0]['id'] + r = api(admin, 'PATCH', '/api/user/entity', json={'id': uid, 'roles': [f'{project_id}_2']}) + check(r.json()['code'] == 0, '管理员为新用户分配 “测试人员” 角色', r) + r = api(member, 'GET', '/api/user/permission') + check([p['id'] for p in r.json()['data']['projects']] == [project_id], '成员获得项目权限', r) + + # ---- 缺陷系统配置 (密钥掩码) + r = api(admin, 'PATCH', '/api/project/config?cate=BugTracker', json={ + 'project_id': project_id, 'tracker_type': 'bugzilla', 'base_url': 'http://127.0.0.1:9', + 'api_key': 'secret-key', 'product': 'P', 'component': 'C'}) + check(r.json()['code'] == 0 and r.json()['data']['config']['api_key'] == '******', '保存缺陷系统配置 (返回掩码)', r) + r = api(admin, 'PATCH', '/api/project/config?cate=BugTracker', json={ + 'project_id': project_id, 'tracker_type': 'bugzilla', 'base_url': 'http://127.0.0.1:9', + 'api_key': '******', 'product': 'P2', 'component': 'C'}) + r = api(member, 'GET', f'/api/project/config?project_id={project_id}&cate=BugTracker') + cfg = r.json()['data']['list'][0] + check(cfg['api_key'] == '******' and cfg['product'] == 'P2', '回传掩码不覆盖已保存的密钥', r) + r = api(member, 'POST', '/api/bug/tracker_test', json={'project_id': project_id, 'tracker_type': 'bugzilla'}) + check(r.json()['code'] == 1006, '非项目管理员不能测试缺陷系统连接', r) + r = api(admin, 'POST', '/api/bug/tracker_test', json={ + 'project_id': project_id, 'tracker_type': 'bugzilla', 'base_url': 'http://127.0.0.1:9', + 'api_key': '******', 'product': 'P2'}) + check(r.json()['code'] == 1000 and 'Bugzilla' in r.json()['msg'], '缺陷系统不可达时返回明确错误', r) + r = api(admin, 'PATCH', '/api/project/config?cate=BugTracker', json={'project_id': project_id, 'tracker_type': 'none'}) + r = api(member, 'GET', f'/api/bug/tracker_meta?project_id={project_id}') + check(r.json()['data']['type'] == 'none', '切换为 “平台内记录”', r) + + # ---- 还原执行 (Webhook) + r = api(admin, 'PATCH', '/api/project/config?cate=Other', json={ + 'project_id': project_id, 'webhook_url': 'not-a-url'}) + check(r.json()['code'] == 1001, 'Webhook 地址格式校验', r) + r = api(admin, 'PATCH', '/api/project/config?cate=Other', json={ + 'project_id': project_id, 'webhook_url': 'https://ci.example.com/job/lqa/buildWithParameters?JOB={{job_id}}', + 'webhook_method': 'POST', 'webhook_headers': '{"Authorization": "Bearer t-{{project_code}}"}', + 'webhook_body': '{"job": "{{job_id}}", "langs": "{{language_values}}", "name": "任务-{{job_name}}"}', + 'editor_path': 'C:/Unity/Editor/Unity.exe'}) + check(r.json()['code'] == 0, '保存 Webhook 配置', r) + + # ---- 任务 + today = time.strftime('%Y-%m-%d 00:00:00') + r = api(member, 'POST', '/api/job/entity', json={ + 'project_id': project_id, 'discern': 1, 'name': f'smoke job {suffix}', 'languages': [2, 6], + 'plan_start_at': today, 'plan_end_at': today, 'trans_res_type': 'git'}) + check(r.json()['code'] == 0, '成员创建任务', r) + job_id = r.json()['data']['job']['id'] + + r = api(member, 'POST', '/api/job/action', json={'action': 'start', 'job_id': job_id}) + data = r.json()['data'] + trigger = data.get('trigger', {}) + check(r.json()['code'] == 0 and trigger.get('url') == + f'https://ci.example.com/job/lqa/buildWithParameters?JOB={job_id}', '开始任务: 返回渲染后的 Webhook 地址', r) + check(trigger['headers']['Authorization'] == f'Bearer t-{code}' and trigger['body']['job'] == job_id + and trigger['body']['langs'] == [2, 6] and trigger['body']['name'] == f'任务-smoke job {suffix}', + 'Webhook 请求头/请求体变量替换 (保留原始类型)', r) + + r = api(member, 'POST', '/api/job/action', json={'action': 'started', 'job_id': job_id, 'build_id': '#42'}) + check(r.json()['code'] == 0, 'Webhook 调用成功后回调 started', r) + r = api(member, 'GET', '/api/job/entity', params={'job_id': job_id}) + job = r.json()['data']['job'] + check(job['status'] == 2 and job['build_id'] == '#42', '任务状态变为执行中', r) + r = api(member, 'POST', '/api/job/action', json={'action': 'start', 'job_id': job_id}) + check(r.json()['code'] != 0, '执行中的任务不能再次开始', r) + r = api(member, 'POST', '/api/job/action', json={'action': 'stop', 'job_id': job_id}) + check(r.json()['code'] == 0, '结束任务', r) + + outsider = requests.Session() + other = f'smoke_o_{suffix}' + api(anon, 'POST', '/api/user/register', json={'username': other, 'password': 'Smoke12345'}) + api(outsider, 'POST', '/api/user/login', json={'username': other, 'password': 'Smoke12345'}) + r = api(outsider, 'POST', '/api/job/action', json={'action': 'start', 'job_id': job_id}) + check(r.json()['code'] == 1006, '非项目成员不能操作任务', r) + + # ---- 密码 / 禁用 + r = api(member, 'POST', '/api/user/password', json={'old_password': 'bad', 'new_password': 'Smoke67890'}) + check(r.json()['code'] != 0, '原密码错误时不能修改密码', r) + r = api(member, 'POST', '/api/user/password', json={'old_password': 'Smoke12345', 'new_password': 'Smoke67890'}) + check(r.json()['code'] == 0, '修改密码', r) + r = api(admin, 'POST', '/api/user/reset_password', json={'id': uid, 'new_password': 'Reset12345'}) + check(r.json()['code'] == 0, '超管重置密码', r) + r = api(requests.Session(), 'POST', '/api/user/login', json={'username': username, 'password': 'Reset12345'}) + check(r.json()['code'] == 0, '使用重置后的密码登录', r) + r = api(admin, 'PATCH', '/api/user/entity', json={'id': uid, 'status': 0}) + check(r.json()['code'] == 0, '超管禁用账号', r) + r = api(member, 'GET', '/api/user/entity') + check(r.json()['code'] == 1003, '被禁用账号的会话立即失效', r) + r = api(requests.Session(), 'POST', '/api/user/login', json={'username': username, 'password': 'Reset12345'}) + check(r.json()['code'] == 1003 and '禁用' in r.json()['msg'], '被禁用账号不能登录', r) + + # ---- 登出 + r = api(admin, 'POST', '/api/user/logout') + check(r.json()['code'] == 0, '退出登录', r) + r = api(admin, 'GET', '/api/user/entity') + check(r.json()['code'] == 1003, '退出后会话失效', r) + + print(f'\n全部通过: {_passed} 项') + + +if __name__ == '__main__': + main() diff --git a/timi_hok_game_translator/LQA_WMP/server/scripts/test_bug_flow.py b/timi_hok_game_translator/LQA_WMP/server/scripts/test_bug_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..cb60dae02e6c20d2fd38717fa0b21777191d236c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/scripts/test_bug_flow.py @@ -0,0 +1,136 @@ +""" +提单 + 回归 全流程测试 (平台内记录模式 & Bugzilla 模拟服务) + python scripts/test_bug_flow.py +""" +import datetime +import logging +import os +import sys +import threading +from http.server import ThreadingHTTPServer + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') +import django # noqa: E402 + +django.setup() +import orjson # noqa: E402 + +from apps.bug.models import Bug # noqa: E402 +from apps.bug import service as bug_svr # noqa: E402 +from apps.data.models import Data # noqa: E402 +from apps.image.models import Image # noqa: E402 +from apps.job.models import Job # noqa: E402 +from apps.project.models import Project, ProjectConfigBugTracker, ProjectConfigBugBillMethod # noqa: E402 +from apps.user.models import User # noqa: E402 +from libs import storage # noqa: E402 +from libs.defs import BugBillStatusEnum, BugRegressStatusEnum # noqa: E402 +from scripts.test_bugtracker import MockHandler # noqa: E402 + +logger = logging.getLogger('test') +logger.setLevel(logging.WARNING) + + +def ok(cond, title): + if not cond: + print(f'[FAIL] {title}') + sys.exit(1) + print(f'[ OK ] {title}') + + +def make_fixture(tracker_cfg): + now = datetime.datetime.now() + code = f'flow_{now.strftime("%H%M%S%f")}' + project = Project.objects.create(code=code, name='流程测试', project_type=2, project_phase=3, game_type=1) + ProjectConfigBugTracker.objects.create(project=project, **tracker_cfg) + ProjectConfigBugBillMethod.objects.create(project=project) + user = User.objects.filter(is_admin=1).first() + job = Job.objects.create(project=project, creator=user, name='parent', languages=[2], plan_start_at=now, + plan_end_at=now, bill_bug_types=[1, 3]) + regress_job = Job.objects.create(project=project, creator=user, name='parent-回归', languages=[2], parent_id=job.id, + plan_start_at=now, plan_end_at=now) + data = Data.objects.create(project=project, job_id=job.id, resource_version='1.0', + device={'phone_type': 'PC', 'screen_w': 1920, 'screen_h': 1080}) + img_abs, img_url = storage.gen_job_file_path(project.id, job.id, 'image', f'{job.id}-{data.id}-LAN_EN_US.png') + os.makedirs(os.path.dirname(img_abs), exist_ok=True) + with open(img_abs, 'wb') as fp: + fp.write(b'\x89PNG\r\n\x1a\nfake') + detail = {'1': [['KEY_HELLO', [1, 2, 3, 4]]], '3': [['KEY_MISS', [5, 6, 7, 8]]]} + image = Image.objects.create(project=project, job_id=job.id, data_id=data.id, language=2, + file_name=f'{job.id}-{data.id}-LAN_EN_US.png', file_path=img_url, + ai_mark_img_path=img_url, size='1920,1080', rect_location='{"text":[]}', + ai_check_detail=orjson.dumps(detail).decode(), ai_bug_types=[1, 3]) + return project, user, job, regress_job, data, image, img_abs, img_url + + +def run_flow(name, tracker_cfg, expect_tracker): + print(f'\n==== {name}') + project, user, job, regress_job, data, image, img_abs, img_url = make_fixture(tracker_cfg) + + # 1. AI 识别后自动提单 (与 AiImageSignTask.create_bug 同一路径) + err, ctx = bug_svr.prepare_create_bug_task_ctx_by_ai_sign(image.id) + ok(not err and ctx['title'].startswith('【EN】【LQA】') and '漏译' in ctx['title'] and '漏key' in ctx['title'] + and 'KEY_HELLO' in ctx['description'] and ctx['reporter'] == user.name, f'生成提单内容: {ctx.get("title")}') + err, bug = bug_svr.CreateBugTask(ctx, None, logger).run() + bug = Bug.objects.get(pk=bug.id) + ok(not err and bug.bill_status == BugBillStatusEnum.SUCCESS and bug.tracker == expect_tracker + and bug.external_id, f'提单成功 tracker={bug.tracker} external_id={bug.external_id} url={bug.external_url}') + + # 2. 回归:新截图中仍有漏译(1) -> 重新打开 + Bug.update_db(bug.id, {'regress_status': BugRegressStatusEnum.RUNNING}) + if expect_tracker == 'bugzilla': + MockHandler.bugs[f'bz{bug.external_id}']['status'] = 'RESOLVED' # 模拟开发已解决 + elif expect_tracker == 'none': + Bug.update_db(bug.id, {'status': 'open'}) + new_img = Image.objects.create(project=project, job_id=regress_job.id, data_id=data.id, language=2, + file_name=image.file_name, file_path=img_url, ai_mark_img_path=img_url, + size='1920,1080', rect_location='{"text":[]}', + ai_check_detail=orjson.dumps({'1': [['KEY_HELLO', [1, 2, 3, 4]]]}).decode(), + ai_bug_types=[1]) + code, msg, stats = bug_svr.UpdateBugByRegressedImageService( + {'image_id': new_img.id, 'bug_ids': [bug.id]}, None, logger).run() + ok(code == 0 and stats and stats[0][0] == 'reopen' and stats[0][3] == 'suc', f'回归不通过 -> 重新打开 {stats}') + + # 3. 回归: 新截图已无问题 -> 关闭 + Bug.update_db(bug.id, {'regress_status': BugRegressStatusEnum.RUNNING}) + clean_img = Image.objects.create(project=project, job_id=regress_job.id, data_id=data.id, language=2, + file_name=image.file_name, file_path=img_url, ai_mark_img_path=img_url, + size='1920,1080', rect_location='{"text":[]}', ai_check_detail='{}', + ai_bug_types=[]) + code, msg, stats = bug_svr.UpdateBugByRegressedImageService( + {'image_id': clean_img.id, 'bug_ids': [bug.id]}, None, logger).run() + bug = Bug.objects.get(pk=bug.id) + ok(code == 0 and stats and stats[0][0] == 'close' and bug.regress_status == BugRegressStatusEnum.SUCCESS + and bug.status == 'closed', f'回归通过 -> 关闭 {stats}') + if expect_tracker == 'none': + ok(len(bug.comments) == 2, f'平台内记录处理日志: {[c["text"][:20] for c in bug.comments]}') + + # 4. 缺陷系统配置错误时提单失败要有记录 + os.remove(img_abs) + return project + + +def main(): + run_flow('平台内记录', {'tracker_type': 'none'}, 'none') + + server = ThreadingHTTPServer(('127.0.0.1', 0), MockHandler) + threading.Thread(target=server.serve_forever, daemon=True).start() + base = f'http://127.0.0.1:{server.server_port}' + run_flow('Bugzilla (模拟服务)', {'tracker_type': 'bugzilla', 'base_url': base, 'api_key': 'bz-key', + 'product': 'Game', 'component': 'UI'}, 'bugzilla') + + print('\n==== 缺陷系统不可用') + project, user, job, regress_job, data, image, img_abs, img_url = make_fixture( + {'tracker_type': 'bugzilla', 'base_url': base, 'api_key': 'wrong', 'product': 'Game', 'component': 'UI'}) + err, ctx = bug_svr.prepare_create_bug_task_ctx_by_ai_sign(image.id) + err, bug = bug_svr.CreateBugTask(ctx, None, logger).run() + bug = Bug.objects.get(pk=bug.id) + ok(err and bug.bill_status == BugBillStatusEnum.FAILED and 'HTTP 401' in bug.bill_text, + f'提单失败记录原因: {bug.bill_text[:60]}') + os.remove(img_abs) + server.shutdown() + print('\n提单/回归全流程测试通过') + + +if __name__ == '__main__': + main() diff --git a/timi_hok_game_translator/LQA_WMP/server/scripts/test_bugtracker.py b/timi_hok_game_translator/LQA_WMP/server/scripts/test_bugtracker.py new file mode 100644 index 0000000000000000000000000000000000000000..a546d4e28d02070c2a04a316eb08d1cdfa9cd748 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/scripts/test_bugtracker.py @@ -0,0 +1,245 @@ +""" +缺陷系统适配器测试: 用本地模拟服务验证 Bugzilla / 禅道 适配器的请求格式与状态流转 +用法 (需要可用的 MySQL/Redis, 即 .env 配置): + python scripts/test_bugtracker.py +""" +import json +import os +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse, parse_qs + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') +import django # noqa: E402 + +django.setup() + +from libs import bugtracker # noqa: E402 +from libs.bugtracker import BugPayload, BugTrackerError # noqa: E402 + +CALLS = [] + + +class MockHandler(BaseHTTPRequestHandler): + bugs = {} + seq = 100 + + def log_message(self, *args): + pass + + def _send(self, code, obj): + body = json.dumps(obj).encode() + self.send_response(code) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _body(self): + n = int(self.headers.get('Content-Length') or 0) + return json.loads(self.rfile.read(n) or b'{}') + + def do_GET(self): + self._dispatch('GET', {}) + + def do_POST(self): + self._dispatch('POST', self._body()) + + def do_PUT(self): + self._dispatch('PUT', self._body()) + + def _dispatch(self, method, body): + url = urlparse(self.path) + CALLS.append((method, url.path, dict(self.headers), body, parse_qs(url.query))) + if url.path.startswith('/rest/'): + return self._bugzilla(method, url, body) + if url.path.startswith('/api.php/v1/'): + return self._zentao(method, url, body) + self._send(404, {'error': 'not found'}) + + # ------------------------------------------------------------ Bugzilla + def _bugzilla(self, method, url, body): + if self.headers.get('X-BUGZILLA-API-KEY') != 'bz-key': + return self._send(401, {'error': True, 'code': 410, 'message': 'invalid api key'}) + path = url.path[len('/rest/'):] + if method == 'POST' and path == 'bug': + MockHandler.seq += 1 + MockHandler.bugs[f'bz{MockHandler.seq}'] = {'status': 'CONFIRMED', 'is_open': True, + 'assigned_to': body.get('assigned_to', '')} + return self._send(200, {'id': MockHandler.seq}) + if method == 'POST' and path.endswith('/attachment'): + return self._send(201, {'ids': ['9001']}) + if method == 'POST' and path.endswith('/comment'): + return self._send(201, {'id': 77}) + if method == 'GET' and path == 'bug': + ids = parse_qs(url.query)['id'][0].split(',') + bugs = [{'id': int(i), 'summary': 's', 'status': MockHandler.bugs[f'bz{i}']['status'], + 'resolution': 'FIXED' if MockHandler.bugs[f'bz{i}']['status'] == 'RESOLVED' else '', + 'is_open': MockHandler.bugs[f'bz{i}']['is_open'], 'assigned_to': 'dev@example.com', + 'creator': 'qa@example.com', 'priority': 'High', 'severity': 'major'} + for i in ids if f'bz{i}' in MockHandler.bugs] + return self._send(200, {'bugs': bugs}) + if method == 'PUT' and path.startswith('bug/'): + bug = MockHandler.bugs[f'bz{path.split("/")[1]}'] + bug['status'] = body['status'] + bug['is_open'] = body['status'] not in ('RESOLVED', 'VERIFIED', 'CLOSED') or body['status'] == 'RESOLVED' + return self._send(200, {'bugs': [{'id': 1, 'changes': {}}]}) + if method == 'GET' and path == 'product': + return self._send(200, {'products': [{'name': 'Game', 'versions': [{'name': '1.0', 'is_active': True}], + 'milestones': [{'name': 'M1', 'is_active': True}]}]}) + if method == 'GET' and path == 'whoami': + return self._send(200, {'name': 'qa@example.com'}) + if method == 'GET' and path == 'field/bug': + return self._send(200, {'fields': [ + {'name': 'cf_platform', 'display_name': '平台', 'is_custom': True, 'values': [{'name': 'PC'}]}, + {'name': 'short_desc', 'display_name': 'Summary', 'is_custom': False}]}) + self._send(404, {'error': True, 'code': 32000, 'message': f'unknown {method} {path}'}) + + # ------------------------------------------------------------ 禅道 + def _zentao(self, method, url, body): + path = url.path[len('/api.php/v1/'):] + if method == 'POST' and path == 'tokens': + if body.get('password') != 'zt-pass': + return self._send(400, {'error': '登录失败'}) + return self._send(201, {'token': 'zt-token'}) + if self.headers.get('Token') != 'zt-token': + return self._send(401, {'error': 'Unauthorized'}) + if method == 'POST' and path == 'products/3/bugs': + MockHandler.seq += 1 + MockHandler.bugs[f'zt{MockHandler.seq}'] = {'status': 'active'} + return self._send(201, {'id': MockHandler.seq, 'status': 'active'}) + parts = path.split('/') + if parts[0] == 'bugs' and len(parts) >= 2: + bug = MockHandler.bugs.get(f'zt{parts[1]}') + if not bug: + return self._send(404, {'error': 'not found'}) + if method == 'GET' and len(parts) == 2: + return self._send(200, {'id': int(parts[1]), 'title': 't', 'status': bug['status'], 'pri': 2, + 'severity': 2, 'deleted': False, + 'openedBy': {'account': 'qa'}, 'assignedTo': {'account': 'dev'}, + 'resolvedBy': {'account': 'dev2'} if bug['status'] == 'resolved' else None}) + action = parts[2] + if action == 'resolve': + bug['status'] = 'resolved' + elif action == 'close': + if bug['status'] != 'resolved': + return self._send(400, {'error': '只能关闭已解决的Bug'}) + bug['status'] = 'closed' + elif action == 'active': + bug['status'] = 'active' + return self._send(200, {'id': int(parts[1]), 'status': bug['status']}) + if method == 'GET' and path == 'products/3': + return self._send(200, {'id': 3, 'name': '游戏A'}) + if method == 'GET' and path == 'products/3/plans': + return self._send(200, {'plans': [{'id': 8, 'title': '1.0 发布'}]}) + if method == 'GET' and path == 'projects/5/builds': + return self._send(200, {'builds': [{'id': 12, 'name': 'build-12'}]}) + self._send(404, {'error': f'unknown {method} {path}'}) + + +def last_call(method, path_part): + for c in reversed(CALLS): + if c[0] == method and path_part in c[1]: + return c + raise AssertionError(f'未找到请求 {method} {path_part}') + + +def ok(cond, title): + if not cond: + print(f'[FAIL] {title}') + sys.exit(1) + print(f'[ OK ] {title}') + + +def main(): + # 确保禅道截图走 内嵌分支 (不依赖 .env 的 PUBLIC_URL 配置) + import settings + settings.PUBLIC_URL = 'http://lqa.test' + server = ThreadingHTTPServer(('127.0.0.1', 0), MockHandler) + threading.Thread(target=server.serve_forever, daemon=True).start() + base = f'http://127.0.0.1:{server.server_port}' + img = tempfile.NamedTemporaryFile(suffix='.png', delete=False) + img.write(b'\x89PNG\r\n\x1a\nfake') + img.close() + payload = BugPayload(lqa_bug_id=1, title='【LQA】漏译', description='

步骤
1.页面中【KEY】存在 漏译 问题

', + priority=2, severity=1, version_report='1.0', version_fix='M1', assignees=['dev', 'dev3'], + reporter='qa', custom_fields={'cf_platform': 'PC'}) + + # ======================================================= Bugzilla + try: + bugtracker.get_tracker(1, {'tracker_type': 'bugzilla', 'base_url': base}) + ok(False, 'Bugzilla 缺少配置时报错') + except BugTrackerError: + ok(True, 'Bugzilla 缺少配置时报错') + bz = bugtracker.get_tracker(1, {'tracker_type': 'bugzilla', 'base_url': base + '/', 'api_key': 'bz-key', + 'product': 'Game', 'component': 'UI', 'extra': {'assignee_field': 'name'}}) + ok(bz.test_connection().startswith('连接成功'), 'Bugzilla 测试连接') + bug_id = bz.create_bug(payload, [img.name]) + _, _, headers, body, _ = last_call('POST', '/rest/bug') + c = [x for x in CALLS if x[0] == 'POST' and x[1] == '/rest/bug'][-1] + body = c[3] + ok(body['product'] == 'Game' and body['component'] == 'UI' and body['version'] == '1.0' + and body['priority'] == 'High' and body['severity'] == 'critical' and body['target_milestone'] == 'M1' + and body['assigned_to'] == 'dev' and body['cc'] == ['dev3'] and body['cf_platform'] == 'PC' + and '<' not in body['description'] and '1.页面中【KEY】存在 漏译 问题' in body['description'], + 'Bugzilla 创建缺陷字段映射 (HTML 转纯文本、优先级/严重程度映射、自定义字段)') + att = last_call('POST', '/attachment')[3] + ok(att['ids'] == [int(bug_id)] and att['content_type'] == 'image/png' and att['data'], 'Bugzilla 上传截图附件') + ok(bz.bug_url(bug_id) == f'{base}/show_bug.cgi?id={bug_id}', 'Bugzilla 缺陷链接') + ok(bz.get_bugs([bug_id])[bug_id].is_open, 'Bugzilla 查询缺陷状态') + ok(bz.get_options()['version_report_list'] == [{'value': '1.0', 'label': '1.0'}], 'Bugzilla 版本选项') + ok([f['key'] for f in bz.get_fields()] == ['cf_platform'], 'Bugzilla 自定义字段列表') + bz.close_bug(bug_id, '回归通过') + put = last_call('PUT', f'/rest/bug/{bug_id}')[3] + ok(put['status'] == 'RESOLVED' and put['resolution'] == 'FIXED', 'Bugzilla 回归通过 -> RESOLVED/FIXED') + bz.reopen_bug(bug_id, '

回归不通过

', [img.name], 'dev2') + put = last_call('PUT', f'/rest/bug/{bug_id}')[3] + ok(put['status'] == 'CONFIRMED' and put['assigned_to'] == 'dev2' and put['comment']['body'] == '回归不通过', + 'Bugzilla 回归不通过 -> 重新打开并指派') + bz.reopen_bug(bug_id, '仍未修复', [], '') + ok(last_call('POST', '/comment')[3]['comment'] == '仍未修复', 'Bugzilla 缺陷仍打开时只追加评论') + bad = bugtracker.get_tracker(1, {'tracker_type': 'bugzilla', 'base_url': base, 'api_key': 'x', 'product': 'Game'}) + try: + bad.get_options() + ok(False, 'Bugzilla 错误的 API Key') + except BugTrackerError as err: + ok('HTTP 401' in str(err), 'Bugzilla 错误的 API Key 返回明确错误') + + # ======================================================= 禅道 + zt = bugtracker.get_tracker(1, {'tracker_type': 'zentao', 'base_url': base, 'username': 'qa', + 'api_key': 'zt-pass', 'product': '3', 'extra': {'project_id': 5}}) + from libs import cache + cache.get_redis_client().delete(f'{cache.BASE_KEY}{zt._token_key}') + ok(zt.test_connection() == '连接成功, 产品: 游戏A', '禅道 测试连接 (获取 Token)') + bug_id = zt.create_bug(payload, [img.name]) + body = last_call('POST', '/products/3/bugs')[3] + ok(body['pri'] == 2 and body['severity'] == 1 and body['openedBuild'] == ['1.0'] and body['type'] == 'others' + and body['assignedTo'] == 'dev' and '

步骤' in body['steps'] and '回归不通过

', [img.name], '') + active = last_call('POST', f'/bugs/{bug_id}/active')[3] + ok(MockHandler.bugs[f'zt{bug_id}']['status'] == 'active' and active['openedBuild'] == ['trunk'] + and '回归不通过' in active['comment'], '禅道 回归不通过 -> 激活') + + # Token 过期自动刷新 + cache.get_redis_client().set(f'{cache.BASE_KEY}{zt._token_key}', 'expired-token') + ok(zt.get_bugs([bug_id])[bug_id].status == 'active', '禅道 Token 失效后自动重新获取') + + os.unlink(img.name) + server.shutdown() + print('\n缺陷系统适配器测试全部通过') + + +if __name__ == '__main__': + main() diff --git a/timi_hok_game_translator/LQA_WMP/server/settings.py b/timi_hok_game_translator/LQA_WMP/server/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..98187fe75a2a655eaafbfc027bb97081da35411f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/settings.py @@ -0,0 +1,313 @@ +""" +lqa 后端项目的 Django 配置文件 + +本文件最初由 'django-admin startproject' 基于 Django 5.1 自动生成, +现已扩展为实际项目配置, 涵盖: 环境变量加载 (config/env.{APP_ENV}/.env)、 +应用 (INSTALLED_APPS) 与中间件 (MIDDLEWARE) 注册、数据库 (MySQL) 与缓存 (Redis)、 +Session、Celery 异步任务队列、日志 (LOGGING) 等核心配置 + +更多关于本文件的说明, 参见: +https://docs.djangoproject.com/en/5.1/topics/settings/ + +完整的配置项列表及取值说明, 参见: +https://docs.djangoproject.com/en/5.1/ref/settings/ +""" +import os +import sys +import re +import environ +from pathlib import Path + + +# 项目内部路径均基于 BASE_DIR 构建, 例如 BASE_DIR / 'subdir'; +# 同时写入环境变量供其他模块读取, 并将 BASE_DIR 及其下的 apps 目录加入模块搜索路径 (sys.path) +BASE_DIR = Path(__file__).resolve().parent +os.environ.setdefault('BASE_DIR', str(BASE_DIR)) +sys.path.insert(0, BASE_DIR) +sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) + + +APP_ENV = os.environ.get('APP_ENV', 'dev') +env = environ.Env( + APP_ENV=(str, 'dev'), + APP_NAME=(str, 'LQA'), + DEBUG=(bool, False), + APP_DATA_ROOT=(str, os.path.join(BASE_DIR, 'data', 'n0')), + APP_MEDIA_ROOT=(str, os.path.join(BASE_DIR, 'data', 'media_root')), + NODE_NAME=(str, 'n0'), # 当前节点名称 (响应头 Lqa-Node) + COMPRESS=(bool, False), + ALLOW_REGISTER=(bool, True), # 是否开放自助注册 + PUBLIC_URL=(str, ''), # 平台对外访问地址, 如 https://lqa.example.com (用于缺陷中的截图链接、Webhook 变量) + MEDIA_PUBLIC=(bool, False), # /media/ 截图是否允许匿名访问 (禅道内嵌截图时需要开启) + AI_BASE_URL=(str, ''), # AI 识别服务地址 + SESSION_COOKIE_SECURE=(bool, False), +) +# 配置读取顺序: 系统环境变量 > config/env.{APP_ENV} > .env +for env_file in (os.path.join(BASE_DIR, 'config', f'env.{APP_ENV}'), os.path.join(BASE_DIR, '.env')): + if os.path.exists(env_file): + environ.Env.read_env(env_file) + print(f'READ ENV FILE: {env_file}') + +# 安全警告: 生产环境务必关闭 DEBUG 模式! 开启 DEBUG 会暴露详细的报错堆栈、 +# 源码片段及配置信息等敏感内容, 存在严重安全风险 +DEBUG = env('DEBUG') +APP_NAME = env('APP_NAME') +def _abs_path(path): + """相对路径以 server 目录为基准; 统一使用 / 分隔 (libs.storage 依赖路径前缀替换)""" + return os.path.abspath(os.path.join(BASE_DIR, path)).replace('\\', '/') + + +APP_DATA_ROOT = _abs_path(env('APP_DATA_ROOT')) +APP_MEDIA_ROOT = _abs_path(env('APP_MEDIA_ROOT')) +ALLOW_REGISTER = env('ALLOW_REGISTER') +PUBLIC_URL = env('PUBLIC_URL').rstrip('/') +MEDIA_PUBLIC = env('MEDIA_PUBLIC') + +# 用户上传文件的存储目录 (绝对路径) +MEDIA_ROOT = os.path.join(APP_DATA_ROOT, 'media') +# 静态文件 (CSS/JS/Images等) 收集汇总后存放的目录 (绝对路径), +# 通常由 collectstatic 命令在部署时写入该目录 +STATIC_ROOT = os.path.join(APP_DATA_ROOT, 'static') +LOG_ROOT = os.path.join(APP_DATA_ROOT, 'logs') +LOG_FILE_PATH = os.path.join(LOG_ROOT, 'app.log') +TEMP_ROOT = os.path.join(APP_DATA_ROOT, 'temp') + +NODE_NAME = env('NODE_NAME') +COMPRESS = env('COMPRESS') + +print(f'PID: {os.getpid()} \nDEBUG: {DEBUG} \nLOG_FILE_PATH: {LOG_FILE_PATH}\nAPP_MEDIA_ROOT:{APP_MEDIA_ROOT}') + + +must_dirs = (TEMP_ROOT, STATIC_ROOT, MEDIA_ROOT, LOG_ROOT, APP_MEDIA_ROOT) +for root_path in must_dirs: + os.makedirs(root_path, exist_ok=True) + + + +# 以下为快速启动的开发环境配置, 不适合直接用于生产环境 +# 详见部署检查清单: https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ + +# 安全警告: 生产环境使用的 SECRET_KEY 必须妥善保密, 不可泄露或提交到代码仓库! +SECRET_KEY = env('SECRET_KEY', default='') +if not SECRET_KEY or SECRET_KEY.startswith('change-me'): + if not DEBUG: + raise RuntimeError('请在环境变量或 .env 中设置随机的 SECRET_KEY (生产环境必须)') + SECRET_KEY = 'django-insecure-dev-only-do-not-use-in-production' # nosemgrep: rule-id-here -- 仅用于本地开发默认值, 生产环境强制要求配置 + +ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=['*']) + + +# 应用定义: 已注册的 Django App (包括业务应用 image/bug/data/job/project/system/user/lqa +# 及部分 Django 内置应用) + +INSTALLED_APPS = [ + 'image', + 'bug', + 'data', + 'job', + 'project', + 'system', + 'user', + 'lqa', + # 'django.contrib.admin', + # 'django.contrib.auth', + # 'django.contrib.contenttypes', + 'django.contrib.sessions', + # 'django.contrib.messages', + 'django.contrib.staticfiles', + # 'user.apps.UserConfig', +] + +MIDDLEWARE = [ + 'apps.lqa.middleware.AccessLogMiddleware', + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + # 'django.middleware.csrf.CsrfViewMiddleware', + # 'django.contrib.auth.middleware.AuthenticationMiddleware', + # 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'apps.lqa.middleware.ExceptionMiddleware', + # 'lqa.middleware.DistinctBodyMiddleware', + 'apps.user.middleware.AuthRequiredMiddleware' +] + +ROOT_URLCONF = 'urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [BASE_DIR / 'templates'] + , + 'APP_DIRS': True, + 'OPTIONS': { + 'string_if_invalid': '[undefined]', + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'wsgi.application' + + +# 数据库配置 +# 详见: https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + 'default': env.db_url('MYSQL_URL') +} +if DATABASES['default']['ENGINE'] == 'django.db.backends.mysql': + DATABASES['default']['ENGINE'] = 'libs.db_mysql' # 允许系统模板项目 id=0, 见 libs/db_mysql/base.py + DATABASES['default'].setdefault('OPTIONS', {}).setdefault('charset', 'utf8mb4') + +CACHES = { + "default": env.cache_url('REDIS_URL') +} + +KEY_PREFIX = 'lqa' # 设个设置不起作用, django代码写死了 (不重要) +SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 指定 session 存储后端, 默认用的 db +SESSION_COOKIE_AGE = 60 * 60 * 24 * 3 # session cookie 有效期默认两周, 改为3天 +SESSION_COOKIE_NAME = 'lqa_sessionid' +SESSION_COOKIE_HTTPONLY = True +SESSION_COOKIE_SAMESITE = 'Lax' +SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE') # 使用 HTTPS 部署时建议开启 + +# 密码校验规则 +# 详见: https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# 国际化配置 (语言、时区等) +# 详见: https://docs.djangoproject.com/en/5.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'Asia/Shanghai' + +USE_I18N = True + +USE_TZ = False + + +# 静态文件配置 (CSS、JavaScript、图片等) +# 详见: https://docs.djangoproject.com/en/5.1/howto/static-files/ + +STATIC_URL = 'static/' + +# POST 请求体最大允许大小 (字节), 当前限制为 100MB +DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 100 + + +# Celery 异步任务队列配置, 详见: https://docs.celeryq.dev/en/stable/userguide/configuration.html#configuration +CELERY_BROKER_URL = env('CELERY_BROKER_URL') # broker 地址 +CELERY_RESULT_BACKEND = env('CELERY_BACKEND_URL') # 任务结果存储地址 + +CELERY_ENABLE_UTC = False +CELERY_TIMEZONE = 'Asia/Shanghai' + +# 在默认情况下, CELERY_TASK_TRACK_STARTED 的值为 False, 这意味着当一个任务开始执行时, Celery 不会在任务状态中记录 STARTED 状态 +# 任务状态会直接从 PENDING 跳转到 SUCCESS 或 FAILURE +CELERY_TASK_TRACK_STARTED = True +# 用于设置 Celery 中任务的时间限制, 具体来说, 这个选项决定了任务在被强制终止之前可以运行的最长时间 +CELERY_TASK_TIME_LIMIT = 30 * 60 +# 用于控制 Celery 在启动时如何处理与消息代理 (broker) 的连接重试 +CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True +CELERY_CANCEL_LONG_RUNNING_TASKS_ON_CONNECTION_LOSS = False +# 用于控制 Celery 工作者 (worker) 在重定向标准输出 (stdout) 和标准错误 (stderr) 时的日志级别 +CELERY_WORKER_REDIRECT_STDOUTS_LEVEL = 'INFO' +# 这个参数如果设置为 True, 那么任务实例的执行会在任务实例执行完毕之后才会确认; 否则只要开始执行任务实例就确认了, 防止丢掉任务 +CELERY_TASK_ACKS_LATE = True +CELERY_TASK_REJECT_ON_WORKER_LOST = True +CELERY_ROUTES = { + 'lqa_queue_ai_sign': {'queue': 'lqa_queue_ai_sign'}, + 'lqa_queue_bug': {'queue': 'lqa_queue_bug'}, + 'lqa_queue_submit_ai_sign': {'queue': 'lqa_queue_submit_ai_sign'}, +} +# Celery 工作进程会接管根日志记录器, 默认 True +# CELERY_WORKER_HIJACK_ROOT_LOGGER = False +if not DEBUG: + # 设置 worker 日志文件的路径 + CELERY_WORKER_LOGFILE=os.path.join(LOG_ROOT, 'celery.log') + print(f'CELERY_WORKER_LOGFILE: {CELERY_WORKER_LOGFILE}') + # 启用标准输出和标准错误的重定向 重定向到文件中去 + CELERY_WORKER_REDIRECT_STDOUTS = True + + +# 默认主键字段类型 +# 详见: https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +LOGGING = { + 'version': 1, + "disable_existing_loggers": False, + "formatters": { + "verbose": { + "format": "[{asctime} {name} {levelname} {process:d} {thread:d}] {message}", + "style": "{", + }, + "simple": { + "format": "{levelname} {message}", + "style": "{", + }, + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "formatter": "verbose", + }, + "file": { + "class": "logging.handlers.RotatingFileHandler", + 'maxBytes': 1024 * 1024 * 1024 * 2, + "formatter": "verbose", + "filename": LOG_FILE_PATH, + # "when": "D", + # "backupCount": 90, + }, + # "celery": { + # "class": "logging.handlers.TimedRotatingFileHandler", + # "formatter": "verbose", + # "filename": env('LOG_FILE_PATH').replace('.log', '.celery.log'), + # "when": "D", + # "backupCount": 90, + # } + }, + # "root": { + # "handlers": ["console", "file"], + # "level": "INFO", + # }, + "loggers": { + "": { + "handlers": ["console", "file"], + 'level': 'DEBUG' if DEBUG else 'INFO', + }, + # 'django.db.backends': { # 打开可以看sql + # # 'handlers': ['console'], + # 'level': 'DEBUG' if DEBUG else 'INFO', + # }, + # 'celery': { + # 'handlers': ["celery"], + # # 'propagate': True, # 如果属性设置为 True, 则该消息不仅会被当前记录器处理, 还会被传递给其所有祖先记录器 + # 'level': 'INFO', + # }, + } +} diff --git a/timi_hok_game_translator/LQA_WMP/server/urls.py b/timi_hok_game_translator/LQA_WMP/server/urls.py new file mode 100644 index 0000000000000000000000000000000000000000..b1617ea0a52baab810f838b940f239e59e186c21 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/urls.py @@ -0,0 +1,19 @@ +from django.urls import path, re_path, include +from django.utils.module_loading import import_string +from django.views.static import serve + +import settings + +urlpatterns = [ + # 截图等上传文件, 由登录中间件鉴权 (MEDIA_PUBLIC=true 时允许匿名访问) + # 访问量大时可改为由 Nginx 直接提供 APP_MEDIA_ROOT/media 目录 + re_path(r'^media/(?P.*)$', serve, {'document_root': f'{settings.APP_MEDIA_ROOT}/media/'}), + *import_string('lqa.urls.urlpatterns'), + path('api/bug/', include('bug.urls')), + path('api/data/', include('data.urls')), + path('api/image/', include('image.urls')), + path('api/job/', include('job.urls')), + path('api/project/', include('project.urls')), + path('api/user/', include('user.urls')), + path('api/system/', include('system.urls')) +] diff --git a/timi_hok_game_translator/LQA_WMP/server/wsgi.py b/timi_hok_game_translator/LQA_WMP/server/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc0b6777d2805334bd6231fc5db49dbe305ae54 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/server/wsgi.py @@ -0,0 +1,23 @@ +""" +lqa 后端项目的 WSGI 配置文件 + +该文件将 WSGI 可调用对象以模块级变量 `application` 的形式暴露出来, +供 WSGI 服务器 (如 Gunicorn/uWSGI) 加载并处理 HTTP 请求 + +同时导入 celery_app, 确保 Django 应用启动时 Celery 实例已初始化 +(用于异步任务处理) + +更多关于本文件的说明, 参见: +https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') + +application = get_wsgi_application() + + +from celery_app import app as celery_app \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/web/.dockerignore b/timi_hok_game_translator/LQA_WMP/web/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..70b56faad33e309c6ddca9696540f39a7f0ace51 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.dockerignore @@ -0,0 +1,5 @@ +node_modules +dist +.env.*.local +*.local +.eslintcache diff --git a/timi_hok_game_translator/LQA_WMP/web/.editorconfig b/timi_hok_game_translator/LQA_WMP/web/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..d22b47228145fe91c69c9607f056340dd9c5e503 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.editorconfig @@ -0,0 +1,25 @@ +# 修改配置后重启编辑器 +# 配置项文档:https://editorconfig.org/ + +# 告知 EditorConfig 插件,当前即是根文件 +root = true + +# 适用全部文件 +[*] +## 设置字符集 +charset = utf-8 +## 缩进风格 space | tab,建议 space(会自动继承给 Prettier) +indent_style = space +## 缩进的空格数(会自动继承给 Prettier) +indent_size = 2 +## 换行符类型 lf | cr | crlf,一般都是设置为 lf +end_of_line = lf +## 是否在文件末尾插入空白行 +insert_final_newline = true +## 是否删除一行中的前后空格 +trim_trailing_whitespace = true + +# 适用 .md 文件 +[*.md] +insert_final_newline = false +trim_trailing_whitespace = false diff --git a/timi_hok_game_translator/LQA_WMP/web/.env.development b/timi_hok_game_translator/LQA_WMP/web/.env.development new file mode 100644 index 0000000000000000000000000000000000000000..4eb863bbd24b5d9f92d3ea556920312348c5c146 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.env.development @@ -0,0 +1,16 @@ +# 开发环境自定义的环境变量(命名必须以 VITE_ 开头) + +## 后端接口公共路径(开发环境通过 Vite 代理转发,见 vite.config.ts) +VITE_BASE_API = '/api-pro' + +## 截图等资源地址前缀(与 BASE_API 相同,走同一个 vite 代理) +VITE_RESOURCE_API = '/api-pro' + +## 开发代理目标:后端地址。可在 .env.development.local 中覆盖 +VITE_PROXY_TARGET = 'http://127.0.0.1:8000/' + +## 路由模式 hash 或 html5 +VITE_ROUTER_HISTORY = 'html5' + +## 开发环境地址前缀(一般 '/','./' 都可以) +VITE_PUBLIC_PATH = '/' diff --git a/timi_hok_game_translator/LQA_WMP/web/.env.production b/timi_hok_game_translator/LQA_WMP/web/.env.production new file mode 100644 index 0000000000000000000000000000000000000000..8ec044169be78a591acc8727422e4466cb351cab --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.env.production @@ -0,0 +1,14 @@ +# 生产环境自定义的环境变量(命名必须以 VITE_ 开头) + +## 后端接口公共路径:默认与前端同域,由 Nginx 将 /api-pro/ 反向代理到后端(见 web/nginx.conf) +## 前后端分域部署时填写后端完整地址,并在后端配置 CORS +VITE_BASE_API = '/api-pro' + +## 截图等资源地址前缀(与 BASE_API 相同,由 Nginx 反向代理到后端) +VITE_RESOURCE_API = '/api-pro' + +## 路由模式 hash 或 html5 +VITE_ROUTER_HISTORY = 'html5' + +## 打包路径(就是网站前缀,例如部署到 https://example.com/lqa/ 下,就需要填写 /lqa/) +VITE_PUBLIC_PATH = '/' diff --git a/timi_hok_game_translator/LQA_WMP/web/.eslintignore b/timi_hok_game_translator/LQA_WMP/web/.eslintignore new file mode 100644 index 0000000000000000000000000000000000000000..7ac0eb98708a64b1d856965df17cb4a0e8c05fe8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.eslintignore @@ -0,0 +1,8 @@ +# Eslint 会忽略的文件 + +.DS_Store +node_modules +dist +dist-ssr +*.local +.npmrc diff --git a/timi_hok_game_translator/LQA_WMP/web/.eslintrc.cjs b/timi_hok_game_translator/LQA_WMP/web/.eslintrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..bd2d8870df6198b8e5ff66db9ce20460a7530b5b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.eslintrc.cjs @@ -0,0 +1,63 @@ +module.exports = { + root: true, + env: { + browser: true, + node: true, + es6: true + }, + extends: [ + "eslint:recommended", + "plugin:vue/vue3-recommended", + "@vue/typescript/recommended", + ], + parser: "vue-eslint-parser", + parserOptions: { + parser: '@typescript-eslint/parser', + ecmaVersion: 2020, + sourceType: "module", + jsxPragma: "React", + ecmaFeatures: { + jsx: true, + tsx: true + } + }, + overrides: [ + // typescript + { + files: ['*.ts', '*.tsx'], // Your TypeScript files extension + parser: '@typescript-eslint/parser', + parserOptions: { + project: ['./tsconfig.json'], // Specify it only for TypeScript files + }, + }, + ], + rules: { + // TS + "@typescript-eslint/no-explicit-any": "off", + "no-debugger": "off", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/ban-ts-comment": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_" + } + ], + "no-unused-vars": [ + "error", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_" + } + ], + // Vue + "vue/no-v-html": "off", + "vue/require-default-prop": "off", + "vue/require-explicit-emits": "off", + "vue/multi-word-component-names": "off", + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/.gitignore b/timi_hok_game_translator/LQA_WMP/web/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a1ebec916cd3f58431600c068ab79225dcc2e883 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.gitignore @@ -0,0 +1,35 @@ +# Git 会忽略的文件 + +.DS_Store +node_modules +dist +dist-ssr +.eslintcache + +# Local env files +*.local + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json +!.vscode/*.code-snippets +.idea +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# Use the PNPM +package-lock.json +yarn.lock diff --git a/timi_hok_game_translator/LQA_WMP/web/.husky/pre-commit b/timi_hok_game_translator/LQA_WMP/web/.husky/pre-commit new file mode 100644 index 0000000000000000000000000000000000000000..36af219892fda8ea669cd4b6725cd7b892231967 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npx lint-staged diff --git a/timi_hok_game_translator/LQA_WMP/web/.npmrc b/timi_hok_game_translator/LQA_WMP/web/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..da691e7b29fa5ce9f620bf66e4cac1fd67741f10 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.npmrc @@ -0,0 +1,2 @@ +# 通过该配置兜底解决组件没有类型提示的问题 +shamefully-hoist = true diff --git a/timi_hok_game_translator/LQA_WMP/web/.prettierignore b/timi_hok_game_translator/LQA_WMP/web/.prettierignore new file mode 100644 index 0000000000000000000000000000000000000000..e7f8c1090efbfbffc260edecd77792ff3af6ea41 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/.prettierignore @@ -0,0 +1,8 @@ +# Prettier 会忽略的文件 + +.DS_Store +node_modules +dist +dist-ssr +*.local +.npmrc diff --git a/timi_hok_game_translator/LQA_WMP/web/Dockerfile b/timi_hok_game_translator/LQA_WMP/web/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05aa2a4502342cf9ac641132acaa9be42b7983ed --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/Dockerfile @@ -0,0 +1,13 @@ +FROM node:22-alpine AS build +WORKDIR /app +ARG NPM_REGISTRY=https://registry.npmjs.org +RUN npm install -g pnpm@11.7.0 --registry=${NPM_REGISTRY} +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./ +RUN pnpm install --frozen-lockfile --registry=${NPM_REGISTRY} +COPY . . +RUN pnpm build + +FROM nginx:1.27-alpine +COPY --from=build /app/dist /usr/share/nginx/html +COPY nginx.conf /etc/nginx/conf.d/default.conf +EXPOSE 80 diff --git a/timi_hok_game_translator/LQA_WMP/web/README.md b/timi_hok_game_translator/LQA_WMP/web/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c217c1b5e7bcd5d76b3dfa80971d92c802752e4a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/README.md @@ -0,0 +1,51 @@ +# LQA Web + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +Vue 3 + Vite 5 + TypeScript + Element Plus + fast-crud, 基于 [v3-admin-vite](https://github.com/un-pany/v3-admin-vite) + +## 本地开发 + +要求 Node.js 20+、pnpm 11 + +```bash +cd web +pnpm install +pnpm dev # http://localhost:3333 +``` + +开发时接口请求 `/api-pro/*` 由 Vite 代理到后端, 默认 `http://127.0.0.1:8000/`, 需要指向其他地址时新建 `.env.development.local` (已被 git 忽略): + +``` +VITE_PROXY_TARGET = 'http://192.168.1.10:8000/' +``` + +## 构建 + +```bash +pnpm build # 输出到 dist/ +``` + +生产环境默认前后端同域部署, 由 Nginx 把 `/api-pro/` 和 `/media/` 反向代理到后端, 参考 [nginx.conf](nginx.conf) + +## 环境变量 + +| 变量 | 说明 | +|---|---| +| `VITE_APP_TITLE` | 页面标题 | +| `VITE_BASE_API` | 后端接口前缀, 默认 `/api-pro` | +| `VITE_RESOURCE_API` | 截图等资源地址前缀, 默认 `/api-pro` | +| `VITE_PROXY_TARGET` | 仅开发环境: Vite 代理的后端地址 | +| `VITE_ADMIN_CONTACT` | 403 页面展示的管理员联系方式 (选填) | +| `VITE_PUBLIC_PATH` | 部署子路径, 默认 `/` | + +## 代码检查 + +```bash +pnpm lint +pnpm test +``` + +## 许可证 + +本目录基于 v3-admin-vite,现以 **Apache-2.0** 开源,详见 [LICENSE](../LICENSE)。 diff --git a/timi_hok_game_translator/LQA_WMP/web/extensions.json b/timi_hok_game_translator/LQA_WMP/web/extensions.json new file mode 100644 index 0000000000000000000000000000000000000000..c7b884b32826a1fd0d0f20656a2e8bfda80d5388 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/extensions.json @@ -0,0 +1,11 @@ +{ + "recommendations": [ + "editorconfig.editorconfig", + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "vue.volar", + "antfu.unocss", + "vitest.explorer", + "wiensss.region-highlighter" + ] +} diff --git a/timi_hok_game_translator/LQA_WMP/web/hook.code-snippets b/timi_hok_game_translator/LQA_WMP/web/hook.code-snippets new file mode 100644 index 0000000000000000000000000000000000000000..158d9ce952910eefda559bf2b7c742b5fe1833a3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/hook.code-snippets @@ -0,0 +1,16 @@ +{ + "Vue3 Hook 代码结构一键生成": { + "prefix": "Vue3 Hook", + "body": [ + "import { ref } from \"vue\"\n", + "const refName1 = ref(\"这是一个响应式变量\")\n", + "export function useHookName() {", + "\tconst refName2 = ref(\"这是一个响应式变量\")\n", + "\tconst fnName = () => {}\n", + "\treturn { refName1, refName2, fnName }", + "}", + "$1" + ], + "description": "Vue3 Hook" + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/index.html b/timi_hok_game_translator/LQA_WMP/web/index.html new file mode 100644 index 0000000000000000000000000000000000000000..10d7303d76d3e56ac75fd71289098fca65555c4c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/index.html @@ -0,0 +1,16 @@ + + + + + + + + %VITE_APP_TITLE% + + +
+
+
+ + + diff --git a/timi_hok_game_translator/LQA_WMP/web/nginx.conf b/timi_hok_game_translator/LQA_WMP/web/nginx.conf new file mode 100644 index 0000000000000000000000000000000000000000..90e5c513af91cccaf54e90a923197f89e67b206d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/nginx.conf @@ -0,0 +1,36 @@ +server { + listen 80; + server_name _; + client_max_body_size 200m; + + gzip on; + gzip_static on; + gzip_types text/css application/javascript application/json image/svg+xml; + + root /usr/share/nginx/html; + + # 后端接口与截图:/api-pro/api/xxx -> backend/api/xxx,/api-pro/media/xxx -> backend/media/xxx + location /api-pro/ { + proxy_pass http://server:8000/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 300s; + } + + # 缺陷系统(禅道)中内嵌的截图链接为 {PUBLIC_URL}/media/... + location /media/ { + proxy_pass http://server:8000/media/; + proxy_set_header Host $host; + } + + location /static/ { + expires 30d; + try_files $uri =404; + } + + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/package.json b/timi_hok_game_translator/LQA_WMP/web/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9ca20cfb58933eb8ba676bfdcb3c17df836098d9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/package.json @@ -0,0 +1,111 @@ +{ + "name": "lqa-web", + "version": "1.0.0", + "private": true, + "description": "LQA 本地化质量检查平台前端(基于 v3-admin-vite)", + "type": "module", + "packageManager": "pnpm@11.7.0", + "engines": { + "node": ">=20" + }, + "scripts": { + "dev": "vite", + "build": "vite build", + "build:prod": "vue-tsc --noEmit && vite build", + "preview": "vite preview", + "lint:eslint": "eslint --cache \"{src,tests,types}/**/*.{vue,js,jsx,ts,tsx}\" --fix", + "lint:prettier": "prettier --write \"{src,tests,types}/**/*.{vue,js,jsx,ts,tsx,json,css,less,scss,html,md}\"", + "lint": "pnpm lint:eslint && pnpm lint:prettier", + "prepare": "husky || true", + "test": "vitest" + }, + "dependencies": { + "@element-plus/icons-vue": "2.3.1", + "@fast-crud/fast-crud": "1.23.4", + "@fast-crud/fast-extends": "1.23.4", + "@fast-crud/ui-element": "1.23.4", + "@fast-crud/ui-interface": "1.23.4", + "@iconify/vue": "4.2.0", + "@tinymce/tinymce-vue": "6.1.0", + "axios": "1.6.8", + "dayjs": "1.11.10", + "element-plus": "2.9.11", + "js-cookie": "3.0.5", + "lodash-es": "4.17.21", + "mitt": "3.0.1", + "normalize.css": "8.0.1", + "nprogress": "0.2.0", + "pako": "2.1.0", + "path-browserify": "1.0.1", + "path-to-regexp": "6.2.1", + "pinia": "2.1.7", + "screenfull": "6.0.2", + "sortablejs": "^1.15.7", + "tinymce": "7.6.0", + "uuid": "14.0.0", + "vue": "3.4.21", + "vue-router": "4.3.0", + "vue3-json-viewer": "2.2.2", + "vxe-table": "4.5.21", + "vxe-table-plugin-element": "4.0.1", + "xe-utils": "3.5.22" + }, + "devDependencies": { + "@types/js-cookie": "3.0.6", + "@types/lodash-es": "4.17.12", + "@types/node": "20.11.30", + "@types/nprogress": "0.2.3", + "@types/path-browserify": "1.0.2", + "@types/sortablejs": "^1.15.9", + "@types/uuid": "^11.0.0", + "@typescript-eslint/eslint-plugin": "7.3.1", + "@typescript-eslint/parser": "7.3.1", + "@vitejs/plugin-vue": "5.0.4", + "@vitejs/plugin-vue-jsx": "3.1.0", + "@vue/eslint-config-prettier": "9.0.0", + "@vue/eslint-config-typescript": "13.0.0", + "@vue/test-utils": "2.4.5", + "eslint": "8.57.0", + "eslint-plugin-prettier": "5.1.3", + "eslint-plugin-vue": "9.23.0", + "husky": "9.0.11", + "jsdom": "24.0.0", + "lint-staged": "15.2.2", + "prettier": "3.2.5", + "sass": "1.72.0", + "typescript": "5.4.3", + "unocss": "0.58.6", + "vite": "5.4.15", + "vite-plugin-compression": "^0.5.1", + "vite-plugin-svg-icons": "2.0.1", + "vite-svg-loader": "5.1.0", + "vitest": "1.4.0", + "vue-eslint-parser": "9.4.2", + "vue-tsc": "2.0.7" + }, + "lint-staged": { + "*.{vue,js,jsx,ts,tsx}": [ + "eslint --fix" + ], + "*.{css,less,scss,html,md}": [ + "prettier --write" + ], + "package.json": [ + "prettier --write" + ] + }, + "keywords": [ + "vue", + "vue3", + "admin", + "vue-admin", + "vue3-admin", + "vite", + "vite-admin", + "element-plus", + "element-plus-admin", + "ts", + "typescript" + ], + "license": "Apache-2.0" +} diff --git a/timi_hok_game_translator/LQA_WMP/web/pnpm-lock.yaml b/timi_hok_game_translator/LQA_WMP/web/pnpm-lock.yaml new file mode 100644 index 0000000000000000000000000000000000000000..272ad8d3fe154281c3f2ac6c5680e7a090f1c75b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/pnpm-lock.yaml @@ -0,0 +1,9474 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@element-plus/icons-vue': + specifier: 2.3.1 + version: 2.3.1(vue@3.4.21(typescript@5.4.3)) + '@fast-crud/fast-crud': + specifier: 1.23.4 + version: 1.23.4(vue@3.4.21(typescript@5.4.3)) + '@fast-crud/fast-extends': + specifier: 1.23.4 + version: 1.23.4(vue@3.4.21(typescript@5.4.3)) + '@fast-crud/ui-element': + specifier: 1.23.4 + version: 1.23.4 + '@fast-crud/ui-interface': + specifier: 1.23.4 + version: 1.23.4 + '@iconify/vue': + specifier: 4.2.0 + version: 4.2.0(vue@3.4.21(typescript@5.4.3)) + '@tinymce/tinymce-vue': + specifier: 6.1.0 + version: 6.1.0(tinymce@7.6.0)(vue@3.4.21(typescript@5.4.3)) + axios: + specifier: 1.6.8 + version: 1.6.8 + dayjs: + specifier: 1.11.10 + version: 1.11.10 + element-plus: + specifier: 2.9.11 + version: 2.9.11(vue@3.4.21(typescript@5.4.3)) + js-cookie: + specifier: 3.0.5 + version: 3.0.5 + lodash-es: + specifier: 4.17.21 + version: 4.17.21 + mitt: + specifier: 3.0.1 + version: 3.0.1 + normalize.css: + specifier: 8.0.1 + version: 8.0.1 + nprogress: + specifier: 0.2.0 + version: 0.2.0 + pako: + specifier: 2.1.0 + version: 2.1.0 + path-browserify: + specifier: 1.0.1 + version: 1.0.1 + path-to-regexp: + specifier: 6.2.1 + version: 6.2.1 + pinia: + specifier: 2.1.7 + version: 2.1.7(typescript@5.4.3)(vue@3.4.21(typescript@5.4.3)) + screenfull: + specifier: 6.0.2 + version: 6.0.2 + sortablejs: + specifier: ^1.15.7 + version: 1.15.7 + tinymce: + specifier: 7.6.0 + version: 7.6.0 + uuid: + specifier: 14.0.0 + version: 14.0.0 + vue: + specifier: 3.4.21 + version: 3.4.21(typescript@5.4.3) + vue-router: + specifier: 4.3.0 + version: 4.3.0(vue@3.4.21(typescript@5.4.3)) + vue3-json-viewer: + specifier: 2.2.2 + version: 2.2.2(vue@3.4.21(typescript@5.4.3)) + vxe-table: + specifier: 4.5.21 + version: 4.5.21(vue@3.4.21(typescript@5.4.3))(xe-utils@3.5.22) + vxe-table-plugin-element: + specifier: 4.0.1 + version: 4.0.1(vxe-table@4.5.21(vue@3.4.21(typescript@5.4.3))(xe-utils@3.5.22)) + xe-utils: + specifier: 3.5.22 + version: 3.5.22 + devDependencies: + '@types/js-cookie': + specifier: 3.0.6 + version: 3.0.6 + '@types/lodash-es': + specifier: 4.17.12 + version: 4.17.12 + '@types/node': + specifier: 20.11.30 + version: 20.11.30 + '@types/nprogress': + specifier: 0.2.3 + version: 0.2.3 + '@types/path-browserify': + specifier: 1.0.2 + version: 1.0.2 + '@types/sortablejs': + specifier: ^1.15.9 + version: 1.15.9 + '@types/uuid': + specifier: ^11.0.0 + version: 11.0.0 + '@typescript-eslint/eslint-plugin': + specifier: 7.3.1 + version: 7.3.1(@typescript-eslint/parser@7.3.1(eslint@8.57.0)(typescript@5.4.3))(eslint@8.57.0)(typescript@5.4.3) + '@typescript-eslint/parser': + specifier: 7.3.1 + version: 7.3.1(eslint@8.57.0)(typescript@5.4.3) + '@vitejs/plugin-vue': + specifier: 5.0.4 + version: 5.0.4(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))(vue@3.4.21(typescript@5.4.3)) + '@vitejs/plugin-vue-jsx': + specifier: 3.1.0 + version: 3.1.0(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))(vue@3.4.21(typescript@5.4.3)) + '@vue/eslint-config-prettier': + specifier: 9.0.0 + version: 9.0.0(eslint@8.57.0)(prettier@3.2.5) + '@vue/eslint-config-typescript': + specifier: 13.0.0 + version: 13.0.0(eslint-plugin-vue@9.23.0(eslint@8.57.0))(eslint@8.57.0)(typescript@5.4.3) + '@vue/test-utils': + specifier: 2.4.5 + version: 2.4.5 + eslint: + specifier: 8.57.0 + version: 8.57.0 + eslint-plugin-prettier: + specifier: 5.1.3 + version: 5.1.3(eslint-config-prettier@9.1.2(eslint@8.57.0))(eslint@8.57.0)(prettier@3.2.5) + eslint-plugin-vue: + specifier: 9.23.0 + version: 9.23.0(eslint@8.57.0) + husky: + specifier: 9.0.11 + version: 9.0.11 + jsdom: + specifier: 24.0.0 + version: 24.0.0 + lint-staged: + specifier: 15.2.2 + version: 15.2.2 + prettier: + specifier: 3.2.5 + version: 3.2.5 + sass: + specifier: 1.72.0 + version: 1.72.0 + typescript: + specifier: 5.4.3 + version: 5.4.3 + unocss: + specifier: 0.58.6 + version: 0.58.6(postcss@8.5.29)(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + vite: + specifier: 5.4.15 + version: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + vite-plugin-compression: + specifier: ^0.5.1 + version: 0.5.1(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + vite-plugin-svg-icons: + specifier: 2.0.1 + version: 2.0.1(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + vite-svg-loader: + specifier: 5.1.0 + version: 5.1.0(vue@3.4.21(typescript@5.4.3)) + vitest: + specifier: 1.4.0 + version: 1.4.0(@types/node@20.11.30)(jsdom@24.0.0)(sass@1.72.0) + vue-eslint-parser: + specifier: 9.4.2 + version: 9.4.2(eslint@8.57.0) + vue-tsc: + specifier: 2.0.7 + version: 2.0.7(typescript@5.4.3) + +packages: + + '@ampproject/remapping@2.3.0': + resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==} + engines: {node: '>=6.0.0'} + + '@antfu/install-pkg@0.1.1': + resolution: {integrity: sha512-LyB/8+bSfa0DFGC06zpCEfs89/XoWZwws5ygEa5D+Xsm3OfI+aXQ86VgVG7Acyef+rSZ5HE7J8rrxzrQeM3PjQ==} + + '@antfu/utils@0.7.10': + resolution: {integrity: sha512-+562v9k4aI80m1+VuMHehNJWLOFjBnXn3tdOitzD0il5b7smkSBal4+a3oKiQTbrwMmN/TBUMDvbdoWDehgOww==} + + '@aws-sdk/checksums@3.1001.1': + resolution: {integrity: sha512-x12Q17KYlJAd3nKf8LV5LV0vt8sh8/6YfQLGPtrGnQf/tW4jqxPGq5GPpuVitpQYM3eUR4XB7CbxZf751NMbLw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/client-s3@3.1147.0': + resolution: {integrity: sha512-uTrcJxnJKPr8bc1z7cMxopYSQyAm2dPfiMK+UiBr51L8MzimDxHbW/d9GR6X/LFbWDpMzfFPLhB4UohDrCSaPQ==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/core@3.978.1': + resolution: {integrity: sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-env@3.972.72': + resolution: {integrity: sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-http@3.972.74': + resolution: {integrity: sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-ini@3.973.17': + resolution: {integrity: sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-login@3.972.79': + resolution: {integrity: sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-node@3.972.84': + resolution: {integrity: sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-process@3.972.72': + resolution: {integrity: sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-sso@3.973.16': + resolution: {integrity: sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/credential-provider-web-identity@3.972.78': + resolution: {integrity: sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/crt-loader@3.972.76': + resolution: {integrity: sha512-BOYKj66K4vlFQHLtsU88ycebrZCphnoQOyBPhqibmzZPlNwzHVhTWp+RdCCKNsFhQj7p1IAbIJ711DrvVYE95g==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/middleware-sdk-s3@3.972.77': + resolution: {integrity: sha512-E7W2UOeUoc+lg3uIfR/dM7ZwusHwhBQrKMnlkRv4EXRR+C0YtV1pg25xC7GdZIhXH+NAMgZPCbE7o5to2cjFiw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/nested-clients@3.997.46': + resolution: {integrity: sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/s3-request-presigner@3.1147.0': + resolution: {integrity: sha512-9za8GOn8IRFz+foPbLfjFFfqDV87mLBhNbUg+8YgqaSIuvzx+o6bWgOAETqPev5wul6DAImTQSCgt8mBsKtGUg==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/signature-v4-crt@3.1146.0': + resolution: {integrity: sha512-X1ZGumL5kNK6UEJFYMAwFLqJ58W4qHOVyEK5u3fTHBwPSoW9nwaPqN2paNR+KTU/wjHY1bl6FPjPe9UvDD1E0A==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/signature-v4-multi-region@3.996.47': + resolution: {integrity: sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/token-providers@3.1138.0': + resolution: {integrity: sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/types@3.974.6': + resolution: {integrity: sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==} + engines: {node: '>=20.0.0'} + + '@aws-sdk/util-utf8-browser@3.259.0': + resolution: {integrity: sha512-UvFa/vR+e19XookZF8RzFZBrw2EUkQWxiBW0yYQAhvk3C+QVGl0H3ouca8LDBlBfQKXwmW3huo/59H8rwb1wJw==} + + '@aws-sdk/xml-builder@3.972.41': + resolution: {integrity: sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==} + engines: {node: '>=20.0.0'} + + '@aws/lambda-invoke-store@0.3.0': + resolution: {integrity: sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==} + engines: {node: '>=18.0.0'} + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.29.8': + resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-annotate-as-pure@7.29.7': + resolution: {integrity: sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-create-class-features-plugin@7.29.7': + resolution: {integrity: sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-member-expression-to-functions@7.29.7': + resolution: {integrity: sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-optimise-call-expression@7.29.7': + resolution: {integrity: sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==} + engines: {node: '>=6.9.0'} + + '@babel/helper-plugin-utils@7.29.7': + resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-replace-supers@7.29.7': + resolution: {integrity: sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-skip-transparent-expression-wrappers@7.29.7': + resolution: {integrity: sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.9': + resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/plugin-syntax-jsx@7.29.7': + resolution: {integrity: sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-syntax-typescript@7.29.7': + resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-transform-modules-commonjs@7.29.7': + resolution: {integrity: sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-transform-typescript@7.29.9': + resolution: {integrity: sha512-FFwIwzU+7SCOuxxV4YtJql6T9981ZVTm+FHO5GhVsRqCTdy0WwrEZh3l42ARpXruJUDGOptdduHW6Zr7pNPLNg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/preset-typescript@7.29.7': + resolution: {integrity: sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/runtime-corejs2@7.29.7': + resolution: {integrity: sha512-5GidEBf/rOQlv4sUknPRgboZEvzt/je7CpbkCZ2o7ojs9JbldxdXJinGLYE0sYR9mfPpRz3Q3D7rP+oSCal70g==} + engines: {node: '>=6.9.0'} + + '@babel/runtime@7.29.7': + resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} + engines: {node: '>=6.9.0'} + + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.8': + resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} + + '@ctrl/tinycolor@3.4.1': + resolution: {integrity: sha512-ej5oVy6lykXsvieQtqZxCOaLT+xD4+QNarq78cIYISHmZXshCvROLudpQN3lfL8G0NL7plMSSK+zlyvCaIJ4Iw==} + engines: {node: '>=10'} + + '@element-plus/icons-vue@2.3.1': + resolution: {integrity: sha512-XxVUZv48RZAd87ucGS48jPf6pKu0yV5UCg9f4FFwtrYxXOwWuVJo6wOvSLKEoMQKjv8GsX/mhP6UsC1lRwbUWg==} + peerDependencies: + vue: ^3.2.0 + + '@esbuild/aix-ppc64@0.21.3': + resolution: {integrity: sha512-yTgnwQpFVYfvvo4SvRFB0SwrW8YjOxEoT7wfMT7Ol5v7v5LDNvSGo67aExmxOb87nQNeWPVvaGBNfQ7BXcrZ9w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.3': + resolution: {integrity: sha512-c+ty9necz3zB1Y+d/N+mC6KVVkGUUOcm4ZmT5i/Fk5arOaY3i6CA3P5wo/7+XzV8cb4GrI/Zjp8NuOQ9Lfsosw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.3': + resolution: {integrity: sha512-bviJOLMgurLJtF1/mAoJLxDZDL6oU5/ztMHnJQRejbJrSc9FFu0QoUoFhvi6qSKJEw9y5oGyvr9fuDtzJ30rNQ==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.3': + resolution: {integrity: sha512-JReHfYCRK3FVX4Ra+y5EBH1b9e16TV2OxrPAvzMsGeES0X2Ndm9ImQRI4Ket757vhc5XBOuGperw63upesclRw==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.3': + resolution: {integrity: sha512-U3fuQ0xNiAkXOmQ6w5dKpEvXQRSpHOnbw7gEfHCRXPeTKW9sBzVck6C5Yneb8LfJm0l6le4NQfkNPnWMSlTFUQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.3': + resolution: {integrity: sha512-3m1CEB7F07s19wmaMNI2KANLcnaqryJxO1fXHUV5j1rWn+wMxdUYoPyO2TnAbfRZdi7ADRwJClmOwgT13qlP3Q==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.3': + resolution: {integrity: sha512-fsNAAl5pU6wmKHq91cHWQT0Fz0vtyE1JauMzKotrwqIKAswwP5cpHUCxZNSTuA/JlqtScq20/5KZ+TxQdovU/g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.3': + resolution: {integrity: sha512-tci+UJ4zP5EGF4rp8XlZIdq1q1a/1h9XuronfxTMCNBslpCtmk97Q/5qqy1Mu4zIc0yswN/yP/BLX+NTUC1bXA==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.3': + resolution: {integrity: sha512-vvG6R5g5ieB4eCJBQevyDMb31LMHthLpXTc2IGkFnPWS/GzIFDnaYFp558O+XybTmYrVjxnryru7QRleJvmZ6Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.3': + resolution: {integrity: sha512-f6kz2QpSuyHHg01cDawj0vkyMwuIvN62UAguQfnNVzbge2uWLhA7TCXOn83DT0ZvyJmBI943MItgTovUob36SQ==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.3': + resolution: {integrity: sha512-HjCWhH7K96Na+66TacDLJmOI9R8iDWDDiqe17C7znGvvE4sW1ECt9ly0AJ3dJH62jHyVqW9xpxZEU1jKdt+29A==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.3': + resolution: {integrity: sha512-BGpimEccmHBZRcAhdlRIxMp7x9PyJxUtj7apL2IuoG9VxvU/l/v1z015nFs7Si7tXUwEsvjc1rOJdZCn4QTU+Q==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.3': + resolution: {integrity: sha512-5rMOWkp7FQGtAH3QJddP4w3s47iT20hwftqdm7b+loe95o8JU8ro3qZbhgMRy0VuFU0DizymF1pBKkn3YHWtsw==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.3': + resolution: {integrity: sha512-h0zj1ldel89V5sjPLo5H1SyMzp4VrgN1tPkN29TmjvO1/r0MuMRwJxL8QY05SmfsZRs6TF0c/IDH3u7XYYmbAg==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.3': + resolution: {integrity: sha512-dkAKcTsTJ+CRX6bnO17qDJbLoW37npd5gSNtSzjYQr0svghLJYGYB0NF1SNcU1vDcjXLYS5pO4qOW4YbFama4A==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.3': + resolution: {integrity: sha512-vnD1YUkovEdnZWEuMmy2X2JmzsHQqPpZElXx6dxENcIwTu+Cu5ERax6+Ke1QsE814Zf3c6rxCfwQdCTQ7tPuXA==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.3': + resolution: {integrity: sha512-IOXOIm9WaK7plL2gMhsWJd+l2bfrhfilv0uPTptoRoSb2p09RghhQQp9YY6ZJhk/kqmeRt6siRdMSLLwzuT0KQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-x64@0.21.3': + resolution: {integrity: sha512-uTgCwsvQ5+vCQnqM//EfDSuomo2LhdWhFPS8VL8xKf+PKTCrcT/2kPPoWMTs22aB63MLdGMJiE3f1PHvCDmUOw==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-x64@0.21.3': + resolution: {integrity: sha512-vNAkR17Ub2MgEud2Wag/OE4HTSI6zlb291UYzHez/psiKarp0J8PKGDnAhMBcHFoOHMXHfExzmjMojJNbAStrQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/sunos-x64@0.21.3': + resolution: {integrity: sha512-W8H9jlGiSBomkgmouaRoTXo49j4w4Kfbl6I1bIdO/vT0+0u4f20ko3ELzV3hPI6XV6JNBVX+8BC+ajHkvffIJA==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.3': + resolution: {integrity: sha512-EjEomwyLSCg8Ag3LDILIqYCZAq/y3diJ04PnqGRgq8/4O3VNlXyMd54j/saShaN4h5o5mivOjAzmU6C3X4v0xw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.3': + resolution: {integrity: sha512-WGiE/GgbsEwR33++5rzjiYsKyHywE8QSZPF7Rfx9EBfK3Qn3xyR6IjyCr5Uk38Kg8fG4/2phN7sXp4NPWd3fcw==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.3': + resolution: {integrity: sha512-xRxC0jaJWDLYvcUvjQmHCJSfMrgmUuvsoXgDeU/wTorQ1ngDdUBuFtgY3W1Pc5sprGAvZBtWdJX7RPg/iZZUqA==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.10.1': + resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/eslintrc@2.1.4': + resolution: {integrity: sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + '@eslint/js@8.57.0': + resolution: {integrity: sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + '@fast-crud/fast-crud@1.23.4': + resolution: {integrity: sha512-VkLQxYhd3tbpeqCgebhuHqNi/gtTz/tkM+tRIwPmt40yO3zlW4OVmDDUecNY1yDZTxrCxLCQpKrstOFAu0tFfg==} + + '@fast-crud/fast-extends@1.23.4': + resolution: {integrity: sha512-FBqxPPYMAXLW+eqNZmzd8s1mENnfpBIivKCH/7mZwyzsJ7tN2ayvvrkCfQfVnDmOJGMHoHm2Tkc3FNG/kZt2/w==} + + '@fast-crud/ui-element@1.23.4': + resolution: {integrity: sha512-l9ULZYrKwT3FpZuXEQOmG0jG9NQUM5PaCnDAFDT1XDK3ClrTkNGc90DZ968cz3/S4no1UQNjFPHhyP/HhMZKRw==} + + '@fast-crud/ui-interface@1.23.4': + resolution: {integrity: sha512-Knum/Tl11VVO+3EsPdATQGy7qMbo8dKpF/6w5J/D3ScQF6S/RlbnsCBMX6UEK8qu4eJjhSLzRrYhLU9Sx71nlA==} + + '@floating-ui/core@1.8.0': + resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==} + + '@floating-ui/dom@1.8.0': + resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==} + + '@floating-ui/utils@0.2.12': + resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} + + '@httptoolkit/websocket-stream@6.0.1': + resolution: {integrity: sha512-A0NOZI+Glp3Xgcz6Na7i7o09+/+xm2m0UCU8gdtM2nIv6/cjLmhMZMqehSpTlgbx9omtLmV8LVqOskPEyWnmZQ==} + + '@humanwhocodes/config-array@0.11.14': + resolution: {integrity: sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==} + engines: {node: '>=10.10.0'} + deprecated: Use @eslint/config-array instead + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/object-schema@2.0.3': + resolution: {integrity: sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==} + deprecated: Use @eslint/object-schema instead + + '@iconify/types@2.0.0': + resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} + + '@iconify/utils@2.1.22': + resolution: {integrity: sha512-6UHVzTVXmvO8uS6xFF+L/QTSpTzA/JZxtgU+KYGFyDYMEObZ1bu/b5l+zNJjHy+0leWjHI+C0pXlzGvv3oXZMA==} + + '@iconify/vue@4.2.0': + resolution: {integrity: sha512-CMynoz9BDWugDO2B7LU/s8L99dHCiqDGCjCki6bhVx5etZhw9x0BTV7wWRdj82jtl1yQTc+QQRcHQmSvUY6R+g==} + peerDependencies: + vue: '>=3' + + '@isaacs/cliui@8.0.2': + resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} + engines: {node: '>=12'} + + '@jest/schemas@29.6.3': + resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jridgewell/gen-mapping@0.3.12': + resolution: {integrity: sha512-OuLGC46TjB5BbN1dH8JULVVZY4WTdkF7tV9Ys6wLL1rubZnCMstOhNHueU5bLCrnRuDhKPDM4g6sw4Bel5Gzqg==} + + '@jridgewell/gen-mapping@0.3.5': + resolution: {integrity: sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==} + engines: {node: '>=6.0.0'} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/set-array@1.2.1': + resolution: {integrity: sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + + '@one-ini/wasm@0.1.1': + resolution: {integrity: sha512-XuySG1E38YScSJoMlqovLru4KTUNSjgVTIjyh7qMX6aNN5HY5Ct5LhRJdxO79JtTzKfzV/bnWpz+zquYrISsvw==} + + '@pkgjs/parseargs@0.11.0': + resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} + engines: {node: '>=14'} + + '@pkgr/core@0.3.6': + resolution: {integrity: sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==} + engines: {node: ^14.18.0 || >=16.0.0} + + '@pkgr/utils@2.4.2': + resolution: {integrity: sha512-POgTXhjrTfbTV63DiFXav4lBHiICLKKwDeaKn9Nphwj7WH6m0hMMCaJkMyRWjgtPFyRKRVoMXXjczsTQRDEhYw==} + engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} + + '@polka/url@1.0.0-next.29': + resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} + + '@rollup/pluginutils@5.4.0': + resolution: {integrity: sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==} + engines: {node: '>=14.0.0'} + peerDependencies: + rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0 + peerDependenciesMeta: + rollup: + optional: true + + '@rollup/rollup-android-arm-eabi@4.64.1': + resolution: {integrity: sha512-QRU7UpoS9hd8Ij5I6fCVBxZ0UpdfAbZ5y7BWG5STFGMoM9jGzUP464yYAa3CzZxvG+jBwq1kI8L07xx0ReAdGA==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.64.1': + resolution: {integrity: sha512-ttQF6Rp4MrNy9/2AOPmHmMXbNE8kIlNPYoGC3ksid9tonleMQALfrhTFJiQxobBvXYKG5Wcc8VGcHWTHR0ik8w==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.64.1': + resolution: {integrity: sha512-MvzZ+qbBi5jrafURHsASUF1qW/58tOJFt/gFVJo2znQWrKX4CSf/Lt/qGONtoA4yHsNL5QzgdXMuITZxAs62Vg==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.64.1': + resolution: {integrity: sha512-9uj1VBuiPK5ij/+g0mCK17X+V/4SbErvRQMXIQjZAtbl4VcUhv63RhPZsFSWHrCRkTd3FKDtaVTrtT0+8bIhhQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.64.1': + resolution: {integrity: sha512-FCoXm836IqcXWhWPRkqlLx3Hjnv9S7c8tg5MFwsgHB3aFCz1JjUy6b1ssrxEjEbqaHpnvRmNjUUHxsXuU85NYA==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.64.1': + resolution: {integrity: sha512-Xa6Oxo86Ilx1hq1vNb69541NOuUyhGEH3Sc0g7eGkfsfRblWh4hAa4Lj2GWwZyfUVYL+Z4xK3TxhwIuZ3fNPLg==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.64.1': + resolution: {integrity: sha512-Nkw7cVMu1yrczpzr42Mh1BZ5Ai5A4Fsz2Je/frbwHmazpQTJzP+qo7pNjdxHrxVj56ivKTJihNoN90OD1hGxBA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.64.1': + resolution: {integrity: sha512-JONaLM9mZPXbSetxMzYG3496qoJuWvG2ERCTrrVptfw/Fwe4UzrQoEx/mYEeZCRv/Xz0RldOLFeqDfqmH75/Zg==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.64.1': + resolution: {integrity: sha512-OfimHma+prmdoobHI3tfYud2enQ2LXYaMu+iMUQH7IjJkykJ6qUmAs1M/scdQaEKRWysiKwTctsDa2LXvaO0xw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.64.1': + resolution: {integrity: sha512-X5fwh2HM8EHbgfFwpf4m2x2pG/AHdQ2aPDPk+JCDwV4DPeM8yxYmKG1vvm123JSc9gBSu8tu9NECA99wHPztsw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.64.1': + resolution: {integrity: sha512-8dp2TxKdjiX/4f7Da9gF7BR29hygxOQlHxKNa8qxJHoqZ13ytrogFTpMPhtVEFrgFu9MSOabAn006PeoygavjA==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.64.1': + resolution: {integrity: sha512-YuYDpRSZnU9qLf6sqyhiBdMRCw5ImECGLNqRjM2hZrJIEwAckameWkRJ3SUnn0oxSewZIib/4iLwyEXj40QqQQ==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.64.1': + resolution: {integrity: sha512-gGj3v7YYkysy7IbfclMI4PDtHaa6YX4nU1D5NR1fyvXAGqM4TDk28ZWvrpOkkK92eoQRryAludWz6jNjsm77Qg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.64.1': + resolution: {integrity: sha512-DTZVwvS94FUYpP0CjCfz2iT0XTmBfQGc/arx9IdwUbDImpe9h8dWuMT/oPUvcGiwLKMQoNmuFBx3AVajm+FNjA==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.64.1': + resolution: {integrity: sha512-NWnyiq2moc8iEHGyTjIFadJTy8VCvCU/rUBfor+3l30JOQKAifpmKdxX4ZxRRPSPE/rLhFpLADdzNjS3Ldctdw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.64.1': + resolution: {integrity: sha512-yIz+7L37g7bVOGLaUQmGqiYADH262krL4dtf5zU6QGldPgOairLEgW1FTs5pP0UFkHq5uf2qxDttOFsVAX6kxg==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.64.1': + resolution: {integrity: sha512-sRK+GWovJZV6ijyV/k1Ft3FL5+4DscF5OYsJolTbhVTTLFxKOPVjS0wxUUHakvL0vRw/cbFxZNeZLfM/EzuQhA==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.64.1': + resolution: {integrity: sha512-T2C0NXqqD063yJdm8UGdcoudBATDODdphEXWS7rEoh0jOITfoEBv7LHfRBYVsy+pI7wwxgScoZpkFiQOf40ryQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.64.1': + resolution: {integrity: sha512-05wl8uRZMkcobB6YZrzskr2SiM0VOdzlFw3bAxOjKKTt3M6o3O0X/hE/8xk15u8oQY17xUCdTKcNMMg45ZAFog==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.64.1': + resolution: {integrity: sha512-NoRZK1VclOgn9x3b9vPJ3sTxwvQ/F+Hf93xurRKSFJKiwNZyQZnLxVpqlCejhDvesMLMF8VNN+Y4jHTFddV/Xg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.64.1': + resolution: {integrity: sha512-SDkX4OkZBePUPf0/XsXVJLwS+O61CmkDKuIyk5CeWddK3vkE8AZjmWK+p1ILRez4wnbS5rTK+U9YmcbRyx2dHw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.64.1': + resolution: {integrity: sha512-JQ7el/Plr3juYFxIVu9YXDPNl57XR2L8WIc87JX9wj0L3goV8fXQPQXb3DaHVXq61X/WCGWsTCQsQHo6/Mz5UQ==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.64.1': + resolution: {integrity: sha512-oZSlQ2H3ZDOz3ce1jEyuOZKuD0tPY/D2cKGMcMl0jhHQauBvkHHKAGR1OeRiMluvu3itzLRU2xCTUZptLayObA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.64.1': + resolution: {integrity: sha512-Do2m3jUeVAvUDpee/yVZYRqhO8Ecx4x5sX3EVGalqLx+OxecLDGx3sIwPEm1Nq+MFK2FV3pgdpwWP4624b85Og==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.64.1': + resolution: {integrity: sha512-KpxCwRn1Qh3tmBHAqIAF4HtUCVKqZd0w57TsItWblx3QVeJLtXaSgeBFAj1WAvBSpBo+Mh9iZCjj6YW/HaBVMw==} + cpu: [x64] + os: [win32] + + '@sinclair/typebox@0.27.12': + resolution: {integrity: sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==} + + '@smithy/core@3.35.1': + resolution: {integrity: sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w==} + engines: {node: '>=18.0.0'} + + '@smithy/credential-provider-imds@4.5.2': + resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==} + engines: {node: '>=18.0.0'} + + '@smithy/fetch-http-handler@5.8.0': + resolution: {integrity: sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==} + engines: {node: '>=18.0.0'} + + '@smithy/node-http-handler@4.12.1': + resolution: {integrity: sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==} + engines: {node: '>=18.0.0'} + + '@smithy/signature-v4@5.7.4': + resolution: {integrity: sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==} + engines: {node: '>=18.0.0'} + + '@smithy/types@4.19.0': + resolution: {integrity: sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==} + engines: {node: '>=18.0.0'} + + '@soerenmartius/vue3-clipboard@0.1.2': + resolution: {integrity: sha512-a5er6cFGcFIQ/3qg6kWvU0yFqIz9iWoQGEVs9azjevyRyMAKvj1w3JuLH9y6+u0WhMNby3kn7nuR8nktSnDesg==} + + '@sphinxxxx/color-conversion@2.2.2': + resolution: {integrity: sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw==} + + '@sxzz/popperjs-es@2.11.8': + resolution: {integrity: sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==} + + '@tinymce/tinymce-vue@6.1.0': + resolution: {integrity: sha512-7JdaKMOaohuFWpjKwRmaZJbT/eNVUUYHG93R7+lUf7SUN+hSqd2spbuqZcki+tG9kaSAGd2ZmvJIsmzWDNAzpw==} + peerDependencies: + tinymce: ^7.0.0 || ^6.0.0 || ^5.5.1 + vue: ^3.0.0 + peerDependenciesMeta: + tinymce: + optional: true + + '@transloadit/prettier-bytes@0.0.7': + resolution: {integrity: sha512-VeJbUb0wEKbcwaSlj5n+LscBl9IPgLPkHVGBkh00cztv6X4L/TJXK58LzFuBKX7/GAfiGhIwH67YTLTlzvIzBA==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/event-emitter@0.3.5': + resolution: {integrity: sha512-zx2/Gg0Eg7gwEiOIIh5w9TrhKKTeQh7CPCOPNc0el4pLSwzebA8SmnHwZs2dWlLONvyulykSwGSQxQHLhjGLvQ==} + + '@types/js-cookie@3.0.6': + resolution: {integrity: sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/lodash-es@4.17.12': + resolution: {integrity: sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==} + + '@types/lodash@4.17.25': + resolution: {integrity: sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==} + + '@types/node@20.11.30': + resolution: {integrity: sha512-dHM6ZxwlmuZaRmUPfv1p+KrdD1Dci04FbdEm/9wEMouFqxYoFl5aMkt0VMAUtYRQDyYvD41WJLukhq/ha3YuTw==} + + '@types/node@26.6.4': + resolution: {integrity: sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==} + + '@types/nprogress@0.2.3': + resolution: {integrity: sha512-k7kRA033QNtC+gLc4VPlfnue58CM1iQLgn1IMAU8VPHGOj7oIHPp9UlhedEnD/Gl8evoCjwkZjlBORtZ3JByUA==} + + '@types/path-browserify@1.0.2': + resolution: {integrity: sha512-ZkC5IUqqIFPXx3ASTTybTzmQdwHwe2C0u3eL75ldQ6T9E9IWFJodn6hIfbZGab73DfyiHN4Xw15gNxUq2FbvBA==} + + '@types/semver@7.8.0': + resolution: {integrity: sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==} + + '@types/sortablejs@1.15.9': + resolution: {integrity: sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==} + + '@types/svgo@2.6.4': + resolution: {integrity: sha512-l4cmyPEckf8moNYHdJ+4wkHvFxjyW6ulm9l4YGaOxeyBWPhBOT0gvni1InpFPdzx1dKf/2s62qGITwxNWnPQng==} + + '@types/uuid@11.0.0': + resolution: {integrity: sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA==} + deprecated: This is a stub types definition. uuid provides its own type definitions, so you do not need this installed. + + '@types/web-bluetooth@0.0.15': + resolution: {integrity: sha512-w7hEHXnPMEZ+4nGKl/KDRVpxkwYxYExuHOYXyzIzCDzEZ9ZCGMAewulr9IqJu2LR4N37fcnb1XVeuZ09qgOxhA==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + + '@typescript-eslint/eslint-plugin@7.3.1': + resolution: {integrity: sha512-STEDMVQGww5lhCuNXVSQfbfuNII5E08QWkvAw5Qwf+bj2WT+JkG1uc+5/vXA3AOYMDHVOSpL+9rcbEUiHIm2dw==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + '@typescript-eslint/parser': ^7.0.0 + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/parser@7.3.1': + resolution: {integrity: sha512-Rq49+pq7viTRCH48XAbTA+wdLRrB/3sRq4Lpk0oGDm0VmnjBrAOVXH/Laalmwsv2VpekiEfVFwJYVk6/e8uvQw==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/scope-manager@7.3.1': + resolution: {integrity: sha512-fVS6fPxldsKY2nFvyT7IP78UO1/I2huG+AYu5AMjCT9wtl6JFiDnsv4uad4jQ0GTFzcUV5HShVeN96/17bTBag==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@typescript-eslint/type-utils@7.3.1': + resolution: {integrity: sha512-iFhaysxFsMDQlzJn+vr3OrxN8NmdQkHks4WaqD4QBnt5hsq234wcYdyQ9uquzJJIDAj5W4wQne3yEsYA6OmXGw==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/types@7.3.1': + resolution: {integrity: sha512-2tUf3uWggBDl4S4183nivWQ2HqceOZh1U4hhu4p1tPiIJoRRXrab7Y+Y0p+dozYwZVvLPRI6r5wKe9kToF9FIw==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@typescript-eslint/typescript-estree@7.3.1': + resolution: {integrity: sha512-tLpuqM46LVkduWP7JO7yVoWshpJuJzxDOPYIVWUUZbW+4dBpgGeUdl/fQkhuV0A8eGnphYw3pp8d2EnvPOfxmQ==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/utils@7.3.1': + resolution: {integrity: sha512-jIERm/6bYQ9HkynYlNZvXpzmXWZGhMbrOvq3jJzOSOlKXsVjrrolzWBjDW6/TvT5Q3WqaN4EkmcfdQwi9tDjBQ==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + + '@typescript-eslint/visitor-keys@7.3.1': + resolution: {integrity: sha512-9RMXwQF8knsZvfv9tdi+4D/j7dMG28X/wMJ8Jj6eOHyHWwDW4ngQJcqEczSsqIKKjFiLFr40Mnr7a5ulDD3vmw==} + engines: {node: ^18.18.0 || >=20.0.0} + + '@ungap/structured-clone@1.4.0': + resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==} + + '@unocss/astro@0.58.6': + resolution: {integrity: sha512-0BvbhEp5Ln6wFNnhISusB2hcfycWkdgnjlFMcLT69efvj4G39MzB6JYT/1qiidLfpj35HcqkpBz7TfZ4bUmOAw==} + peerDependencies: + vite: ^2.9.0 || ^3.0.0-0 || ^4.0.0 || ^5.0.0-0 + peerDependenciesMeta: + vite: + optional: true + + '@unocss/cli@0.58.6': + resolution: {integrity: sha512-cfJBiEAKElo9vcA4ZU1WTXeUha5qVBtn3+ZjgdgOvveSX0oY0gOheG+DD2LaEjwWzjCstFU38lblUHWzHRv0sQ==} + engines: {node: '>=14'} + hasBin: true + + '@unocss/config@0.58.6': + resolution: {integrity: sha512-YyywfigaEzGkDJ0ztp/tvruD+0xfdCcMZUvaGH4IElAwZDdcSsuaHdR1HW3EixCETOyFHBcuFk6sJwfLPIZLTw==} + engines: {node: '>=14'} + + '@unocss/core@0.58.6': + resolution: {integrity: sha512-m87iuENM/PLqLKnfE2mJbpfzj7NQ99LP2go0r+x5X4kXKppyGRJNQg6RIW3AqTS22jup1YPgd62UNXvvRtHtww==} + + '@unocss/extractor-arbitrary-variants@0.58.6': + resolution: {integrity: sha512-iSrjLEM+dtcpCmJ8myttPZ/0Dg4HKYVYpM71rNTybrX1HB/cfRsGwIHobjsvvRnve+LAxC4Hmdi8EXRd8V1xPg==} + + '@unocss/inspector@0.58.6': + resolution: {integrity: sha512-JCcnIwSofdIdpR/GYTZ78d4dMZP8Z2oF/g9f9MlPG96LLLwqXSmYtR83vC34fUWm1hz7FZyTLK5OqTV7VfUb+w==} + + '@unocss/postcss@0.58.6': + resolution: {integrity: sha512-jTwu7llhRm7luscsk0JekCeo6RS2W98CXiCJRE1H6IDQnjGQQ/9uRAqW4wuLsv7OQ1ThF8m9NKEj0wFJv7ePNg==} + engines: {node: '>=14'} + peerDependencies: + postcss: ^8.4.21 + + '@unocss/preset-attributify@0.58.6': + resolution: {integrity: sha512-IW2aIBH0RiYsP50VckgxXhMwjDk/XVZykUUklgko9aT+gNC2xDBm3936RWLVLmHdBHG1Vnnjc71BG6aUAqrtEA==} + + '@unocss/preset-icons@0.58.6': + resolution: {integrity: sha512-20P1ISxEX2J5mhyNkMm0nKp2p0qJfmDArolC10Fjyl+GUTCsojDNFfonzQEkHeIIJwzgRcubdtNaotTgYSKSRg==} + + '@unocss/preset-mini@0.58.6': + resolution: {integrity: sha512-COaM/04Z6/gawzrFcCwoyD6t0FCpuKRyljKKs3VxitoGxsN9BHKiFE3U/cPSQarpG789rmZg8D/wmLHCChSXvg==} + + '@unocss/preset-tagify@0.58.6': + resolution: {integrity: sha512-xhpHMz8KLrFlLXaOCeShu0/yVpe6J8bd2WcOTd5VuU5W1uCsplcaagpfTRkBpaH1tJt/MTTU5e4cQLa20l0JZQ==} + + '@unocss/preset-typography@0.58.6': + resolution: {integrity: sha512-s4SSw3SK/JjAqYlga51XnxzPc7jF+TmkEkW09IkYYLPrmqJ76U4i5Po2N7HzyjpVGWnmIp1fQ5mCvbhj4tNyNQ==} + + '@unocss/preset-uno@0.58.6': + resolution: {integrity: sha512-QFbgvxCvTFqKIA/VGcPM+XcfPGDgbmaiXKbnh7hIbkER6TRxjt4DIGapPt150w/kQT+zC/jerWditSdyn+s3xQ==} + + '@unocss/preset-web-fonts@0.58.6': + resolution: {integrity: sha512-W/8102vurABwfnb9QQyp9GBKP80kpy/IADSM7hbqLNaqmgxHASELXkjhqqt+et39Zn2tnXpIHNVWoqG6QNWBwQ==} + + '@unocss/preset-wind@0.58.6': + resolution: {integrity: sha512-zs41CpFVvLB8CutroUeI1iqxzPsztiur9ei0QjRshxpYerPSsTSgdTkF+eul5D1q3BcsebLebzqtCSqnpFOuOA==} + + '@unocss/reset@0.58.6': + resolution: {integrity: sha512-mYyOe5QDRHc1BBRff+G97j3SGGC8s3Vk7cCcXc/l48FvPHKtLCphMZaBS+KkGkzWqwAtxv0QRbGhTixJCVDRug==} + + '@unocss/rule-utils@0.58.6': + resolution: {integrity: sha512-qbVDeyKzExFY/YeoIbMw/lu8PXEGJzSHrFXRumNHX5lvTu8ggAjH6p9xyvYa/YnuNU0+pFKuYxG8LNK2F8f1EQ==} + engines: {node: '>=14'} + + '@unocss/scope@0.58.6': + resolution: {integrity: sha512-22BDrZPOkfEKuXY4NROhY+J25TAXN+GIxZpE4IbT1Wh+dkjnMXyC85VKGzOAuY/0v0zbaj12dYkmtndueQ/04w==} + + '@unocss/transformer-attributify-jsx-babel@0.58.6': + resolution: {integrity: sha512-IVU/ZozKTFhP9z1I9ZgSKiEx3WfDFDNXbTYTqwNW2SHPmAj5Qf99kn6o7br7Kd1dnxSjKFXOmNfNGkW9AMDraA==} + + '@unocss/transformer-attributify-jsx@0.58.6': + resolution: {integrity: sha512-S+mTR5qwMsEaq8nYtqUgYdYIIRAA4oltxfGMYGj3Gxy9V0uteyo56QNp7IOjlYxAB8Dq9jQ8GLYEQe5JlffO1A==} + + '@unocss/transformer-compile-class@0.58.6': + resolution: {integrity: sha512-iung3cPA+IpBHoP6dTs9gkPN/wEVujqMZYxf6FQLjRH+v70rPxqTgaeGDyuQZAYikfDhdUZF8PJ4IUMOxEFsmw==} + + '@unocss/transformer-directives@0.58.6': + resolution: {integrity: sha512-8/+KGRmRnlkAJCRt4VqcYK16SnEr9wf1q7D9OCM2kZhk33Sx5SlsO6vjNZ1IH4c67/WviwNV6+KeS4elnQY8bA==} + + '@unocss/transformer-variant-group@0.58.6': + resolution: {integrity: sha512-6IFmfzketh4j+Mc/ik4nU+Oec0cptNR+aVfZZkGb4wd2h1lH+teAT2Y/Vz2xY8rDExOrbjY5y5FgRGd16LY2Rw==} + + '@unocss/vite@0.58.6': + resolution: {integrity: sha512-DPXCoYU/Ozqc/Jeptd41XvtW8MSgVxmtTyhpMAsm/hJuBfwIV7Fy3TZquf4V9BpaTb4ao1LVXzgXmVUmj2HXpA==} + peerDependencies: + vite: ^2.9.0 || ^3.0.0-0 || ^4.0.0 || ^5.0.0-0 + + '@uppy/companion-client@2.2.2': + resolution: {integrity: sha512-5mTp2iq97/mYSisMaBtFRry6PTgZA6SIL7LePteOV5x0/DxKfrZW3DEiQERJmYpHzy7k8johpm2gHnEKto56Og==} + + '@uppy/core@2.1.1': + resolution: {integrity: sha512-dFlcy6+05zwsJk1KNeUKVWUyAfhOVwNpnPLaR1NX9Qsjv7KlYfUNRVW3uCCmIpd/EZsX44+haiqGrhLcYDAcxA==} + + '@uppy/store-default@2.1.1': + resolution: {integrity: sha512-xnpTxvot2SeAwGwbvmJ899ASk5tYXhmZzD/aCFsXePh/v8rNvR2pKlcQUH7cF/y4baUGq3FHO/daKCok/mpKqQ==} + + '@uppy/utils@4.0.1': + resolution: {integrity: sha512-blgQkWkc6yrxGcNXehf9gFTT/f1MNonuxkpBNOwI51DT/yv/QFLLdRPMFM6CpcuA0TNhVwSUuFLeNTkerRrXeQ==} + + '@uppy/utils@4.0.3': + resolution: {integrity: sha512-LApneC8lNvTonzSJFupxzuEvKhwp/Klc1otq8t+zXpdgjLVVSuW/rJBFfdIDrmDoqSzVLQKYjMy07CmhDAWfKg==} + + '@uppy/utils@4.1.2': + resolution: {integrity: sha512-rl9aKRE4o2mRKVAhYHHf8uV7BoUOQkvDH6yOaJ4tuHJ6HgPkvxVxqUY8L+yKV1hx4mw6OF9hLIzpW/+TLSfyfQ==} + + '@uppy/xhr-upload@2.0.3': + resolution: {integrity: sha512-odIzJzRQSg5vFcHmcjCq+NzdAAa+7VpXGRBSebKXx53FTkGKaHhzTD9yc3Uwz25mG4sVKseTVz75+buywS/2qQ==} + peerDependencies: + '@uppy/core': ^2.0.0 + + '@vitejs/plugin-vue-jsx@3.1.0': + resolution: {integrity: sha512-w9M6F3LSEU5kszVb9An2/MmXNxocAnUb3WhRr8bHlimhDrXNt6n6D2nJQR3UXpGlZHh/EsgouOHCsM8V3Ln+WA==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + vite: ^4.0.0 || ^5.0.0 + vue: ^3.0.0 + + '@vitejs/plugin-vue@5.0.4': + resolution: {integrity: sha512-WS3hevEszI6CEVEx28F8RjTX97k3KsrcY6kvTg7+Whm5y3oYvcqzVeGCU3hxSAn4uY2CLCkeokkGKpoctccilQ==} + engines: {node: ^18.0.0 || >=20.0.0} + peerDependencies: + vite: ^5.0.0 + vue: ^3.2.25 + + '@vitest/expect@1.4.0': + resolution: {integrity: sha512-Jths0sWCJZ8BxjKe+p+eKsoqev1/T8lYcrjavEaz8auEJ4jAVY0GwW3JKmdVU4mmNPLPHixh4GNXP7GFtAiDHA==} + + '@vitest/runner@1.4.0': + resolution: {integrity: sha512-EDYVSmesqlQ4RD2VvWo3hQgTJ7ZrFQ2VSJdfiJiArkCerDAGeyF1i6dHkmySqk573jLp6d/cfqCN+7wUB5tLgg==} + + '@vitest/snapshot@1.4.0': + resolution: {integrity: sha512-saAFnt5pPIA5qDGxOHxJ/XxhMFKkUSBJmVt5VgDsAqPTX6JP326r5C/c9UuCMPoXNzuudTPsYDZCoJ5ilpqG2A==} + + '@vitest/spy@1.4.0': + resolution: {integrity: sha512-Ywau/Qs1DzM/8Uc+yA77CwSegizMlcgTJuYGAi0jujOteJOUf1ujunHThYo243KG9nAyWT3L9ifPYZ5+As/+6Q==} + + '@vitest/utils@1.4.0': + resolution: {integrity: sha512-mx3Yd1/6e2Vt/PUC98DcqTirtfxUyAZ32uK82r8rZzbtBeBo+nqgnjx/LvqQdWsrvNtm14VmurNgcf4nqY5gJg==} + + '@volar/language-core@2.1.3': + resolution: {integrity: sha512-F93KYZYqcYltG7NihfnLt/omMZOtrQtsh2+wj+cgx3xolopU+TZvmwlZWOjw3ObZGFj3SKBb4jJn6VSfSch6RA==} + + '@volar/source-map@2.1.3': + resolution: {integrity: sha512-j+R+NG/OlDgdNMttADxNuSM9Z26StT/Bjw0NgSydI05Vihngn9zvaP/xXwfWs5qQrRzbKVFxJebS2ks5m/URuA==} + + '@volar/typescript@2.1.3': + resolution: {integrity: sha512-ZZqLMih4mvu2eJAW3UCFm84OM/ojYMoA/BU/W1TctT5F2nVzNJmW4jxMWmP3wQzxCbATfTa5gLb1+BSI9NBMBg==} + + '@vue/babel-helper-vue-transform-on@1.1.5': + resolution: {integrity: sha512-SgUymFpMoAyWeYWLAY+MkCK3QEROsiUnfaw5zxOVD/M64KQs8D/4oK6Q5omVA2hnvEOE0SCkH2TZxs/jnnUj7w==} + + '@vue/babel-plugin-jsx@1.1.5': + resolution: {integrity: sha512-nKs1/Bg9U1n3qSWnsHhCVQtAzI6aQXqua8j/bZrau8ywT1ilXQbK4FwEJGmU8fV7tcpuFvWmmN7TMmV1OBma1g==} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@vue/compiler-core@3.4.21': + resolution: {integrity: sha512-MjXawxZf2SbZszLPYxaFCjxfibYrzr3eYbKxwpLR9EQN+oaziSu3qKVbwBERj1IFIB8OLUewxB5m/BFzi613og==} + + '@vue/compiler-core@3.5.43': + resolution: {integrity: sha512-zdiLhnbe1QQqgDT8xZMpNmyqZ3qlI+/Q/FHQco57Kwl/b05HhCzN6eVGN9QU9rbga4CrS0H5SYY8VGHZCt/1Hg==} + + '@vue/compiler-dom@3.4.21': + resolution: {integrity: sha512-IZC6FKowtT1sl0CR5DpXSiEB5ayw75oT2bma1BEhV7RRR1+cfwLrxc2Z8Zq/RGFzJ8w5r9QtCOvTjQgdn0IKmA==} + + '@vue/compiler-dom@3.5.43': + resolution: {integrity: sha512-PEZoAk3NQmsn/ejMzSOCyTYqwGqczrWm70PuhBKjjv1+TCoQAaO/zOqNwjV+honlNstT5ILxtc+8r8UUfj+iEQ==} + + '@vue/compiler-sfc@3.4.21': + resolution: {integrity: sha512-me7epoTxYlY+2CUM7hy9PCDdpMPfIwrOvAXud2Upk10g4YLv9UBW7kL798TvMeDhPthkZ0CONNrK2GoeI1ODiQ==} + + '@vue/compiler-ssr@3.4.21': + resolution: {integrity: sha512-M5+9nI2lPpAsgXOGQobnIueVqc9sisBFexh5yMIMRAPYLa7+5wEJs8iqOZc1WAa9WQbx9GR2twgznU8LTIiZ4Q==} + + '@vue/devtools-api@6.5.0': + resolution: {integrity: sha512-o9KfBeaBmCKl10usN4crU53fYtC1r7jJwdGKjPT24t348rHxgfpZ0xL3Xm/gLUYnc0oTp8LAmrxOeLyu6tbk2Q==} + + '@vue/devtools-api@6.5.1': + resolution: {integrity: sha512-+KpckaAQyfbvshdDW5xQylLni1asvNSGme1JFs8I1+/H5pHEhqUKMEQD/qn3Nx5+/nycBq11qAEi8lk+LXI2dA==} + + '@vue/eslint-config-prettier@9.0.0': + resolution: {integrity: sha512-z1ZIAAUS9pKzo/ANEfd2sO+v2IUalz7cM/cTLOZ7vRFOPk5/xuRKQteOu1DErFLAh/lYGXMVZ0IfYKlyInuDVg==} + peerDependencies: + eslint: '>= 8.0.0' + prettier: '>= 3.0.0' + + '@vue/eslint-config-typescript@13.0.0': + resolution: {integrity: sha512-MHh9SncG/sfqjVqjcuFLOLD6Ed4dRAis4HNt0dXASeAuLqIAx4YMB1/m2o4pUKK1vCt8fUvYG8KKX2Ot3BVZTg==} + engines: {node: ^18.18.0 || >=20.0.0} + peerDependencies: + eslint: ^8.56.0 + eslint-plugin-vue: ^9.0.0 + typescript: '>=4.7.4' + peerDependenciesMeta: + typescript: + optional: true + + '@vue/language-core@2.0.7': + resolution: {integrity: sha512-Vh1yZX3XmYjn9yYLkjU8DN6L0ceBtEcapqiyclHne8guG84IaTzqtvizZB1Yfxm3h6m7EIvjerLO5fvOZO6IIQ==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@vue/reactivity@3.4.21': + resolution: {integrity: sha512-UhenImdc0L0/4ahGCyEzc/pZNwVgcglGy9HVzJ1Bq2Mm9qXOpP8RyNTjookw/gOCUlXSEtuZ2fUg5nrHcoqJcw==} + + '@vue/runtime-core@3.4.21': + resolution: {integrity: sha512-pQthsuYzE1XcGZznTKn73G0s14eCJcjaLvp3/DKeYWoFacD9glJoqlNBxt3W2c5S40t6CCcpPf+jG01N3ULyrA==} + + '@vue/runtime-dom@3.4.21': + resolution: {integrity: sha512-gvf+C9cFpevsQxbkRBS1NpU8CqxKw0ebqMvLwcGQrNpx6gqRDodqKqA+A2VZZpQ9RpK2f9yfg8VbW/EpdFUOJw==} + + '@vue/server-renderer@3.4.21': + resolution: {integrity: sha512-aV1gXyKSN6Rz+6kZ6kr5+Ll14YzmIbeuWe7ryJl5muJ4uwSwY/aStXTixx76TwkZFJLm1aAlA/HSWEJ4EyiMkg==} + peerDependencies: + vue: 3.4.21 + + '@vue/shared@3.4.21': + resolution: {integrity: sha512-PuJe7vDIi6VYSinuEbUIQgMIRZGgM8e4R+G+/dQTk0X1NEdvgvvgv7m+rfmDH1gZzyA1OjjoWskvHlfRNfQf3g==} + + '@vue/shared@3.5.43': + resolution: {integrity: sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==} + + '@vue/test-utils@2.4.5': + resolution: {integrity: sha512-oo2u7vktOyKUked36R93NB7mg2B+N7Plr8lxp2JBGwr18ch6EggFjixSCdIVVLkT6Qr0z359Xvnafc9dcKyDUg==} + + '@vueuse/core@9.1.0': + resolution: {integrity: sha512-BIroqvXEqt826aE9r3K5cox1zobuPuAzdYJ36kouC2TVhlXvFKIILgFVWrpp9HZPwB3aLzasmG3K87q7TSyXZg==} + + '@vueuse/metadata@9.1.0': + resolution: {integrity: sha512-8OEhlog1iaAGTD3LICZ8oBGQdYeMwByvXetOtAOZCJOzyCRSwqwdggTsmVZZ1rkgYIEqgUBk942AsAPwM21s6A==} + + '@vueuse/shared@9.1.0': + resolution: {integrity: sha512-pB/3njQu4tfJJ78ajELNda0yMG6lKfpToQW7Soe09CprF1k3QuyoNi1tBNvo75wBDJWD+LOnr+c4B5HZ39jY/Q==} + + '@wangeditor/basic-modules@1.1.7': + resolution: {integrity: sha512-cY9CPkLJaqF05STqfpZKWG4LpxTMeGSIIF1fHvfm/mz+JXatCagjdkbxdikOuKYlxDdeqvOeBmsUBItufDLXZg==} + peerDependencies: + '@wangeditor/core': 1.x + dom7: ^3.0.0 + lodash.throttle: ^4.1.1 + nanoid: ^3.2.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/code-highlight@1.0.3': + resolution: {integrity: sha512-iazHwO14XpCuIWJNTQTikqUhGKyqj+dUNWJ9288Oym9M2xMVHvnsOmDU2sgUDWVy+pOLojReMPgXCsvvNlOOhw==} + peerDependencies: + '@wangeditor/core': 1.x + dom7: ^3.0.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/core@1.1.19': + resolution: {integrity: sha512-KevkB47+7GhVszyYF2pKGKtCSj/YzmClsD03C3zTt+9SR2XWT5T0e3yQqg8baZpcMvkjs1D8Dv4fk8ok/UaS2Q==} + peerDependencies: + '@uppy/core': ^2.1.1 + '@uppy/xhr-upload': ^2.0.3 + dom7: ^3.0.0 + is-hotkey: ^0.2.0 + lodash.camelcase: ^4.3.0 + lodash.clonedeep: ^4.5.0 + lodash.debounce: ^4.0.8 + lodash.foreach: ^4.5.0 + lodash.isequal: ^4.5.0 + lodash.throttle: ^4.1.1 + lodash.toarray: ^4.4.0 + nanoid: ^3.2.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/editor-for-vue@5.1.12': + resolution: {integrity: sha512-0Ds3D8I+xnpNWezAeO7HmPRgTfUxHLMd9JKcIw+QzvSmhC5xUHbpCcLU+KLmeBKTR/zffnS5GQo6qi3GhTMJWQ==} + peerDependencies: + '@wangeditor/editor': '>=5.1.0' + vue: ^3.0.5 + + '@wangeditor/editor@5.1.23': + resolution: {integrity: sha512-0RxfeVTuK1tktUaPROnCoFfaHVJpRAIE2zdS0mpP+vq1axVQpLjM8+fCvKzqYIkH0Pg+C+44hJpe3VVroSkEuQ==} + + '@wangeditor/list-module@1.0.5': + resolution: {integrity: sha512-uDuYTP6DVhcYf7mF1pTlmNn5jOb4QtcVhYwSSAkyg09zqxI1qBqsfUnveeDeDqIuptSJhkh81cyxi+MF8sEPOQ==} + peerDependencies: + '@wangeditor/core': 1.x + dom7: ^3.0.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/table-module@1.1.4': + resolution: {integrity: sha512-5saanU9xuEocxaemGdNi9t8MCDSucnykEC6jtuiT72kt+/Hhh4nERYx1J20OPsTCCdVr7hIyQenFD1iSRkIQ6w==} + peerDependencies: + '@wangeditor/core': 1.x + dom7: ^3.0.0 + lodash.isequal: ^4.5.0 + lodash.throttle: ^4.1.1 + nanoid: ^3.2.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/upload-image-module@1.0.2': + resolution: {integrity: sha512-z81lk/v71OwPDYeQDxj6cVr81aDP90aFuywb8nPD6eQeECtOymrqRODjpO6VGvCVxVck8nUxBHtbxKtjgcwyiA==} + peerDependencies: + '@uppy/core': ^2.0.3 + '@uppy/xhr-upload': ^2.0.3 + '@wangeditor/basic-modules': 1.x + '@wangeditor/core': 1.x + dom7: ^3.0.0 + lodash.foreach: ^4.5.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + '@wangeditor/video-module@1.1.4': + resolution: {integrity: sha512-ZdodDPqKQrgx3IwWu4ZiQmXI8EXZ3hm2/fM6E3t5dB8tCaIGWQZhmqd6P5knfkRAd3z2+YRSRbxOGfoRSp/rLg==} + peerDependencies: + '@uppy/core': ^2.1.4 + '@uppy/xhr-upload': ^2.0.7 + '@wangeditor/core': 1.x + dom7: ^3.0.0 + nanoid: ^3.2.0 + slate: ^0.72.0 + snabbdom: ^3.1.0 + + abbrev@1.0.3: + resolution: {integrity: sha512-s07HMJf6O5iTLVDx9cH7c9VbOdrmzxE+AzWz9CPi94zVNBQQA3jIwIZKTrHQj4dGR1T/MdwMnVJzSpjaVEXtXw==} + + ace-builds@1.44.0: + resolution: {integrity: sha512-PFNMSYqFdEUkul2Ntud0HvA09AgY+F1ag0UYdpMH60wNI/qOA8cB8tlTgoALMEwIdUPJK2CjrIQ7OnbiSS/ugQ==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn-walk@8.3.5: + resolution: {integrity: sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==} + engines: {node: '>=0.4.0'} + + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} + engines: {node: '>=0.4.0'} + hasBin: true + + address@1.2.2: + resolution: {integrity: sha512-4B/qKCfeE/ODUaAUpSwfzazo5x29WD4r3vXiWsB7I2mSDAihwEqKO+g8GELZUQSSAo5e1XTYh3ZVfLyxBc12nA==} + engines: {node: '>= 10.0.0'} + + adler-32@1.3.1: + resolution: {integrity: sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==} + engines: {node: '>=0.8'} + + agent-base@6.0.0: + resolution: {integrity: sha512-j1Q7cSCqN+AwrmDd+pzgqc0/NpC655x2bUf5ZjRIO77DcNBFmh+OgRNzF6OKdCC9RSCb19fGd99+bhXFdkRNqw==} + engines: {node: '>= 6.0.0'} + + agent-base@7.0.2: + resolution: {integrity: sha512-k2/tQ1+8Zf50dEUJWklUP80LcE/+Ph+OJ6cf2Ff2fD/c/TtCe6ofnCoNMz9UnyxOQYlaAALZtEWETzn+1JjfHg==} + engines: {node: '>= 14'} + + agent-base@7.1.0: + resolution: {integrity: sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==} + engines: {node: '>= 14'} + + agentkeepalive@3.5.3: + resolution: {integrity: sha512-yqXL+k5rr8+ZRpOAntkaaRgWgE5o8ESAj5DyRmVTCSoZxXmqemb9Dd7T4i5UzwuERdLAJUy6XzR9zFVuf0kzkw==} + engines: {node: '>= 4.0.0'} + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + ali-oss@6.18.0: + resolution: {integrity: sha512-6wjHOsLvIsAkp9EZRocp99I2DZUHUti4vbap57vhbfQR/0mrZBwzMfGkLE9cmG2F4J9hYQWvVy3GbKjDLdrSGw==} + engines: {node: '>=8'} + + ansi-escapes@6.2.0: + resolution: {integrity: sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw==} + engines: {node: '>=14.16'} + + ansi-regex@2.0.0: + resolution: {integrity: sha512-jCcLjwL2jOaTcRIaJkoRteMwNXg8nfJvwT/9K91kwZhH7bf4lsprqZ2+Qa7tSp8BYtejobOCBkDreC07q0KmZw==} + engines: {node: '>=0.10.0'} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.4.0: + resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} + engines: {node: '>=12'} + + ansi-styles@2.2.1: + resolution: {integrity: sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==} + engines: {node: '>=0.10.0'} + + ansi-styles@4.0.0: + resolution: {integrity: sha512-8zjUtFJ3db/QoPXuuEMloS2AUf79/yeyttJ7Abr3hteopJu9HK8vsgGviGUMq+zyA6cZZO6gAyZoMTF6TgaEjA==} + engines: {node: '>=8'} + + ansi-styles@4.1.0: + resolution: {integrity: sha512-Qts4KCLKG+waHc9C4m07weIY8qyeixoS0h6RnbsNVD6Fw+pEZGW3vTyObL3WXpE09Mq4Oi7/lBEyLmOiLtlYWQ==} + engines: {node: '>=8'} + + ansi-styles@5.0.0: + resolution: {integrity: sha512-6564t0m0fuQMnockqBv7wJxo9T5C2V9JpYXyNScfRDPVLusOQQhkpMGrFC17QbiolraQ1sMXX+Y5nJpjqozL4g==} + engines: {node: '>=10'} + + ansi-styles@6.0.0: + resolution: {integrity: sha512-4nUCKPhvbhgqc4a1S0w446veDod0i6krCOMF/bPBbBq9eP11BKztPS4Mp5yxUXhr1PFEe6mYcUSAv1jfoMUuOg==} + engines: {node: '>=12'} + + ansi-styles@6.1.0: + resolution: {integrity: sha512-VbqNsoz55SYGczauuup0MFUyXNQviSpFTj1RQtFzmQLk18qbVSpTFFGMT293rmDaQuKCT6InmbuEyUne4mTuxQ==} + engines: {node: '>=12'} + + ansi-styles@6.2.1: + resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==} + engines: {node: '>=12'} + + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + arr-diff@4.0.0: + resolution: {integrity: sha512-YVIQ82gZPGBebQV/a8dar4AitzCQs0jjXwMPZllpXMaGjXPYVUawSxQrRsjhjupyVxEvbHgUmIhKVlND+j02kA==} + engines: {node: '>=0.10.0'} + + arr-flatten@1.1.0: + resolution: {integrity: sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==} + engines: {node: '>=0.10.0'} + + arr-union@3.1.0: + resolution: {integrity: sha512-sKpyeERZ02v1FeCZT8lrfJq5u6goHCtpTAzPwJYe7c8SPFOboNjNg1vz2L4VTn9T4PQxEx13TbXLmYUcS6Ug7Q==} + engines: {node: '>=0.10.0'} + + array-buffer-byte-length@1.0.2: + resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} + engines: {node: '>= 0.4'} + + array-union@2.1.0: + resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} + engines: {node: '>=8'} + + array-unique@0.3.2: + resolution: {integrity: sha512-SleRWjh9JUud2wH1hPs9rZBZ33H6T9HOiL0uwGnGx9FpE6wKGyfWugmbkEOIs6qWrZhg0LWeLziLrEwQJhs5mQ==} + engines: {node: '>=0.10.0'} + + arraybuffer.prototype.slice@1.0.4: + resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} + engines: {node: '>= 0.4'} + + assertion-error@1.1.0: + resolution: {integrity: sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==} + + assign-symbols@1.0.0: + resolution: {integrity: sha512-Q+JC7Whu8HhmTdBph/Tq59IoRtoy6KAm5zzPv00WdujX82lbAL8K7WVjne7vdCsAmbF4AYaDOPyO3k0kl8qIrw==} + engines: {node: '>=0.10.0'} + + async-function@1.0.0: + resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} + engines: {node: '>= 0.4'} + + async-validator@4.2.5: + resolution: {integrity: sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + atob@2.1.2: + resolution: {integrity: sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==} + engines: {node: '>= 4.5.0'} + hasBin: true + + available-typed-arrays@1.0.7: + resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} + engines: {node: '>= 0.4'} + + aws-crt@1.33.2: + resolution: {integrity: sha512-KERzCXkmWSe07f7c/3Ll5PKiZpYZgp6by57Y4UPzqAIBSX7WMScnNSdOi6H1kleJm10sF/Zoj+gyi++TV14OYg==} + + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} + + axios@1.6.8: + resolution: {integrity: sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==} + + balanced-match@1.0.0: + resolution: {integrity: sha512-9Y0g0Q8rmSt+H33DfKv7FOc3v+iRI+o1lbzt8jGcIosYW37IIW/2XVYq5NPdmaD5NQ59Nk26Kl/vZbwW9Fr8vg==} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + base@0.11.2: + resolution: {integrity: sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==} + engines: {node: '>=0.10.0'} + + baseline-browser-mapping@2.11.27: + resolution: {integrity: sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + big-integer@1.6.52: + resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==} + engines: {node: '>=0.6'} + + big.js@5.2.2: + resolution: {integrity: sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==} + + binary-extensions@2.0.0: + resolution: {integrity: sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==} + engines: {node: '>=8'} + + bluebird@3.7.2: + resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==} + + boolbase@1.0.0: + resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} + + bowser@1.6.0: + resolution: {integrity: sha512-Fk23J0+vRnI2eKDEDoUZXWtbMjijr098lKhuj4DKAfMKMCRVfJOuxXlbpxy0sTgbZ/Nr2N8MexmOir+GGI/ZMA==} + + bowser@2.14.1: + resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==} + + bplist-parser@0.2.0: + resolution: {integrity: sha512-z0M+byMThzQmD9NILRniCUXYsYpjwnlO8N5uCFaCqIOpqRsJCrQL9NK3JsD67CN5a08nF5oIL2bD6loTdHOuKw==} + engines: {node: '>= 5.10.0'} + + brace-expansion@1.1.21: + resolution: {integrity: sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==} + + brace-expansion@2.1.7: + resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} + + braces@2.3.2: + resolution: {integrity: sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==} + engines: {node: '>=0.10.0'} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.29.3: + resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + buffer@6.0.3: + resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==} + + builtin-status-codes@3.0.0: + resolution: {integrity: sha512-HpGFw18DgFWlncDfjTa2rcQ4W88O1mC8e8yZ2AvQY5KDaktSTwo+KRf6nHK6FRI5FyRyb/5T6+TSxfP7QyGsmQ==} + + bundle-name@3.0.0: + resolution: {integrity: sha512-PKA4BeSvBpQKQ8iPOGCSiell+N8P+Tf1DlwqmYhpe2gAhKPHn8EYOxVT+ShuGmhg8lN8XiSlS80yiExKXrURlw==} + engines: {node: '>=12'} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + cache-base@1.0.1: + resolution: {integrity: sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==} + engines: {node: '>=0.10.0'} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + call-bind@1.0.9: + resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==} + engines: {node: '>= 0.4'} + + call-bound@1.0.4: + resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} + engines: {node: '>= 0.4'} + + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + + camelcase@6.3.0: + resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} + engines: {node: '>=10'} + + caniuse-lite@1.0.30001814: + resolution: {integrity: sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==} + + cfb@1.2.2: + resolution: {integrity: sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==} + engines: {node: '>=0.8'} + + chai@4.3.10: + resolution: {integrity: sha512-0UXG04VuVbruMUYbJ6JctvH0YnC/4q3/AkT18q4NaITo91CUm0liMS9VqzT9vZhVQ/1eqPanMWjBM+Juhfb/9g==} + engines: {node: '>=4'} + + chalk@1.1.3: + resolution: {integrity: sha512-U3lRVLMSlsCfjqYPbLyVv11M9CPW4I728d6TCKMAOJueEeB9/8o+eSsMnxPJD+Q+K909sdESg7C+tIkoH6on1A==} + engines: {node: '>=0.10.0'} + + chalk@4.0.0: + resolution: {integrity: sha512-N9oWFcegS0sFr9oh1oz2d7Npos6vNoWW9HvtCg5N1KRFpUhaAhvTv5Y58g880fZaEYSNm3qDz8SU1UrGvp+n7A==} + engines: {node: '>=10'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chalk@5.3.0: + resolution: {integrity: sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==} + engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} + + check-error@1.0.3: + resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==} + + chokidar@3.6.0: + resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} + engines: {node: '>= 8.10.0'} + + class-utils@0.3.6: + resolution: {integrity: sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==} + engines: {node: '>=0.10.0'} + + cli-cursor@4.0.0: + resolution: {integrity: sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + cli-truncate@4.0.0: + resolution: {integrity: sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==} + engines: {node: '>=18'} + + clipboard@2.0.11: + resolution: {integrity: sha512-C+0bbOqkezLIsmWSvlsXS0Q0bmkugu7jcfMIACB+RDEntIzQIkdr148we28AfSloQLRdZlYL/QYyrq05j/3Faw==} + + clone@2.1.2: + resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==} + engines: {node: '>=0.8'} + + codepage@1.15.0: + resolution: {integrity: sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==} + engines: {node: '>=0.8'} + + collection-visit@1.0.0: + resolution: {integrity: sha512-lNkKvzEeMBBjUGHZ+q6z9pSJla0KWAQPvtzhEV9+iGyQYG+pBpl7xKDhxoNSOZH2hhv0v5k0y2yAM4o4SjoSkw==} + engines: {node: '>=0.10.0'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + colorette@2.0.20: + resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@10.0.0: + resolution: {integrity: sha512-zS5PnTI22FIRM6ylNW8G4Ap0IEOyk62fhLSD0+uHRT9McRCLGpkVNvao4bjimpK/GShynyQkFFxHhwMcETmduA==} + engines: {node: '>=14'} + + commander@11.1.0: + resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} + engines: {node: '>=16'} + + commander@7.2.0: + resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} + engines: {node: '>= 10'} + + component-emitter@1.3.1: + resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==} + + compute-scroll-into-view@1.0.20: + resolution: {integrity: sha512-UCB0ioiyj8CRjtrvaceBLqqhZCVP+1B8+NWQhmdsm0VXOJtobBCf1dBQmebCCo34qZmUwZfIH2MZLqNHazrfjg==} + + computeds@0.0.1: + resolution: {integrity: sha512-7CEBgcMjVmitjYo5q8JTJVra6X5mQ20uTThdK+0kR7UEaDrAWEQcRiBtWJzga4eRpP6afNwwLsX2SET2JhVB1Q==} + + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + + confbox@0.1.8: + resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==} + + config-chain@1.1.13: + resolution: {integrity: sha512-qj+f8APARXHrM0hraqXYb2/bOVSV4PvJQlNZ/DVj0QrmNM2q2euizkeuVckQ57J+W0mRH6Hvi+k50M4Jul2VRQ==} + + consola@3.4.2: + resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} + engines: {node: ^14.18.0 || >=16.10.0} + + content-type@1.0.2: + resolution: {integrity: sha512-TFmXoAjJQD7hApJpE/GttZreniTw+DYE4zlDmPRc8Q75KXrU8hFt3Qeckml/mOTVAxwbMZ3WwdEcQCzTpfV5ZA==} + engines: {node: '>= 0.6'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + copy-descriptor@0.1.1: + resolution: {integrity: sha512-XgZ0pFcakEUlbwQEVNg3+QAis1FyTL3Qel9FYy8pSkQqoG3PNoT0bOCQtOXcOkur21r2Eq2kI+IE+gsmAEVlYw==} + engines: {node: '>=0.10.0'} + + copy-to@2.0.1: + resolution: {integrity: sha512-3DdaFaU/Zf1AnpLiFDeNCD4TOWe3Zl2RZaTzUvWiIk5ERzcCodOE20Vqq4fzCbNoHURFHT4/us/Lfq+S2zyY4w==} + + core-js@2.6.12: + resolution: {integrity: sha512-Kb2wC0fvsWfQrgk8HU5lW6U/Lcs8+9aaYcy4ZFc6DDlo4nZ7n70dEgE5rtR0oG6ufKDUnrwfWL1mXR5ljDatrQ==} + deprecated: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js. + + core-util-is@1.0.3: + resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} + + cors@2.8.6: + resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} + engines: {node: '>= 0.10'} + + cos-js-sdk-v5@1.10.1: + resolution: {integrity: sha512-a4SRfCY5g6Z35C7OWe9te/S1zk77rVQzfpvZ33gmTdJQzKxbNbEG7Aw/v453XwVMsQB352FIf7KRMm5Ya/wlZQ==} + + crc-32@1.2.2: + resolution: {integrity: sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==} + engines: {node: '>=0.8'} + hasBin: true + + cropperjs@1.6.3: + resolution: {integrity: sha512-BRb0PRIzjbfM5n+i6L2D85pSbXI/w6cnnwb9W9cRKgAmbiP+OjDeq+Irhd86IujZDXm/7JWECfscllFIdrlmfw==} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + crypto-js@4.2.0: + resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==} + deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained. + + css-select@4.1.3: + resolution: {integrity: sha512-gT3wBNd9Nj49rAbmtFHj1cljIAOLYSX1nZ8CB7TBO3INYckygm5B7LISU/szY//YmdiSLbJvDLOx9VnMVpMBxA==} + + css-select@5.1.0: + resolution: {integrity: sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==} + + css-tree@1.1.3: + resolution: {integrity: sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q==} + engines: {node: '>=8.0.0'} + + css-tree@2.2.0: + resolution: {integrity: sha512-7y32czN0VBL8WkevhC/mrHnoHOmQaJ1Wvp8sjRuTz6/n9cjL83jQaUru2MvP7kzjpGVwrSy5CE4XyQObWGIHQQ==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'} + + css-tree@2.3.1: + resolution: {integrity: sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + + css-what@5.0.0: + resolution: {integrity: sha512-qxyKHQvgKwzwDWC/rGbT821eJalfupxYW2qbSJSAtdSTimsr/MlaGONoNLllaUPZWf8QnbcKM/kPVYUQuEKAFA==} + engines: {node: '>= 6'} + + css-what@6.1.0: + resolution: {integrity: sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==} + engines: {node: '>= 6'} + + cssesc@3.0.0: + resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} + engines: {node: '>=4'} + hasBin: true + + csso@4.2.0: + resolution: {integrity: sha512-wvlcdIbf6pwKEk7vHj8/Bkc0B4ylXZruLvOgs9doS5eOsOpuodOV2zJChSpkp+pRpYQLQMeF04nr3Z68Sta9jA==} + engines: {node: '>=8.0.0'} + + csso@5.0.5: + resolution: {integrity: sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0, npm: '>=7.0.0'} + + cssstyle@4.0.1: + resolution: {integrity: sha512-8ZYiJ3A/3OkDd093CBT/0UKDWry7ak4BdPTFP2+QEP7cmhouyq/Up709ASSj2cK02BbZiMgk7kYjZNS4QP5qrQ==} + engines: {node: '>=18'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + d@1.0.2: + resolution: {integrity: sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==} + engines: {node: '>=0.12'} + + data-urls@5.0.0: + resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==} + engines: {node: '>=18'} + + data-view-buffer@1.0.2: + resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} + engines: {node: '>= 0.4'} + + data-view-byte-length@1.0.2: + resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} + engines: {node: '>= 0.4'} + + data-view-byte-offset@1.0.1: + resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} + engines: {node: '>= 0.4'} + + dateformat@2.2.0: + resolution: {integrity: sha512-GODcnWq3YGoTnygPfi02ygEiRxqUxpJwuRHjdhJYuxpcZmDq4rjBiXYmbCCzStxo176ixfLT6i4NPwQooRySnw==} + + dayjs@1.11.10: + resolution: {integrity: sha512-vjAczensTgRcqDERK0SR2XMwsF/tSvnvlv6VcF2GIhg6Sx4yOIt/irsr1RDJsKiIyBzJDpCoXiWWq28MqH2cnQ==} + + dayjs@1.11.23: + resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==} + + de-indent@1.0.2: + resolution: {integrity: sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==} + + debug@2.6.9: + resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + debug@4.3.4: + resolution: {integrity: sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + decode-uri-component@0.2.0: + resolution: {integrity: sha512-hjf+xovcEn31w/EUYdTXQh/8smFL/dzYjohQGEIgjyNavaJfBY2p5F527Bo1VPATxv0VYTUC2bOcXvqFwk78Og==} + engines: {node: '>=0.10'} + + deep-eql@4.1.4: + resolution: {integrity: sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==} + engines: {node: '>=6'} + + deep-equal@1.1.2: + resolution: {integrity: sha512-5tdhKF6DbU7iIzrIOa1AOUt39ZRm13cmL1cGEh//aqR8x9+tNfbywRf0n5FD/18OKMdo7DNEtrX2t22ZAkI+eg==} + engines: {node: '>= 0.4'} + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + default-browser-id@3.0.0: + resolution: {integrity: sha512-OZ1y3y0SqSICtE8DE4S8YOE9UZOJ8wO16fKWVP5J1Qz42kV9jcnMVFrEE/noXb/ss3Q4pZIH79kxofzyNNtUNA==} + engines: {node: '>=12'} + + default-browser@4.0.0: + resolution: {integrity: sha512-wX5pXO1+BrhMkSbROFsyxUm0i/cJEScyNhA4PPxc41ICuv05ZZB/MX28s8aZx6xjmatvebIapF6hLEKEcpneUA==} + engines: {node: '>=14.16'} + + default-user-agent@1.0.0: + resolution: {integrity: sha512-bDF7bg6OSNcSwFWPu4zYKpVkJZQYVrAANMYB8bc9Szem1D0yKdm4sa/rOCs2aC9+2GMqQ7KnwtZRvDhmLF0dXw==} + engines: {node: '>= 0.10.0'} + + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-lazy-prop@3.0.0: + resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==} + engines: {node: '>=12'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + + define-property@0.2.5: + resolution: {integrity: sha512-Rr7ADjQZenceVOAKop6ALkkRAmH1A4Gx9hV/7ZujPUN2rkATqFO0JZLZInbAjpZYoJ1gUx8MRMQVkYemcbMSTA==} + engines: {node: '>=0.10.0'} + + define-property@1.0.0: + resolution: {integrity: sha512-cZTYKFWspt9jZsMscWo8sc/5lbPC9Q0N5nBLgb+Yd915iL3udB1uFgS3B8YCx66UVHq018DAVFoee7x+gxggeA==} + engines: {node: '>=0.10.0'} + + define-property@2.0.2: + resolution: {integrity: sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==} + engines: {node: '>=0.10.0'} + + defu@6.1.7: + resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + delegate@3.2.0: + resolution: {integrity: sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw==} + + destr@2.0.5: + resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==} + + destroy@1.2.0: + resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} + engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + + diff-sequences@29.6.3: + resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + digest-header@1.1.0: + resolution: {integrity: sha512-glXVh42vz40yZb9Cq2oMOt70FIoWiv+vxNvdKdU8CwjLad25qHM3trLxhl9bVjdr6WaslIXhWpn0NO8T/67Qjg==} + engines: {node: '>= 8.0.0'} + + dir-glob@3.0.1: + resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} + engines: {node: '>=8'} + + doctrine@3.0.0: + resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} + engines: {node: '>=6.0.0'} + + dom-serializer@1.0.1: + resolution: {integrity: sha512-1Aj1Qy3YLbdslkI75QEOfdp9TkQ3o8LRISAzxOibjBs/xWwr1WxZFOQphFkZuepHFGo+kB8e5FVJSS0faAJ4Rw==} + + dom-serializer@2.0.0: + resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} + + dom-zindex@1.0.7: + resolution: {integrity: sha512-cKU/h8v8IPBgdZOTPbPmq3Ib+Ac5C+kKoh9I4LbGR9BM3GwbmB16KYWKJcj5M2BavnA66EbgYzxYDLd1IytnlQ==} + + dom7@3.0.0: + resolution: {integrity: sha512-oNlcUdHsC4zb7Msx7JN3K0Nro1dzJ48knvBOnDPKJ2GV9wl1i5vydJZUSyOfrkKFDZEud/jBsTk92S/VGSAe/g==} + + domelementtype@1.0.0: + resolution: {integrity: sha512-SvYc2cmxJwtg1BCgacD1YA8hh6BPcTupLJt4dRHkk7tSUeiEvDCct1+KQx99upAntvL/YFTT7oOXAiYuhvDmWA==} + + domelementtype@2.3.0: + resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} + + domhandler@2.3.0: + resolution: {integrity: sha512-q9bUwjfp7Eif8jWxxxPSykdRZAb6GkguBGSgvvCrhI9wB71W2K/Kvv4E61CF/mcCfnVJDeDWx/Vb/uAqbDj6UQ==} + + domhandler@3.0.0: + resolution: {integrity: sha512-eKLdI5v9m67kbXQbJSNn1zjh0SDzvzWVWtX+qEI3eMjZw8daH9k8rlj1FZY9memPwjiskQFbe7vHVVJIAqoEhw==} + engines: {node: '>= 4'} + + domhandler@4.2.0: + resolution: {integrity: sha512-zk7sgt970kzPks2Bf+dwT/PLzghLnsivb9CcxkvR8Mzr66Olr0Ofd8neSbglHJHaHa2MadfoSdNlKYAaafmWfA==} + engines: {node: '>= 4'} + + domhandler@5.0.2: + resolution: {integrity: sha512-pr8ToPIuwBonzUy42STpc5Cf0m69zsQ7gtCLLvKrTbhVRnRohT2pLiJmGp3PAh16nDVWpYpcRpdjuk1vFmnQUg==} + engines: {node: '>= 4'} + + domutils@1.5.0: + resolution: {integrity: sha512-389qXukJlNZvjy3XHPpMc295cZsUus5XklwdkeMqJWlro86MbHg7WH8FMoIEC4VeAlKjFTdGeDgRr+mjJ8bZFg==} + + domutils@2.6.0: + resolution: {integrity: sha512-y0BezHuy4MDYxh6OvolXYsH+1EMGmFbwv5FKW7ovwMG6zTPWqNPq3WF9ayZssFq+UlKdffGLbOEaghNdaOm1WA==} + + domutils@3.0.1: + resolution: {integrity: sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + duplexer@0.1.2: + resolution: {integrity: sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==} + + duplexify@3.7.1: + resolution: {integrity: sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==} + + eastasianwidth@0.2.0: + resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + + editorconfig@1.0.7: + resolution: {integrity: sha512-e0GOtq/aTQhVdNyDU9e02+wz9oDDM+SIOQxWME2QRjzRX5yyLAuHDE+0aE8vHb9XRC8XD37eO2u57+F09JqFhw==} + engines: {node: '>=14'} + hasBin: true + + ee-first@1.1.1: + resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + + electron-to-chromium@1.5.449: + resolution: {integrity: sha512-dKeYk/3SFQz+nXi5whp3OuJzeWABEG4zCtkWJ9+Vby1E1iFM2y0gElRtQvNXRPJTsj8WAF4HMP7hvP790QtJ9g==} + + element-plus@2.9.11: + resolution: {integrity: sha512-x4L/6YC8de4JtuE3vpaEugJdQIeHQaHtIYKyk67IeF6dTIiVax45aX4nWOygnh+xX+0gTvL6xO+9BZhPA3G82w==} + peerDependencies: + vue: ^3.2.0 + + emoji-regex@10.3.0: + resolution: {integrity: sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + + emojis-list@3.0.0: + resolution: {integrity: sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==} + engines: {node: '>= 4'} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + end-or-error@1.0.1: + resolution: {integrity: sha512-OclLMSug+k2A0JKuf494im25ANRBVW8qsjmwbgX7lQ8P82H21PQ1PWkoYwb9y5yMBS69BPlwtzdIFClo3+7kOQ==} + engines: {node: '>= 0.11.14'} + + entities@1.0.0: + resolution: {integrity: sha512-LbLqfXgJMmy81t+7c14mnulFHJ170cM6E+0vMXR9k/ZiZwgX8i5pNgjTCX3SO4VeUsFLV+8InixoretwU+MjBQ==} + + entities@2.0.0: + resolution: {integrity: sha512-D9f7V0JSRwIxlRI2mjMqufDrRDnx8p+eEOz7aUM9SuvF8gsBzra0/6tbjl1m8eQHrZlYj6PxqE00hZ1SAIKPLw==} + + entities@4.2.0: + resolution: {integrity: sha512-wEJa03bJgqEwPnkUqYdgmcfUXfm6+4hePQhntIvRy/1/+C4dFuhYHsgKBRjbQ6OWBh42P+VhAoCDO77DUh0e/Q==} + engines: {node: '>=0.12'} + + entities@4.4.0: + resolution: {integrity: sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==} + engines: {node: '>=0.12'} + + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + es-abstract-get@1.0.0: + resolution: {integrity: sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==} + engines: {node: '>= 0.4'} + + es-abstract@1.24.2: + resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==} + engines: {node: '>= 0.4'} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + es-to-primitive@1.3.4: + resolution: {integrity: sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==} + engines: {node: '>= 0.4'} + + es5-ext@0.10.64: + resolution: {integrity: sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==} + engines: {node: '>=0.10'} + + es6-iterator@2.0.3: + resolution: {integrity: sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==} + + es6-symbol@3.1.4: + resolution: {integrity: sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==} + engines: {node: '>=0.12'} + + esbuild@0.21.3: + resolution: {integrity: sha512-Kgq0/ZsAPzKrbOjCQcjoSmPoWhlcVnGAUo7jvaLHoxW1Drto0KGkR1xBNg2Cp43b9ImvxmPEJZ9xkfcnqPsfBw==} + engines: {node: '>=12'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-html@1.0.3: + resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + + escape-string-regexp@1.0.5: + resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==} + engines: {node: '>=0.8.0'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-config-prettier@9.1.2: + resolution: {integrity: sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==} + hasBin: true + peerDependencies: + eslint: '>=7.0.0' + + eslint-plugin-prettier@5.1.3: + resolution: {integrity: sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + '@types/eslint': '>=8.0.0' + eslint: '>=8.0.0' + eslint-config-prettier: '*' + prettier: '>=3.0.0' + peerDependenciesMeta: + '@types/eslint': + optional: true + eslint-config-prettier: + optional: true + + eslint-plugin-prettier@5.5.6: + resolution: {integrity: sha512-ifetmTcxWfz+4qRW3pH/ujdTq2jQIj59AxJMIN26K5avYgU8dxycUETQonWiW+wPrYXA0j3Try0l1CnwVQtDqQ==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + '@types/eslint': '>=8.0.0' + eslint: '>=8.0.0' + eslint-config-prettier: '>= 7.0.0 <10.0.0 || >=10.1.0' + prettier: '>=3.0.0' + peerDependenciesMeta: + '@types/eslint': + optional: true + eslint-config-prettier: + optional: true + + eslint-plugin-vue@9.23.0: + resolution: {integrity: sha512-Bqd/b7hGYGrlV+wP/g77tjyFmp81lh5TMw0be9093X02SyelxRRfCI6/IsGq/J7Um0YwB9s0Ry0wlFyjPdmtUw==} + engines: {node: ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.2.0 || ^7.0.0 || ^8.0.0 + + eslint-scope@7.1.1: + resolution: {integrity: sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-scope@7.2.2: + resolution: {integrity: sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@3.3.0: + resolution: {integrity: sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@3.4.1: + resolution: {integrity: sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint@8.57.0: + resolution: {integrity: sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. + hasBin: true + + esniff@2.0.1: + resolution: {integrity: sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==} + engines: {node: '>=0.10'} + + espree@9.3.1: + resolution: {integrity: sha512-bvdyLmJMfwkV3NCRl5ZhJf22zBFo1y8bYh3VYb+bfzqNB4Je68P2sSuXyuFquzWLebHpNd2/d5uv7yoP9ISnGQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + espree@9.6.1: + resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@2.0.2: + resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + + event-emitter@0.3.5: + resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==} + + eventemitter3@2.0.3: + resolution: {integrity: sha512-jLN68Dx5kyFHaePoXWPsCGW5qdyZQtLYHkxkg02/Mz6g0kYpDx4FyP6XfArhQdlOC4b8Mv+EMxPo/8La7Tzghg==} + + eventemitter3@5.0.4: + resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} + + execa@5.0.0: + resolution: {integrity: sha512-ov6w/2LCiuyO4RLYGdpFGjkcs0wMTgGE8PrkTHikeUy5iJekXyPIKUjifk5CsE0pt7sMCrMZ3YNqoCj6idQOnQ==} + engines: {node: '>=10'} + + execa@5.1.1: + resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} + engines: {node: '>=10'} + + execa@7.1.1: + resolution: {integrity: sha512-wH0eMf/UXckdUYnO21+HDztteVv05rq2GXksxT4fCGeHkBhw1DROXh40wcjMcRqDOWE7iPJ4n3M7e2+YFP+76Q==} + engines: {node: ^14.18.0 || ^16.14.0 || >=18.0.0} + + execa@8.0.1: + resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==} + engines: {node: '>=16.17'} + + expand-brackets@2.1.4: + resolution: {integrity: sha512-w/ozOKR9Obk3qoWeY/WDi6MFta9AoMR+zud60mdnbniMcBxRuFJyDt2LdX/14A1UABeqk+Uk+LDfUpvoGKppZA==} + engines: {node: '>=0.10.0'} + + ext@1.7.0: + resolution: {integrity: sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==} + + extend-shallow@2.0.1: + resolution: {integrity: sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==} + engines: {node: '>=0.10.0'} + + extend-shallow@3.0.2: + resolution: {integrity: sha512-BwY5b5Ql4+qZoefgMj2NUmx+tehVTH/Kf4k1ZEtOHNFcm2wSxMRo992l6X3TIgni2eZVTZ85xMOjF31fwZAj6Q==} + engines: {node: '>=0.10.0'} + + extend@3.0.2: + resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} + + extglob@2.0.4: + resolution: {integrity: sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==} + engines: {node: '>=0.10.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-diff@1.1.2: + resolution: {integrity: sha512-KaJUt+M9t1qaIteSvjc6P3RbMdXsNhK61GRftR6SNxqmhthcd9MGIi4T+o0jD8LUSpSnSKXE20nLtJ3fOHxQig==} + + fast-diff@1.3.0: + resolution: {integrity: sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==} + + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fast-xml-parser@4.5.0: + resolution: {integrity: sha512-/PlTQCI96+fZMAOLMZK4CWG1ItCbfZ/0jx7UIJFChPNrx7tcEgerUgWbeieCM9MfHInUDyK8DWYZ+YrywDJuTg==} + hasBin: true + + fastq@1.20.3: + resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + + file-entry-cache@6.0.1: + resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} + engines: {node: ^10.12.0 || >=12.0.0} + + file-saver@2.0.5: + resolution: {integrity: sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==} + + fill-range@4.0.0: + resolution: {integrity: sha512-VcpLTWqWDiTerugjj8e3+esbg+skS3M9e54UuR3iCeIDMXCLTsAH8hTSzDQU/X6/6t3eYkOKoZSef2PlU6U1XQ==} + engines: {node: '>=0.10.0'} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@3.0.4: + resolution: {integrity: sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==} + engines: {node: ^10.12.0 || >=12.0.0} + + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + + follow-redirects@1.16.1: + resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + + for-each@0.3.5: + resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} + engines: {node: '>= 0.4'} + + for-in@1.0.2: + resolution: {integrity: sha512-7EwmXrOjyL+ChxMhmG5lnW9MPt1aIeZEwKhQzoBUdTV0N3zuwWDZYVJatDvZ2OyzPUvdIAZDsCetk3coyMfcnQ==} + engines: {node: '>=0.10.0'} + + foreground-child@3.1.0: + resolution: {integrity: sha512-lXeSPRCndWPaipZbtI4CkvTZpF6OPsy19dkvf7+5AHeJD+w+iAKPc9Q78xWBmX4SdR+8xrtY9jTXs/YDv8q+Ug==} + engines: {node: '>=14'} + + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} + engines: {node: '>= 6'} + + formstream@1.5.2: + resolution: {integrity: sha512-NASf0lgxC1AyKNXQIrXTEYkiX99LhCEXTkiGObXAkpBui86a4u8FjH1o2bGb3PpqI3kafC+yw4zWeK6l6VHTgg==} + + frac@1.1.2: + resolution: {integrity: sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==} + engines: {node: '>=0.8'} + + fragment-cache@0.2.1: + resolution: {integrity: sha512-GMBAbW9antB8iZRHLoGw0b3HANt57diZYFO/HL1JGIC1MjKrdmhxvrJbupnVvpys0zsz7yBApXdQyfepKly2kA==} + engines: {node: '>=0.10.0'} + + fs-extra@10.0.0: + resolution: {integrity: sha512-C5owb14u9eJwizKGdchcDUQeFtlSHHthBk8pbX9Vc1PFZrLombudjDnNns88aYslCyF6IY5SUw3Roz6xShcEIQ==} + engines: {node: '>=12'} + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + function.prototype.name@1.2.0: + resolution: {integrity: sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==} + engines: {node: '>= 0.4'} + + functions-have-names@1.2.3: + resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} + + generator-function@2.0.1: + resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} + engines: {node: '>= 0.4'} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + get-east-asian-width@1.7.0: + resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} + engines: {node: '>=18'} + + get-func-name@2.0.2: + resolution: {integrity: sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + get-ready@1.0.0: + resolution: {integrity: sha512-mFXCZPJIlcYcth+N8267+mghfYN9h3EhsDa6JSnbA3Wrhh/XFpuowviFcsDeYZtKspQyWyJqfs4O6P8CHeTwzw==} + + get-stream@6.0.1: + resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} + engines: {node: '>=10'} + + get-stream@8.0.1: + resolution: {integrity: sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==} + engines: {node: '>=16'} + + get-symbol-description@1.1.0: + resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} + engines: {node: '>= 0.4'} + + get-value@2.0.6: + resolution: {integrity: sha512-Ln0UQDlxH1BapMu3GPtf7CuYNwRZf2gwCuPqbyG6pB8WfmFpzqcy4xtAaAMUhnNqjMKTiCPZG2oMT3YSx8U2NA==} + engines: {node: '>=0.10.0'} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + + glob@7.2.0: + resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + + glob@8.1.0: + resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==} + engines: {node: '>=12'} + deprecated: Glob versions prior to v9 are no longer supported + + globals@13.19.0: + resolution: {integrity: sha512-dkQ957uSRWHw7CFXLUtUHQI3g3aWApYhfNR2O6jn/907riyTYKVBmxYVROkBcY614FSSeSJh7Xm7SrUWCxvJMQ==} + engines: {node: '>=8'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + + globby@11.1.0: + resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} + engines: {node: '>=10'} + + good-listener@1.2.2: + resolution: {integrity: sha512-goW1b+d9q/HIwbVYZzZ6SsTr4IgE+WA44A0GmPIQstuOrgsFcT7VEJ48nmr9GaRtNu0XTKacFLGnBPAM6Afouw==} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + graphemer@1.4.0: + resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + + gzip-size@6.0.0: + resolution: {integrity: sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==} + engines: {node: '>=10'} + + has-ansi@2.0.0: + resolution: {integrity: sha512-C8vBJ8DwUCx19vhm7urhTuUsr4/IyP6l4VzNQDv+ryHQObW3TTTp9yB68WpYgRe2bbaGuZ/se74IqFeVnMnLZg==} + engines: {node: '>=0.10.0'} + + has-bigints@1.1.0: + resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} + engines: {node: '>= 0.4'} + + has-flag@1.0.0: + resolution: {integrity: sha512-DyYHfIYwAJmjAjSSPKANxI8bFY9YtFrgkAfinBojQ8YJTOuOuav64tMUJv584SES4xl74PmuaevIyaLESHdTAA==} + engines: {node: '>=0.10.0'} + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + + has-proto@1.2.0: + resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} + engines: {node: '>= 0.4'} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + has-value@0.3.1: + resolution: {integrity: sha512-gpG936j8/MzaeID5Yif+577c17TxaDmhuyVgSwtnL/q8UUTySg8Mecb+8Cf1otgLoD7DDH75axp86ER7LFsf3Q==} + engines: {node: '>=0.10.0'} + + has-value@1.0.0: + resolution: {integrity: sha512-IBXk4GTsLYdQ7Rvt+GRBrFSVEkmuOUy4re0Xjd9kJSUQpnTrWR4/y9RpfexN9vkAPMFuQoeWKwqzPozRTlasGw==} + engines: {node: '>=0.10.0'} + + has-values@0.1.4: + resolution: {integrity: sha512-J8S0cEdWuQbqD9//tlZxiMuMNmxB8PlEwvYwuxsTmR1G5RXUePEX/SJn7aD0GMLieuZYSwNH0cQuJGwnYunXRQ==} + engines: {node: '>=0.10.0'} + + has-values@1.0.0: + resolution: {integrity: sha512-ODYZC64uqzmtfGMEAX/FvZiRyWLpAC3vYnNunURUnkGVTS+mI0smVsWaPydRBsE3g+ok7h960jChO8mFcWlHaQ==} + engines: {node: '>=0.10.0'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + he@1.1.1: + resolution: {integrity: sha512-z/GDPjlRMNOa2XJiB4em8wJpuuBfrFOlYKTZxtpkdr1uPdibHI8rYA3MY0KDObpVyaes0e/aunid/t88ZI2EKA==} + hasBin: true + + he@1.2.0: + resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} + hasBin: true + + html-encoding-sniffer@4.0.0: + resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==} + engines: {node: '>=18'} + + html-tags@3.3.1: + resolution: {integrity: sha512-ztqyC3kLto0e9WbNp0aeP+M3kTt+nbaIveGmUxAtZa+8iFgKLUOD4YKM5j+f3QD89bra7UeumolZHKuOXnTmeQ==} + engines: {node: '>=8'} + + html-void-elements@2.0.1: + resolution: {integrity: sha512-0quDb7s97CfemeJAnW9wC0hw78MtW7NU3hqtCD75g2vFlDLt36llsYD7uB7SUzojLMP24N5IatXf7ylGXiGG9A==} + + htmlparser2@3.8.3: + resolution: {integrity: sha512-hBxEg3CYXe+rPIua8ETe7tmG3XDn9B0edOE/e9wH2nLczxzgdu0m0aNHY+5wFZiviLWLdANPJTssa92dMcXQ5Q==} + + http-proxy-agent@7.0.0: + resolution: {integrity: sha512-+ZT+iBxVUQ1asugqnD6oWoRiS25AkjNfG085dKJGtGxkdwLQrMKU5wJr2bOOFAXzKcTuqq+7fZlTMgG3SRfIYQ==} + engines: {node: '>= 14'} + + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + + https-proxy-agent@7.0.2: + resolution: {integrity: sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==} + engines: {node: '>= 14'} + + human-signals@2.1.0: + resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} + engines: {node: '>=10.17.0'} + + human-signals@4.3.1: + resolution: {integrity: sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ==} + engines: {node: '>=14.18.0'} + + human-signals@5.0.0: + resolution: {integrity: sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==} + engines: {node: '>=16.17.0'} + + humanize-duration@3.35.0: + resolution: {integrity: sha512-+KYh+R85n1yadHHwy/QXF0JgPq5NPPBNrvigA5aAKrlKFd0bJpMx7wE3Xd6rM0kEaBQMCFrdMihkaDSgWERNvQ==} + + humanize-ms@1.2.1: + resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==} + + husky@9.0.11: + resolution: {integrity: sha512-AB6lFlbwwyIqMdHYhwPe+kjOC3Oc5P3nThEoW/AaO2BX3vJDjWPFxYLxokUZOo6RNX20He3AaT8sESs9NJcmEw==} + engines: {node: '>=18'} + hasBin: true + + i18next@20.4.0: + resolution: {integrity: sha512-89iWWJudmaHJwzIdJ/1eu98GtsJnwBhOUWwlAre70itPMuTE/NTPtgVeaS1CGaB8Q3XrYBGpEqlq4jsScDx9kg==} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + ignore@5.2.0: + resolution: {integrity: sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==} + engines: {node: '>= 4'} + + ignore@5.2.4: + resolution: {integrity: sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==} + engines: {node: '>= 4'} + + image-size@0.5.1: + resolution: {integrity: sha512-mFIGpGG9OtwbyPivj+E97lKOC9IICkXa6UZZ+2eD/wDineTOPrarpUnYiMdpOv5cGzSxkuFMPZG8ANO2CpXCaw==} + engines: {node: '>=0.10.0'} + hasBin: true + + immer@9.0.6: + resolution: {integrity: sha512-G95ivKpy+EvVAnAab4fVa4YGYn24J1SpEktnJX7JJ45Bd7xqME/SCplFzYFmTbrkwZbQ4xJK1xMTUYBkN6pWsQ==} + + immutable@4.3.9: + resolution: {integrity: sha512-ObHy4YN7ycwZOUCLI1/6svfyAFu7vL8RhAvVu/bh/RZW9EPlOyDaQ9jDQWCtdqzaXUjgXZCW1migtHE7YI7UGQ==} + + import-fresh@3.2.1: + resolution: {integrity: sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ==} + engines: {node: '>=6'} + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.4: + resolution: {integrity: sha512-VUA7WAWNCWfm6/8f9kAb8Y6iGBWnmCfgFS5dTrv2C38LLm1KUmpY388mCVCJCsMKQomvOQ1oW8/edXdChd9ZXQ==} + deprecated: Please update to ini >=1.3.6 to avoid a prototype pollution issue + + internal-slot@1.1.0: + resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} + engines: {node: '>= 0.4'} + + is-accessor-descriptor@1.0.2: + resolution: {integrity: sha512-AIbwAcazqP3R65dGvqk1V+a+vE5Fg1yu/ZKMOiBWSUIXXiwQkYmXQcVa2O0nh0tSDKDFKxG2mY7dB1Sr4hEP1g==} + engines: {node: '>= 0.4'} + + is-arguments@1.2.0: + resolution: {integrity: sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==} + engines: {node: '>= 0.4'} + + is-array-buffer@3.0.5: + resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} + engines: {node: '>= 0.4'} + + is-async-function@2.1.1: + resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==} + engines: {node: '>= 0.4'} + + is-bigint@1.1.0: + resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} + engines: {node: '>= 0.4'} + + is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + + is-boolean-object@1.2.2: + resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} + engines: {node: '>= 0.4'} + + is-buffer@1.1.6: + resolution: {integrity: sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==} + + is-callable@1.2.7: + resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} + engines: {node: '>= 0.4'} + + is-class-hotfix@0.0.6: + resolution: {integrity: sha512-0n+pzCC6ICtVr/WXnN2f03TK/3BfXY7me4cjCAqT8TYXEl0+JBRoqBo94JJHXcyDSLUeWbNX8Fvy5g5RJdAstQ==} + + is-data-descriptor@1.0.1: + resolution: {integrity: sha512-bc4NlCDiCr28U4aEsQ3Qs2491gVq4V8G7MQyws968ImqjKuYtTJXrl7Vq7jsN7Ly/C3xj5KWFrY7sHNeDkAzXw==} + engines: {node: '>= 0.4'} + + is-data-view@1.0.2: + resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} + engines: {node: '>= 0.4'} + + is-date-object@1.1.0: + resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} + engines: {node: '>= 0.4'} + + is-descriptor@0.1.8: + resolution: {integrity: sha512-SceYGWXvdqlWa/OnQ5FQuV+NxvNmMRhMw/w9AHkH71hTzveND4BTYgvp16g+oITK47qbOl/3D0bl0iygehWAWQ==} + engines: {node: '>= 0.4'} + + is-descriptor@1.0.4: + resolution: {integrity: sha512-bv5z95W0dDtLfKwDfkTNxaRxmISBD3eQBKJeVxv2AQ7MjuUnDNG7cIQqvFtMOUYhsILWHhMayWdoGqNqYYYjww==} + engines: {node: '>= 0.4'} + + is-docker@2.2.1: + resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==} + engines: {node: '>=8'} + hasBin: true + + is-docker@3.0.0: + resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + hasBin: true + + is-document.all@1.0.0: + resolution: {integrity: sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==} + engines: {node: '>= 0.4'} + + is-extendable@0.1.1: + resolution: {integrity: sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==} + engines: {node: '>=0.10.0'} + + is-extendable@1.0.1: + resolution: {integrity: sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==} + engines: {node: '>=0.10.0'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-finalizationregistry@1.1.1: + resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} + engines: {node: '>= 0.4'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-fullwidth-code-point@4.0.0: + resolution: {integrity: sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==} + engines: {node: '>=12'} + + is-fullwidth-code-point@5.1.0: + resolution: {integrity: sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==} + engines: {node: '>=18'} + + is-generator-function@1.1.2: + resolution: {integrity: sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==} + engines: {node: '>= 0.4'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-hotkey@0.2.0: + resolution: {integrity: sha512-UknnZK4RakDmTgz4PI1wIph5yxSs/mvChWs9ifnlXsKuXgWmOkY/hAE0H/k2MIqH0RlRye0i1oC07MCRSD28Mw==} + + is-inside-container@1.0.0: + resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==} + engines: {node: '>=14.16'} + hasBin: true + + is-map@2.0.3: + resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} + engines: {node: '>= 0.4'} + + is-negative-zero@2.0.3: + resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==} + engines: {node: '>= 0.4'} + + is-number-object@1.1.1: + resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} + engines: {node: '>= 0.4'} + + is-number@3.0.0: + resolution: {integrity: sha512-4cboCqIpliH+mAvFNegjZQ4kgKc3ZUhQVr3HvWbSh5q3WH2v82ct+T2Y1hdU5Gdtorx/cLifQjqCbL7bpznLTg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-path-inside@3.0.3: + resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} + engines: {node: '>=8'} + + is-plain-obj@1.1.0: + resolution: {integrity: sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==} + engines: {node: '>=0.10.0'} + + is-plain-object@2.0.3: + resolution: {integrity: sha512-4QumWYGOyh/PBXAjqTavDrW61AXQMo9MddhHneiqHZkeql0uKV6ytfEPQuZFNf/hoaRi8ooNYFvQBC5tI3i8xA==} + engines: {node: '>=0.10.0'} + + is-plain-object@2.0.4: + resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} + engines: {node: '>=0.10.0'} + + is-plain-object@5.1.0: + resolution: {integrity: sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==} + engines: {node: '>=0.10.0'} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + is-regex@1.2.1: + resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} + engines: {node: '>= 0.4'} + + is-set@2.0.3: + resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} + engines: {node: '>= 0.4'} + + is-shared-array-buffer@1.0.4: + resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} + engines: {node: '>= 0.4'} + + is-stream@2.0.1: + resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} + engines: {node: '>=8'} + + is-stream@3.0.0: + resolution: {integrity: sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + is-string@1.1.1: + resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} + engines: {node: '>= 0.4'} + + is-symbol@1.1.1: + resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} + engines: {node: '>= 0.4'} + + is-type-of@1.4.0: + resolution: {integrity: sha512-EddYllaovi5ysMLMEN7yzHEKh8A850cZ7pykrY1aNRQGn/CDjRDE9qEWbIdt7xGEVJmjBXzU/fNnC4ABTm8tEQ==} + + is-typed-array@1.1.15: + resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} + engines: {node: '>= 0.4'} + + is-url@1.2.4: + resolution: {integrity: sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==} + + is-weakmap@2.0.2: + resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} + engines: {node: '>= 0.4'} + + is-weakref@1.1.1: + resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==} + engines: {node: '>= 0.4'} + + is-weakset@2.0.4: + resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} + engines: {node: '>= 0.4'} + + is-windows@1.0.2: + resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==} + engines: {node: '>=0.10.0'} + + is-wsl@2.2.0: + resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} + engines: {node: '>=8'} + + isarray@0.0.1: + resolution: {integrity: sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==} + + isarray@1.0.0: + resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} + + isarray@2.0.5: + resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + isobject@2.0.0: + resolution: {integrity: sha512-r4CAG0OFgyZDPfDEhVOHKjegEkzIO2kJP+hhI/07kkcg6Ap9AGVh19CfXGUzpMCP4hQ0liYJQogg505amBHG7w==} + engines: {node: '>=0.10.0'} + + isobject@2.1.0: + resolution: {integrity: sha512-+OUdGJlgjOBZDfxnDjYYG6zp487z0JGNQq3cYQYg5f5hKR+syHMsaztzGeml/4kGG55CSpKSpWTY+jYGgsHLgA==} + engines: {node: '>=0.10.0'} + + isobject@3.0.1: + resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} + engines: {node: '>=0.10.0'} + + isomorphic-ws@4.0.1: + resolution: {integrity: sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==} + peerDependencies: + ws: '*' + + isstream@0.1.2: + resolution: {integrity: sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==} + + jackspeak@3.1.2: + resolution: {integrity: sha512-kWmLKn2tRtfYMF/BakihVVRzBKOxz4gJMiL2Rj91WnAB5TPZumSH99R/Yf1qE1u4uRimvCSJfm6hnxohXeEXjQ==} + engines: {node: '>=14'} + + javascript-natural-sort@0.7.1: + resolution: {integrity: sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==} + + jiti@1.20.0: + resolution: {integrity: sha512-3TV69ZbrvV6U5DfQimop50jE9Dl6J8O1ja1dvBbMba/sZ3YBEQqJ2VZRoQPVnhlzjNtU1vaXRZVrVjU4qtm8yA==} + hasBin: true + + jmespath@0.16.0: + resolution: {integrity: sha512-9FzQjJ7MATs1tSpnco1K6ayiYE3figslrXA72G2HQ/n76RzvYlofyi5QM+iX4YRs/pu3yzxlVQSST23+dMDknw==} + engines: {node: '>= 0.6.0'} + + js-base64@2.1.9: + resolution: {integrity: sha512-f+5mYh8iF7FlF7zgmj/yqvvYQUHI0kAxGiLjIfNxZzqJ7RQNc4sjgp8crVJw0Kzv2O6aFGZWgMTnO71I9utHSg==} + + js-base64@2.5.2: + resolution: {integrity: sha512-Vg8czh0Q7sFBSUMWWArX/miJeBWYBPpdU/3M/DKSaekLMqrqVPaedp+5mZhie/r0lgrcaYBfwXatEew6gwgiQQ==} + + js-beautify@1.14.9: + resolution: {integrity: sha512-coM7xq1syLcMyuVGyToxcj2AlzhkDjmfklL8r0JgJ7A76wyGMpJ1oA35mr4APdYNO/o/4YY8H54NQIJzhMbhBg==} + engines: {node: '>=12'} + hasBin: true + + js-cookie@3.0.5: + resolution: {integrity: sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==} + engines: {node: '>=14'} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + js-tokens@8.0.2: + resolution: {integrity: sha512-Olnt+V7xYdvGze9YTbGFZIfQXuGV4R3nQwwl8BrtgaPE/wq8UFpUHWuTNc05saowhSr1ZO6tx+V6RjE9D5YQog==} + + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} + hasBin: true + + jsdom@24.0.0: + resolution: {integrity: sha512-UDS2NayCvmXSXVP6mpTj+73JnNQadZlr9N68189xib2tx5Mls7swlTNao26IoHv46BZJFvXygyRtyXd1feAk1A==} + engines: {node: '>=18'} + peerDependencies: + canvas: ^2.11.2 + peerDependenciesMeta: + canvas: + optional: true + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-source-map@0.6.1: + resolution: {integrity: sha512-1QoztHPsMQqhDq0hlXY5ZqcEdUzxQEIxgFkKl4WUp2pgShObl+9ovi4kRh2TfvAfxAoHOJ9vIMEqk3k4iex7tg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@1.0.2: + resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==} + hasBin: true + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + jsonc-parser@3.2.0: + resolution: {integrity: sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==} + + jsoneditor@9.10.2: + resolution: {integrity: sha512-sT9U8T9MB7We5uyCnofugqYPJtQ5rPJngFlvpdtyFTFKFjOMnlWE1jVhFwjTXwGBoFeiLS+S6rVuhIhJ35Jutw==} + + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + + jsonrepair@3.15.0: + resolution: {integrity: sha512-wy8OTjwsJwQRnQJkKnMJJ9vcytRdBPAgIF/Hy6+s1dAj42BHMKiyL8JzEieIl3JY7idt8eyHwBWTO8mh/+mtwA==} + hasBin: true + + jstoxml@2.0.0: + resolution: {integrity: sha512-Wcuph3jZ03JcZK5Cw3IQCipZScvne3nbpIAgjNSw9INP230YMJm/imjN9tywgpnl9H2heFF7Pi9Su4ZQq0rGrQ==} + + kind-of@3.2.2: + resolution: {integrity: sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ==} + engines: {node: '>=0.10.0'} + + kind-of@4.0.0: + resolution: {integrity: sha512-24XsCxmEbRwEDbz/qz3stgin8TTzZ1ESR56OMCN0ujYg+vRutNSiOj9bHH9u85DKgXguraugV5sFuvbD4FW/hw==} + engines: {node: '>=0.10.0'} + + kind-of@5.1.0: + resolution: {integrity: sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==} + engines: {node: '>=0.10.0'} + + kind-of@6.0.3: + resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} + engines: {node: '>=0.10.0'} + + kolorist@1.8.0: + resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lilconfig@3.0.0: + resolution: {integrity: sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==} + engines: {node: '>=14'} + + lint-staged@15.2.2: + resolution: {integrity: sha512-TiTt93OPh1OZOsb5B7k96A/ATl2AjIZo+vnzFZ6oHK5FuTk63ByDtxGQpHm+kFETjEWqgkF95M8FRXKR/LEBcw==} + engines: {node: '>=18.12.0'} + hasBin: true + + listr2@8.0.1: + resolution: {integrity: sha512-ovJXBXkKGfq+CwmKTjluEqFi3p4h8xvkxGQQAQan22YCgef4KZ1mKGjzfGh6PL6AW5Csw0QiQPNuQyH+6Xk3hA==} + engines: {node: '>=18.0.0'} + + loader-utils@1.4.2: + resolution: {integrity: sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==} + engines: {node: '>=4.0.0'} + + local-pkg@0.5.0: + resolution: {integrity: sha512-ok6z3qlYyCDS4ZEU27HaU6x/xZa9Whf8jD4ptH5UZTQYZVYeb9bnZ3ojVhiJNLiXK1Hfc0GNbLXcmZ5plLDDBg==} + engines: {node: '>=14'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash-es@4.17.21: + resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==} + + lodash-es@4.18.1: + resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} + + lodash-unified@1.0.3: + resolution: {integrity: sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==} + peerDependencies: + '@types/lodash-es': '*' + lodash: '*' + lodash-es: '*' + + lodash.camelcase@4.3.0: + resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==} + + lodash.clonedeep@4.5.0: + resolution: {integrity: sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==} + + lodash.debounce@4.0.8: + resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} + + lodash.foreach@4.5.0: + resolution: {integrity: sha512-aEXTF4d+m05rVOAUG3z4vZZ4xVexLKZGF0lIxuHZ1Hplpk/3B6Z1+/ICICYRLm7c41Z2xiejbkCkJoTlypoXhQ==} + + lodash.isequal@4.5.0: + resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==} + deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead. + + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + + lodash.throttle@4.1.1: + resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==} + + lodash.toarray@4.4.0: + resolution: {integrity: sha512-QyffEA3i5dma5q2490+SgCvDN0pXLmRGSyAANuVi0HQ01Pkfr9fuoKQW8wm1wGBnJITs/mS7wQvS6VshUEBFCw==} + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + log-update@6.0.0: + resolution: {integrity: sha512-niTvB4gqvtof056rRIrTZvjNYE4rCUzO6X/X+kYjd7WFxXeJ0NwEFnRxX6ehkvv3jTwrXnNdtAak5XYZuIyPFw==} + engines: {node: '>=18'} + + loupe@2.3.7: + resolution: {integrity: sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==} + + lru-cache@10.0.0: + resolution: {integrity: sha512-svTf/fzsKHffP42sujkO/Rjs37BCIsQVRCeNYIm9WN8rgT7ffoUnRtZCqU+6BqcSBdv8gwJeTz8knJpgACeQMw==} + engines: {node: 14 || >=16.14} + + lru-cache@10.2.0: + resolution: {integrity: sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q==} + engines: {node: 14 || >=16.14} + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + magic-string@0.30.5: + resolution: {integrity: sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==} + engines: {node: '>=12'} + + magic-string@0.30.7: + resolution: {integrity: sha512-8vBuFF/I/+OSLRmdf2wwFCJCz+nSn0m6DPvGH1fS/KiQoSaR+sETbov0eIk9KhEKy8CYqIkIAnbohxT/4H0kuA==} + engines: {node: '>=12'} + + magic-string@0.30.8: + resolution: {integrity: sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ==} + engines: {node: '>=12'} + + map-cache@0.2.2: + resolution: {integrity: sha512-8y/eV9QQZCiyn1SprXSrCmqJN0yNRATe+PO8ztwqrvrbdRLA3eYJF0yaR0YayLWkMbsQSKWS9N2gPcGEc4UsZg==} + engines: {node: '>=0.10.0'} + + map-visit@1.0.0: + resolution: {integrity: sha512-4y7uGv8bd2WdM9vpQsiQNo41Ln1NvhvDRuVt0k2JZQ+ezN2uaQes7lZeZ+QQUHOLQAtDaBJ+7wCbi+ab/KFs+w==} + engines: {node: '>=0.10.0'} + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + mdn-data@2.0.14: + resolution: {integrity: sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow==} + + mdn-data@2.0.28: + resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==} + + mdn-data@2.0.30: + resolution: {integrity: sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==} + + memoize-one@6.0.0: + resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==} + + merge-descriptors@1.0.3: + resolution: {integrity: sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==} + + merge-options@1.0.1: + resolution: {integrity: sha512-iuPV41VWKWBIOpBsjoxjDZw8/GbSfZ2mk7N1453bwMrfzdrIk7EzBd+8UVR6rkw67th7xnk9Dytl3J+lHPdxvg==} + engines: {node: '>=4'} + + merge-stream@2.0.0: + resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + + micromatch@3.1.0: + resolution: {integrity: sha512-3StSelAE+hnRvMs8IdVW7Uhk8CVed5tp+kLLGlBP6WiRAXS21GPGu/Nat4WNPXj2Eoc24B02SaeoyozPMfj0/g==} + engines: {node: '>=0.10.0'} + + micromatch@4.0.5: + resolution: {integrity: sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==} + engines: {node: '>=8.6'} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-match@1.0.2: + resolution: {integrity: sha512-VXp/ugGDVh3eCLOBCiHZMYWQaTNUHv2IJrut+yXA6+JbLPXHglHwfS/5A5L0ll+jkCY7fIzRJcH6OIunF+c6Cg==} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + mime@2.6.0: + resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} + engines: {node: '>=4.0.0'} + hasBin: true + + mimic-fn@2.1.0: + resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} + engines: {node: '>=6'} + + mimic-fn@4.0.0: + resolution: {integrity: sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==} + engines: {node: '>=12'} + + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + + minimatch@5.1.9: + resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==} + engines: {node: '>=10'} + + minimatch@9.0.3: + resolution: {integrity: sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==} + engines: {node: '>=16 || 14 >=14.17'} + + minimatch@9.0.9: + resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} + engines: {node: '>=16 || 14 >=14.17'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + mitt@3.0.1: + resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} + + mixin-deep@1.3.2: + resolution: {integrity: sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==} + engines: {node: '>=0.10.0'} + + mkdirp@0.5.6: + resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} + hasBin: true + + mlly@1.8.2: + resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} + + mobius1-selectr@2.4.13: + resolution: {integrity: sha512-Mk9qDrvU44UUL0EBhbAA1phfQZ7aMZPjwtL7wkpiBzGh8dETGqfsh50mWoX9EkjDlkONlErWXArHCKfoxVg0Bw==} + + mrmime@2.0.1: + resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} + engines: {node: '>=10'} + + ms@2.0.0: + resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} + + ms@2.1.2: + resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + muggle-string@0.4.1: + resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} + + mz@2.7.0: + resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + + namespace-emitter@2.0.1: + resolution: {integrity: sha512-N/sMKHniSDJBjfrkbS/tpkPj4RAbvW3mr8UAzvlMHyun93XEm83IAvhWtJVHo+RHn/oO8Job5YN4b+wRjSVp5g==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + nanomatch@1.2.13: + resolution: {integrity: sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==} + engines: {node: '>=0.10.0'} + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + next-tick@1.1.0: + resolution: {integrity: sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==} + + node-fetch-native@1.6.7: + resolution: {integrity: sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==} + + node-hex@1.0.1: + resolution: {integrity: sha512-iwpZdvW6Umz12ICmu9IYPRxg0tOLGmU3Tq2tKetejCj3oZd7b2nUXwP3a7QA5M9glWy8wlPS1G3RwM/CdsUbdQ==} + engines: {node: '>=8.0.0'} + + node-releases@2.0.57: + resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==} + engines: {node: '>=18'} + + nopt@6.0.0: + resolution: {integrity: sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + hasBin: true + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + normalize-wheel-es@1.2.0: + resolution: {integrity: sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==} + + normalize.css@8.0.1: + resolution: {integrity: sha512-qizSNPO93t1YUuUhP22btGOo3chcvDFqFaj2TRybP0DMxkHOCTYwp3n34fel4a31ORXy4m1Xq0Gyqpb5m33qIg==} + + npm-run-path@4.0.1: + resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} + engines: {node: '>=8'} + + npm-run-path@5.3.0: + resolution: {integrity: sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + nprogress@0.2.0: + resolution: {integrity: sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==} + + nth-check@2.0.0: + resolution: {integrity: sha512-i4sc/Kj8htBrAiH1viZ0TgU8Y5XqCaV/FziYK6TBczxmeKm3AEFWqqF3195yKudrarqy7Zu80Ra5dobFjn9X/Q==} + + nth-check@2.0.1: + resolution: {integrity: sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w==} + + nth-check@2.1.1: + resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} + + nwsapi@2.2.28: + resolution: {integrity: sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==} + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + object-copy@0.1.0: + resolution: {integrity: sha512-79LYn6VAb63zgtmAteVOWo9Vdj71ZVBy3Pbse+VqxDpEP83XuujMrGqHIwAXJ5I/aM0zU7dIyIAhifVTPrNItQ==} + engines: {node: '>=0.10.0'} + + object-inspect@1.13.4: + resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} + engines: {node: '>= 0.4'} + + object-is@1.1.6: + resolution: {integrity: sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==} + engines: {node: '>= 0.4'} + + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + + object-visit@1.0.1: + resolution: {integrity: sha512-GBaMwwAVK9qbQN3Scdo0OyvgPW7l3lnaVMj84uTOZlswkX0KpF6fyDBJhtTthf7pymztoN36/KEr1DyhF96zEA==} + engines: {node: '>=0.10.0'} + + object.assign@4.1.7: + resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} + engines: {node: '>= 0.4'} + + object.pick@1.3.0: + resolution: {integrity: sha512-tqa/UMy/CCoYmj+H5qc07qvSL9dqcs/WZENZ1JbtWBlATP+iVOe778gE6MSijnyCnORzDuX6hU+LA4SZ09YjFQ==} + engines: {node: '>=0.10.0'} + + ofetch@1.5.1: + resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + onetime@5.1.0: + resolution: {integrity: sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==} + engines: {node: '>=6'} + + onetime@5.1.2: + resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} + engines: {node: '>=6'} + + onetime@6.0.0: + resolution: {integrity: sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==} + engines: {node: '>=12'} + + open@9.1.0: + resolution: {integrity: sha512-OS+QTnw1/4vrf+9hh1jc1jnYjzSG4ttTBB8UxOwAnInG3Uo4ssetzC1ihqaIHjLJnA5GGlRl6QlZXOTQhRBUvg==} + engines: {node: '>=14.16'} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + os-name@1.0.3: + resolution: {integrity: sha512-f5estLO2KN8vgtTRaILIgEGBoBrMnZ3JQ7W9TMZCnOIGwHe8TRGSpcagnWDo+Dfhd/z08k9Xe75hvciJJ8Qaew==} + engines: {node: '>=0.10.0'} + hasBin: true + + osx-release@1.1.0: + resolution: {integrity: sha512-ixCMMwnVxyHFQLQnINhmIpWqXIfS2YOXchwQrk+OFzmo6nDjQ0E4KXAyyUh0T0MZgV4bUhkRrAbVqlE4yLVq4A==} + engines: {node: '>=0.10.0'} + hasBin: true + + own-keys@1.0.2: + resolution: {integrity: sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==} + engines: {node: '>= 0.4'} + + p-limit@3.0.2: + resolution: {integrity: sha512-iwqZSOoWIW+Ew4kAGUlN16J4M7OB3ysMLSZtnhmqx7njIHFPlxWBX8xo3lVTyFVq6mI/lL9qt2IsN1sHwaxJkg==} + engines: {node: '>=10'} + + p-limit@5.0.0: + resolution: {integrity: sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==} + engines: {node: '>=18'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + + pako@2.1.0: + resolution: {integrity: sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==} + + parchment@1.1.4: + resolution: {integrity: sha512-J5FBQt/pM2inLzg4hEWmzQx/8h8D0CiDxaG3vyp9rKrQRSDgBlhjdP5jQGgosEajXPSQouXGHOmVdgo7QmJuOg==} + + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + + parse5@7.1.2: + resolution: {integrity: sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==} + + pascalcase@0.1.1: + resolution: {integrity: sha512-XHXfu/yOQRy9vYOtUDVMN60OEJjW013GoObG1o+xwQTpB9eYJX/BjXMsdW13ZDPruFhYYn0AG22w0xgQMwl3Nw==} + engines: {node: '>=0.10.0'} + + path-browserify@1.0.1: + resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-key@4.0.0: + resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} + engines: {node: '>=12'} + + path-scurry@1.11.1: + resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} + engines: {node: '>=16 || 14 >=14.18'} + + path-to-regexp@6.2.1: + resolution: {integrity: sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==} + + path-type@4.0.0: + resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} + engines: {node: '>=8'} + + pathe@0.2.0: + resolution: {integrity: sha512-sTitTPYnn23esFR3RlqYBWn4c45WGeLcsKzQiUpXJAyfcWkolvlYpV8FLo7JishK946oQwMFUCHXQ9AjGPKExw==} + + pathe@1.1.2: + resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@1.1.1: + resolution: {integrity: sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==} + + pause-stream@0.0.11: + resolution: {integrity: sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==} + + perfect-debounce@1.0.0: + resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + picomodal@3.0.0: + resolution: {integrity: sha512-FoR3TDfuLlqUvcEeK5ifpKSVVns6B4BQvc8SDF6THVMuadya6LLtji0QgUDSStw0ZR2J7I6UGi5V2V23rnPWTw==} + + pidtree@0.6.0: + resolution: {integrity: sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==} + engines: {node: '>=0.10'} + hasBin: true + + pinia@2.1.7: + resolution: {integrity: sha512-+C2AHFtcFqjPih0zpYuvof37SFxMQ7OEG2zV9jRI12i9BOy3YQVAHwdKtyyc8pDcDyIc33WCIsZaCFWU7WWxGQ==} + peerDependencies: + '@vue/composition-api': ^1.4.0 + typescript: '>=4.4.4' + vue: ^2.6.14 || ^3.3.0 + peerDependenciesMeta: + '@vue/composition-api': + optional: true + typescript: + optional: true + + pkg-types@1.0.3: + resolution: {integrity: sha512-nN7pYi0AQqJnoLPC9eHFQ8AcyaixBUOwvqc5TDnIKCMEE6I0y8P7OKA7fPexsXGCGxQDl/cmrLAp26LhcwxZ4A==} + + pkg-types@1.3.1: + resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} + + platform@1.3.6: + resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + + posix-character-classes@0.1.1: + resolution: {integrity: sha512-xTgYBc3fuo7Yt7JbiuFxSYGToMoz8fLoE6TC9Wx1P/u+LfeThMOAqmuyECnlBaaJb+u1m9hHiXUEtwW4OzfUJg==} + engines: {node: '>=0.10.0'} + + possible-typed-array-names@1.1.0: + resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} + engines: {node: '>= 0.4'} + + postcss-prefix-selector@1.6.0: + resolution: {integrity: sha512-Fnmz+Jew/Ap3f8ZY3m0YkslAPu0f7I83+hKaVXwSNJxF3sOWAgO1JmmvPWKECgVocbPHSEDe0kga9Mev4fs7LQ==} + + postcss-selector-parser@6.1.4: + resolution: {integrity: sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==} + engines: {node: '>=4'} + + postcss@5.2.17: + resolution: {integrity: sha512-0n4/a5Exgod60L1TjXAYJYqb8kwohUsXqUxYKOUqpRL8h2xL+vhQEuxxkvnWz8PtQiX1Qon3Xfzkx8yeJBBLLw==} + engines: {node: '>=0.12'} + + postcss@8.5.29: + resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==} + engines: {node: ^10 || ^12 || >=14} + + posthtml-parser@0.2.1: + resolution: {integrity: sha512-nPC53YMqJnc/+1x4fRYFfm81KV2V+G9NZY+hTohpYg64Ay7NemWWcV4UWuy/SgMupqQ3kJ88M/iRfZmSnxT+pw==} + + posthtml-rename-id@1.0.12: + resolution: {integrity: sha512-UKXf9OF/no8WZo9edRzvuMenb6AD5hDLzIepJW+a4oJT+T/Lx7vfMYWT4aWlGNQh0WMhnUx1ipN9OkZ9q+ddEw==} + + posthtml-render@1.4.0: + resolution: {integrity: sha512-W1779iVHGfq0Fvh2PROhCe2QhB8mEErgqzo1wpIt36tCgChafP+hbXIhLDOM8ePJrZcFs0vkNEtdibEWVqChqw==} + engines: {node: '>=10'} + + posthtml-svg-mode@1.0.3: + resolution: {integrity: sha512-hEqw9NHZ9YgJ2/0G7CECOeuLQKZi8HjWLkBaSVtOWjygQ9ZD8P7tqeowYs7WrFdKsWEKG7o+IlsPY8jrr0CJpQ==} + + posthtml@0.9.2: + resolution: {integrity: sha512-spBB5sgC4cv2YcW03f/IAUN1pgDJWNWD8FzkyY4mArLUMJW+KlQhlmUdKAHQuPfb00Jl5xIfImeOsf6YL8QK7Q==} + engines: {node: '>=0.10.0'} + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier-linter-helpers@1.0.1: + resolution: {integrity: sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg==} + engines: {node: '>=6.0.0'} + + prettier@3.2.5: + resolution: {integrity: sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==} + engines: {node: '>=14'} + hasBin: true + + pretty-format@29.7.0: + resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + prismjs@1.23.0: + resolution: {integrity: sha512-c29LVsqOaLbBHuIbsTxaKENh1N2EQBOHaWv7gkHN4dgRbxSREqDnDbtFJYdpPauS4YCplMSNCABQ6Eeor69bAA==} + + process-nextick-args@2.0.1: + resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} + + process@0.11.10: + resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==} + engines: {node: '>= 0.6.0'} + + proto-list@1.2.4: + resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} + + proxy-from-env@1.1.0: + resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} + + proxy-from-env@2.1.0: + resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==} + engines: {node: '>=10'} + + psl@1.15.0: + resolution: {integrity: sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + qiniu-js@3.4.1: + resolution: {integrity: sha512-8vxrLqDPlJUk3fUAaTozh3TAT3ww9B5KqGogmGuTiFHnewXDoMxTCSY5z8Ab5UNdrCo6ZxDM07G/o++CICRUFw==} + + qs@6.16.0: + resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==} + engines: {node: '>=0.6'} + + query-string@4.3.2: + resolution: {integrity: sha512-NfC9QeWbiuFMw/SdgidPi2ysRwFhstptHs78EkWASRvXc1sNduUURCEggWB4OZ5aP5Mw9TKGu68idsOnjLuvrA==} + engines: {node: '>=0.10.0'} + + querystring@0.2.1: + resolution: {integrity: sha512-wkvS7mL/JMugcup3/rMitHmd9ecIGd2lhFhK9N3UUQ450h66d1r3Y9nvXzQAW1Lq+wyx61k/1pfKS5KuKiyEbg==} + engines: {node: '>=0.4.x'} + deprecated: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. + + querystringify@2.2.0: + resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} + + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + quill-delta@3.6.3: + resolution: {integrity: sha512-wdIGBlcX13tCHOXGMVnnTVFtGRLoP0imqxM696fIPwIf5ODIYUHIvHbZcyvGlZFiFhK5XzDC2lpjbxRhnM05Tg==} + engines: {node: '>=0.10'} + + quill@1.3.7: + resolution: {integrity: sha512-hG/DVzh/TiknWtE6QmWAF/pxoZKYxfe3J/d/+ShUWkDvvkZQVTPeVmUJVu1uE6DDooC4fWTiCLh84ul89oNz5g==} + + react-is@18.0.0: + resolution: {integrity: sha512-yUcBYdBBbo3QiPsgYDcfQcIkGZHfxOaoE6HLSnr1sPzMhdyxusbfKOSUbSd/ocGi32dxcj366PsTj+5oggeKKw==} + + readable-stream@1.1.14: + resolution: {integrity: sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==} + + readable-stream@2.3.8: + resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} + + readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + + reflect.getprototypeof@1.0.10: + resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} + engines: {node: '>= 0.4'} + + regex-not@1.0.2: + resolution: {integrity: sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==} + engines: {node: '>=0.10.0'} + + regexp.prototype.flags@1.5.4: + resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} + engines: {node: '>= 0.4'} + + repeat-element@1.1.4: + resolution: {integrity: sha512-LFiNfRcSu7KK3evMyYOuCzv3L10TW7yC1G2/+StMjK8Y6Vqd2MG7r/Qjw4ghtuCOjFvlnms/iMmLqpvW/ES/WQ==} + engines: {node: '>=0.10.0'} + + repeat-string@1.6.1: + resolution: {integrity: sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==} + engines: {node: '>=0.10'} + + requires-port@1.0.0: + resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} + + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + + resolve-url@0.2.1: + resolution: {integrity: sha512-ZuF55hVUQaaczgOIwqWzkEcEidmlD/xl44x1UZnhOXcYuFN2S6+rcxpG+C1N3So0wvNI3DmJICUFfu2SxhBmvg==} + deprecated: https://github.com/lydell/resolve-url#deprecated + + restore-cursor@4.0.0: + resolution: {integrity: sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + ret@0.1.15: + resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==} + engines: {node: '>=0.12'} + + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + + rfdc@1.4.1: + resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==} + + rimraf@3.0.2: + resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} + deprecated: Rimraf versions prior to v4 are no longer supported + hasBin: true + + rollup@4.64.1: + resolution: {integrity: sha512-7s4V+3J8ux75WNj9qwSJnrWmlCmZ2YHr2fojtHy5RiIMvhJv6DGe7HKKz7L6G1sq1Eg1fLC8SjYtAtDis1F4CQ==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + rrweb-cssom@0.6.0: + resolution: {integrity: sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==} + + run-applescript@5.0.0: + resolution: {integrity: sha512-XcT5rBksx1QdIhlFOCtgZkB99ZEouFZ1E2Kc2LHqNW13U3/74YGdkQRmThTwxy4QIyookibDKYZOPqX//6BlAg==} + engines: {node: '>=12'} + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + + safe-array-concat@1.1.4: + resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} + engines: {node: '>=0.4'} + + safe-buffer@5.1.2: + resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safe-push-apply@1.0.0: + resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} + engines: {node: '>= 0.4'} + + safe-regex-test@1.1.0: + resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} + engines: {node: '>= 0.4'} + + safe-regex@1.1.0: + resolution: {integrity: sha512-aJXcif4xnaNUzvUuC5gcb46oTS7zvg4jpMTnuqtrEPlR3vFr4pxtdTwaF1Qs3Enjn9HK+ZlwQui+a7z0SywIzg==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + sass@1.72.0: + resolution: {integrity: sha512-Gpczt3WA56Ly0Mn8Sl21Vj94s1axi9hDIzDFn9Ph9x3C3p4nNyvsqJoQyVXKou6cBlfFWEgRW4rT8Tb4i3XnVA==} + engines: {node: '>=14.0.0'} + hasBin: true + + sax@1.6.1: + resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==} + engines: {node: '>=11.0.0'} + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + screenfull@6.0.2: + resolution: {integrity: sha512-AQdy8s4WhNvUZ6P8F6PB21tSPIYKniic+Ogx0AacBMjKP1GUHN2E9URxQHtCusiwxudnCKkdy4GrHXPPJSkCCw==} + engines: {node: ^14.13.1 || >=16.0.0} + + scroll-into-view-if-needed@2.2.31: + resolution: {integrity: sha512-dGCXy99wZQivjmjIqihaBQNjryrz5rueJY7eHfTdyWEiR4ttYpsajb14rn9s5d4DY4EcY6+4+U/maARBXJedkA==} + + sdk-base@2.0.1: + resolution: {integrity: sha512-eeG26wRwhtwYuKGCDM3LixCaxY27Pa/5lK4rLKhQa7HBjJ3U3Y+f81MMZQRsDw/8SC2Dao/83yJTXJ8aULuN8Q==} + + select@1.1.2: + resolution: {integrity: sha512-OwpTSOfy6xSs1+pwcNrv0RBMOzI39Lp3qQKUTPVVPRjCdNa5JH/oPRiqsesIskK8TVgmRiHwO4KXlV2Li9dANA==} + + semver@5.0.1: + resolution: {integrity: sha512-Ne6/HdGZvvpXBdjW3o8J0pvxC2jnmVNBK7MKkMgsOBfrsIdTXfA5x+H9DUbQ2xzyvnLv0A0v9x8R4B40xNZIRQ==} + hasBin: true + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + set-function-length@1.2.2: + resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} + engines: {node: '>= 0.4'} + + set-function-name@2.0.2: + resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} + engines: {node: '>= 0.4'} + + set-proto@1.0.0: + resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} + engines: {node: '>= 0.4'} + + set-value@2.0.1: + resolution: {integrity: sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==} + engines: {node: '>=0.10.0'} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} + engines: {node: '>= 0.4'} + + side-channel-map@1.0.1: + resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} + engines: {node: '>= 0.4'} + + side-channel-weakmap@1.0.2: + resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} + engines: {node: '>= 0.4'} + + side-channel@1.1.1: + resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==} + engines: {node: '>= 0.4'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + sirv@2.0.4: + resolution: {integrity: sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==} + engines: {node: '>= 10'} + + slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + + slate-history@0.66.0: + resolution: {integrity: sha512-6MWpxGQZiMvSINlCbMW43E2YBSVMCMCIwQfBzGssjWw4kb0qfvj0pIdblWNRQZD0hR6WHP+dHHgGSeVdMWzfng==} + peerDependencies: + slate: '>=0.65.3' + + slate@0.72.0: + resolution: {integrity: sha512-PdyMSxsv6ZOeoPp/tKb3mCfn7jWdtnavKzzuVrTYbydOIubYq60N9D3kJRcvR7Z86kxIOzu1ZXB8vsUzy30/vg==} + + slice-ansi@5.0.0: + resolution: {integrity: sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==} + engines: {node: '>=12'} + + slice-ansi@7.0.0: + resolution: {integrity: sha512-AkAZP6rVu1V3D+B5CocNzW83TlqiV9cI/Eb/Thr2u5TvoqPW5uzOhJfhZk5PG5jiXTmX8mhaq0/GkyGz29qtEg==} + engines: {node: '>=14.16'} + + snabbdom@3.6.4: + resolution: {integrity: sha512-VmxEfuw1/Y/eFj5VtMhYnukExpYiPkNzoo3+N3qwAOUDMl8wXgbli5ebR+j0knE3lZ/0eYskLxNcX64uy10N9w==} + engines: {node: '>=12.17.0'} + + snapdragon-node@2.1.1: + resolution: {integrity: sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==} + engines: {node: '>=0.10.0'} + + snapdragon-util@3.0.1: + resolution: {integrity: sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==} + engines: {node: '>=0.10.0'} + + snapdragon@0.8.2: + resolution: {integrity: sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==} + engines: {node: '>=0.10.0'} + + sortablejs@1.14.0: + resolution: {integrity: sha512-pBXvQCs5/33fdN1/39pPL0NZF20LeRbLQ5jtnheIPN9JQAaufGjKdWduZn4U7wCtVuzKhmRkI0DFYHYRbB2H1w==} + + sortablejs@1.15.7: + resolution: {integrity: sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + source-map-resolve@0.5.3: + resolution: {integrity: sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==} + deprecated: See https://github.com/lydell/source-map-resolve#deprecated + + source-map-url@0.4.1: + resolution: {integrity: sha512-cPiFOTLUKvJFIg4SKVScy4ilPPW6rFgMgfuZJPNoDuMs3nC1HbMUycBoJw77xFIp6z1UJQJOfx6C9GMH80DiTw==} + deprecated: See https://github.com/lydell/source-map-url#deprecated + + source-map@0.5.6: + resolution: {integrity: sha512-MjZkVp0NHr5+TPihLcadqnlVoGIoWo4IBHptutGh9wI3ttUYvCG26HkSuDi+K6lsZ25syXJXcctwgyVCt//xqA==} + engines: {node: '>=0.10.0'} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + spark-md5@3.0.2: + resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==} + + split-string@3.1.0: + resolution: {integrity: sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==} + engines: {node: '>=0.10.0'} + + ssf@0.11.2: + resolution: {integrity: sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==} + engines: {node: '>=0.8'} + + ssr-window@3.0.0: + resolution: {integrity: sha512-q+8UfWDg9Itrg0yWK7oe5p/XRCJpJF9OBtXfOPgSJl+u3Xd5KI328RUEvUqSMVM9CiQUEf1QdBzJMkYGErj9QA==} + + stable@0.1.8: + resolution: {integrity: sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w==} + deprecated: 'Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility' + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + static-extend@0.1.2: + resolution: {integrity: sha512-72E9+uLc27Mt718pMHt9VMNiAL4LMsmDbBva8mxWUCkT07fSzEGMYUCk0XWY6lp0j6RBAG4cJ3mWuZv2OE3s0g==} + engines: {node: '>=0.10.0'} + + statuses@1.5.0: + resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} + engines: {node: '>= 0.6'} + + std-env@3.5.0: + resolution: {integrity: sha512-JGUEaALvL0Mf6JCfYnJOTcobY+Nc7sG/TemDRBqCA0wEr4DER7zDchaaixTlmOxAjG1uRJmX82EQcxwTQTkqVA==} + + stop-iteration-iterator@1.1.0: + resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} + engines: {node: '>= 0.4'} + + stream-http@2.8.2: + resolution: {integrity: sha512-QllfrBhqF1DPcz46WxKTs6Mz1Bpc+8Qm6vbqOpVav5odAXwbyzwnEczoWqtxrsmlO+cJqtPrp/8gWKWjaKLLlA==} + + stream-shift@1.0.3: + resolution: {integrity: sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==} + + stream-wormhole@1.1.0: + resolution: {integrity: sha512-gHFfL3px0Kctd6Po0M8TzEvt3De/xu6cnRrjlfYNhwbhLPLwigI2t1nc6jrzNuaYg5C4YF78PPFuQPzRiqn9ew==} + engines: {node: '>=4.0.0'} + + strict-uri-encode@1.1.0: + resolution: {integrity: sha512-R3f198pcvnB+5IpnBlRkphuE9n46WyVl8I39W/ZUTZLz4nqSP/oLYUrcnJrw462Ds8he4YKMov2efsTIw1BDGQ==} + engines: {node: '>=0.10.0'} + + string-argv@0.3.2: + resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} + engines: {node: '>=0.6.19'} + + string-width@4.2.0: + resolution: {integrity: sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg==} + engines: {node: '>=8'} + + string-width@5.1.2: + resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} + engines: {node: '>=12'} + + string-width@7.0.0: + resolution: {integrity: sha512-GPQHj7row82Hjo9hKZieKcHIhaAIKOJvFSIZXuCU9OASVZrMNUaZuz++SPVrBjnLsnk4k+z9f2EIypgxf2vNFw==} + engines: {node: '>=18'} + + string.prototype.trim@1.2.11: + resolution: {integrity: sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==} + engines: {node: '>= 0.4'} + + string.prototype.trimend@1.0.10: + resolution: {integrity: sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==} + engines: {node: '>= 0.4'} + + string.prototype.trimstart@1.0.8: + resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} + engines: {node: '>= 0.4'} + + string_decoder@0.10.31: + resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==} + + string_decoder@1.1.1: + resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} + + strip-ansi@3.0.0: + resolution: {integrity: sha512-leU/wDjPxUZLHqEy4mYnNETRx1jAO1BJ6oTgn9PQWeAiO8kfng2LBq1iXYsN8UYPPRmAizc51nUY6w2Nv12Hog==} + engines: {node: '>=0.10.0'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.2.0: + resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} + engines: {node: '>=12'} + + strip-final-newline@2.0.0: + resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} + engines: {node: '>=6'} + + strip-final-newline@3.0.0: + resolution: {integrity: sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==} + engines: {node: '>=12'} + + strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + + strip-literal@2.0.0: + resolution: {integrity: sha512-f9vHgsCWBq2ugHAkGMiiYY+AYG0D/cbloKKg0nhaaaSNsujdGIpVXCNsrJpCKr5M0f4aI31mr13UjY6GAuXCKA==} + + strnum@1.0.5: + resolution: {integrity: sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==} + + supports-color@2.0.0: + resolution: {integrity: sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g==} + engines: {node: '>=0.8.0'} + + supports-color@3.2.3: + resolution: {integrity: sha512-Jds2VIYDrlp5ui7t8abHN2bjAu4LV/q4N2KivFPpGH0lrka0BMq/33AmECUXlKPcHigkNaqfXRENFju+rlcy+A==} + engines: {node: '>=0.8.0'} + + supports-color@7.1.0: + resolution: {integrity: sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==} + engines: {node: '>=8'} + + svg-baker@1.7.0: + resolution: {integrity: sha512-nibslMbkXOIkqKVrfcncwha45f97fGuAOn1G99YwnwTj8kF9YiM6XexPcUso97NxOm6GsP0SIvYVIosBis1xLg==} + + svg-tags@1.0.0: + resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==} + + svgo@2.8.4: + resolution: {integrity: sha512-2GJ4h3rl13qYTdwllaK6QlL8tG+UrM8626V2Ylcd/yBUv2Y/EwLsYisVV6UDCRmlk+C74G8nMpxJCk0RWPdDCw==} + engines: {node: '>=10.13.0'} + hasBin: true + + svgo@3.3.5: + resolution: {integrity: sha512-8SQMzdrvWaD8deUmrnYB+ASyxBVgWUOilg+A75nE/76WdLpj6LopCwiAVvkzkcqy/9b7t2Mg7faFLjg0ZRcZ3w==} + engines: {node: '>=14.0.0'} + hasBin: true + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + synckit@0.11.13: + resolution: {integrity: sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==} + engines: {node: ^14.18.0 || >=16.0.0} + + synckit@0.8.6: + resolution: {integrity: sha512-laHF2savN6sMeHCjLRkheIU4wo3Zg9Ln5YOjOo7sZ5dVQW8yF5pPE5SIw1dsPhq3TRp1jisKRCdPhfs/1WMqDA==} + engines: {node: ^14.18.0 || >=16.0.0} + + text-table@0.2.0: + resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} + + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + + through@2.3.8: + resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==} + + tiny-emitter@2.1.0: + resolution: {integrity: sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==} + + tiny-warning@1.0.3: + resolution: {integrity: sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==} + + tinybench@2.5.1: + resolution: {integrity: sha512-65NKvSuAVDP/n4CqH+a9w2kTlLReS9vhsAP06MWx+/89nMinJyB2icyl58RIcqCmIggpojIGeuJGhjU1aGMBSg==} + + tinymce@7.6.0: + resolution: {integrity: sha512-kUrklnD7H8JbpSDEGRh51GKK6Mrf+pR9neSDzUHvXKV+2oRtMB7sqfAtEOnM0/WKdstwaX0qoNCZNo2H1Y0EFA==} + + tinypool@0.8.2: + resolution: {integrity: sha512-SUszKYe5wgsxnNOVlBYO6IC+8VGWdVGZWAqUxp3UErNBtptZvWbwyUOyzNL59zigz2rCA92QiL3wvG+JDSdJdQ==} + engines: {node: '>=14.0.0'} + + tinyspy@2.2.0: + resolution: {integrity: sha512-d2eda04AN/cPOR89F7Xv5bK/jrQEhmcLFe6HFldoeO9AJtps+fqEnh486vnT/8y4bw38pSyxDcTCAq+Ks2aJTg==} + engines: {node: '>=14.0.0'} + + titleize@3.0.0: + resolution: {integrity: sha512-KxVu8EYHDPBdUYdKZdKtU2aj2XfEx9AfjXxE/Aj0vT06w2icA09Vus1rh6eSu1y01akYg6BjIK/hxyLJINoMLQ==} + engines: {node: '>=12'} + + to-arraybuffer@1.0.1: + resolution: {integrity: sha512-okFlQcoGTi4LQBG/PgSYblw9VOyptsz2KJZqc6qtgGdes8VktzUQkj4BI2blit072iS8VODNcMA+tvnS9dnuMA==} + + to-object-path@0.3.0: + resolution: {integrity: sha512-9mWHdnGRuh3onocaHzukyvCZhzvr6tiflAy/JRFXcJX0TjgfWA9pk9t8CMbzmBE4Jfw58pXbkngtBtqYxzNEyg==} + engines: {node: '>=0.10.0'} + + to-regex-range@2.1.1: + resolution: {integrity: sha512-ZZWNfCjUokXXDGXFpZehJIkZqq91BcULFq/Pi7M5i4JnxXdhMKAK682z8bCW3o8Hj1wuuzoKcW3DfVzaP6VuNg==} + engines: {node: '>=0.10.0'} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + to-regex@3.0.2: + resolution: {integrity: sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==} + engines: {node: '>=0.10.0'} + + totalist@3.0.1: + resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} + engines: {node: '>=6'} + + tough-cookie@4.1.3: + resolution: {integrity: sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==} + engines: {node: '>=6'} + + tr46@5.0.0: + resolution: {integrity: sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==} + engines: {node: '>=18'} + + traverse@0.6.14: + resolution: {integrity: sha512-CYRAVGfnSSe+4Wlof62oUH6y9fGwo0NNS84hMq76MTZtwXQU7Oqna9SgWfrCGj5JPUtHQudnIEt1BP7PInPkPQ==} + engines: {node: '>= 0.4'} + + ts-api-utils@1.0.1: + resolution: {integrity: sha512-lC/RGlPmwdrIBFTX59wwNzqh7aR2otPNPR/5brHZm/XKFYKsfqxihXUe9pU3JI+3vGkl+vyCoNNnPhJn3aLK1A==} + engines: {node: '>=16.13.0'} + peerDependencies: + typescript: '>=4.2.0' + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + type-detect@4.1.0: + resolution: {integrity: sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==} + engines: {node: '>=4'} + + type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + + type-fest@3.0.0: + resolution: {integrity: sha512-MINvUN5ug9u+0hJDzSZNSnuKXI8M4F5Yvb6SQZ2CYqe7SgKXKOosEcU5R7tRgo85I6eAVBbkVF7TCvB4AUK2xQ==} + engines: {node: '>=14.16'} + + type@2.7.3: + resolution: {integrity: sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==} + + typed-array-buffer@1.0.3: + resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} + engines: {node: '>= 0.4'} + + typed-array-byte-length@1.0.3: + resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} + engines: {node: '>= 0.4'} + + typed-array-byte-offset@1.0.5: + resolution: {integrity: sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==} + engines: {node: '>= 0.4'} + + typed-array-length@1.0.8: + resolution: {integrity: sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==} + engines: {node: '>= 0.4'} + + typedarray.prototype.slice@1.0.6: + resolution: {integrity: sha512-r+7YvGfM5TkTiDQ5EqWi/Z4L4KP3jUI+YCmTtWg1tmTHUw6xladLJqzR2heMaHBIM0TTFLZmn/EkIaEHYs/bIA==} + engines: {node: '>= 0.4'} + + typescript@5.4.3: + resolution: {integrity: sha512-KrPd3PKaCLr78MalgiwJnA25Nm8HAmdwN3mYUYZgG/wizIo9EainNVQI9/yDavtVFRN2h3k8uf3GLHuhDMgEHg==} + engines: {node: '>=14.17'} + hasBin: true + + ufo@1.6.4: + resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} + + unbox-primitive@1.1.0: + resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} + engines: {node: '>= 0.4'} + + unconfig@0.3.11: + resolution: {integrity: sha512-bV/nqePAKv71v3HdVUn6UefbsDKQWRX+bJIkiSm0+twIds6WiD2bJLWWT3i214+J/B4edufZpG2w7Y63Vbwxow==} + + undici-types@5.26.4: + resolution: {integrity: sha512-nSNuWyiXbGptNQjUVhJGKA0KufCryCa6yjc2IAfg4HRblpUNgF5xhqEXNO3+F8cVYFiJsIgurydTuKphzszEmA==} + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + unescape@1.0.1: + resolution: {integrity: sha512-O0+af1Gs50lyH1nUu3ZyYS1cRh01Q/kUKatTOkSs7jukXE6/NebucDVxyiDsA9AQ4JC1V1jUH9EO8JX2nMDgGQ==} + engines: {node: '>=0.10.0'} + + union-value@1.0.1: + resolution: {integrity: sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==} + engines: {node: '>=0.10.0'} + + universalify@0.2.0: + resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==} + engines: {node: '>= 4.0.0'} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + unocss@0.58.6: + resolution: {integrity: sha512-HBstDtC6KKD5yCYh5hHpPdHGZai0B/iLlDwkOIK+xfQYrvl8tNBvKfRz3xgiaI5MJ+fLmEOxbfXQIjleU1A0iA==} + engines: {node: '>=14'} + peerDependencies: + '@unocss/webpack': 0.58.6 + vite: ^2.9.0 || ^3.0.0-0 || ^4.0.0 || ^5.0.0-0 + peerDependenciesMeta: + '@unocss/webpack': + optional: true + vite: + optional: true + + unset-value@1.0.0: + resolution: {integrity: sha512-PcA2tsuGSF9cnySLHTLSh2qrQiJ70mn+r+Glzxv2TWZblxsxCC52BDlZoPCsz7STd9pN7EZetkWZBAvk4cgZdQ==} + engines: {node: '>=0.10.0'} + + untildify@4.0.0: + resolution: {integrity: sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==} + engines: {node: '>=8'} + + update-browserslist-db@1.3.3: + resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + urix@0.1.0: + resolution: {integrity: sha512-Am1ousAhSLBeB9cG/7k7r2R0zj50uDRlZHPGbazid5s9rlF1F/QKYObEKSIunSjIOkJZqwRRLpvewjEkM7pSqg==} + deprecated: Please see https://github.com/lydell/urix#deprecated + + url-parse@1.5.10: + resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==} + + urllib@2.44.1: + resolution: {integrity: sha512-vreOVvFizoiIz5NK9IYMgUknkriHHBVccn2VFfJhgKz6O2qwm0SgjFk4OpXFRDXpdrTx8EzM1DB0/pejrqXwPA==} + engines: {node: '>= 0.10.0'} + peerDependencies: + proxy-agent: ^5.0.0 + peerDependenciesMeta: + proxy-agent: + optional: true + + use@3.1.1: + resolution: {integrity: sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==} + engines: {node: '>=0.10.0'} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + utility@1.18.0: + resolution: {integrity: sha512-PYxZDA+6QtvRvm//++aGdmKG/cI07jNwbROz0Ql+VzFV1+Z0Dy55NI4zZ7RHc9KKpBePNFwoErqIuqQv/cjiTA==} + engines: {node: '>= 0.12.0'} + + uuid@14.0.0: + resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==} + hasBin: true + + uuid@14.0.2: + resolution: {integrity: sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ==} + hasBin: true + + vanilla-picker@2.12.3: + resolution: {integrity: sha512-qVkT1E7yMbUsB2mmJNFmaXMWE2hF8ffqzMMwe9zdAikd8u2VfnsVY2HQcOUi2F38bgbxzlJBEdS1UUhOXdF9GQ==} + + vary@1.1.2: + resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} + engines: {node: '>= 0.8'} + + vite-node@1.4.0: + resolution: {integrity: sha512-VZDAseqjrHgNd4Kh8icYHWzTKSCZMhia7GyHfhtzLW33fZlG9SwsB6CEhgyVOWkJfJ2pFLrp/Gj1FSfAiqH9Lw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + + vite-plugin-compression@0.5.1: + resolution: {integrity: sha512-5QJKBDc+gNYVqL/skgFAP81Yuzo9R+EAf19d+EtsMF/i8kFUpNi3J/H01QD3Oo8zBQn+NzoCIFkpPLynoOzaJg==} + peerDependencies: + vite: '>=2.0.0' + + vite-plugin-svg-icons@2.0.1: + resolution: {integrity: sha512-6ktD+DhV6Rz3VtedYvBKKVA2eXF+sAQVaKkKLDSqGUfnhqXl3bj5PPkVTl3VexfTuZy66PmINi8Q6eFnVfRUmA==} + peerDependencies: + vite: '>=2.0.0' + + vite-svg-loader@5.1.0: + resolution: {integrity: sha512-M/wqwtOEjgb956/+m5ZrYT/Iq6Hax0OakWbokj8+9PXOnB7b/4AxESHieEtnNEy7ZpjsjYW1/5nK8fATQMmRxw==} + peerDependencies: + vue: '>=3.2.13' + + vite@5.4.15: + resolution: {integrity: sha512-6ANcZRivqL/4WtwPGTKNaosuNJr5tWiftOC7liM7G9+rMb8+oeJeyzymDu4rTN93seySBmbjSfsS3Vzr19KNtA==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitest@1.4.0: + resolution: {integrity: sha512-gujzn0g7fmwf83/WzrDTnncZt2UiXP41mHuFYFrdwaLRVQ6JYQEiME2IfEjU3vcFL3VKa75XhI3lFgn+hfVsQw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/node': ^18.0.0 || >=20.0.0 + '@vitest/browser': 1.4.0 + '@vitest/ui': 1.4.0 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vue-component-type-helpers@2.0.0: + resolution: {integrity: sha512-r+lO2aYasxliE6I76dutaY0GBCnqM7Q/c3VO2MPxrJsIUwPZIESLfis9/1EXAMWajnpF+o0syJAIV6Y6/crKNw==} + + vue-cropperjs@5.0.0: + resolution: {integrity: sha512-RhnC8O33uRZNkn74aiHZwNHnBJOXWlS4P6gsRI0lw4cZlWjKSCywZI9oSI9POlIPI6OYv30jvnHMXGch85tw7w==} + peerDependencies: + vue: '>=3.0.0' + + vue-demi@0.14.10: + resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==} + engines: {node: '>=12'} + hasBin: true + peerDependencies: + '@vue/composition-api': ^1.0.0-rc.1 + vue: ^3.0.0-0 || ^2.6.0 + peerDependenciesMeta: + '@vue/composition-api': + optional: true + + vue-eslint-parser@9.4.2: + resolution: {integrity: sha512-Ry9oiGmCAK91HrKMtCrKFWmSFWvYkpGglCeFAIqDdr9zdXmMMpJOmUJS7WWsW7fX81h6mwHmUZCQQ1E0PkSwYQ==} + engines: {node: ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: '>=6.0.0' + + vue-router@4.3.0: + resolution: {integrity: sha512-dqUcs8tUeG+ssgWhcPbjHvazML16Oga5w34uCUmsk7i0BcnskoLGwjpa15fqMr2Fa5JgVBrdL2MEgqz6XZ/6IQ==} + peerDependencies: + vue: ^3.2.0 + + vue-template-compiler@2.7.16: + resolution: {integrity: sha512-AYbUWAJHLGGQM7+cNTELw+KsOG9nl2CnSv467WobS5Cv9uk3wFcnr1Etsz2sEIHEZvw1U+o9mRlEO6QbZvUPGQ==} + + vue-tsc@2.0.7: + resolution: {integrity: sha512-LYa0nInkfcDBB7y8jQ9FQ4riJTRNTdh98zK/hzt4gEpBZQmf30dPhP+odzCa+cedGz6B/guvJEd0BavZaRptjg==} + hasBin: true + peerDependencies: + typescript: '*' + + vue3-json-viewer@2.2.2: + resolution: {integrity: sha512-56l3XDGggnpwEqZieXsSMhNT4NhtO6d7zuSAxHo4i0UVxymyY2jRb7UMQOU1ztChKALZCAzX7DlgrsnEhxu77A==} + peerDependencies: + vue: ^3.2.0 + + vue@3.4.21: + resolution: {integrity: sha512-5hjyV/jLEIKD/jYl4cavMcnzKwjMKohureP8ejn3hhEjwhWIhWeuzL2kJAjzl/WyVsgPY56Sy4Z40C3lVshxXA==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + vuedraggable-es@4.1.1: + resolution: {integrity: sha512-F35pjSwC8HS/lnaOd+B59nYR4FZmwuhWAzccK9xftRuWds8SU1TZh5myKVM86j5dFOI7S26O64Kwe7LUHnXjlA==} + peerDependencies: + vue: ^3.2.31 + + vxe-table-plugin-element@4.0.1: + resolution: {integrity: sha512-q5CS+aeFl4LmRmgzLhj+n6ob25O7nU7uxkpBsdHuSK/Ql9DuI3fUO95HsOHZdzdTMDvrcOtu1eV5Z5nK4b7arA==} + peerDependencies: + vxe-table: ^4.5.0 + + vxe-table@4.5.21: + resolution: {integrity: sha512-yp+BNGCy61lk7ayf0LI3UNcR2fRmipGSiIAh3lNOIdyW1nAobf/GwIx3rXghjzFb0a6NNJeYxv2NM+gwXxtmww==} + peerDependencies: + vue: ^3.2.28 + xe-utils: ^3.5.0 + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-url@14.0.0: + resolution: {integrity: sha512-1lfMEm2IEr7RIV+f4lUNPOqfFL+pO+Xw3fJSqmjX9AbXcXcYOkCe1P6+9VBZB6n94af16NfZf+sSk0JCBZC9aw==} + engines: {node: '>=18'} + + which-boxed-primitive@1.1.1: + resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} + engines: {node: '>= 0.4'} + + which-builtin-type@1.2.1: + resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} + engines: {node: '>= 0.4'} + + which-collection@1.0.2: + resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} + engines: {node: '>= 0.4'} + + which-typed-array@1.1.24: + resolution: {integrity: sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==} + engines: {node: '>= 0.4'} + + which@2.0.1: + resolution: {integrity: sha512-N7GBZOTswtB9lkQBZA4+zAXrjEIWAUOB93AvzUiudRzRxhUdLURQ7D/gAIMY1gatT/LTbmbcv8SiYazy3eYB7w==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wildcard@1.1.2: + resolution: {integrity: sha512-DXukZJxpHA8LuotRwL0pP1+rS6CS7FF2qStDDE1C7DDg2rLud2PXRMuEDYIPhgEezwnlHNL4c+N6MfMTjCGTng==} + + win-release@1.1.1: + resolution: {integrity: sha512-iCRnKVvGxOQdsKhcQId2PXV1vV3J/sDPXKA4Oe9+Eti2nb2ESEsYHRYls/UjoUW3bIc5ZDO8dTH50A/5iVN+bw==} + engines: {node: '>=0.10.0'} + + wmf@1.0.2: + resolution: {integrity: sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==} + engines: {node: '>=0.8'} + + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + word@0.3.0: + resolution: {integrity: sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==} + engines: {node: '>=0.8'} + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + wrap-ansi@8.1.0: + resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} + engines: {node: '>=12'} + + wrap-ansi@9.0.0: + resolution: {integrity: sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==} + engines: {node: '>=18'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + ws@8.22.0: + resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xe-utils@3.5.22: + resolution: {integrity: sha512-rhWuM2fVXsdrqUtyjRAsYTDLvVzYSSZqg/uCRyDqcw96AweB1AWsnTJZyl9g68ejnP0xhxfSoNBSrIcOeX1yxA==} + + xlsx@0.18.5: + resolution: {integrity: sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==} + engines: {node: '>=0.8'} + hasBin: true + + xml-name-validator@4.0.0: + resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} + engines: {node: '>=12'} + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xml2js@0.4.23: + resolution: {integrity: sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + + yaml@2.3.4: + resolution: {integrity: sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA==} + engines: {node: '>= 14'} + + yocto-queue@1.2.2: + resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} + engines: {node: '>=12.20'} + +snapshots: + + '@ampproject/remapping@2.3.0': + dependencies: + '@jridgewell/gen-mapping': 0.3.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@antfu/install-pkg@0.1.1': + dependencies: + execa: 5.1.1 + find-up: 5.0.0 + + '@antfu/utils@0.7.10': {} + + '@aws-sdk/checksums@3.1001.1': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/client-s3@3.1147.0': + dependencies: + '@aws-sdk/checksums': 3.1001.1 + '@aws-sdk/core': 3.978.1 + '@aws-sdk/credential-provider-node': 3.972.84 + '@aws-sdk/middleware-sdk-s3': 3.972.77 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/core@3.978.1': + dependencies: + '@aws-sdk/types': 3.974.6 + '@aws-sdk/xml-builder': 3.972.41 + '@aws/lambda-invoke-store': 0.3.0 + '@smithy/core': 3.35.1 + '@smithy/signature-v4': 5.7.4 + '@smithy/types': 4.19.0 + bowser: 2.14.1 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-env@3.972.72': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-http@3.972.74': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-ini@3.973.17': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/credential-provider-env': 3.972.72 + '@aws-sdk/credential-provider-http': 3.972.74 + '@aws-sdk/credential-provider-login': 3.972.79 + '@aws-sdk/credential-provider-process': 3.972.72 + '@aws-sdk/credential-provider-sso': 3.973.16 + '@aws-sdk/credential-provider-web-identity': 3.972.78 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/credential-provider-imds': 4.5.2 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-login@3.972.79': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-node@3.972.84': + dependencies: + '@aws-sdk/credential-provider-env': 3.972.72 + '@aws-sdk/credential-provider-http': 3.972.74 + '@aws-sdk/credential-provider-ini': 3.973.17 + '@aws-sdk/credential-provider-process': 3.972.72 + '@aws-sdk/credential-provider-sso': 3.973.16 + '@aws-sdk/credential-provider-web-identity': 3.972.78 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/credential-provider-imds': 4.5.2 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-process@3.972.72': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-sso@3.973.16': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/token-providers': 3.1138.0 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/credential-provider-web-identity@3.972.78': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/crt-loader@3.972.76': + dependencies: + '@aws-sdk/core': 3.978.1 + aws-crt: 1.33.2 + tslib: 2.8.1 + transitivePeerDependencies: + - bufferutil + - debug + - supports-color + - utf-8-validate + + '@aws-sdk/middleware-sdk-s3@3.972.77': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/nested-clients@3.997.46': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/fetch-http-handler': 5.8.0 + '@smithy/node-http-handler': 4.12.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/s3-request-presigner@3.1147.0': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/signature-v4-crt@3.1146.0': + dependencies: + '@aws-sdk/crt-loader': 3.972.76 + '@aws-sdk/signature-v4-multi-region': 3.996.47 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/signature-v4': 5.7.4 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + transitivePeerDependencies: + - bufferutil + - debug + - supports-color + - utf-8-validate + + '@aws-sdk/signature-v4-multi-region@3.996.47': + dependencies: + '@aws-sdk/types': 3.974.6 + '@smithy/signature-v4': 5.7.4 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/token-providers@3.1138.0': + dependencies: + '@aws-sdk/core': 3.978.1 + '@aws-sdk/nested-clients': 3.997.46 + '@aws-sdk/types': 3.974.6 + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/types@3.974.6': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws-sdk/util-utf8-browser@3.259.0': + dependencies: + tslib: 2.8.1 + + '@aws-sdk/xml-builder@3.972.41': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@aws/lambda-invoke-store@0.3.0': {} + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.7': {} + + '@babel/core@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.29.8': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@jridgewell/gen-mapping': 0.3.12 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-annotate-as-pure@7.29.7': + dependencies: + '@babel/types': 7.29.8 + + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.29.3 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-annotate-as-pure': 7.29.7 + '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/helper-optimise-call-expression': 7.29.7 + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/traverse': 7.29.8 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/helper-globals@7.29.7': {} + + '@babel/helper-member-expression-to-functions@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-imports@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-optimise-call-expression@7.29.7': + dependencies: + '@babel/types': 7.29.8 + + '@babel/helper-plugin-utils@7.29.7': {} + + '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/helper-optimise-call-expression': 7.29.7 + '@babel/traverse': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-skip-transparent-expression-wrappers@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color + + '@babel/helper-string-parser@7.29.7': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helpers@7.29.7': + dependencies: + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + + '@babel/parser@7.29.9': + dependencies: + '@babel/types': 7.29.8 + + '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 + + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 + + '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-plugin-utils': 7.29.7 + transitivePeerDependencies: + - supports-color + + '@babel/plugin-transform-typescript@7.29.9(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-annotate-as-pure': 7.29.7 + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/helper-plugin-utils': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) + transitivePeerDependencies: + - supports-color + + '@babel/preset-typescript@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-transform-typescript': 7.29.9(@babel/core@7.29.7) + transitivePeerDependencies: + - supports-color + + '@babel/runtime-corejs2@7.29.7': + dependencies: + core-js: 2.6.12 + + '@babel/runtime@7.29.7': {} + + '@babel/template@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + + '@babel/traverse@7.29.8': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + + '@ctrl/tinycolor@3.4.1': {} + + '@element-plus/icons-vue@2.3.1(vue@3.4.21(typescript@5.4.3))': + dependencies: + vue: 3.4.21(typescript@5.4.3) + + '@esbuild/aix-ppc64@0.21.3': + optional: true + + '@esbuild/android-arm64@0.21.3': + optional: true + + '@esbuild/android-arm@0.21.3': + optional: true + + '@esbuild/android-x64@0.21.3': + optional: true + + '@esbuild/darwin-arm64@0.21.3': + optional: true + + '@esbuild/darwin-x64@0.21.3': + optional: true + + '@esbuild/freebsd-arm64@0.21.3': + optional: true + + '@esbuild/freebsd-x64@0.21.3': + optional: true + + '@esbuild/linux-arm64@0.21.3': + optional: true + + '@esbuild/linux-arm@0.21.3': + optional: true + + '@esbuild/linux-ia32@0.21.3': + optional: true + + '@esbuild/linux-loong64@0.21.3': + optional: true + + '@esbuild/linux-mips64el@0.21.3': + optional: true + + '@esbuild/linux-ppc64@0.21.3': + optional: true + + '@esbuild/linux-riscv64@0.21.3': + optional: true + + '@esbuild/linux-s390x@0.21.3': + optional: true + + '@esbuild/linux-x64@0.21.3': + optional: true + + '@esbuild/netbsd-x64@0.21.3': + optional: true + + '@esbuild/openbsd-x64@0.21.3': + optional: true + + '@esbuild/sunos-x64@0.21.3': + optional: true + + '@esbuild/win32-arm64@0.21.3': + optional: true + + '@esbuild/win32-ia32@0.21.3': + optional: true + + '@esbuild/win32-x64@0.21.3': + optional: true + + '@eslint-community/eslint-utils@4.10.1(eslint@8.57.0)': + dependencies: + eslint: 8.57.0 + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.2': {} + + '@eslint/eslintrc@2.1.4': + dependencies: + ajv: 6.15.0 + debug: 4.4.3 + espree: 9.6.1 + globals: 13.19.0 + ignore: 5.2.0 + import-fresh: 3.2.1 + js-yaml: 4.3.2 + minimatch: 3.1.5 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@eslint/js@8.57.0': {} + + '@fast-crud/fast-crud@1.23.4(vue@3.4.21(typescript@5.4.3))': + dependencies: + file-saver: 2.0.5 + lru-cache: 10.0.0 + vuedraggable-es: 4.1.1(vue@3.4.21(typescript@5.4.3)) + xlsx: 0.18.5 + transitivePeerDependencies: + - vue + + '@fast-crud/fast-extends@1.23.4(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@aws-sdk/client-s3': 3.1147.0 + '@aws-sdk/s3-request-presigner': 3.1147.0 + '@aws-sdk/signature-v4-crt': 3.1146.0 + '@soerenmartius/vue3-clipboard': 0.1.2 + '@wangeditor/editor': 5.1.23 + '@wangeditor/editor-for-vue': 5.1.12(@wangeditor/editor@5.1.23)(vue@3.4.21(typescript@5.4.3)) + ali-oss: 6.18.0 + cos-js-sdk-v5: 1.10.1 + cropperjs: 1.6.3 + dayjs: 1.11.23 + glob: 10.5.0 + humanize-duration: 3.35.0 + jsoneditor: 9.10.2 + lodash-es: 4.18.1 + object-assign: 4.1.1 + qiniu-js: 3.4.1 + quill: 1.3.7 + vue-cropperjs: 5.0.0(vue@3.4.21(typescript@5.4.3)) + transitivePeerDependencies: + - bufferutil + - debug + - preact-render-to-string + - proxy-agent + - supports-color + - utf-8-validate + - vue + + '@fast-crud/ui-element@1.23.4': {} + + '@fast-crud/ui-interface@1.23.4': + dependencies: + lodash-es: 4.18.1 + + '@floating-ui/core@1.8.0': + dependencies: + '@floating-ui/utils': 0.2.12 + + '@floating-ui/dom@1.8.0': + dependencies: + '@floating-ui/core': 1.8.0 + '@floating-ui/utils': 0.2.12 + + '@floating-ui/utils@0.2.12': {} + + '@httptoolkit/websocket-stream@6.0.1': + dependencies: + '@types/ws': 8.18.2 + duplexify: 3.7.1 + inherits: 2.0.4 + isomorphic-ws: 4.0.1(ws@8.22.0) + readable-stream: 2.3.8 + safe-buffer: 5.2.1 + ws: 8.22.0 + xtend: 4.0.2 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + '@humanwhocodes/config-array@0.11.14': + dependencies: + '@humanwhocodes/object-schema': 2.0.3 + debug: 4.4.3 + minimatch: 3.1.5 + transitivePeerDependencies: + - supports-color + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/object-schema@2.0.3': {} + + '@iconify/types@2.0.0': {} + + '@iconify/utils@2.1.22': + dependencies: + '@antfu/install-pkg': 0.1.1 + '@antfu/utils': 0.7.10 + '@iconify/types': 2.0.0 + debug: 4.4.3 + kolorist: 1.8.0 + local-pkg: 0.5.0 + mlly: 1.8.2 + transitivePeerDependencies: + - supports-color + + '@iconify/vue@4.2.0(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@iconify/types': 2.0.0 + vue: 3.4.21(typescript@5.4.3) + + '@isaacs/cliui@8.0.2': + dependencies: + string-width: 5.1.2 + string-width-cjs: string-width@4.2.0 + strip-ansi: 7.2.0 + strip-ansi-cjs: strip-ansi@6.0.1 + wrap-ansi: 8.1.0 + wrap-ansi-cjs: wrap-ansi@7.0.0 + + '@jest/schemas@29.6.3': + dependencies: + '@sinclair/typebox': 0.27.12 + + '@jridgewell/gen-mapping@0.3.12': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/gen-mapping@0.3.5': + dependencies: + '@jridgewell/set-array': 1.2.1 + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/set-array@1.2.1': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.3 + + '@one-ini/wasm@0.1.1': {} + + '@pkgjs/parseargs@0.11.0': + optional: true + + '@pkgr/core@0.3.6': {} + + '@pkgr/utils@2.4.2': + dependencies: + cross-spawn: 7.0.6 + fast-glob: 3.3.3 + is-glob: 4.0.3 + open: 9.1.0 + picocolors: 1.1.1 + tslib: 2.8.1 + + '@polka/url@1.0.0-next.29': {} + + '@rollup/pluginutils@5.4.0(rollup@4.64.1)': + dependencies: + '@types/estree': 1.0.9 + estree-walker: 2.0.2 + picomatch: 4.0.7 + optionalDependencies: + rollup: 4.64.1 + + '@rollup/rollup-android-arm-eabi@4.64.1': + optional: true + + '@rollup/rollup-android-arm64@4.64.1': + optional: true + + '@rollup/rollup-darwin-arm64@4.64.1': + optional: true + + '@rollup/rollup-darwin-x64@4.64.1': + optional: true + + '@rollup/rollup-freebsd-arm64@4.64.1': + optional: true + + '@rollup/rollup-freebsd-x64@4.64.1': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.64.1': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.64.1': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.64.1': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.64.1': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.64.1': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.64.1': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.64.1': + optional: true + + '@rollup/rollup-linux-x64-musl@4.64.1': + optional: true + + '@rollup/rollup-openbsd-x64@4.64.1': + optional: true + + '@rollup/rollup-openharmony-arm64@4.64.1': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.64.1': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.64.1': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.64.1': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.64.1': + optional: true + + '@sinclair/typebox@0.27.12': {} + + '@smithy/core@3.35.1': + dependencies: + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/credential-provider-imds@4.5.2': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/fetch-http-handler@5.8.0': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/node-http-handler@4.12.1': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/signature-v4@5.7.4': + dependencies: + '@smithy/core': 3.35.1 + '@smithy/types': 4.19.0 + tslib: 2.8.1 + + '@smithy/types@4.19.0': + dependencies: + tslib: 2.8.1 + + '@soerenmartius/vue3-clipboard@0.1.2': + dependencies: + clipboard: 2.0.11 + + '@sphinxxxx/color-conversion@2.2.2': {} + + '@sxzz/popperjs-es@2.11.8': {} + + '@tinymce/tinymce-vue@6.1.0(tinymce@7.6.0)(vue@3.4.21(typescript@5.4.3))': + dependencies: + vue: 3.4.21(typescript@5.4.3) + optionalDependencies: + tinymce: 7.6.0 + + '@transloadit/prettier-bytes@0.0.7': {} + + '@types/estree@1.0.9': {} + + '@types/event-emitter@0.3.5': {} + + '@types/js-cookie@3.0.6': {} + + '@types/json-schema@7.0.15': {} + + '@types/lodash-es@4.17.12': + dependencies: + '@types/lodash': 4.17.25 + + '@types/lodash@4.17.25': {} + + '@types/node@20.11.30': + dependencies: + undici-types: 5.26.4 + + '@types/node@26.6.4': + dependencies: + undici-types: 8.9.0 + + '@types/nprogress@0.2.3': {} + + '@types/path-browserify@1.0.2': {} + + '@types/semver@7.8.0': {} + + '@types/sortablejs@1.15.9': {} + + '@types/svgo@2.6.4': + dependencies: + '@types/node': 26.6.4 + + '@types/uuid@11.0.0': + dependencies: + uuid: 14.0.2 + + '@types/web-bluetooth@0.0.15': {} + + '@types/ws@8.18.2': + dependencies: + '@types/node': 26.6.4 + + '@typescript-eslint/eslint-plugin@7.3.1(@typescript-eslint/parser@7.3.1(eslint@8.57.0)(typescript@5.4.3))(eslint@8.57.0)(typescript@5.4.3)': + dependencies: + '@eslint-community/regexpp': 4.12.2 + '@typescript-eslint/parser': 7.3.1(eslint@8.57.0)(typescript@5.4.3) + '@typescript-eslint/scope-manager': 7.3.1 + '@typescript-eslint/type-utils': 7.3.1(eslint@8.57.0)(typescript@5.4.3) + '@typescript-eslint/utils': 7.3.1(eslint@8.57.0)(typescript@5.4.3) + '@typescript-eslint/visitor-keys': 7.3.1 + debug: 4.4.3 + eslint: 8.57.0 + graphemer: 1.4.0 + ignore: 5.2.4 + natural-compare: 1.4.0 + semver: 7.8.5 + ts-api-utils: 1.0.1(typescript@5.4.3) + optionalDependencies: + typescript: 5.4.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@7.3.1(eslint@8.57.0)(typescript@5.4.3)': + dependencies: + '@typescript-eslint/scope-manager': 7.3.1 + '@typescript-eslint/types': 7.3.1 + '@typescript-eslint/typescript-estree': 7.3.1(typescript@5.4.3) + '@typescript-eslint/visitor-keys': 7.3.1 + debug: 4.4.3 + eslint: 8.57.0 + optionalDependencies: + typescript: 5.4.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@7.3.1': + dependencies: + '@typescript-eslint/types': 7.3.1 + '@typescript-eslint/visitor-keys': 7.3.1 + + '@typescript-eslint/type-utils@7.3.1(eslint@8.57.0)(typescript@5.4.3)': + dependencies: + '@typescript-eslint/typescript-estree': 7.3.1(typescript@5.4.3) + '@typescript-eslint/utils': 7.3.1(eslint@8.57.0)(typescript@5.4.3) + debug: 4.4.3 + eslint: 8.57.0 + ts-api-utils: 1.0.1(typescript@5.4.3) + optionalDependencies: + typescript: 5.4.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@7.3.1': {} + + '@typescript-eslint/typescript-estree@7.3.1(typescript@5.4.3)': + dependencies: + '@typescript-eslint/types': 7.3.1 + '@typescript-eslint/visitor-keys': 7.3.1 + debug: 4.4.3 + globby: 11.1.0 + is-glob: 4.0.3 + minimatch: 9.0.3 + semver: 7.8.5 + ts-api-utils: 1.0.1(typescript@5.4.3) + optionalDependencies: + typescript: 5.4.3 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@7.3.1(eslint@8.57.0)(typescript@5.4.3)': + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@8.57.0) + '@types/json-schema': 7.0.15 + '@types/semver': 7.8.0 + '@typescript-eslint/scope-manager': 7.3.1 + '@typescript-eslint/types': 7.3.1 + '@typescript-eslint/typescript-estree': 7.3.1(typescript@5.4.3) + eslint: 8.57.0 + semver: 7.8.5 + transitivePeerDependencies: + - supports-color + - typescript + + '@typescript-eslint/visitor-keys@7.3.1': + dependencies: + '@typescript-eslint/types': 7.3.1 + eslint-visitor-keys: 3.4.1 + + '@ungap/structured-clone@1.4.0': {} + + '@unocss/astro@0.58.6(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/reset': 0.58.6 + '@unocss/vite': 0.58.6(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + optionalDependencies: + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - rollup + + '@unocss/cli@0.58.6(rollup@4.64.1)': + dependencies: + '@ampproject/remapping': 2.3.0 + '@rollup/pluginutils': 5.4.0(rollup@4.64.1) + '@unocss/config': 0.58.6 + '@unocss/core': 0.58.6 + '@unocss/preset-uno': 0.58.6 + cac: 6.7.14 + chokidar: 3.6.0 + colorette: 2.0.20 + consola: 3.4.2 + fast-glob: 3.3.3 + magic-string: 0.30.8 + pathe: 1.1.2 + perfect-debounce: 1.0.0 + transitivePeerDependencies: + - rollup + + '@unocss/config@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + unconfig: 0.3.11 + + '@unocss/core@0.58.6': {} + + '@unocss/extractor-arbitrary-variants@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/inspector@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/rule-utils': 0.58.6 + gzip-size: 6.0.0 + sirv: 2.0.4 + + '@unocss/postcss@0.58.6(postcss@8.5.29)': + dependencies: + '@unocss/config': 0.58.6 + '@unocss/core': 0.58.6 + '@unocss/rule-utils': 0.58.6 + css-tree: 2.3.1 + fast-glob: 3.3.3 + magic-string: 0.30.8 + postcss: 8.5.29 + + '@unocss/preset-attributify@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/preset-icons@0.58.6': + dependencies: + '@iconify/utils': 2.1.22 + '@unocss/core': 0.58.6 + ofetch: 1.5.1 + transitivePeerDependencies: + - supports-color + + '@unocss/preset-mini@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/extractor-arbitrary-variants': 0.58.6 + '@unocss/rule-utils': 0.58.6 + + '@unocss/preset-tagify@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/preset-typography@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/preset-mini': 0.58.6 + + '@unocss/preset-uno@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/preset-mini': 0.58.6 + '@unocss/preset-wind': 0.58.6 + '@unocss/rule-utils': 0.58.6 + + '@unocss/preset-web-fonts@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + ofetch: 1.5.1 + + '@unocss/preset-wind@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/preset-mini': 0.58.6 + '@unocss/rule-utils': 0.58.6 + + '@unocss/reset@0.58.6': {} + + '@unocss/rule-utils@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + magic-string: 0.30.8 + + '@unocss/scope@0.58.6': {} + + '@unocss/transformer-attributify-jsx-babel@0.58.6': + dependencies: + '@babel/core': 7.29.7 + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/preset-typescript': 7.29.7(@babel/core@7.29.7) + '@unocss/core': 0.58.6 + transitivePeerDependencies: + - supports-color + + '@unocss/transformer-attributify-jsx@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/transformer-compile-class@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/transformer-directives@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + '@unocss/rule-utils': 0.58.6 + css-tree: 2.3.1 + + '@unocss/transformer-variant-group@0.58.6': + dependencies: + '@unocss/core': 0.58.6 + + '@unocss/vite@0.58.6(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))': + dependencies: + '@ampproject/remapping': 2.3.0 + '@rollup/pluginutils': 5.4.0(rollup@4.64.1) + '@unocss/config': 0.58.6 + '@unocss/core': 0.58.6 + '@unocss/inspector': 0.58.6 + '@unocss/scope': 0.58.6 + '@unocss/transformer-directives': 0.58.6 + chokidar: 3.6.0 + fast-glob: 3.3.3 + magic-string: 0.30.8 + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - rollup + + '@uppy/companion-client@2.2.2': + dependencies: + '@uppy/utils': 4.1.2 + namespace-emitter: 2.0.1 + + '@uppy/core@2.1.1': + dependencies: + '@transloadit/prettier-bytes': 0.0.7 + '@uppy/store-default': 2.1.1 + '@uppy/utils': 4.0.3 + lodash.throttle: 4.1.1 + mime-match: 1.0.2 + namespace-emitter: 2.0.1 + nanoid: 3.3.20 + preact: 10.29.8 + transitivePeerDependencies: + - preact-render-to-string + + '@uppy/store-default@2.1.1': {} + + '@uppy/utils@4.0.1': + dependencies: + lodash.throttle: 4.1.1 + + '@uppy/utils@4.0.3': + dependencies: + lodash.throttle: 4.1.1 + + '@uppy/utils@4.1.2': + dependencies: + lodash.throttle: 4.1.1 + + '@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1)': + dependencies: + '@uppy/companion-client': 2.2.2 + '@uppy/core': 2.1.1 + '@uppy/utils': 4.0.1 + nanoid: 3.3.20 + + '@vitejs/plugin-vue-jsx@3.1.0(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@babel/core': 7.29.7 + '@babel/plugin-transform-typescript': 7.29.9(@babel/core@7.29.7) + '@vue/babel-plugin-jsx': 1.1.5(@babel/core@7.29.7) + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + vue: 3.4.21(typescript@5.4.3) + transitivePeerDependencies: + - supports-color + + '@vitejs/plugin-vue@5.0.4(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0))(vue@3.4.21(typescript@5.4.3))': + dependencies: + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + vue: 3.4.21(typescript@5.4.3) + + '@vitest/expect@1.4.0': + dependencies: + '@vitest/spy': 1.4.0 + '@vitest/utils': 1.4.0 + chai: 4.3.10 + + '@vitest/runner@1.4.0': + dependencies: + '@vitest/utils': 1.4.0 + p-limit: 5.0.0 + pathe: 1.1.2 + + '@vitest/snapshot@1.4.0': + dependencies: + magic-string: 0.30.5 + pathe: 1.1.2 + pretty-format: 29.7.0 + + '@vitest/spy@1.4.0': + dependencies: + tinyspy: 2.2.0 + + '@vitest/utils@1.4.0': + dependencies: + diff-sequences: 29.6.3 + estree-walker: 3.0.3 + loupe: 2.3.7 + pretty-format: 29.7.0 + + '@volar/language-core@2.1.3': + dependencies: + '@volar/source-map': 2.1.3 + + '@volar/source-map@2.1.3': + dependencies: + muggle-string: 0.4.1 + + '@volar/typescript@2.1.3': + dependencies: + '@volar/language-core': 2.1.3 + path-browserify: 1.0.1 + + '@vue/babel-helper-vue-transform-on@1.1.5': {} + + '@vue/babel-plugin-jsx@1.1.5(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + '@vue/babel-helper-vue-transform-on': 1.1.5 + camelcase: 6.3.0 + html-tags: 3.3.1 + svg-tags: 1.0.0 + transitivePeerDependencies: + - supports-color + + '@vue/compiler-core@3.4.21': + dependencies: + '@babel/parser': 7.29.9 + '@vue/shared': 3.4.21 + entities: 4.5.0 + estree-walker: 2.0.2 + source-map-js: 1.2.2 + + '@vue/compiler-core@3.5.43': + dependencies: + '@babel/parser': 7.29.9 + '@vue/shared': 3.5.43 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.2.2 + + '@vue/compiler-dom@3.4.21': + dependencies: + '@vue/compiler-core': 3.4.21 + '@vue/shared': 3.4.21 + + '@vue/compiler-dom@3.5.43': + dependencies: + '@vue/compiler-core': 3.5.43 + '@vue/shared': 3.5.43 + + '@vue/compiler-sfc@3.4.21': + dependencies: + '@babel/parser': 7.29.9 + '@vue/compiler-core': 3.4.21 + '@vue/compiler-dom': 3.4.21 + '@vue/compiler-ssr': 3.4.21 + '@vue/shared': 3.4.21 + estree-walker: 2.0.2 + magic-string: 0.30.7 + postcss: 8.5.29 + source-map-js: 1.2.2 + + '@vue/compiler-ssr@3.4.21': + dependencies: + '@vue/compiler-dom': 3.4.21 + '@vue/shared': 3.4.21 + + '@vue/devtools-api@6.5.0': {} + + '@vue/devtools-api@6.5.1': {} + + '@vue/eslint-config-prettier@9.0.0(eslint@8.57.0)(prettier@3.2.5)': + dependencies: + eslint: 8.57.0 + eslint-config-prettier: 9.1.2(eslint@8.57.0) + eslint-plugin-prettier: 5.5.6(eslint-config-prettier@9.1.2(eslint@8.57.0))(eslint@8.57.0)(prettier@3.2.5) + prettier: 3.2.5 + transitivePeerDependencies: + - '@types/eslint' + + '@vue/eslint-config-typescript@13.0.0(eslint-plugin-vue@9.23.0(eslint@8.57.0))(eslint@8.57.0)(typescript@5.4.3)': + dependencies: + '@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/parser@7.3.1(eslint@8.57.0)(typescript@5.4.3))(eslint@8.57.0)(typescript@5.4.3) + '@typescript-eslint/parser': 7.3.1(eslint@8.57.0)(typescript@5.4.3) + eslint: 8.57.0 + eslint-plugin-vue: 9.23.0(eslint@8.57.0) + vue-eslint-parser: 9.4.2(eslint@8.57.0) + optionalDependencies: + typescript: 5.4.3 + transitivePeerDependencies: + - supports-color + + '@vue/language-core@2.0.7(typescript@5.4.3)': + dependencies: + '@volar/language-core': 2.1.3 + '@vue/compiler-dom': 3.5.43 + '@vue/shared': 3.5.43 + computeds: 0.0.1 + minimatch: 9.0.9 + path-browserify: 1.0.1 + vue-template-compiler: 2.7.16 + optionalDependencies: + typescript: 5.4.3 + + '@vue/reactivity@3.4.21': + dependencies: + '@vue/shared': 3.4.21 + + '@vue/runtime-core@3.4.21': + dependencies: + '@vue/reactivity': 3.4.21 + '@vue/shared': 3.4.21 + + '@vue/runtime-dom@3.4.21': + dependencies: + '@vue/runtime-core': 3.4.21 + '@vue/shared': 3.4.21 + csstype: 3.2.3 + + '@vue/server-renderer@3.4.21(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@vue/compiler-ssr': 3.4.21 + '@vue/shared': 3.4.21 + vue: 3.4.21(typescript@5.4.3) + + '@vue/shared@3.4.21': {} + + '@vue/shared@3.5.43': {} + + '@vue/test-utils@2.4.5': + dependencies: + js-beautify: 1.14.9 + vue-component-type-helpers: 2.0.0 + + '@vueuse/core@9.1.0(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@types/web-bluetooth': 0.0.15 + '@vueuse/metadata': 9.1.0 + '@vueuse/shared': 9.1.0(vue@3.4.21(typescript@5.4.3)) + vue-demi: 0.14.10(vue@3.4.21(typescript@5.4.3)) + transitivePeerDependencies: + - '@vue/composition-api' + - vue + + '@vueuse/metadata@9.1.0': {} + + '@vueuse/shared@9.1.0(vue@3.4.21(typescript@5.4.3))': + dependencies: + vue-demi: 0.14.10(vue@3.4.21(typescript@5.4.3)) + transitivePeerDependencies: + - '@vue/composition-api' + - vue + + '@wangeditor/basic-modules@1.1.7(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + is-url: 1.2.4 + lodash.throttle: 4.1.1 + nanoid: 3.3.20 + slate: 0.72.0 + snabbdom: 3.6.4 + + '@wangeditor/code-highlight@1.0.3(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + prismjs: 1.23.0 + slate: 0.72.0 + snabbdom: 3.6.4 + + '@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@types/event-emitter': 0.3.5 + '@uppy/core': 2.1.1 + '@uppy/xhr-upload': 2.0.3(@uppy/core@2.1.1) + dom7: 3.0.0 + event-emitter: 0.3.5 + html-void-elements: 2.0.1 + i18next: 20.4.0 + is-hotkey: 0.2.0 + lodash.camelcase: 4.3.0 + lodash.clonedeep: 4.5.0 + lodash.debounce: 4.0.8 + lodash.foreach: 4.5.0 + lodash.isequal: 4.5.0 + lodash.throttle: 4.1.1 + lodash.toarray: 4.4.0 + nanoid: 3.3.20 + scroll-into-view-if-needed: 2.2.31 + slate: 0.72.0 + slate-history: 0.66.0(slate@0.72.0) + snabbdom: 3.6.4 + + '@wangeditor/editor-for-vue@5.1.12(@wangeditor/editor@5.1.23)(vue@3.4.21(typescript@5.4.3))': + dependencies: + '@wangeditor/editor': 5.1.23 + vue: 3.4.21(typescript@5.4.3) + + '@wangeditor/editor@5.1.23': + dependencies: + '@uppy/core': 2.1.1 + '@uppy/xhr-upload': 2.0.3(@uppy/core@2.1.1) + '@wangeditor/basic-modules': 1.1.7(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/code-highlight': 1.0.3(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/list-module': 1.0.5(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/table-module': 1.1.4(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/upload-image-module': 1.0.2(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(@wangeditor/basic-modules@1.1.7(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.foreach@4.5.0)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/video-module': 1.1.4(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + is-hotkey: 0.2.0 + lodash.camelcase: 4.3.0 + lodash.clonedeep: 4.5.0 + lodash.debounce: 4.0.8 + lodash.foreach: 4.5.0 + lodash.isequal: 4.5.0 + lodash.throttle: 4.1.1 + lodash.toarray: 4.4.0 + nanoid: 3.3.20 + slate: 0.72.0 + snabbdom: 3.6.4 + transitivePeerDependencies: + - preact-render-to-string + + '@wangeditor/list-module@1.0.5(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + slate: 0.72.0 + snabbdom: 3.6.4 + + '@wangeditor/table-module@1.1.4(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + lodash.isequal: 4.5.0 + lodash.throttle: 4.1.1 + nanoid: 3.3.20 + slate: 0.72.0 + snabbdom: 3.6.4 + + '@wangeditor/upload-image-module@1.0.2(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(@wangeditor/basic-modules@1.1.7(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.foreach@4.5.0)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@uppy/core': 2.1.1 + '@uppy/xhr-upload': 2.0.3(@uppy/core@2.1.1) + '@wangeditor/basic-modules': 1.1.7(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(lodash.throttle@4.1.1)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + lodash.foreach: 4.5.0 + slate: 0.72.0 + snabbdom: 3.6.4 + + '@wangeditor/video-module@1.1.4(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(@wangeditor/core@1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4))(dom7@3.0.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4)': + dependencies: + '@uppy/core': 2.1.1 + '@uppy/xhr-upload': 2.0.3(@uppy/core@2.1.1) + '@wangeditor/core': 1.1.19(@uppy/core@2.1.1)(@uppy/xhr-upload@2.0.3(@uppy/core@2.1.1))(dom7@3.0.0)(is-hotkey@0.2.0)(lodash.camelcase@4.3.0)(lodash.clonedeep@4.5.0)(lodash.debounce@4.0.8)(lodash.foreach@4.5.0)(lodash.isequal@4.5.0)(lodash.throttle@4.1.1)(lodash.toarray@4.4.0)(nanoid@3.3.20)(slate@0.72.0)(snabbdom@3.6.4) + dom7: 3.0.0 + nanoid: 3.3.20 + slate: 0.72.0 + snabbdom: 3.6.4 + + abbrev@1.0.3: {} + + ace-builds@1.44.0: {} + + acorn-jsx@5.3.2(acorn@8.19.0): + dependencies: + acorn: 8.19.0 + + acorn-walk@8.3.5: + dependencies: + acorn: 8.19.0 + + acorn@8.19.0: {} + + address@1.2.2: {} + + adler-32@1.3.1: {} + + agent-base@6.0.0: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + agent-base@7.0.2: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + agent-base@7.1.0: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + agentkeepalive@3.5.3: + dependencies: + humanize-ms: 1.2.1 + + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ali-oss@6.18.0: + dependencies: + address: 1.2.2 + agentkeepalive: 3.5.3 + bowser: 1.6.0 + copy-to: 2.0.1 + dateformat: 2.2.0 + debug: 2.6.9 + destroy: 1.2.0 + end-or-error: 1.0.1 + get-ready: 1.0.0 + humanize-ms: 1.2.1 + is-type-of: 1.4.0 + js-base64: 2.5.2 + jstoxml: 2.0.0 + merge-descriptors: 1.0.3 + mime: 2.6.0 + platform: 1.3.6 + pump: 3.0.4 + sdk-base: 2.0.1 + stream-http: 2.8.2 + stream-wormhole: 1.1.0 + urllib: 2.44.1 + utility: 1.18.0 + xml2js: 0.4.23 + transitivePeerDependencies: + - proxy-agent + - supports-color + + ansi-escapes@6.2.0: + dependencies: + type-fest: 3.0.0 + + ansi-regex@2.0.0: {} + + ansi-regex@5.0.1: {} + + ansi-regex@6.4.0: {} + + ansi-styles@2.2.1: {} + + ansi-styles@4.0.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@4.1.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.0.0: {} + + ansi-styles@6.0.0: {} + + ansi-styles@6.1.0: {} + + ansi-styles@6.2.1: {} + + any-promise@1.3.0: {} + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.2 + + argparse@2.0.1: {} + + arr-diff@4.0.0: {} + + arr-flatten@1.1.0: {} + + arr-union@3.1.0: {} + + array-buffer-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + is-array-buffer: 3.0.5 + + array-union@2.1.0: {} + + array-unique@0.3.2: {} + + arraybuffer.prototype.slice@1.0.4: + dependencies: + array-buffer-byte-length: 1.0.2 + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + is-array-buffer: 3.0.5 + + assertion-error@1.1.0: {} + + assign-symbols@1.0.0: {} + + async-function@1.0.0: {} + + async-validator@4.2.5: {} + + asynckit@0.4.0: {} + + atob@2.1.2: {} + + available-typed-arrays@1.0.7: + dependencies: + possible-typed-array-names: 1.1.0 + + aws-crt@1.33.2: + dependencies: + '@aws-sdk/util-utf8-browser': 3.259.0 + '@httptoolkit/websocket-stream': 6.0.1 + axios: 1.20.0 + buffer: 6.0.3 + crypto-js: 4.2.0 + process: 0.11.10 + transitivePeerDependencies: + - bufferutil + - debug + - supports-color + - utf-8-validate + + axios@1.20.0: + dependencies: + follow-redirects: 1.16.1 + form-data: 4.0.6 + https-proxy-agent: 5.0.1 + proxy-from-env: 2.1.0 + transitivePeerDependencies: + - debug + - supports-color + + axios@1.6.8: + dependencies: + follow-redirects: 1.16.1 + form-data: 4.0.6 + proxy-from-env: 1.1.0 + transitivePeerDependencies: + - debug + + balanced-match@1.0.0: {} + + base64-js@1.5.1: {} + + base@0.11.2: + dependencies: + cache-base: 1.0.1 + class-utils: 0.3.6 + component-emitter: 1.3.1 + define-property: 1.0.0 + isobject: 3.0.1 + mixin-deep: 1.3.2 + pascalcase: 0.1.1 + + baseline-browser-mapping@2.11.27: {} + + big-integer@1.6.52: {} + + big.js@5.2.2: {} + + binary-extensions@2.0.0: {} + + bluebird@3.7.2: {} + + boolbase@1.0.0: {} + + bowser@1.6.0: {} + + bowser@2.14.1: {} + + bplist-parser@0.2.0: + dependencies: + big-integer: 1.6.52 + + brace-expansion@1.1.21: + dependencies: + balanced-match: 1.0.0 + concat-map: 0.0.1 + + brace-expansion@2.1.7: + dependencies: + balanced-match: 1.0.0 + + braces@2.3.2: + dependencies: + arr-flatten: 1.1.0 + array-unique: 0.3.2 + extend-shallow: 2.0.1 + fill-range: 4.0.0 + isobject: 3.0.1 + repeat-element: 1.1.4 + snapdragon: 0.8.2 + snapdragon-node: 2.1.1 + split-string: 3.1.0 + to-regex: 3.0.2 + transitivePeerDependencies: + - supports-color + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.29.3: + dependencies: + baseline-browser-mapping: 2.11.27 + caniuse-lite: 1.0.30001814 + electron-to-chromium: 1.5.449 + node-releases: 2.0.57 + update-browserslist-db: 1.3.3(browserslist@4.29.3) + + buffer@6.0.3: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + + builtin-status-codes@3.0.0: {} + + bundle-name@3.0.0: + dependencies: + run-applescript: 5.0.0 + + cac@6.7.14: {} + + cache-base@1.0.1: + dependencies: + collection-visit: 1.0.0 + component-emitter: 1.3.1 + get-value: 2.0.6 + has-value: 1.0.0 + isobject: 3.0.1 + set-value: 2.0.1 + to-object-path: 0.3.0 + union-value: 1.0.1 + unset-value: 1.0.0 + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + call-bind@1.0.9: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + get-intrinsic: 1.3.0 + set-function-length: 1.2.2 + + call-bound@1.0.4: + dependencies: + call-bind-apply-helpers: 1.0.2 + get-intrinsic: 1.3.0 + + callsites@3.1.0: {} + + camelcase@6.3.0: {} + + caniuse-lite@1.0.30001814: {} + + cfb@1.2.2: + dependencies: + adler-32: 1.3.1 + crc-32: 1.2.2 + + chai@4.3.10: + dependencies: + assertion-error: 1.1.0 + check-error: 1.0.3 + deep-eql: 4.1.4 + get-func-name: 2.0.2 + loupe: 2.3.7 + pathval: 1.1.1 + type-detect: 4.1.0 + + chalk@1.1.3: + dependencies: + ansi-styles: 2.2.1 + escape-string-regexp: 1.0.5 + has-ansi: 2.0.0 + strip-ansi: 3.0.0 + supports-color: 2.0.0 + + chalk@4.0.0: + dependencies: + ansi-styles: 4.1.0 + supports-color: 7.1.0 + + chalk@4.1.2: + dependencies: + ansi-styles: 4.1.0 + supports-color: 7.1.0 + + chalk@5.3.0: {} + + check-error@1.0.3: + dependencies: + get-func-name: 2.0.2 + + chokidar@3.6.0: + dependencies: + anymatch: 3.1.3 + braces: 3.0.3 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.3 + + class-utils@0.3.6: + dependencies: + arr-union: 3.1.0 + define-property: 0.2.5 + isobject: 3.0.1 + static-extend: 0.1.2 + + cli-cursor@4.0.0: + dependencies: + restore-cursor: 4.0.0 + + cli-truncate@4.0.0: + dependencies: + slice-ansi: 5.0.0 + string-width: 7.0.0 + + clipboard@2.0.11: + dependencies: + good-listener: 1.2.2 + select: 1.1.2 + tiny-emitter: 2.1.0 + + clone@2.1.2: {} + + codepage@1.15.0: {} + + collection-visit@1.0.0: + dependencies: + map-visit: 1.0.0 + object-visit: 1.0.1 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + colorette@2.0.20: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@10.0.0: {} + + commander@11.1.0: {} + + commander@7.2.0: {} + + component-emitter@1.3.1: {} + + compute-scroll-into-view@1.0.20: {} + + computeds@0.0.1: {} + + concat-map@0.0.1: {} + + confbox@0.1.8: {} + + config-chain@1.1.13: + dependencies: + ini: 1.3.4 + proto-list: 1.2.4 + + consola@3.4.2: {} + + content-type@1.0.2: {} + + convert-source-map@2.0.0: {} + + copy-descriptor@0.1.1: {} + + copy-to@2.0.1: {} + + core-js@2.6.12: {} + + core-util-is@1.0.3: {} + + cors@2.8.6: + dependencies: + object-assign: 4.1.1 + vary: 1.1.2 + + cos-js-sdk-v5@1.10.1: + dependencies: + fast-xml-parser: 4.5.0 + + crc-32@1.2.2: {} + + cropperjs@1.6.3: {} + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.1 + + crypto-js@4.2.0: {} + + css-select@4.1.3: + dependencies: + boolbase: 1.0.0 + css-what: 5.0.0 + domhandler: 4.2.0 + domutils: 2.6.0 + nth-check: 2.0.0 + + css-select@5.1.0: + dependencies: + boolbase: 1.0.0 + css-what: 6.1.0 + domhandler: 5.0.2 + domutils: 3.0.1 + nth-check: 2.0.1 + + css-tree@1.1.3: + dependencies: + mdn-data: 2.0.14 + source-map: 0.6.1 + + css-tree@2.2.0: + dependencies: + mdn-data: 2.0.28 + source-map-js: 1.2.2 + + css-tree@2.3.1: + dependencies: + mdn-data: 2.0.30 + source-map-js: 1.2.2 + + css-what@5.0.0: {} + + css-what@6.1.0: {} + + cssesc@3.0.0: {} + + csso@4.2.0: + dependencies: + css-tree: 1.1.3 + + csso@5.0.5: + dependencies: + css-tree: 2.2.0 + + cssstyle@4.0.1: + dependencies: + rrweb-cssom: 0.6.0 + + csstype@3.2.3: {} + + d@1.0.2: + dependencies: + es5-ext: 0.10.64 + type: 2.7.3 + + data-urls@5.0.0: + dependencies: + whatwg-mimetype: 4.0.0 + whatwg-url: 14.0.0 + + data-view-buffer@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-length@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + data-view-byte-offset@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-data-view: 1.0.2 + + dateformat@2.2.0: {} + + dayjs@1.11.10: {} + + dayjs@1.11.23: {} + + de-indent@1.0.2: {} + + debug@2.6.9: + dependencies: + ms: 2.0.0 + + debug@4.3.4: + dependencies: + ms: 2.1.2 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decimal.js@10.6.0: {} + + decode-uri-component@0.2.0: {} + + deep-eql@4.1.4: + dependencies: + type-detect: 4.1.0 + + deep-equal@1.1.2: + dependencies: + is-arguments: 1.2.0 + is-date-object: 1.1.0 + is-regex: 1.2.1 + object-is: 1.1.6 + object-keys: 1.1.1 + regexp.prototype.flags: 1.5.4 + + deep-is@0.1.4: {} + + default-browser-id@3.0.0: + dependencies: + bplist-parser: 0.2.0 + untildify: 4.0.0 + + default-browser@4.0.0: + dependencies: + bundle-name: 3.0.0 + default-browser-id: 3.0.0 + execa: 7.1.1 + titleize: 3.0.0 + + default-user-agent@1.0.0: + dependencies: + os-name: 1.0.3 + + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-lazy-prop@3.0.0: {} + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + + define-property@0.2.5: + dependencies: + is-descriptor: 0.1.8 + + define-property@1.0.0: + dependencies: + is-descriptor: 1.0.4 + + define-property@2.0.2: + dependencies: + is-descriptor: 1.0.4 + isobject: 3.0.1 + + defu@6.1.7: {} + + delayed-stream@1.0.0: {} + + delegate@3.2.0: {} + + destr@2.0.5: {} + + destroy@1.2.0: {} + + diff-sequences@29.6.3: {} + + digest-header@1.1.0: {} + + dir-glob@3.0.1: + dependencies: + path-type: 4.0.0 + + doctrine@3.0.0: + dependencies: + esutils: 2.0.3 + + dom-serializer@1.0.1: + dependencies: + domelementtype: 2.3.0 + domhandler: 3.0.0 + entities: 2.0.0 + + dom-serializer@2.0.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.2 + entities: 4.2.0 + + dom-zindex@1.0.7: {} + + dom7@3.0.0: + dependencies: + ssr-window: 3.0.0 + + domelementtype@1.0.0: {} + + domelementtype@2.3.0: {} + + domhandler@2.3.0: + dependencies: + domelementtype: 1.0.0 + + domhandler@3.0.0: + dependencies: + domelementtype: 2.3.0 + + domhandler@4.2.0: + dependencies: + domelementtype: 2.3.0 + + domhandler@5.0.2: + dependencies: + domelementtype: 2.3.0 + + domutils@1.5.0: + dependencies: + domelementtype: 1.0.0 + + domutils@2.6.0: + dependencies: + dom-serializer: 1.0.1 + domelementtype: 2.3.0 + domhandler: 4.2.0 + + domutils@3.0.1: + dependencies: + dom-serializer: 2.0.0 + domelementtype: 2.3.0 + domhandler: 5.0.2 + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + duplexer@0.1.2: {} + + duplexify@3.7.1: + dependencies: + end-of-stream: 1.4.5 + inherits: 2.0.4 + readable-stream: 2.3.8 + stream-shift: 1.0.3 + + eastasianwidth@0.2.0: {} + + editorconfig@1.0.7: + dependencies: + '@one-ini/wasm': 0.1.1 + commander: 10.0.0 + minimatch: 9.0.9 + semver: 7.8.5 + + ee-first@1.1.1: {} + + electron-to-chromium@1.5.449: {} + + element-plus@2.9.11(vue@3.4.21(typescript@5.4.3)): + dependencies: + '@ctrl/tinycolor': 3.4.1 + '@element-plus/icons-vue': 2.3.1(vue@3.4.21(typescript@5.4.3)) + '@floating-ui/dom': 1.8.0 + '@popperjs/core': '@sxzz/popperjs-es@2.11.8' + '@types/lodash': 4.17.25 + '@types/lodash-es': 4.17.12 + '@vueuse/core': 9.1.0(vue@3.4.21(typescript@5.4.3)) + async-validator: 4.2.5 + dayjs: 1.11.23 + escape-html: 1.0.3 + lodash: 4.18.1 + lodash-es: 4.18.1 + lodash-unified: 1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1) + memoize-one: 6.0.0 + normalize-wheel-es: 1.2.0 + vue: 3.4.21(typescript@5.4.3) + transitivePeerDependencies: + - '@vue/composition-api' + + emoji-regex@10.3.0: {} + + emoji-regex@8.0.0: {} + + emoji-regex@9.2.2: {} + + emojis-list@3.0.0: {} + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + end-or-error@1.0.1: {} + + entities@1.0.0: {} + + entities@2.0.0: {} + + entities@4.2.0: {} + + entities@4.4.0: {} + + entities@4.5.0: {} + + entities@7.0.1: {} + + es-abstract-get@1.0.0: + dependencies: + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + is-callable: 1.2.7 + object-inspect: 1.13.4 + + es-abstract@1.24.2: + dependencies: + array-buffer-byte-length: 1.0.2 + arraybuffer.prototype.slice: 1.0.4 + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + data-view-buffer: 1.0.2 + data-view-byte-length: 1.0.2 + data-view-byte-offset: 1.0.1 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + es-set-tostringtag: 2.1.0 + es-to-primitive: 1.3.4 + function.prototype.name: 1.2.0 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + get-symbol-description: 1.1.0 + globalthis: 1.0.4 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + has-proto: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + internal-slot: 1.1.0 + is-array-buffer: 3.0.5 + is-callable: 1.2.7 + is-data-view: 1.0.2 + is-negative-zero: 2.0.3 + is-regex: 1.2.1 + is-set: 2.0.3 + is-shared-array-buffer: 1.0.4 + is-string: 1.1.1 + is-typed-array: 1.1.15 + is-weakref: 1.1.1 + math-intrinsics: 1.1.0 + object-inspect: 1.13.4 + object-keys: 1.1.1 + object.assign: 4.1.7 + own-keys: 1.0.2 + regexp.prototype.flags: 1.5.4 + safe-array-concat: 1.1.4 + safe-push-apply: 1.0.0 + safe-regex-test: 1.1.0 + set-proto: 1.0.0 + stop-iteration-iterator: 1.1.0 + string.prototype.trim: 1.2.11 + string.prototype.trimend: 1.0.10 + string.prototype.trimstart: 1.0.8 + typed-array-buffer: 1.0.3 + typed-array-byte-length: 1.0.3 + typed-array-byte-offset: 1.0.5 + typed-array-length: 1.0.8 + unbox-primitive: 1.1.0 + which-typed-array: 1.1.24 + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + es-to-primitive@1.3.4: + dependencies: + es-abstract-get: 1.0.0 + es-define-property: 1.0.1 + es-errors: 1.3.0 + is-callable: 1.2.7 + is-date-object: 1.1.0 + is-symbol: 1.1.1 + + es5-ext@0.10.64: + dependencies: + es6-iterator: 2.0.3 + es6-symbol: 3.1.4 + esniff: 2.0.1 + next-tick: 1.1.0 + + es6-iterator@2.0.3: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + es6-symbol: 3.1.4 + + es6-symbol@3.1.4: + dependencies: + d: 1.0.2 + ext: 1.7.0 + + esbuild@0.21.3: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.3 + '@esbuild/android-arm': 0.21.3 + '@esbuild/android-arm64': 0.21.3 + '@esbuild/android-x64': 0.21.3 + '@esbuild/darwin-arm64': 0.21.3 + '@esbuild/darwin-x64': 0.21.3 + '@esbuild/freebsd-arm64': 0.21.3 + '@esbuild/freebsd-x64': 0.21.3 + '@esbuild/linux-arm': 0.21.3 + '@esbuild/linux-arm64': 0.21.3 + '@esbuild/linux-ia32': 0.21.3 + '@esbuild/linux-loong64': 0.21.3 + '@esbuild/linux-mips64el': 0.21.3 + '@esbuild/linux-ppc64': 0.21.3 + '@esbuild/linux-riscv64': 0.21.3 + '@esbuild/linux-s390x': 0.21.3 + '@esbuild/linux-x64': 0.21.3 + '@esbuild/netbsd-x64': 0.21.3 + '@esbuild/openbsd-x64': 0.21.3 + '@esbuild/sunos-x64': 0.21.3 + '@esbuild/win32-arm64': 0.21.3 + '@esbuild/win32-ia32': 0.21.3 + '@esbuild/win32-x64': 0.21.3 + + escalade@3.2.0: {} + + escape-html@1.0.3: {} + + escape-string-regexp@1.0.5: {} + + escape-string-regexp@4.0.0: {} + + eslint-config-prettier@9.1.2(eslint@8.57.0): + dependencies: + eslint: 8.57.0 + + eslint-plugin-prettier@5.1.3(eslint-config-prettier@9.1.2(eslint@8.57.0))(eslint@8.57.0)(prettier@3.2.5): + dependencies: + eslint: 8.57.0 + prettier: 3.2.5 + prettier-linter-helpers: 1.0.1 + synckit: 0.8.6 + optionalDependencies: + eslint-config-prettier: 9.1.2(eslint@8.57.0) + + eslint-plugin-prettier@5.5.6(eslint-config-prettier@9.1.2(eslint@8.57.0))(eslint@8.57.0)(prettier@3.2.5): + dependencies: + eslint: 8.57.0 + prettier: 3.2.5 + prettier-linter-helpers: 1.0.1 + synckit: 0.11.13 + optionalDependencies: + eslint-config-prettier: 9.1.2(eslint@8.57.0) + + eslint-plugin-vue@9.23.0(eslint@8.57.0): + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@8.57.0) + eslint: 8.57.0 + natural-compare: 1.4.0 + nth-check: 2.1.1 + postcss-selector-parser: 6.1.4 + semver: 7.8.5 + vue-eslint-parser: 9.4.2(eslint@8.57.0) + xml-name-validator: 4.0.0 + transitivePeerDependencies: + - supports-color + + eslint-scope@7.1.1: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-scope@7.2.2: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.3.0: {} + + eslint-visitor-keys@3.4.1: {} + + eslint-visitor-keys@3.4.3: {} + + eslint@8.57.0: + dependencies: + '@eslint-community/eslint-utils': 4.10.1(eslint@8.57.0) + '@eslint-community/regexpp': 4.12.2 + '@eslint/eslintrc': 2.1.4 + '@eslint/js': 8.57.0 + '@humanwhocodes/config-array': 0.11.14 + '@humanwhocodes/module-importer': 1.0.1 + '@nodelib/fs.walk': 1.2.8 + '@ungap/structured-clone': 1.4.0 + ajv: 6.15.0 + chalk: 4.0.0 + cross-spawn: 7.0.6 + debug: 4.4.3 + doctrine: 3.0.0 + escape-string-regexp: 4.0.0 + eslint-scope: 7.2.2 + eslint-visitor-keys: 3.4.3 + espree: 9.6.1 + esquery: 1.7.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 6.0.1 + find-up: 5.0.0 + glob-parent: 6.0.2 + globals: 13.19.0 + graphemer: 1.4.0 + ignore: 5.2.0 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + is-path-inside: 3.0.3 + js-yaml: 4.3.2 + json-stable-stringify-without-jsonify: 1.0.1 + levn: 0.4.1 + lodash.merge: 4.6.2 + minimatch: 3.1.5 + natural-compare: 1.4.0 + optionator: 0.9.4 + strip-ansi: 6.0.1 + text-table: 0.2.0 + transitivePeerDependencies: + - supports-color + + esniff@2.0.1: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + event-emitter: 0.3.5 + type: 2.7.3 + + espree@9.3.1: + dependencies: + acorn: 8.19.0 + acorn-jsx: 5.3.2(acorn@8.19.0) + eslint-visitor-keys: 3.3.0 + + espree@9.6.1: + dependencies: + acorn: 8.19.0 + acorn-jsx: 5.3.2(acorn@8.19.0) + eslint-visitor-keys: 3.4.3 + + esquery@1.7.0: + dependencies: + estraverse: 5.3.0 + + esrecurse@4.3.0: + dependencies: + estraverse: 5.3.0 + + estraverse@5.3.0: {} + + estree-walker@2.0.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + esutils@2.0.3: {} + + etag@1.8.1: {} + + event-emitter@0.3.5: + dependencies: + d: 1.0.2 + es5-ext: 0.10.64 + + eventemitter3@2.0.3: {} + + eventemitter3@5.0.4: {} + + execa@5.0.0: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 2.1.0 + is-stream: 2.0.1 + merge-stream: 2.0.0 + npm-run-path: 4.0.1 + onetime: 5.1.2 + signal-exit: 3.0.7 + strip-final-newline: 2.0.0 + + execa@5.1.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 2.1.0 + is-stream: 2.0.1 + merge-stream: 2.0.0 + npm-run-path: 4.0.1 + onetime: 5.1.2 + signal-exit: 3.0.7 + strip-final-newline: 2.0.0 + + execa@7.1.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 4.3.1 + is-stream: 3.0.0 + merge-stream: 2.0.0 + npm-run-path: 5.3.0 + onetime: 6.0.0 + signal-exit: 3.0.7 + strip-final-newline: 3.0.0 + + execa@8.0.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 8.0.1 + human-signals: 5.0.0 + is-stream: 3.0.0 + merge-stream: 2.0.0 + npm-run-path: 5.3.0 + onetime: 6.0.0 + signal-exit: 4.1.0 + strip-final-newline: 3.0.0 + + expand-brackets@2.1.4: + dependencies: + debug: 2.6.9 + define-property: 0.2.5 + extend-shallow: 2.0.1 + posix-character-classes: 0.1.1 + regex-not: 1.0.2 + snapdragon: 0.8.2 + to-regex: 3.0.2 + transitivePeerDependencies: + - supports-color + + ext@1.7.0: + dependencies: + type: 2.7.3 + + extend-shallow@2.0.1: + dependencies: + is-extendable: 0.1.1 + + extend-shallow@3.0.2: + dependencies: + assign-symbols: 1.0.0 + is-extendable: 1.0.1 + + extend@3.0.2: {} + + extglob@2.0.4: + dependencies: + array-unique: 0.3.2 + define-property: 1.0.0 + expand-brackets: 2.1.4 + extend-shallow: 2.0.1 + fragment-cache: 0.2.1 + regex-not: 1.0.2 + snapdragon: 0.8.2 + to-regex: 3.0.2 + transitivePeerDependencies: + - supports-color + + fast-deep-equal@3.1.3: {} + + fast-diff@1.1.2: {} + + fast-diff@1.3.0: {} + + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fast-json-stable-stringify@2.1.0: {} + + fast-levenshtein@2.0.6: {} + + fast-xml-parser@4.5.0: + dependencies: + strnum: 1.0.5 + + fastq@1.20.3: + dependencies: + reusify: 1.1.0 + + file-entry-cache@6.0.1: + dependencies: + flat-cache: 3.0.4 + + file-saver@2.0.5: {} + + fill-range@4.0.0: + dependencies: + extend-shallow: 2.0.1 + is-number: 3.0.0 + repeat-string: 1.6.1 + to-regex-range: 2.1.1 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@3.0.4: + dependencies: + flatted: 3.4.4 + rimraf: 3.0.2 + + flatted@3.4.4: {} + + follow-redirects@1.16.1: {} + + for-each@0.3.5: + dependencies: + is-callable: 1.2.7 + + for-in@1.0.2: {} + + foreground-child@3.1.0: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + + form-data@4.0.6: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.4 + mime-types: 2.1.35 + + formstream@1.5.2: + dependencies: + destroy: 1.2.0 + mime: 2.6.0 + node-hex: 1.0.1 + pause-stream: 0.0.11 + + frac@1.1.2: {} + + fragment-cache@0.2.1: + dependencies: + map-cache: 0.2.2 + + fs-extra@10.0.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fs.realpath@1.0.0: {} + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + function.prototype.name@1.2.0: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + es-define-property: 1.0.1 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + hasown: 2.0.4 + is-callable: 1.2.7 + is-document.all: 1.0.0 + + functions-have-names@1.2.3: {} + + generator-function@2.0.1: {} + + gensync@1.0.0-beta.2: {} + + get-east-asian-width@1.7.0: {} + + get-func-name@2.0.2: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + get-ready@1.0.0: {} + + get-stream@6.0.1: {} + + get-stream@8.0.1: {} + + get-symbol-description@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + + get-value@2.0.6: {} + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + + glob@10.5.0: + dependencies: + foreground-child: 3.1.0 + jackspeak: 3.1.2 + minimatch: 9.0.9 + minipass: 7.1.3 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + + glob@7.2.0: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.5 + once: 1.4.0 + path-is-absolute: 1.0.1 + + glob@8.1.0: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 5.1.9 + once: 1.4.0 + + globals@13.19.0: + dependencies: + type-fest: 0.20.2 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + + globby@11.1.0: + dependencies: + array-union: 2.1.0 + dir-glob: 3.0.1 + fast-glob: 3.3.3 + ignore: 5.2.0 + merge2: 1.4.1 + slash: 3.0.0 + + good-listener@1.2.2: + dependencies: + delegate: 3.2.0 + + gopd@1.2.0: {} + + graceful-fs@4.2.11: {} + + graphemer@1.4.0: {} + + gzip-size@6.0.0: + dependencies: + duplexer: 0.1.2 + + has-ansi@2.0.0: + dependencies: + ansi-regex: 2.0.0 + + has-bigints@1.1.0: {} + + has-flag@1.0.0: {} + + has-flag@4.0.0: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + + has-proto@1.2.0: + dependencies: + dunder-proto: 1.0.1 + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + has-value@0.3.1: + dependencies: + get-value: 2.0.6 + has-values: 0.1.4 + isobject: 2.0.0 + + has-value@1.0.0: + dependencies: + get-value: 2.0.6 + has-values: 1.0.0 + isobject: 3.0.1 + + has-values@0.1.4: {} + + has-values@1.0.0: + dependencies: + is-number: 3.0.0 + kind-of: 4.0.0 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + he@1.1.1: {} + + he@1.2.0: {} + + html-encoding-sniffer@4.0.0: + dependencies: + whatwg-encoding: 3.1.1 + + html-tags@3.3.1: {} + + html-void-elements@2.0.1: {} + + htmlparser2@3.8.3: + dependencies: + domelementtype: 1.0.0 + domhandler: 2.3.0 + domutils: 1.5.0 + entities: 1.0.0 + readable-stream: 1.1.14 + + http-proxy-agent@7.0.0: + dependencies: + agent-base: 7.1.0 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@5.0.1: + dependencies: + agent-base: 6.0.0 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.2: + dependencies: + agent-base: 7.0.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + human-signals@2.1.0: {} + + human-signals@4.3.1: {} + + human-signals@5.0.0: {} + + humanize-duration@3.35.0: {} + + humanize-ms@1.2.1: + dependencies: + ms: 2.1.3 + + husky@9.0.11: {} + + i18next@20.4.0: + dependencies: + '@babel/runtime': 7.29.7 + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + ieee754@1.2.1: {} + + ignore@5.2.0: {} + + ignore@5.2.4: {} + + image-size@0.5.1: {} + + immer@9.0.6: {} + + immutable@4.3.9: {} + + import-fresh@3.2.1: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + + imurmurhash@0.1.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + ini@1.3.4: {} + + internal-slot@1.1.0: + dependencies: + es-errors: 1.3.0 + hasown: 2.0.4 + side-channel: 1.1.1 + + is-accessor-descriptor@1.0.2: + dependencies: + hasown: 2.0.4 + + is-arguments@1.2.0: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-array-buffer@3.0.5: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + + is-async-function@2.1.1: + dependencies: + async-function: 1.0.0 + call-bound: 1.0.4 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + + is-bigint@1.1.0: + dependencies: + has-bigints: 1.1.0 + + is-binary-path@2.1.0: + dependencies: + binary-extensions: 2.0.0 + + is-boolean-object@1.2.2: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-buffer@1.1.6: {} + + is-callable@1.2.7: {} + + is-class-hotfix@0.0.6: {} + + is-data-descriptor@1.0.1: + dependencies: + hasown: 2.0.4 + + is-data-view@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + is-typed-array: 1.1.15 + + is-date-object@1.1.0: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-descriptor@0.1.8: + dependencies: + is-accessor-descriptor: 1.0.2 + is-data-descriptor: 1.0.1 + + is-descriptor@1.0.4: + dependencies: + is-accessor-descriptor: 1.0.2 + is-data-descriptor: 1.0.1 + + is-docker@2.2.1: {} + + is-docker@3.0.0: {} + + is-document.all@1.0.0: + dependencies: + call-bound: 1.0.4 + + is-extendable@0.1.1: {} + + is-extendable@1.0.1: + dependencies: + is-plain-object: 2.0.4 + + is-extglob@2.1.1: {} + + is-finalizationregistry@1.1.1: + dependencies: + call-bound: 1.0.4 + + is-fullwidth-code-point@3.0.0: {} + + is-fullwidth-code-point@4.0.0: {} + + is-fullwidth-code-point@5.1.0: + dependencies: + get-east-asian-width: 1.7.0 + + is-generator-function@1.1.2: + dependencies: + call-bound: 1.0.4 + generator-function: 2.0.1 + get-proto: 1.0.1 + has-tostringtag: 1.0.2 + safe-regex-test: 1.1.0 + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-hotkey@0.2.0: {} + + is-inside-container@1.0.0: + dependencies: + is-docker: 3.0.0 + + is-map@2.0.3: {} + + is-negative-zero@2.0.3: {} + + is-number-object@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-number@3.0.0: + dependencies: + kind-of: 3.2.2 + + is-number@7.0.0: {} + + is-path-inside@3.0.3: {} + + is-plain-obj@1.1.0: {} + + is-plain-object@2.0.3: + dependencies: + isobject: 3.0.1 + + is-plain-object@2.0.4: + dependencies: + isobject: 3.0.1 + + is-plain-object@5.1.0: {} + + is-potential-custom-element-name@1.0.1: {} + + is-regex@1.2.1: + dependencies: + call-bound: 1.0.4 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + is-set@2.0.3: {} + + is-shared-array-buffer@1.0.4: + dependencies: + call-bound: 1.0.4 + + is-stream@2.0.1: {} + + is-stream@3.0.0: {} + + is-string@1.1.1: + dependencies: + call-bound: 1.0.4 + has-tostringtag: 1.0.2 + + is-symbol@1.1.1: + dependencies: + call-bound: 1.0.4 + has-symbols: 1.1.0 + safe-regex-test: 1.1.0 + + is-type-of@1.4.0: + dependencies: + core-util-is: 1.0.3 + is-class-hotfix: 0.0.6 + isstream: 0.1.2 + + is-typed-array@1.1.15: + dependencies: + which-typed-array: 1.1.24 + + is-url@1.2.4: {} + + is-weakmap@2.0.2: {} + + is-weakref@1.1.1: + dependencies: + call-bound: 1.0.4 + + is-weakset@2.0.4: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + + is-windows@1.0.2: {} + + is-wsl@2.2.0: + dependencies: + is-docker: 2.2.1 + + isarray@0.0.1: {} + + isarray@1.0.0: {} + + isarray@2.0.5: {} + + isexe@2.0.0: {} + + isobject@2.0.0: + dependencies: + isarray: 0.0.1 + + isobject@2.1.0: + dependencies: + isarray: 1.0.0 + + isobject@3.0.1: {} + + isomorphic-ws@4.0.1(ws@8.22.0): + dependencies: + ws: 8.22.0 + + isstream@0.1.2: {} + + jackspeak@3.1.2: + dependencies: + '@isaacs/cliui': 8.0.2 + optionalDependencies: + '@pkgjs/parseargs': 0.11.0 + + javascript-natural-sort@0.7.1: {} + + jiti@1.20.0: {} + + jmespath@0.16.0: {} + + js-base64@2.1.9: {} + + js-base64@2.5.2: {} + + js-beautify@1.14.9: + dependencies: + config-chain: 1.1.13 + editorconfig: 1.0.7 + glob: 8.1.0 + nopt: 6.0.0 + + js-cookie@3.0.5: {} + + js-tokens@4.0.0: {} + + js-tokens@8.0.2: {} + + js-yaml@4.3.2: + dependencies: + argparse: 2.0.1 + + jsdom@24.0.0: + dependencies: + cssstyle: 4.0.1 + data-urls: 5.0.0 + decimal.js: 10.6.0 + form-data: 4.0.6 + html-encoding-sniffer: 4.0.0 + http-proxy-agent: 7.0.0 + https-proxy-agent: 7.0.2 + is-potential-custom-element-name: 1.0.1 + nwsapi: 2.2.28 + parse5: 7.1.2 + rrweb-cssom: 0.6.0 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 4.1.3 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 7.0.0 + whatwg-encoding: 3.1.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 14.0.0 + ws: 8.22.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + jsesc@3.1.0: {} + + json-schema-traverse@0.4.1: {} + + json-source-map@0.6.1: {} + + json-stable-stringify-without-jsonify@1.0.1: {} + + json5@1.0.2: + dependencies: + minimist: 1.2.8 + + json5@2.2.3: {} + + jsonc-parser@3.2.0: {} + + jsoneditor@9.10.2: + dependencies: + ace-builds: 1.44.0 + ajv: 6.15.0 + javascript-natural-sort: 0.7.1 + jmespath: 0.16.0 + json-source-map: 0.6.1 + jsonrepair: 3.15.0 + mobius1-selectr: 2.4.13 + picomodal: 3.0.0 + vanilla-picker: 2.12.3 + + jsonfile@6.2.1: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + jsonrepair@3.15.0: {} + + jstoxml@2.0.0: {} + + kind-of@3.2.2: + dependencies: + is-buffer: 1.1.6 + + kind-of@4.0.0: + dependencies: + is-buffer: 1.1.6 + + kind-of@5.1.0: {} + + kind-of@6.0.3: {} + + kolorist@1.8.0: {} + + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + + lilconfig@3.0.0: {} + + lint-staged@15.2.2: + dependencies: + chalk: 5.3.0 + commander: 11.1.0 + debug: 4.3.4 + execa: 8.0.1 + lilconfig: 3.0.0 + listr2: 8.0.1 + micromatch: 4.0.5 + pidtree: 0.6.0 + string-argv: 0.3.2 + yaml: 2.3.4 + transitivePeerDependencies: + - supports-color + + listr2@8.0.1: + dependencies: + cli-truncate: 4.0.0 + colorette: 2.0.20 + eventemitter3: 5.0.4 + log-update: 6.0.0 + rfdc: 1.4.1 + wrap-ansi: 9.0.0 + + loader-utils@1.4.2: + dependencies: + big.js: 5.2.2 + emojis-list: 3.0.0 + json5: 1.0.2 + + local-pkg@0.5.0: + dependencies: + mlly: 1.8.2 + pkg-types: 1.0.3 + + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + + lodash-es@4.17.21: {} + + lodash-es@4.18.1: {} + + lodash-unified@1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1): + dependencies: + '@types/lodash-es': 4.17.12 + lodash: 4.18.1 + lodash-es: 4.18.1 + + lodash.camelcase@4.3.0: {} + + lodash.clonedeep@4.5.0: {} + + lodash.debounce@4.0.8: {} + + lodash.foreach@4.5.0: {} + + lodash.isequal@4.5.0: {} + + lodash.merge@4.6.2: {} + + lodash.throttle@4.1.1: {} + + lodash.toarray@4.4.0: {} + + lodash@4.18.1: {} + + log-update@6.0.0: + dependencies: + ansi-escapes: 6.2.0 + cli-cursor: 4.0.0 + slice-ansi: 7.0.0 + strip-ansi: 7.2.0 + wrap-ansi: 9.0.0 + + loupe@2.3.7: + dependencies: + get-func-name: 2.0.2 + + lru-cache@10.0.0: {} + + lru-cache@10.2.0: {} + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + magic-string@0.30.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@0.30.7: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@0.30.8: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + map-cache@0.2.2: {} + + map-visit@1.0.0: + dependencies: + object-visit: 1.0.1 + + math-intrinsics@1.1.0: {} + + mdn-data@2.0.14: {} + + mdn-data@2.0.28: {} + + mdn-data@2.0.30: {} + + memoize-one@6.0.0: {} + + merge-descriptors@1.0.3: {} + + merge-options@1.0.1: + dependencies: + is-plain-obj: 1.1.0 + + merge-stream@2.0.0: {} + + merge2@1.4.1: {} + + micromatch@3.1.0: + dependencies: + arr-diff: 4.0.0 + array-unique: 0.3.2 + braces: 2.3.2 + define-property: 1.0.0 + extend-shallow: 2.0.1 + extglob: 2.0.4 + fragment-cache: 0.2.1 + kind-of: 5.1.0 + nanomatch: 1.2.13 + object.pick: 1.3.0 + regex-not: 1.0.2 + snapdragon: 0.8.2 + to-regex: 3.0.2 + transitivePeerDependencies: + - supports-color + + micromatch@4.0.5: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mime-db@1.52.0: {} + + mime-match@1.0.2: + dependencies: + wildcard: 1.1.2 + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + mime@2.6.0: {} + + mimic-fn@2.1.0: {} + + mimic-fn@4.0.0: {} + + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.21 + + minimatch@5.1.9: + dependencies: + brace-expansion: 2.1.7 + + minimatch@9.0.3: + dependencies: + brace-expansion: 2.1.7 + + minimatch@9.0.9: + dependencies: + brace-expansion: 2.1.7 + + minimist@1.2.8: {} + + minipass@7.1.3: {} + + mitt@3.0.1: {} + + mixin-deep@1.3.2: + dependencies: + for-in: 1.0.2 + is-extendable: 1.0.1 + + mkdirp@0.5.6: + dependencies: + minimist: 1.2.8 + + mlly@1.8.2: + dependencies: + acorn: 8.19.0 + pathe: 2.0.3 + pkg-types: 1.3.1 + ufo: 1.6.4 + + mobius1-selectr@2.4.13: {} + + mrmime@2.0.1: {} + + ms@2.0.0: {} + + ms@2.1.2: {} + + ms@2.1.3: {} + + muggle-string@0.4.1: {} + + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + + namespace-emitter@2.0.1: {} + + nanoid@3.3.20: {} + + nanomatch@1.2.13: + dependencies: + arr-diff: 4.0.0 + array-unique: 0.3.2 + define-property: 2.0.2 + extend-shallow: 3.0.2 + fragment-cache: 0.2.1 + is-windows: 1.0.2 + kind-of: 6.0.3 + object.pick: 1.3.0 + regex-not: 1.0.2 + snapdragon: 0.8.2 + to-regex: 3.0.2 + transitivePeerDependencies: + - supports-color + + natural-compare@1.4.0: {} + + next-tick@1.1.0: {} + + node-fetch-native@1.6.7: {} + + node-hex@1.0.1: {} + + node-releases@2.0.57: {} + + nopt@6.0.0: + dependencies: + abbrev: 1.0.3 + + normalize-path@3.0.0: {} + + normalize-wheel-es@1.2.0: {} + + normalize.css@8.0.1: {} + + npm-run-path@4.0.1: + dependencies: + path-key: 3.1.1 + + npm-run-path@5.3.0: + dependencies: + path-key: 4.0.0 + + nprogress@0.2.0: {} + + nth-check@2.0.0: + dependencies: + boolbase: 1.0.0 + + nth-check@2.0.1: + dependencies: + boolbase: 1.0.0 + + nth-check@2.1.1: + dependencies: + boolbase: 1.0.0 + + nwsapi@2.2.28: {} + + object-assign@4.1.1: {} + + object-copy@0.1.0: + dependencies: + copy-descriptor: 0.1.1 + define-property: 0.2.5 + kind-of: 3.2.2 + + object-inspect@1.13.4: {} + + object-is@1.1.6: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + + object-keys@1.1.1: {} + + object-visit@1.0.1: + dependencies: + isobject: 3.0.1 + + object.assign@4.1.7: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + has-symbols: 1.1.0 + object-keys: 1.1.1 + + object.pick@1.3.0: + dependencies: + isobject: 3.0.1 + + ofetch@1.5.1: + dependencies: + destr: 2.0.5 + node-fetch-native: 1.6.7 + ufo: 1.6.4 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + onetime@5.1.0: + dependencies: + mimic-fn: 2.1.0 + + onetime@5.1.2: + dependencies: + mimic-fn: 2.1.0 + + onetime@6.0.0: + dependencies: + mimic-fn: 4.0.0 + + open@9.1.0: + dependencies: + default-browser: 4.0.0 + define-lazy-prop: 3.0.0 + is-inside-container: 1.0.0 + is-wsl: 2.2.0 + + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + + os-name@1.0.3: + dependencies: + osx-release: 1.1.0 + win-release: 1.1.1 + + osx-release@1.1.0: + dependencies: + minimist: 1.2.8 + + own-keys@1.0.2: + dependencies: + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + object-keys: 1.1.1 + safe-push-apply: 1.0.0 + + p-limit@3.0.2: + dependencies: + p-try: 2.2.0 + + p-limit@5.0.0: + dependencies: + yocto-queue: 1.2.2 + + p-locate@5.0.0: + dependencies: + p-limit: 3.0.2 + + p-try@2.2.0: {} + + package-json-from-dist@1.0.1: {} + + pako@2.1.0: {} + + parchment@1.1.4: {} + + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + + parse5@7.1.2: + dependencies: + entities: 4.4.0 + + pascalcase@0.1.1: {} + + path-browserify@1.0.1: {} + + path-exists@4.0.0: {} + + path-is-absolute@1.0.1: {} + + path-key@3.1.1: {} + + path-key@4.0.0: {} + + path-scurry@1.11.1: + dependencies: + lru-cache: 10.2.0 + minipass: 7.1.3 + + path-to-regexp@6.2.1: {} + + path-type@4.0.0: {} + + pathe@0.2.0: {} + + pathe@1.1.2: {} + + pathe@2.0.3: {} + + pathval@1.1.1: {} + + pause-stream@0.0.11: + dependencies: + through: 2.3.8 + + perfect-debounce@1.0.0: {} + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.7: {} + + picomodal@3.0.0: {} + + pidtree@0.6.0: {} + + pinia@2.1.7(typescript@5.4.3)(vue@3.4.21(typescript@5.4.3)): + dependencies: + '@vue/devtools-api': 6.5.0 + vue: 3.4.21(typescript@5.4.3) + vue-demi: 0.14.10(vue@3.4.21(typescript@5.4.3)) + optionalDependencies: + typescript: 5.4.3 + + pkg-types@1.0.3: + dependencies: + jsonc-parser: 3.2.0 + mlly: 1.8.2 + pathe: 1.1.2 + + pkg-types@1.3.1: + dependencies: + confbox: 0.1.8 + mlly: 1.8.2 + pathe: 2.0.3 + + platform@1.3.6: {} + + posix-character-classes@0.1.1: {} + + possible-typed-array-names@1.1.0: {} + + postcss-prefix-selector@1.6.0: + dependencies: + postcss: 5.2.17 + + postcss-selector-parser@6.1.4: + dependencies: + cssesc: 3.0.0 + util-deprecate: 1.0.2 + + postcss@5.2.17: + dependencies: + chalk: 1.1.3 + js-base64: 2.1.9 + source-map: 0.5.6 + supports-color: 3.2.3 + + postcss@8.5.29: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + posthtml-parser@0.2.1: + dependencies: + htmlparser2: 3.8.3 + isobject: 2.1.0 + + posthtml-rename-id@1.0.12: + dependencies: + escape-string-regexp: 1.0.5 + + posthtml-render@1.4.0: {} + + posthtml-svg-mode@1.0.3: + dependencies: + merge-options: 1.0.1 + posthtml: 0.9.2 + posthtml-parser: 0.2.1 + posthtml-render: 1.4.0 + + posthtml@0.9.2: + dependencies: + posthtml-parser: 0.2.1 + posthtml-render: 1.4.0 + + preact@10.29.8: {} + + prelude-ls@1.2.1: {} + + prettier-linter-helpers@1.0.1: + dependencies: + fast-diff: 1.3.0 + + prettier@3.2.5: {} + + pretty-format@29.7.0: + dependencies: + '@jest/schemas': 29.6.3 + ansi-styles: 5.0.0 + react-is: 18.0.0 + + prismjs@1.23.0: + optionalDependencies: + clipboard: 2.0.11 + + process-nextick-args@2.0.1: {} + + process@0.11.10: {} + + proto-list@1.2.4: {} + + proxy-from-env@1.1.0: {} + + proxy-from-env@2.1.0: {} + + psl@1.15.0: + dependencies: + punycode: 2.3.1 + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + punycode@2.3.1: {} + + qiniu-js@3.4.1: + dependencies: + '@babel/runtime-corejs2': 7.29.7 + querystring: 0.2.1 + spark-md5: 3.0.2 + + qs@6.16.0: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + + query-string@4.3.2: + dependencies: + object-assign: 4.1.1 + strict-uri-encode: 1.1.0 + + querystring@0.2.1: {} + + querystringify@2.2.0: {} + + queue-microtask@1.2.3: {} + + quill-delta@3.6.3: + dependencies: + deep-equal: 1.1.2 + extend: 3.0.2 + fast-diff: 1.1.2 + + quill@1.3.7: + dependencies: + clone: 2.1.2 + deep-equal: 1.1.2 + eventemitter3: 2.0.3 + extend: 3.0.2 + parchment: 1.1.4 + quill-delta: 3.6.3 + + react-is@18.0.0: {} + + readable-stream@1.1.14: + dependencies: + core-util-is: 1.0.3 + inherits: 2.0.4 + isarray: 0.0.1 + string_decoder: 0.10.31 + + readable-stream@2.3.8: + dependencies: + core-util-is: 1.0.3 + inherits: 2.0.4 + isarray: 1.0.0 + process-nextick-args: 2.0.1 + safe-buffer: 5.1.2 + string_decoder: 1.1.1 + util-deprecate: 1.0.2 + + readdirp@3.6.0: + dependencies: + picomatch: 2.3.2 + + reflect.getprototypeof@1.0.10: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + get-intrinsic: 1.3.0 + get-proto: 1.0.1 + which-builtin-type: 1.2.1 + + regex-not@1.0.2: + dependencies: + extend-shallow: 3.0.2 + safe-regex: 1.1.0 + + regexp.prototype.flags@1.5.4: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-errors: 1.3.0 + get-proto: 1.0.1 + gopd: 1.2.0 + set-function-name: 2.0.2 + + repeat-element@1.1.4: {} + + repeat-string@1.6.1: {} + + requires-port@1.0.0: {} + + resolve-from@4.0.0: {} + + resolve-url@0.2.1: {} + + restore-cursor@4.0.0: + dependencies: + onetime: 5.1.0 + signal-exit: 3.0.7 + + ret@0.1.15: {} + + reusify@1.1.0: {} + + rfdc@1.4.1: {} + + rimraf@3.0.2: + dependencies: + glob: 7.2.0 + + rollup@4.64.1: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.64.1 + '@rollup/rollup-android-arm64': 4.64.1 + '@rollup/rollup-darwin-arm64': 4.64.1 + '@rollup/rollup-darwin-x64': 4.64.1 + '@rollup/rollup-freebsd-arm64': 4.64.1 + '@rollup/rollup-freebsd-x64': 4.64.1 + '@rollup/rollup-linux-arm-gnueabihf': 4.64.1 + '@rollup/rollup-linux-arm-musleabihf': 4.64.1 + '@rollup/rollup-linux-arm64-gnu': 4.64.1 + '@rollup/rollup-linux-arm64-musl': 4.64.1 + '@rollup/rollup-linux-loong64-gnu': 4.64.1 + '@rollup/rollup-linux-loong64-musl': 4.64.1 + '@rollup/rollup-linux-ppc64-gnu': 4.64.1 + '@rollup/rollup-linux-ppc64-musl': 4.64.1 + '@rollup/rollup-linux-riscv64-gnu': 4.64.1 + '@rollup/rollup-linux-riscv64-musl': 4.64.1 + '@rollup/rollup-linux-s390x-gnu': 4.64.1 + '@rollup/rollup-linux-x64-gnu': 4.64.1 + '@rollup/rollup-linux-x64-musl': 4.64.1 + '@rollup/rollup-openbsd-x64': 4.64.1 + '@rollup/rollup-openharmony-arm64': 4.64.1 + '@rollup/rollup-win32-arm64-msvc': 4.64.1 + '@rollup/rollup-win32-ia32-msvc': 4.64.1 + '@rollup/rollup-win32-x64-gnu': 4.64.1 + '@rollup/rollup-win32-x64-msvc': 4.64.1 + fsevents: 2.3.3 + + rrweb-cssom@0.6.0: {} + + run-applescript@5.0.0: + dependencies: + execa: 5.0.0 + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + + safe-array-concat@1.1.4: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + get-intrinsic: 1.3.0 + has-symbols: 1.1.0 + isarray: 2.0.5 + + safe-buffer@5.1.2: {} + + safe-buffer@5.2.1: {} + + safe-push-apply@1.0.0: + dependencies: + es-errors: 1.3.0 + isarray: 2.0.5 + + safe-regex-test@1.1.0: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-regex: 1.2.1 + + safe-regex@1.1.0: + dependencies: + ret: 0.1.15 + + safer-buffer@2.1.2: {} + + sass@1.72.0: + dependencies: + chokidar: 3.6.0 + immutable: 4.3.9 + source-map-js: 1.2.2 + + sax@1.6.1: {} + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + screenfull@6.0.2: {} + + scroll-into-view-if-needed@2.2.31: + dependencies: + compute-scroll-into-view: 1.0.20 + + sdk-base@2.0.1: + dependencies: + get-ready: 1.0.0 + + select@1.1.2: {} + + semver@5.0.1: {} + + semver@6.3.1: {} + + semver@7.8.5: {} + + set-function-length@1.2.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + function-bind: 1.1.2 + get-intrinsic: 1.3.0 + gopd: 1.2.0 + has-property-descriptors: 1.0.2 + + set-function-name@2.0.2: + dependencies: + define-data-property: 1.1.4 + es-errors: 1.3.0 + functions-have-names: 1.2.3 + has-property-descriptors: 1.0.2 + + set-proto@1.0.0: + dependencies: + dunder-proto: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + + set-value@2.0.1: + dependencies: + extend-shallow: 2.0.1 + is-extendable: 0.1.1 + is-plain-object: 2.0.3 + split-string: 3.1.0 + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + side-channel-list@1.0.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + + side-channel-map@1.0.1: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + + side-channel-weakmap@1.0.2: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + object-inspect: 1.13.4 + side-channel-map: 1.0.1 + + side-channel@1.1.1: + dependencies: + es-errors: 1.3.0 + object-inspect: 1.13.4 + side-channel-list: 1.0.1 + side-channel-map: 1.0.1 + side-channel-weakmap: 1.0.2 + + siginfo@2.0.0: {} + + signal-exit@3.0.7: {} + + signal-exit@4.1.0: {} + + sirv@2.0.4: + dependencies: + '@polka/url': 1.0.0-next.29 + mrmime: 2.0.1 + totalist: 3.0.1 + + slash@3.0.0: {} + + slate-history@0.66.0(slate@0.72.0): + dependencies: + is-plain-object: 5.1.0 + slate: 0.72.0 + + slate@0.72.0: + dependencies: + immer: 9.0.6 + is-plain-object: 5.1.0 + tiny-warning: 1.0.3 + + slice-ansi@5.0.0: + dependencies: + ansi-styles: 6.0.0 + is-fullwidth-code-point: 4.0.0 + + slice-ansi@7.0.0: + dependencies: + ansi-styles: 6.2.1 + is-fullwidth-code-point: 5.1.0 + + snabbdom@3.6.4: {} + + snapdragon-node@2.1.1: + dependencies: + define-property: 1.0.0 + isobject: 3.0.1 + snapdragon-util: 3.0.1 + + snapdragon-util@3.0.1: + dependencies: + kind-of: 3.2.2 + + snapdragon@0.8.2: + dependencies: + base: 0.11.2 + debug: 2.6.9 + define-property: 0.2.5 + extend-shallow: 2.0.1 + map-cache: 0.2.2 + source-map: 0.5.6 + source-map-resolve: 0.5.3 + use: 3.1.1 + transitivePeerDependencies: + - supports-color + + sortablejs@1.14.0: {} + + sortablejs@1.15.7: {} + + source-map-js@1.2.2: {} + + source-map-resolve@0.5.3: + dependencies: + atob: 2.1.2 + decode-uri-component: 0.2.0 + resolve-url: 0.2.1 + source-map-url: 0.4.1 + urix: 0.1.0 + + source-map-url@0.4.1: {} + + source-map@0.5.6: {} + + source-map@0.6.1: {} + + spark-md5@3.0.2: {} + + split-string@3.1.0: + dependencies: + extend-shallow: 3.0.2 + + ssf@0.11.2: + dependencies: + frac: 1.1.2 + + ssr-window@3.0.0: {} + + stable@0.1.8: {} + + stackback@0.0.2: {} + + static-extend@0.1.2: + dependencies: + define-property: 0.2.5 + object-copy: 0.1.0 + + statuses@1.5.0: {} + + std-env@3.5.0: {} + + stop-iteration-iterator@1.1.0: + dependencies: + es-errors: 1.3.0 + internal-slot: 1.1.0 + + stream-http@2.8.2: + dependencies: + builtin-status-codes: 3.0.0 + inherits: 2.0.4 + readable-stream: 2.3.8 + to-arraybuffer: 1.0.1 + xtend: 4.0.2 + + stream-shift@1.0.3: {} + + stream-wormhole@1.1.0: {} + + strict-uri-encode@1.1.0: {} + + string-argv@0.3.2: {} + + string-width@4.2.0: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@5.1.2: + dependencies: + eastasianwidth: 0.2.0 + emoji-regex: 9.2.2 + strip-ansi: 7.2.0 + + string-width@7.0.0: + dependencies: + emoji-regex: 10.3.0 + get-east-asian-width: 1.7.0 + strip-ansi: 7.2.0 + + string.prototype.trim@1.2.11: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-data-property: 1.1.4 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-object-atoms: 1.1.2 + has-property-descriptors: 1.0.2 + safe-regex-test: 1.1.0 + + string.prototype.trimend@1.0.10: + dependencies: + call-bind: 1.0.9 + call-bound: 1.0.4 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + + string.prototype.trimstart@1.0.8: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-object-atoms: 1.1.2 + + string_decoder@0.10.31: {} + + string_decoder@1.1.1: + dependencies: + safe-buffer: 5.1.2 + + strip-ansi@3.0.0: + dependencies: + ansi-regex: 2.0.0 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.2.0: + dependencies: + ansi-regex: 6.4.0 + + strip-final-newline@2.0.0: {} + + strip-final-newline@3.0.0: {} + + strip-json-comments@3.1.1: {} + + strip-literal@2.0.0: + dependencies: + js-tokens: 8.0.2 + + strnum@1.0.5: {} + + supports-color@2.0.0: {} + + supports-color@3.2.3: + dependencies: + has-flag: 1.0.0 + + supports-color@7.1.0: + dependencies: + has-flag: 4.0.0 + + svg-baker@1.7.0: + dependencies: + bluebird: 3.7.2 + clone: 2.1.2 + he: 1.1.1 + image-size: 0.5.1 + loader-utils: 1.4.2 + merge-options: 1.0.1 + micromatch: 3.1.0 + postcss: 5.2.17 + postcss-prefix-selector: 1.6.0 + posthtml-rename-id: 1.0.12 + posthtml-svg-mode: 1.0.3 + query-string: 4.3.2 + traverse: 0.6.14 + transitivePeerDependencies: + - supports-color + + svg-tags@1.0.0: {} + + svgo@2.8.4: + dependencies: + commander: 7.2.0 + css-select: 4.1.3 + css-tree: 1.1.3 + csso: 4.2.0 + picocolors: 1.1.1 + sax: 1.6.1 + stable: 0.1.8 + + svgo@3.3.5: + dependencies: + commander: 7.2.0 + css-select: 5.1.0 + css-tree: 2.3.1 + css-what: 6.1.0 + csso: 5.0.5 + picocolors: 1.1.1 + sax: 1.6.1 + + symbol-tree@3.2.4: {} + + synckit@0.11.13: + dependencies: + '@pkgr/core': 0.3.6 + + synckit@0.8.6: + dependencies: + '@pkgr/utils': 2.4.2 + tslib: 2.8.1 + + text-table@0.2.0: {} + + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + + through@2.3.8: {} + + tiny-emitter@2.1.0: {} + + tiny-warning@1.0.3: {} + + tinybench@2.5.1: {} + + tinymce@7.6.0: {} + + tinypool@0.8.2: {} + + tinyspy@2.2.0: {} + + titleize@3.0.0: {} + + to-arraybuffer@1.0.1: {} + + to-object-path@0.3.0: + dependencies: + kind-of: 3.2.2 + + to-regex-range@2.1.1: + dependencies: + is-number: 3.0.0 + repeat-string: 1.6.1 + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + to-regex@3.0.2: + dependencies: + define-property: 2.0.2 + extend-shallow: 3.0.2 + regex-not: 1.0.2 + safe-regex: 1.1.0 + + totalist@3.0.1: {} + + tough-cookie@4.1.3: + dependencies: + psl: 1.15.0 + punycode: 2.3.1 + universalify: 0.2.0 + url-parse: 1.5.10 + + tr46@5.0.0: + dependencies: + punycode: 2.3.1 + + traverse@0.6.14: + dependencies: + define-data-property: 1.1.4 + es-to-primitive: 1.3.4 + gopd: 1.2.0 + typedarray.prototype.slice: 1.0.6 + which-typed-array: 1.1.24 + + ts-api-utils@1.0.1(typescript@5.4.3): + dependencies: + typescript: 5.4.3 + + tslib@2.8.1: {} + + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + + type-detect@4.1.0: {} + + type-fest@0.20.2: {} + + type-fest@3.0.0: {} + + type@2.7.3: {} + + typed-array-buffer@1.0.3: + dependencies: + call-bound: 1.0.4 + es-errors: 1.3.0 + is-typed-array: 1.1.15 + + typed-array-byte-length@1.0.3: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + has-proto: 1.2.0 + is-typed-array: 1.1.15 + + typed-array-byte-offset@1.0.5: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + reflect.getprototypeof: 1.0.10 + + typed-array-length@1.0.8: + dependencies: + call-bind: 1.0.9 + for-each: 0.3.5 + gopd: 1.2.0 + is-typed-array: 1.1.15 + possible-typed-array-names: 1.1.0 + reflect.getprototypeof: 1.0.10 + + typedarray.prototype.slice@1.0.6: + dependencies: + call-bind: 1.0.9 + define-properties: 1.2.1 + es-abstract: 1.24.2 + es-errors: 1.3.0 + get-proto: 1.0.1 + math-intrinsics: 1.1.0 + typed-array-buffer: 1.0.3 + typed-array-byte-offset: 1.0.5 + + typescript@5.4.3: {} + + ufo@1.6.4: {} + + unbox-primitive@1.1.0: + dependencies: + call-bound: 1.0.4 + has-bigints: 1.1.0 + has-symbols: 1.1.0 + which-boxed-primitive: 1.1.1 + + unconfig@0.3.11: + dependencies: + '@antfu/utils': 0.7.10 + defu: 6.1.7 + jiti: 1.20.0 + mlly: 1.8.2 + + undici-types@5.26.4: {} + + undici-types@8.9.0: {} + + unescape@1.0.1: + dependencies: + extend-shallow: 2.0.1 + + union-value@1.0.1: + dependencies: + arr-union: 3.1.0 + get-value: 2.0.6 + is-extendable: 0.1.1 + set-value: 2.0.1 + + universalify@0.2.0: {} + + universalify@2.0.1: {} + + unocss@0.58.6(postcss@8.5.29)(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)): + dependencies: + '@unocss/astro': 0.58.6(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + '@unocss/cli': 0.58.6(rollup@4.64.1) + '@unocss/core': 0.58.6 + '@unocss/extractor-arbitrary-variants': 0.58.6 + '@unocss/postcss': 0.58.6(postcss@8.5.29) + '@unocss/preset-attributify': 0.58.6 + '@unocss/preset-icons': 0.58.6 + '@unocss/preset-mini': 0.58.6 + '@unocss/preset-tagify': 0.58.6 + '@unocss/preset-typography': 0.58.6 + '@unocss/preset-uno': 0.58.6 + '@unocss/preset-web-fonts': 0.58.6 + '@unocss/preset-wind': 0.58.6 + '@unocss/reset': 0.58.6 + '@unocss/transformer-attributify-jsx': 0.58.6 + '@unocss/transformer-attributify-jsx-babel': 0.58.6 + '@unocss/transformer-compile-class': 0.58.6 + '@unocss/transformer-directives': 0.58.6 + '@unocss/transformer-variant-group': 0.58.6 + '@unocss/vite': 0.58.6(rollup@4.64.1)(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)) + optionalDependencies: + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - postcss + - rollup + - supports-color + + unset-value@1.0.0: + dependencies: + has-value: 0.3.1 + isobject: 3.0.1 + + untildify@4.0.0: {} + + update-browserslist-db@1.3.3(browserslist@4.29.3): + dependencies: + browserslist: 4.29.3 + escalade: 3.2.0 + picocolors: 1.1.1 + + uri-js@4.4.1: + dependencies: + punycode: 2.3.1 + + urix@0.1.0: {} + + url-parse@1.5.10: + dependencies: + querystringify: 2.2.0 + requires-port: 1.0.0 + + urllib@2.44.1: + dependencies: + any-promise: 1.3.0 + content-type: 1.0.2 + default-user-agent: 1.0.0 + digest-header: 1.1.0 + ee-first: 1.1.1 + formstream: 1.5.2 + humanize-ms: 1.2.1 + iconv-lite: 0.6.3 + pump: 3.0.4 + qs: 6.16.0 + statuses: 1.5.0 + utility: 1.18.0 + + use@3.1.1: {} + + util-deprecate@1.0.2: {} + + utility@1.18.0: + dependencies: + copy-to: 2.0.1 + escape-html: 1.0.3 + mkdirp: 0.5.6 + mz: 2.7.0 + unescape: 1.0.1 + + uuid@14.0.0: {} + + uuid@14.0.2: {} + + vanilla-picker@2.12.3: + dependencies: + '@sphinxxxx/color-conversion': 2.2.2 + + vary@1.1.2: {} + + vite-node@1.4.0(@types/node@20.11.30)(sass@1.72.0): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + pathe: 1.1.2 + picocolors: 1.1.1 + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite-plugin-compression@0.5.1(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)): + dependencies: + chalk: 4.1.2 + debug: 4.4.3 + fs-extra: 10.0.0 + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - supports-color + + vite-plugin-svg-icons@2.0.1(vite@5.4.15(@types/node@20.11.30)(sass@1.72.0)): + dependencies: + '@types/svgo': 2.6.4 + cors: 2.8.6 + debug: 4.4.3 + etag: 1.8.1 + fs-extra: 10.0.0 + pathe: 0.2.0 + svg-baker: 1.7.0 + svgo: 2.8.4 + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + transitivePeerDependencies: + - supports-color + + vite-svg-loader@5.1.0(vue@3.4.21(typescript@5.4.3)): + dependencies: + svgo: 3.3.5 + vue: 3.4.21(typescript@5.4.3) + + vite@5.4.15(@types/node@20.11.30)(sass@1.72.0): + dependencies: + esbuild: 0.21.3 + postcss: 8.5.29 + rollup: 4.64.1 + optionalDependencies: + '@types/node': 20.11.30 + fsevents: 2.3.3 + sass: 1.72.0 + + vitest@1.4.0(@types/node@20.11.30)(jsdom@24.0.0)(sass@1.72.0): + dependencies: + '@vitest/expect': 1.4.0 + '@vitest/runner': 1.4.0 + '@vitest/snapshot': 1.4.0 + '@vitest/spy': 1.4.0 + '@vitest/utils': 1.4.0 + acorn-walk: 8.3.5 + chai: 4.3.10 + debug: 4.4.3 + execa: 8.0.1 + local-pkg: 0.5.0 + magic-string: 0.30.5 + pathe: 1.1.2 + picocolors: 1.1.1 + std-env: 3.5.0 + strip-literal: 2.0.0 + tinybench: 2.5.1 + tinypool: 0.8.2 + vite: 5.4.15(@types/node@20.11.30)(sass@1.72.0) + vite-node: 1.4.0(@types/node@20.11.30)(sass@1.72.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 20.11.30 + jsdom: 24.0.0 + transitivePeerDependencies: + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vue-component-type-helpers@2.0.0: {} + + vue-cropperjs@5.0.0(vue@3.4.21(typescript@5.4.3)): + dependencies: + cropperjs: 1.6.3 + vue: 3.4.21(typescript@5.4.3) + + vue-demi@0.14.10(vue@3.4.21(typescript@5.4.3)): + dependencies: + vue: 3.4.21(typescript@5.4.3) + + vue-eslint-parser@9.4.2(eslint@8.57.0): + dependencies: + debug: 4.4.3 + eslint: 8.57.0 + eslint-scope: 7.1.1 + eslint-visitor-keys: 3.3.0 + espree: 9.3.1 + esquery: 1.7.0 + lodash: 4.18.1 + semver: 7.8.5 + transitivePeerDependencies: + - supports-color + + vue-router@4.3.0(vue@3.4.21(typescript@5.4.3)): + dependencies: + '@vue/devtools-api': 6.5.1 + vue: 3.4.21(typescript@5.4.3) + + vue-template-compiler@2.7.16: + dependencies: + de-indent: 1.0.2 + he: 1.2.0 + + vue-tsc@2.0.7(typescript@5.4.3): + dependencies: + '@volar/typescript': 2.1.3 + '@vue/language-core': 2.0.7(typescript@5.4.3) + semver: 7.8.5 + typescript: 5.4.3 + + vue3-json-viewer@2.2.2(vue@3.4.21(typescript@5.4.3)): + dependencies: + clipboard: 2.0.11 + vue: 3.4.21(typescript@5.4.3) + + vue@3.4.21(typescript@5.4.3): + dependencies: + '@vue/compiler-dom': 3.4.21 + '@vue/compiler-sfc': 3.4.21 + '@vue/runtime-dom': 3.4.21 + '@vue/server-renderer': 3.4.21(vue@3.4.21(typescript@5.4.3)) + '@vue/shared': 3.4.21 + optionalDependencies: + typescript: 5.4.3 + + vuedraggable-es@4.1.1(vue@3.4.21(typescript@5.4.3)): + dependencies: + sortablejs: 1.14.0 + vue: 3.4.21(typescript@5.4.3) + + vxe-table-plugin-element@4.0.1(vxe-table@4.5.21(vue@3.4.21(typescript@5.4.3))(xe-utils@3.5.22)): + dependencies: + vxe-table: 4.5.21(vue@3.4.21(typescript@5.4.3))(xe-utils@3.5.22) + + vxe-table@4.5.21(vue@3.4.21(typescript@5.4.3))(xe-utils@3.5.22): + dependencies: + dom-zindex: 1.0.7 + vue: 3.4.21(typescript@5.4.3) + xe-utils: 3.5.22 + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@7.0.0: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-url@14.0.0: + dependencies: + tr46: 5.0.0 + webidl-conversions: 7.0.0 + + which-boxed-primitive@1.1.1: + dependencies: + is-bigint: 1.1.0 + is-boolean-object: 1.2.2 + is-number-object: 1.1.1 + is-string: 1.1.1 + is-symbol: 1.1.1 + + which-builtin-type@1.2.1: + dependencies: + call-bound: 1.0.4 + function.prototype.name: 1.2.0 + has-tostringtag: 1.0.2 + is-async-function: 2.1.1 + is-date-object: 1.1.0 + is-finalizationregistry: 1.1.1 + is-generator-function: 1.1.2 + is-regex: 1.2.1 + is-weakref: 1.1.1 + isarray: 2.0.5 + which-boxed-primitive: 1.1.1 + which-collection: 1.0.2 + which-typed-array: 1.1.24 + + which-collection@1.0.2: + dependencies: + is-map: 2.0.3 + is-set: 2.0.3 + is-weakmap: 2.0.2 + is-weakset: 2.0.4 + + which-typed-array@1.1.24: + dependencies: + available-typed-arrays: 1.0.7 + call-bind: 1.0.9 + call-bound: 1.0.4 + for-each: 0.3.5 + get-proto: 1.0.1 + gopd: 1.2.0 + has-tostringtag: 1.0.2 + + which@2.0.1: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wildcard@1.1.2: {} + + win-release@1.1.1: + dependencies: + semver: 5.0.1 + + wmf@1.0.2: {} + + word-wrap@1.2.5: {} + + word@0.3.0: {} + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.0.0 + string-width: 4.2.0 + strip-ansi: 6.0.1 + + wrap-ansi@8.1.0: + dependencies: + ansi-styles: 6.1.0 + string-width: 5.1.2 + strip-ansi: 7.2.0 + + wrap-ansi@9.0.0: + dependencies: + ansi-styles: 6.2.1 + string-width: 7.0.0 + strip-ansi: 7.2.0 + + wrappy@1.0.2: {} + + ws@8.22.0: {} + + xe-utils@3.5.22: {} + + xlsx@0.18.5: + dependencies: + adler-32: 1.3.1 + cfb: 1.2.2 + codepage: 1.15.0 + crc-32: 1.2.2 + ssf: 0.11.2 + wmf: 1.0.2 + word: 0.3.0 + + xml-name-validator@4.0.0: {} + + xml-name-validator@5.0.0: {} + + xml2js@0.4.23: + dependencies: + sax: 1.6.1 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + + xmlchars@2.2.0: {} + + xtend@4.0.2: {} + + yallist@3.1.1: {} + + yaml@2.3.4: {} + + yocto-queue@1.2.2: {} diff --git a/timi_hok_game_translator/LQA_WMP/web/pnpm-workspace.yaml b/timi_hok_game_translator/LQA_WMP/web/pnpm-workspace.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5a3f771506b97835e8637a745435e3c87087084 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/pnpm-workspace.yaml @@ -0,0 +1,7 @@ +allowBuilds: + aws-crt: false + core-js: false + cos-js-sdk-v5: false + es5-ext: false + esbuild: false + vue-demi: false diff --git a/timi_hok_game_translator/LQA_WMP/web/prettier.config.js b/timi_hok_game_translator/LQA_WMP/web/prettier.config.js new file mode 100644 index 0000000000000000000000000000000000000000..ee1dbc9e83c5ef82515b1946751c8a4bf0978da2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/prettier.config.js @@ -0,0 +1,22 @@ +/** + * 修改配置后重启编辑器 + * 配置项文档:https://prettier.io/docs/en/configuration.html + * @type {import("prettier").Config} + */ + +export default { + /** 每一行的宽度 */ + printWidth: 120, + /** 在对象中的括号之间是否用空格来间隔 */ + bracketSpacing: true, + /** 箭头函数的参数无论有几个,都要括号包裹 */ + arrowParens: 'always', + /** 换行符的使用 */ + endOfLine: 'auto', + /** 是否采用单引号 */ + singleQuote: true, + /** 对象或者数组的最后一个元素后面不要加逗号 */ + // trailingComma: 'none', + /** 是否加分号 */ + semi: true, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/public/app-loading.css b/timi_hok_game_translator/LQA_WMP/web/public/app-loading.css new file mode 100644 index 0000000000000000000000000000000000000000..b8f187b99bd4e80958e24b683930a3ebceccb8bb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/public/app-loading.css @@ -0,0 +1,46 @@ +/** 白屏阶段会执行的 CSS 加载动画 */ + +#app-loading { + position: relative; + top: 45vh; + margin: 0 auto; + color: #409eff; + font-size: 12px; +} + +#app-loading, +#app-loading::before, +#app-loading::after { + width: 2em; + height: 2em; + border-radius: 50%; + animation: 2s ease-in-out infinite app-loading-animation; +} + +#app-loading::before, +#app-loading::after { + content: ''; + position: absolute; +} + +#app-loading::before { + left: -4em; + animation-delay: -.2s; +} + +#app-loading::after { + left: 4em; + animation-delay: .2s; +} + +@keyframes app-loading-animation { + 0%, + 80%, + 100% { + box-shadow: 0 2em 0 -2em; + } + + 40% { + box-shadow: 0 2em 0 0; + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/public/favicon-copy.ico b/timi_hok_game_translator/LQA_WMP/web/public/favicon-copy.ico new file mode 100644 index 0000000000000000000000000000000000000000..de03843fcd59a08166d00b6789fae3995ffabe70 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/public/favicon-copy.ico differ diff --git a/timi_hok_game_translator/LQA_WMP/web/public/favicon.ico b/timi_hok_game_translator/LQA_WMP/web/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..e438c2f4e66330ecc397253296b3cb403d5f05cc Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/public/favicon.ico differ diff --git a/timi_hok_game_translator/LQA_WMP/web/settings.json b/timi_hok_game_translator/LQA_WMP/web/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..64247330ca305ecaba008b1e213b630f119a71db --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/settings.json @@ -0,0 +1,29 @@ +{ + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "[vue]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[jsonc]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[html]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[css]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[scss]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/App.vue b/timi_hok_game_translator/LQA_WMP/web/src/App.vue new file mode 100644 index 0000000000000000000000000000000000000000..871954bb0a52a523a5c03f956bd5f971e4e1b991 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/App.vue @@ -0,0 +1,17 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/403.svg b/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/403.svg new file mode 100644 index 0000000000000000000000000000000000000000..a92532238d9749ef33becd2298fdda6988ec98a8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/403.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/404.svg b/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/404.svg new file mode 100644 index 0000000000000000000000000000000000000000..d59f6f1766ee96e215fec6e2b0bceaeed8d1a198 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/assets/error-page/404.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/aim.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/aim.png new file mode 100644 index 0000000000000000000000000000000000000000..089c8dc3b36704de730e55cde142a8cb4bcc0e3c Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/aim.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-1.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-1.png new file mode 100644 index 0000000000000000000000000000000000000000..9076bbeb64ee225dda9684e865a829e81c44f356 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-1.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2-back.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2-back.png new file mode 100644 index 0000000000000000000000000000000000000000..8a1d9aa8e884284af65ac862f989b74bd0e6f187 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2-back.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2.png new file mode 100644 index 0000000000000000000000000000000000000000..74aaf98be770df6d088bec1cb864598c1edb4f0b Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo-text-2.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..b9b730aa855867b34a3566df96150177a9676393 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/layouts/logo.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/close-eyes.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/close-eyes.png new file mode 100644 index 0000000000000000000000000000000000000000..14e483a462f2b6967ee5f39b447b885e1b5cc1b0 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/close-eyes.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/face.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/face.png new file mode 100644 index 0000000000000000000000000000000000000000..a00cb688963096a413dafeb389ca88efa10cddcb Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/face.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-left.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-left.png new file mode 100644 index 0000000000000000000000000000000000000000..aefef6cf3085c5f9a954dbb45b2368eec82e8c79 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-left.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-right.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-right.png new file mode 100644 index 0000000000000000000000000000000000000000..a2602a6a0a021a920553d719fe0c604fc50f76c5 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-down-right.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-left.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-left.png new file mode 100644 index 0000000000000000000000000000000000000000..0d971f80555e577a1984b01c694827804ab11589 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-left.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-right.png b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-right.png new file mode 100644 index 0000000000000000000000000000000000000000..088fa16089012f7fdfb53b93c1895128aa536011 Binary files /dev/null and b/timi_hok_game_translator/LQA_WMP/web/src/assets/login/hand-up-right.png differ diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/NotifyList.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/NotifyList.vue new file mode 100644 index 0000000000000000000000000000000000000000..d6685b94a801f64bd120ee560ecb9f9c63567d0a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/NotifyList.vue @@ -0,0 +1,58 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/data.ts b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/data.ts new file mode 100644 index 0000000000000000000000000000000000000000..07338d53fbf180a19d09867afb13288e2bb9b453 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/data.ts @@ -0,0 +1,66 @@ +export interface ListItem { + avatar?: string + title: string + datetime?: string + description?: string + status?: 'primary' | 'success' | 'info' | 'warning' | 'danger' + extra?: string +} + +export const notifyData: ListItem[] = [ + { + avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png', + title: 'V3 Admin Vite 上线啦', + datetime: '一年前', + description: + '一个免费开源的中后台管理系统基础解决方案,基于 Vue3、TypeScript、Element Plus、Pinia 和 Vite 等主流技术', + }, + { + avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png', + title: 'V3 Admin 上线啦', + datetime: '两年前', + description: '一个中后台管理系统基础解决方案,基于 Vue3、TypeScript、Element Plus 和 Pinia', + }, +]; + +export const messageData: ListItem[] = [ + { + avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', + title: '来自楚门的世界', + description: '如果再也不能见到你,祝你早安、午安和晚安', + datetime: '1998-06-05', + }, + { + avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', + title: '来自大话西游', + description: '如果非要在这份爱上加上一个期限,我希望是一万年', + datetime: '1995-02-04', + }, + { + avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png', + title: '来自龙猫', + description: '心存善意,定能途遇天使', + datetime: '1988-04-16', + }, +]; + +export const todoData: ListItem[] = [ + { + title: '任务名称', + description: '这家伙很懒,什么都没留下', + extra: '未开始', + status: 'info', + }, + { + title: '任务名称', + description: '这家伙很懒,什么都没留下', + extra: '进行中', + status: 'primary', + }, + { + title: '任务名称', + description: '这家伙很懒,什么都没留下', + extra: '已超时', + status: 'danger', + }, +]; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..33d0818f2fc9263463b41cc88d96c69e26637390 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/Notify/index.vue @@ -0,0 +1,93 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/Screenfull/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/Screenfull/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..8ba1a962af197f0d4107b14911b27edbdadde059 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/Screenfull/index.vue @@ -0,0 +1,95 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchFooter.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchFooter.vue new file mode 100644 index 0000000000000000000000000000000000000000..cbb1fcada14527912b42d0571f732d81d15048da --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchFooter.vue @@ -0,0 +1,60 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchModal.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchModal.vue new file mode 100644 index 0000000000000000000000000000000000000000..3d0091fb2e9b766bcb7b0ca8d7070e8fb36489a0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchModal.vue @@ -0,0 +1,200 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchResult.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchResult.vue new file mode 100644 index 0000000000000000000000000000000000000000..33ff80f47028f2e777018a99ddb363540e1c9dc2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/SearchResult.vue @@ -0,0 +1,111 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..ef7f0ea893546c56ea4a65c38fc304f5b8e2bc79 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/SearchMenu/index.vue @@ -0,0 +1,29 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/SvgIcon/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/SvgIcon/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..e981b0e0b73f01d57f076f8af1e4b357e516ab2b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/SvgIcon/index.vue @@ -0,0 +1,29 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/ThemeSwitch/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/ThemeSwitch/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..e8fd97f6323bd12a526442e8efb5a44f802b115a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/ThemeSwitch/index.vue @@ -0,0 +1,50 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/autoPopover.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/autoPopover.vue new file mode 100644 index 0000000000000000000000000000000000000000..5bdcfea6fe585e33ba9cd716f40bf7b8b01616a2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/autoPopover.vue @@ -0,0 +1,43 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/index.js b/timi_hok_game_translator/LQA_WMP/web/src/components/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f1dff5f1d2181ae02b20196ca7450657f05933df --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/index.js @@ -0,0 +1,7 @@ +import scFormTable from './scFormTable/index.vue'; + +export default { + install(app) { + app.component('ScFormTable', scFormTable); + }, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/numberRange.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/numberRange.vue new file mode 100644 index 0000000000000000000000000000000000000000..f219501db61e3fc83528f5d1db0a77d8d4ac3e19 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/numberRange.vue @@ -0,0 +1,104 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/scEditor/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/scEditor/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..37efdda37efd60ed4577d5ff766aabc217c6e53a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/scEditor/index.vue @@ -0,0 +1,269 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/components/scFormTable/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/components/scFormTable/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..86e9f28ae14bb43b96894ca54701d2cc4994e1d4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/components/scFormTable/index.vue @@ -0,0 +1,125 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/config/layouts.ts b/timi_hok_game_translator/LQA_WMP/web/src/config/layouts.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ffd6cc67294771aa20fd37fbae911026f20ea33 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/config/layouts.ts @@ -0,0 +1,55 @@ +import { getConfigLayout } from '@/utils/cache/local-storage'; +import { LayoutModeEnum } from '@/constants/app-key'; + +/** 项目配置类型 */ +export interface LayoutSettings { + /** 是否显示 Settings Panel */ + showSettings: boolean + /** 布局模式 */ + layoutMode: LayoutModeEnum + /** 是否显示标签栏 */ + showTagsView: boolean + /** 是否显示 Logo */ + showLogo: boolean + /** 是否固定 Header */ + fixedHeader: boolean + /** 是否显示页脚 Footer */ + showFooter: boolean + /** 是否显示消息通知 */ + showNotify: boolean + /** 是否显示切换主题按钮 */ + showThemeSwitch: boolean + /** 是否显示全屏按钮 */ + showScreenfull: boolean + /** 是否显示搜索按钮 */ + showSearchMenu: boolean + /** 是否缓存标签栏 */ + cacheTagsView: boolean + /** 开启系统水印 */ + showWatermark: boolean + /** 是否显示灰色模式 */ + showGreyMode: boolean + /** 是否显示色弱模式 */ + showColorWeakness: boolean +} + +/** 默认配置 */ +const defaultSettings: LayoutSettings = { + layoutMode: LayoutModeEnum.LeftTop, // 布局配置 + showSettings: true, + showTagsView: true, + fixedHeader: true, + showFooter: true, + showLogo: true, + showNotify: false, // 显示消息通知 + showThemeSwitch: false, // 显示切换主题 + showScreenfull: true, + showSearchMenu: false, // 显示搜索按钮 + cacheTagsView: false, + showWatermark: false, // 开启系统水印 + showGreyMode: false, + showColorWeakness: false, +}; + +/** 项目配置 */ +export const layoutSettings: LayoutSettings = { ...defaultSettings, ...getConfigLayout() }; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/config/route.ts b/timi_hok_game_translator/LQA_WMP/web/src/config/route.ts new file mode 100644 index 0000000000000000000000000000000000000000..0944e17de7205fa787e16d3768f13823b70b23cb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/config/route.ts @@ -0,0 +1,28 @@ +/** 路由配置 */ +interface RouteSettings { + /** + * 是否开启动态路由功能? + * 1. 开启后需要后端配合,在查询用户详情接口返回当前用户可以用来判断并加载动态路由的字段(该项目用的是角色 roles 字段) + * 2. 假如项目不需要根据不同的用户来显示不同的页面,则应该将 dynamic: false + */ + dynamic: boolean + /** 当动态路由功能关闭时: + * 1. 应该将所有路由都写到常驻路由里面(表明所有登录的用户能访问的页面都是一样的) + * 2. 系统自动给当前登录用户赋值一个没有任何作用的默认角色 + */ + defaultRoles: Array + /** + * 是否开启三级及其以上路由缓存功能? + * 1. 开启后会进行路由降级(把三级及其以上的路由转化为二级路由) + * 2. 由于都会转成二级路由,所以二级及其以上路由有内嵌子路由将会失效 + */ + thirdLevelRouteCache: boolean +} + +const routeSettings: RouteSettings = { + dynamic: true, + defaultRoles: ['DEFAULT_ROLE'], + thirdLevelRouteCache: false, +}; + +export default routeSettings; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/config/white-list.ts b/timi_hok_game_translator/LQA_WMP/web/src/config/white-list.ts new file mode 100644 index 0000000000000000000000000000000000000000..27a4d31a25857c102dba71e15f98e1634abb529d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/config/white-list.ts @@ -0,0 +1,15 @@ +import { type RouteLocationNormalized } from 'vue-router'; + +/** 免登录白名单(匹配路由 path) */ +const whiteListByPath: string[] = ['/login', '/register']; + +/** 免登录白名单(匹配路由 name) */ +const whiteListByName: string[] = []; + +/** 判断是否在白名单 */ +const isWhiteList = (to: RouteLocationNormalized) => + // path 和 name 任意一个匹配上即可 + whiteListByPath.indexOf(to.path) !== -1 || whiteListByName.indexOf(to.name as any) !== -1; + + +export default isWhiteList; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/constants/app-key.ts b/timi_hok_game_translator/LQA_WMP/web/src/constants/app-key.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f030bafec5a68e534b6f33f0b68bf15a612194f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/constants/app-key.ts @@ -0,0 +1,22 @@ +/** 设备类型 */ +export enum DeviceEnum { + Mobile, + Desktop +} + +/** 布局模式 */ +export enum LayoutModeEnum { + Left = 'left', + Top = 'top', + LeftTop = 'left-top' +} + +/** 侧边栏打开状态常量 */ +export const SIDEBAR_OPENED = 'opened'; +/** 侧边栏关闭状态常量 */ +export const SIDEBAR_CLOSED = 'closed'; + +export type SidebarOpened = typeof SIDEBAR_OPENED; +export type SidebarClosed = typeof SIDEBAR_CLOSED; + +export const SUPER_ADMIN_PROJECT_ID = 0; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/constants/cache-key.ts b/timi_hok_game_translator/LQA_WMP/web/src/constants/cache-key.ts new file mode 100644 index 0000000000000000000000000000000000000000..4bd65e4ad79b81350daeb4afe764608b88a549c0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/constants/cache-key.ts @@ -0,0 +1,15 @@ +const SYSTEM_NAME = 'v3-admin-vite'; + +/** 缓存数据时用到的 Key */ +class CacheKey { + static readonly TOKEN = `${SYSTEM_NAME}-token-key`; + static readonly USERNAME_EN = `${SYSTEM_NAME}-username-en-key`; + static readonly USERNAME_CH = `${SYSTEM_NAME}-username-ch-key`; + static readonly CONFIG_LAYOUT = `${SYSTEM_NAME}-config-layout-key`; + static readonly SIDEBAR_STATUS = `${SYSTEM_NAME}-sidebar-status-key`; + static readonly ACTIVE_THEME_NAME = `${SYSTEM_NAME}-active-theme-name-key`; + static readonly VISITED_VIEWS = `${SYSTEM_NAME}-visited-views-key`; + static readonly CACHED_VIEWS = `${SYSTEM_NAME}-cached-views-key`; +} + +export default CacheKey; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/directives/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/directives/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..95526364ff210c983fbfe7d00e6f83b4209b6005 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/directives/index.ts @@ -0,0 +1,7 @@ +import { type App } from 'vue'; +import { permission } from './permission'; + +/** 挂载自定义指令 */ +export function loadDirectives(app: App) { + app.directive('permission', permission); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/directives/permission/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/directives/permission/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..70179f65519c99acbb0db79686c5a1fe5b5e5bd2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/directives/permission/index.ts @@ -0,0 +1,20 @@ +import { type Directive } from 'vue'; +import { useUserStoreHook } from '@/store/modules/user'; + +/** 权限指令,和权限判断函数 checkPermission 功能类似 */ +export const permission: Directive = { + mounted(el, binding) { + const { value: permissionRoles } = binding; + const { roles, superAdmin } = useUserStoreHook(); + if (superAdmin) { + return true; + } + if (Array.isArray(permissionRoles) && permissionRoles.length > 0) { + const hasPermission = roles.some(role => permissionRoles.includes(role)); + // hasPermission || (el.style.display = "none") // 隐藏 + hasPermission || el.parentNode?.removeChild(el); // 销毁 + } else { + throw new Error('need roles! Like v-permission="[\'admin\',\'editor\']"'); + } + }, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/common.ts b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/common.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a6bc3a9a7a74e0b8300b497391892dca511763a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/common.ts @@ -0,0 +1,25 @@ +export const timeCols = { + // 创建时间 + created_at: { + title: '创建时间', + type: 'datetime', + form: { show: false }, + }, + // 更新时间 + updated_at: { + title: '更新时间', + type: 'datetime', + form: { show: false }, + column: { + // 空渲染 + conditionalRender: { + match(scope: any) { + return !scope.value; + }, + render() { + return ''; + }, + }, + }, + }, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..75d1e198380ce83af33d97051eb9b29e795fec11 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/index.ts @@ -0,0 +1,242 @@ +import { dict, FastCrud, useTypes, setLogger } from '@fast-crud/fast-crud'; +import '@fast-crud/fast-crud/dist/style.css'; +import { FsExtendsEditor, FsExtendsJson, FsExtendsCopyable, FsExtendsTime, FsExtendsUploader } from '@fast-crud/fast-extends'; +import '@fast-crud/fast-extends/dist/style.css'; +import UiElement from '@fast-crud/ui-element'; +// import API from '@/api'; +// import tool from '@/utils/tool'; +// import sysConfig from '@/config'; +import './style.scss'; +import { customRequest } from '@/utils/service'; +import { App } from 'vue'; + +function install(app: App, options: any = {}) { + app.use(UiElement); + setLogger({ level: 'error' }); + // @ts-ignore + app.use(FastCrud, { + i18n: options.i18n, + async dictRequest({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + return data.list; + }, + /** + * useCrud时会被执行 + */ + commonOptions() { + return { + search: { + autoSearch: false, + container: { + col: { span: 6 }, // 默认列宽度配置 + }, + }, + /** 表格上方 */ + // 「右上」工具栏 + toolbar: { + compact: false, + // 导出 + export: { + onlyShow: true, + columnBuilder: ({ col }) => { + col.title = col.title.replace('\n', ''); + // 列构建器,调整列宽 + // col.width = '200px'; + }, + }, + buttons: { + search: { show: false }, + // compact: { show: false }, + columns: { show: false }, + refresh: { type: '' }, + }, + }, + // 「左上」动作条 + actionbar: { + buttons: { + add: { + title: '', + }, + }, + }, + + // 操作列 + rowHandle: { + buttons: { + // 查看 + view: { + size: 'small', + title: '', + icon: 'View', + text: null, + style: { height: '30px', width: '32px' }, + tooltip: { content: '查看', enterable: false }, + show: false, + order: 1, + }, + // 编辑 + edit: { + size: 'small', + title: '', + icon: 'EditPen', + text: null, + style: { height: '30px', width: '32px' }, + tooltip: { content: '编辑', enterable: false }, + order: 2, + }, + // 删除 + remove: { + size: 'small', + title: '', + icon: 'Delete', + // class: 'fs-button is-thin', + text: null, + style: { height: '30px', width: '32px' }, + // style: { height: "34px" }, + tooltip: { content: '删除', enterable: false }, + order: 3, + }, + // dropdown: { + // more: { + // size: "default" + // } + // } + }, + fixed: 'right', + align: 'center', + width: 110, + }, + + table: { + size: 'default', + rowKey: 'id', + showOverflowTooltip: true, + headerCellStyle: { + background: '#f5f7fa', + }, + cellClassName: ({ column }: { column: any }) => { + if (!column.showOverflowTooltip) { + return 'no-table-cell-text-ellipsis'; + } + }, + }, + + request: { + transformQuery: ({ page, form, sort }) => { + // @ts-ignore + const order = sort === null ? {} : { orderProp: sort.prop, orderAsc: sort.asc }; + // @ts-ignore + return { page: page.currentPage, page_size: page.pageSize, ...form, ...order }; + }, + // @ts-ignore + transformRes: ({ res }) => ({ + currentPage: res.data.page || 1, pageSize: res.data.page_size || res.data?.list?.length || 20, + total: res.data.total || res.data?.list?.length || 0, records: res.data.list, ...res, + }), + }, + // 表单 + form: { + display: 'flex', + labelWidth: '94px', + wrapper: { + // width: '1000px', + // draggable: true, + }, + }, + }; + }, + }); + + // fast-extends里面的扩展组件均为异步组件,只有在使用时才会被加载,并不会影响首页加载速度 + // 安装editor + // @ts-ignore + app.use(FsExtendsEditor, { + // 编辑器的公共配置 + wangEditor: {}, + quillEditor: {}, + }); + app.use(FsExtendsCopyable); + app.use(FsExtendsJson); + app.use(FsExtendsTime); + + // 安装uploader 公共参数 + app.use(FsExtendsUploader, { + defaultType: 'form', + form: { + name: 'file', + withCredentials: false, + uploadRequest: async ({ file }) => { + const data = new FormData(); + // const token = tool.cookie.get('TOKEN'); + data.append('file', file); + // data.append('file_type_id', action); + return await customRequest({ + url: '/api/upload_file', + method: 'post', + data, + headers: { + 'Content-Type': 'multipart/form-data', + }, + }); + }, + successHandle(ret) { + return Promise.resolve({ url: `${import.meta.env.VITE_RESOURCE_API}${ret.data.file_path}` }); + }, + }, + }); + + // 修改官方字段类型 + // 不要写在页面里,这个是全局的,要写在vue.use(FastCrud)之后 + const { getType } = useTypes(); + + /** dict-select */ + const selectType = getType('dict-select'); + // 下拉框 + selectType.form.component.filterable = true; // 可过滤 + selectType.form.component.style = { width: '100%' }; // 宽度 100% + // values-format + selectType.column.component.color = 'auto'; // 修改官方的字段类型,设置为支持自动染色 + // selectType.column.component.effect = 'plain'; + selectType.column.component.autoEffects = ['plain']; + selectType.column.showOverflowTooltip = false; + selectType.search.component = { collapseTags: true, maxCollapseTags: 3, collapseTagsTooltip: true }; + + /** dict-cascader */ + const cascaderType = getType('dict-cascader'); + cascaderType.column.component = { + name: 'fs-values-format', + color: 'auto', + autoEffects: ['plain'], + }; + + /** number */ + // const numberType = getType('number'); + // numberType.form.component['controls-position'] = 'right'; + + /** text */ + // const textType = getType('text'); + // textType.search.autoSearchTrigger = true; // 修改官方的字段类型,设置为文本变化就触发查询 + + /** dict-switch */ + const switchType = getType('dict-switch'); + switchType.column.align = 'center'; + const switchOptions = [ + { value: 1, label: '是', color: 'success' }, + { value: 0, label: '否', color: 'error' }, + ]; + switchType.dict = dict({ data: switchOptions }); + switchType.form.component.dict = dict({ + data: switchOptions.map(item => ({ ...item, label: '' })), + }); + switchType.search.component.dict = dict({ data: switchOptions }); + + // image-uploader + const imageUploaderType = getType('image-uploader'); + imageUploaderType.column.component.style = { height: '100%' }; +} + +export default { + install, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/presets.js b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/presets.js new file mode 100644 index 0000000000000000000000000000000000000000..e2b4dac91971638a9bed322a6a0e4b9cfeae5c8e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/presets.js @@ -0,0 +1,60 @@ +import { dict, useCompute } from '@fast-crud/fast-crud'; +// import basicApi from '@/api'; +import { request } from '@/utils/service'; + +const { compute } = useCompute(); + +/** + * 下拉框过滤创建,可根据 ;|, 批量创建 + */ +function autoCreate(key) { + return { + multiple: true, + allowCreate: true, + defaultFirstOption: true, + reserveKeyword: false, + filterMethod: compute(({ form }) => { + function userFilter(e) { + if (e.search(',|;') !== -1) { + e.split(/;|,/).map((item) => { + const properValue = item.trim(); + if (properValue && !form[key].includes(properValue)) { + form[key].push(properValue); + } + }); + } + } + + return userFilter; + }), + }; +} + +// function userFormatDict(projectId) { +// return dict({ +// url: () => { +// const params = { current: 1, limit: 10000 }; +// if (projectId) { +// params.project_id = projectId; +// } +// const queryParams = new URLSearchParams(params); +// return `${basicApi.basics.user.url}?${queryParams}`; +// }, +// getData: async ({ url }) => { +// const { records } = await http.get(url); +// records.forEach((item) => { +// // eslint-disable-next-line no-param-reassign +// item.userFormatName = `${item.user_name}(${item.user_chn_name})`; +// }); +// return records; +// }, +// value: 'user_name', +// label: 'userFormatName', +// cache: false, +// }); +// } + +export { + // userFormatDict, + autoCreate, +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/style.scss b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/style.scss new file mode 100644 index 0000000000000000000000000000000000000000..de40dd1ce62598eacba8aa12af10aba3108208c7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/fast-crud/style.scss @@ -0,0 +1,98 @@ +.adminui-main { + position: relative; +} + +.fs-form-wrapper { + .fs-form-header { + .fs-form-header-left { + justify-items: flex-start; + font-weight: bold; + font-size: medium; + } + + .fs-form-header-action { + display: flex; + justify-content: center; + align-items: center; + } + } +} + +.fs-form { + // 折叠面板 + .el-collapse-item { + .el-collapse-item__header { + font-size: 14px; + } + // 折叠面板不设间距 + .el-collapse-item__content { + padding: 0; + padding-bottom: 21px; + } + } +} + +.fs-file-uploader .el-upload--picture-card i { + margin-top: 0; +} +// 弹窗 +.fs-form-wrapper { + .el-dialog__header { + padding: 0 0 20px; + + // 全屏按钮 + .fs-form-header-action { + position: absolute; + top: 4.5px; + right: 0; + width: 108px; + height: 45px; + padding: 0; + font-size: var(--el-message-close-size, 15px); + color: var(--el-color-info); + cursor: pointer; + background: transparent; + border: none; + outline: none; + + :hover { + color: var(--el-color-primary); + } + } + + // 关闭按钮 + .el-dialog__headerbtn { + right: 13px; + width: 30px; + } + } +} +// 操作列 +.fs-row-handle { + // 按钮间距 + .el-button + .el-button { + margin-left: 6px; + } +} +.fs-row-handle > * { + align-items: center; +} + +// container 不要最小高度 +.no-min-height.fs-crud-container { + min-height: 0; +} + +// 图片自由比例展示 +.pic-free { + // 自带的裁剪上传 + .fs-cropper-uploader .image-list .image-item, + .fs-cropper-uploader .image-list .image-item .image { + width: auto; + min-width: 100px; + + img { + max-height: 100px; + } + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useDevice.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useDevice.ts new file mode 100644 index 0000000000000000000000000000000000000000..16b6e60926c319f1e1e1bbfb26402505c82be643 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useDevice.ts @@ -0,0 +1,11 @@ +import { computed } from 'vue'; +import { useAppStore } from '@/store/modules/app'; +import { DeviceEnum } from '@/constants/app-key'; + +const appStore = useAppStore(); +const isMobile = computed(() => appStore.device === DeviceEnum.Mobile); +const isDesktop = computed(() => appStore.device === DeviceEnum.Desktop); + +export function useDevice() { + return { isMobile, isDesktop }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFetchSelect.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFetchSelect.ts new file mode 100644 index 0000000000000000000000000000000000000000..5267ed337686ac84abe4301953e2d5be7fd93298 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFetchSelect.ts @@ -0,0 +1,49 @@ +import { ref, onMounted } from 'vue'; + +type OptionValue = string | number; + +/** Select 需要的数据格式 */ +interface SelectOption { + value: OptionValue + label: string + disabled?: boolean +} + +/** 接口响应格式 */ +type ApiData = ApiResponseData; + +/** 入参格式,暂时只需要传递 api 函数即可 */ +interface FetchSelectProps { + api: () => Promise +} + +export function useFetchSelect(props: FetchSelectProps) { + const { api } = props; + + const loading = ref(false); + const options = ref([]); + const value = ref(''); + + /** 调用接口获取数据 */ + const loadData = () => { + loading.value = true; + options.value = []; + api() + .then((res) => { + options.value = res.data; + }) + .finally(() => { + loading.value = false; + }); + }; + + onMounted(() => { + loadData(); + }); + + return { + loading, + options, + value, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFullscreenLoading.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFullscreenLoading.ts new file mode 100644 index 0000000000000000000000000000000000000000..44000ed954cd11da58bedfcb00a6afc5207a1bad --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useFullscreenLoading.ts @@ -0,0 +1,33 @@ +import { type LoadingOptions, ElLoading } from 'element-plus'; + +const defaultOptions = { + lock: true, + text: '加载中...', +}; + +interface LoadingInstance { + close: () => void +} + +type UseFullscreenLoading = ReturnType>( + fn: T, + options?: LoadingOptions + ) => (...args: Parameters) => Promise>; + +/** + * 传入一个函数 fn,在它执行周期内,加上「全屏」loading + * @param fn 要执行的函数 + * @param options LoadingOptions + * @returns 返回一个新的函数,该函数返回一个 Promise + */ +export const useFullscreenLoading: UseFullscreenLoading = (fn, options = {}) => { + let loadingInstance: LoadingInstance; + return async (...args) => { + try { + loadingInstance = ElLoading.service({ ...defaultOptions, ...options }); + return await fn(...args); + } finally { + loadingInstance?.close(); + } + }; +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useLayoutMode.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useLayoutMode.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bfd6ba2348c1e2ca5a789f5a2c74abe44749280 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useLayoutMode.ts @@ -0,0 +1,16 @@ +import { computed } from 'vue'; +import { useSettingsStore } from '@/store/modules/settings'; +import { LayoutModeEnum } from '@/constants/app-key'; + +const settingsStore = useSettingsStore(); +const isLeft = computed(() => settingsStore.layoutMode === LayoutModeEnum.Left); +const isTop = computed(() => settingsStore.layoutMode === LayoutModeEnum.Top); +const isLeftTop = computed(() => settingsStore.layoutMode === LayoutModeEnum.LeftTop); + +const setLayoutMode = (mode: LayoutModeEnum) => { + settingsStore.layoutMode = mode; +}; + +export function useLayoutMode() { + return { isLeft, isTop, isLeftTop, setLayoutMode }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/usePagination.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/usePagination.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb3dc2807cd7d68b69c626493fc8caae7feea011 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/usePagination.ts @@ -0,0 +1,41 @@ +import { reactive } from 'vue'; + +interface DefaultPaginationData { + total: number + currentPage: number + pageSizes: number[] + pageSize: number + layout: string +} + +interface PaginationData { + total?: number + currentPage?: number + pageSizes?: number[] + pageSize?: number + layout?: string +} + +/** 默认的分页参数 */ +const defaultPaginationData: DefaultPaginationData = { + total: 0, + currentPage: 1, + pageSizes: [10, 20, 50], + pageSize: 10, + layout: 'total, sizes, prev, pager, next, jumper', +}; + +export function usePagination(initialPaginationData: PaginationData = {}) { + /** 合并分页参数 */ + const paginationData = reactive({ ...defaultPaginationData, ...initialPaginationData }); + /** 改变当前页码 */ + const handleCurrentChange = (value: number) => { + paginationData.currentPage = value; + }; + /** 改变页面大小 */ + const handleSizeChange = (value: number) => { + paginationData.pageSize = value; + }; + + return { paginationData, handleCurrentChange, handleSizeChange }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useRouteListener.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useRouteListener.ts new file mode 100644 index 0000000000000000000000000000000000000000..36868272b2098127985675e0f3665a6b211b3d22 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useRouteListener.ts @@ -0,0 +1,48 @@ +import { onBeforeUnmount } from 'vue'; +import mitt, { type Handler } from 'mitt'; +import { type RouteLocationNormalized } from 'vue-router'; + +/** 回调函数的类型 */ +type Callback = (route: RouteLocationNormalized) => void; + +const emitter = mitt(); +const key = Symbol('ROUTE_CHANGE'); +let latestRoute: RouteLocationNormalized; + +/** 设置最新的路由信息,触发路由变化事件 */ +export const setRouteChange = (to: RouteLocationNormalized) => { + // 触发事件 + emitter.emit(key, to); + // 缓存最新的路由信息 + latestRoute = to; +}; + +/** 单独监听路由会浪费渲染性能,使用发布订阅模式去进行分发管理 */ +export function useRouteListener() { + /** 回调函数集合 */ + const callbackList: Callback[] = []; + + /** 监听路由变化(可以选择立即执行) */ + const listenerRouteChange = (callback: Callback, immediate = false) => { + // 缓存回调函数 + callbackList.push(callback); + // 监听事件 + emitter.on(key, callback as Handler); + // 可以选择立即执行一次回调函数 + immediate && latestRoute && callback(latestRoute); + }; + + /** 移除路由变化事件监听器 */ + const removeRouteListener = (callback: Callback) => { + emitter.off(key, callback as Handler); + }; + + /** 组件销毁前移除监听器 */ + onBeforeUnmount(() => { + for (let i = 0; i < callbackList.length; i++) { + removeRouteListener(callbackList[i]); + } + }); + + return { listenerRouteChange, removeRouteListener }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTheme.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTheme.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed4705002db332d9c89f38e749290990f2083f0a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTheme.ts @@ -0,0 +1,57 @@ +import { ref, watchEffect } from 'vue'; +import { getActiveThemeName, setActiveThemeName } from '@/utils/cache/local-storage'; + +const DEFAULT_THEME_NAME = 'normal'; +type DefaultThemeName = typeof DEFAULT_THEME_NAME; + +/** 注册的主题名称, 其中 DefaultThemeName 是必填的 */ +export type ThemeName = DefaultThemeName | 'dark' | 'dark-blue'; + +interface ThemeList { + title: string + name: ThemeName +} + +/** 主题列表 */ +const themeList: ThemeList[] = [ + { + title: '默认', + name: DEFAULT_THEME_NAME, + }, + { + title: '黑暗', + name: 'dark', + }, + { + title: '深蓝', + name: 'dark-blue', + }, +]; + +/** 正在应用的主题名称 */ +const activeThemeName = ref(getActiveThemeName() || DEFAULT_THEME_NAME); + +/** 设置主题 */ +const setTheme = (value: ThemeName) => { + activeThemeName.value = value; +}; + +/** 在 html 根元素上挂载 class */ +const setHtmlRootClassName = (value: ThemeName) => { + document.documentElement.className = value; +}; + +/** 初始化 */ +const initTheme = () => { + // watchEffect 来收集副作用 + watchEffect(() => { + const { value } = activeThemeName; + setHtmlRootClassName(value); + setActiveThemeName(value); + }); +}; + +/** 主题 hook */ +export function useTheme() { + return { themeList, activeThemeName, initTheme, setTheme }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTitle.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTitle.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff91400f964bcdea0896fcf0541fc61db0abedb1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useTitle.ts @@ -0,0 +1,23 @@ +import { ref, watch } from 'vue'; + +/** 项目标题 */ +const VITE_APP_TITLE = import.meta.env.VITE_APP_TITLE ?? 'V3 Admin Vite'; + +/** 动态标题 */ +const dynamicTitle = ref(''); + +/** 设置标题 */ +const setTitle = (title?: string) => { + dynamicTitle.value = title ? `${VITE_APP_TITLE} | ${title}` : VITE_APP_TITLE; +}; + +/** 监听标题变化 */ +watch(dynamicTitle, (value, oldValue) => { + if (document && value !== oldValue) { + document.title = value; + } +}); + +export function useTitle() { + return { setTitle }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/hooks/useWatermark.ts b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useWatermark.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e3dc9cfd7fd01320e0210d180b51b96c6c8d80a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/hooks/useWatermark.ts @@ -0,0 +1,232 @@ +import { type Ref, onBeforeUnmount, ref } from 'vue'; +import { debounce } from 'lodash-es'; + +type Observer = { + watermarkElMutationObserver?: MutationObserver + parentElMutationObserver?: MutationObserver + parentElResizeObserver?: ResizeObserver +}; + +type DefaultConfig = typeof defaultConfig; + +/** 默认配置 */ +const defaultConfig = { + /** 防御(默认开启,能防御水印被删除或隐藏,但可能会有性能损耗) */ + defense: true, + /** 文本颜色 */ + color: '#c0c4cc', + /** 文本透明度 */ + opacity: 0.5, + /** 文本字体大小 */ + size: 16, + /** 文本字体 */ + family: 'serif', + /** 文本倾斜角度 */ + angle: -20, + /** 一处水印所占宽度(数值越大水印密度越低) */ + width: 300, + /** 一处水印所占高度(数值越大水印密度越低) */ + height: 200, +}; + +/** body 元素 */ +const bodyEl = ref(document.body); + +/** + * 创建水印 + * 1. 可以选择传入挂载水印的容器元素,默认是 body + * 2. 做了水印防御,能有效防御别人打开控制台删除或隐藏水印 + */ +export function useWatermark(parentEl: Ref = bodyEl) { + /** 备份文本 */ + let backupText: string; + /** 最终配置 */ + let mergeConfig: DefaultConfig; + /** 水印元素 */ + let watermarkEl: HTMLElement | null = null; + /** 观察器 */ + const observer: Observer = { + watermarkElMutationObserver: undefined, + parentElMutationObserver: undefined, + parentElResizeObserver: undefined, + }; + + /** 设置水印 */ + const setWatermark = (text: string, config: Partial = {}) => { + if (!parentEl.value) { + console.warn('请在 DOM 挂载完成后再调用 setWatermark 方法设置水印'); + return; + } + // 备份文本 + backupText = text; + // 合并配置 + mergeConfig = { ...defaultConfig, ...config }; + // 创建或更新水印元素 + watermarkEl ? updateWatermarkEl() : createWatermarkEl(); + // 监听水印元素和容器元素的变化 + addElListener(parentEl.value); + }; + + /** 创建水印元素 */ + const createWatermarkEl = () => { + const isBody = parentEl.value!.tagName.toLowerCase() === bodyEl.value.tagName.toLowerCase(); + const watermarkElPosition = isBody ? 'fixed' : 'absolute'; + const parentElPosition = isBody ? '' : 'relative'; + watermarkEl = document.createElement('div'); + watermarkEl.style.pointerEvents = 'none'; + watermarkEl.style.top = '0'; + watermarkEl.style.left = '0'; + watermarkEl.style.position = watermarkElPosition; + watermarkEl.style.zIndex = '99999'; + const { clientWidth, clientHeight } = parentEl.value!; + updateWatermarkEl({ width: clientWidth, height: clientHeight }); + // 设置水印容器为相对定位 + parentEl.value!.style.position = parentElPosition; + // 将水印元素添加到水印容器中 + parentEl.value!.appendChild(watermarkEl); + }; + + /** 更新水印元素 */ + const updateWatermarkEl = (options: Partial<{ + width: number + height: number + }> = {}) => { + if (!watermarkEl) return; + backupText && (watermarkEl.style.background = `url(${createBase64()}) left top repeat`); + options.width && (watermarkEl.style.width = `${options.width}px`); + options.height && (watermarkEl.style.height = `${options.height}px`); + }; + + /** 创建 base64 图片 */ + const createBase64 = () => { + const { color, opacity, size, family, angle, width, height } = mergeConfig; + const canvasEl = document.createElement('canvas'); + canvasEl.width = width; + canvasEl.height = height; + const ctx = canvasEl.getContext('2d'); + if (ctx) { + ctx.fillStyle = color; + ctx.globalAlpha = opacity; + ctx.font = `${size}px ${family}`; + ctx.rotate((Math.PI / 180) * angle); + ctx.fillText(backupText, 0, height / 2); + } + return canvasEl.toDataURL(); + }; + + /** 清除水印 */ + const clearWatermark = () => { + if (!parentEl.value || !watermarkEl) return; + // 移除对水印元素和容器元素的监听 + removeListener(); + // 移除水印元素 + try { + parentEl.value.removeChild(watermarkEl); + } catch { + // 比如在无防御情况下,用户打开控制台删除了这个元素 + console.warn('水印元素已不存在,请重新创建'); + } finally { + watermarkEl = null; + } + }; + + /** 刷新水印(防御时调用) */ + const updateWatermark = debounce(() => { + clearWatermark(); + createWatermarkEl(); + addElListener(parentEl.value!); + }, 100); + + /** 监听水印元素和容器元素的变化(DOM 变化 & DOM 大小变化) */ + const addElListener = (targetNode: HTMLElement) => { + // 判断是否开启防御 + if (mergeConfig.defense) { + // 防止重复添加监听 + if (!observer.watermarkElMutationObserver && !observer.parentElMutationObserver) { + // 监听 DOM 变化 + addMutationListener(targetNode); + } + } else { + // 无防御时不需要 mutation 监听 + removeListener('mutation'); + } + // 防止重复添加监听 + if (!observer.parentElResizeObserver) { + // 监听 DOM 大小变化 + addResizeListener(targetNode); + } + }; + + /** 移除对水印元素和容器元素的监听,传参可指定要移除哪个监听,不传默认移除全部监听 */ + const removeListener = (kind: 'mutation' | 'resize' | 'all' = 'all') => { + // 移除 mutation 监听 + if (kind === 'mutation' || kind === 'all') { + observer.watermarkElMutationObserver?.disconnect(); + observer.watermarkElMutationObserver = undefined; + observer.parentElMutationObserver?.disconnect(); + observer.parentElMutationObserver = undefined; + } + // 移除 resize 监听 + if (kind === 'resize' || kind === 'all') { + observer.parentElResizeObserver?.disconnect(); + observer.parentElResizeObserver = undefined; + } + }; + + /** 监听 DOM 变化 */ + const addMutationListener = (targetNode: HTMLElement) => { + // 当观察到变动时执行的回调 + const mutationCallback = debounce((mutationList: MutationRecord[]) => { + // 水印的防御(防止用户手动删除水印元素或通过 CSS 隐藏水印) + mutationList.forEach(debounce((mutation: MutationRecord) => { + switch (mutation.type) { + case 'attributes': + mutation.target === watermarkEl && updateWatermark(); + break; + case 'childList': + mutation.removedNodes.forEach((item) => { + item === watermarkEl && targetNode.appendChild(watermarkEl); + }); + break; + } + }, 100)); + }, 100); + // 创建观察器实例并传入回调 + observer.watermarkElMutationObserver = new MutationObserver(mutationCallback); + observer.parentElMutationObserver = new MutationObserver(mutationCallback); + // 以上述配置开始观察目标节点 + observer.watermarkElMutationObserver.observe(watermarkEl!, { + // 观察目标节点属性是否变动,默认为 true + attributes: true, + // 观察目标子节点是否有添加或者删除,默认为 false + childList: false, + // 是否拓展到观察所有后代节点,默认为 false + subtree: false, + }); + observer.parentElMutationObserver.observe(targetNode, { + attributes: false, + childList: true, + subtree: false, + }); + }; + + /** 监听 DOM 大小变化 */ + const addResizeListener = (targetNode: HTMLElement) => { + // 当 targetNode 元素大小变化时去更新整个水印的大小 + const resizeCallback = debounce(() => { + const { clientWidth, clientHeight } = targetNode; + updateWatermarkEl({ width: clientWidth, height: clientHeight }); + }, 500); + // 创建一个观察器实例并传入回调 + observer.parentElResizeObserver = new ResizeObserver(resizeCallback); + // 开始观察目标节点 + observer.parentElResizeObserver.observe(targetNode); + }; + + /** 在组件卸载前移除水印以及各种监听 */ + onBeforeUnmount(() => { + clearWatermark(); + }); + + return { setWatermark, clearWatermark }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/icons/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f419c6ace7493ce0796e036eb6e95b3906d721e9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/index.ts @@ -0,0 +1,7 @@ +import { type App } from 'vue'; +import SvgIcon from '@/components/SvgIcon/index.vue'; // Svg Component +import 'virtual:svg-icons-register'; + +export function loadSvg(app: App) { + app.component('SvgIcon', SvgIcon); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/404.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/404.svg new file mode 100644 index 0000000000000000000000000000000000000000..1319e77dd7bd0e78c6d6ce34fd3b973165e8c633 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/404.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/bug.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/bug.svg new file mode 100644 index 0000000000000000000000000000000000000000..9b35ad8ad7796c55c76dfd5136fb950cb9dd546e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/bug.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/component.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/component.svg new file mode 100644 index 0000000000000000000000000000000000000000..94280f4ce4f709727356f106400784dd359f4b06 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/component.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/dashboard.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/dashboard.svg new file mode 100644 index 0000000000000000000000000000000000000000..c8863a0456510e1b58b714c2f377a6886973fff7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/dashboard.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen-exit.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen-exit.svg new file mode 100644 index 0000000000000000000000000000000000000000..42aa5059de248bfa7ebce952c6ba44ee2e89a697 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen-exit.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen.svg new file mode 100644 index 0000000000000000000000000000000000000000..a97be9e3c5e02ee6727b1e783066b4cb18046b92 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/fullscreen.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-down.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-down.svg new file mode 100644 index 0000000000000000000000000000000000000000..de625438ba4bb947566d818525710a54136ac6ab --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-down.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-enter.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-enter.svg new file mode 100644 index 0000000000000000000000000000000000000000..819b87efbb490287403f46c36a352d837a484329 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-enter.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-esc.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-esc.svg new file mode 100644 index 0000000000000000000000000000000000000000..33256bf74a47ffa9da275d27e9d4e19274bdd342 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-esc.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-up.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-up.svg new file mode 100644 index 0000000000000000000000000000000000000000..e84519a2ec673f1754e49282fffaab1363b83a1f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/keyboard-up.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/link.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/link.svg new file mode 100644 index 0000000000000000000000000000000000000000..9ac0b2cf6bf6459a1343bfc5a273ddc5fb30e672 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/link.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/lock.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/lock.svg new file mode 100644 index 0000000000000000000000000000000000000000..21a758272190f90dd708c10990cf3f7b49aac04b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/lock.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/menu.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/menu.svg new file mode 100644 index 0000000000000000000000000000000000000000..5321191d2872ae4242c7f534fd7b64670dad311c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/menu.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/search.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/search.svg new file mode 100644 index 0000000000000000000000000000000000000000..691a5f126385b66153ef7a0f6f1dd199b2e31109 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/search.svg @@ -0,0 +1 @@ + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/unocss.svg b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/unocss.svg new file mode 100644 index 0000000000000000000000000000000000000000..5eaef354c9ee188e763f9367a4bc40945943d75f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/icons/svg/unocss.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftMode.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftMode.vue new file mode 100644 index 0000000000000000000000000000000000000000..1f843e5c044b595933804634fcb5085830e128ea --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftMode.vue @@ -0,0 +1,168 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftTopMode.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftTopMode.vue new file mode 100644 index 0000000000000000000000000000000000000000..a7076db0628b86ca423ab4ea767694b9e02f8bbb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/LeftTopMode.vue @@ -0,0 +1,135 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/TopMode.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/TopMode.vue new file mode 100644 index 0000000000000000000000000000000000000000..288b0b59f74883cfd8317fb58e60e7c23c0a1449 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/TopMode.vue @@ -0,0 +1,75 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/AppMain.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/AppMain.vue new file mode 100644 index 0000000000000000000000000000000000000000..c32972735be464abdb1b30873ece9831f89e964e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/AppMain.vue @@ -0,0 +1,76 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Breadcrumb/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Breadcrumb/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..d13d3ac6b0965dbda40300928668d69ac66199b3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Breadcrumb/index.vue @@ -0,0 +1,65 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/CompConsumer/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/CompConsumer/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..caf383fb174e4d594a807a29b9717110bac09345 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/CompConsumer/index.ts @@ -0,0 +1,67 @@ +import { type VNode, cloneVNode, createVNode, defineComponent, h, KeepAlive } from 'vue'; +import { useRoute } from 'vue-router'; +import { useTagsViewStore } from '@/store/modules/tags-view'; + +interface CompConsumerProps { + component: VNode +} + +/** 定义 compMap 对象,用于存储路由名称和对应的组件 */ +const compMap = new Map(); + +/** + * CompConsumer 组件 + * 用法:替换 标签以及内部代码,变成: + * 优点:缓存路由时只需写路由 Name,无需再写组件 Name + * 缺点:当路由表有动态路由匹配时(指向同一个组件),会出现复用组件的情况(例如修改 /info/1 时 /info/2 也会跟着改变) + */ +export const CompConsumer = defineComponent( + (props: CompConsumerProps) => { + const tagsViewStore = useTagsViewStore(); + const route = useRoute(); + return () => { + // 获取传入的组件 + const { component } = props; + // 判断当前是否包含 name,如果不包含 name,那就直接处理掉 name + if (!route.name) return component; + // 获取当前组件的名称 + const compName = (component.type as any)?.name; + // 获取当前路由的名称 + const routeName = route.name as string; + let Comp: VNode; + // 检查 compMap 中是否已经存在对应的组件 + if (compMap.has(routeName)) { + // 如果存在,则直接使用该组件进行渲染 + Comp = compMap.get(routeName)!; + } else { + // 如果不存在,则克隆传入的组件并创建一个新的组件,将其添加到 compMap 中 + const node = cloneVNode(component); + if (compName && compName === routeName) { + ;(node.type as any).name = `__${compName}__CUSTOM_NAME`; + } + // @ts-expect-error this is VNode + Comp = defineComponent({ + name: routeName, + setup() { + return () => node; + }, + }); + compMap.set(routeName, Comp); + } + // 使用 createVNode 函数创建一个 KeepAlive 组件,并缓存 cachedViews 数组中对应的组件 + return createVNode( + KeepAlive, + { + include: tagsViewStore.cachedViews, + }, + { + default: () => h(Comp), + }, + ); + }; + }, + { + name: 'CompConsumer', + props: ['component'], + }, +); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Footer/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Footer/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..f49cbb44879559e6bc31882eec7c20764b8709dc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Footer/index.vue @@ -0,0 +1,19 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Hamburger/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Hamburger/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..716b888ddff49e932c609e192ac864935aa9bef4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Hamburger/index.vue @@ -0,0 +1,36 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Logo/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Logo/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..f8fc2961cf6e3e82874359c147b05b23cb7634ac --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Logo/index.vue @@ -0,0 +1,64 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/NavigationBar/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/NavigationBar/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..8d08fb585be726818a44bd55eff87867cc9fcba1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/NavigationBar/index.vue @@ -0,0 +1,212 @@ + + + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/RightPanel/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/RightPanel/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..f0260497bcae93adbdb99fe89041570f64f73766 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/RightPanel/index.vue @@ -0,0 +1,45 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/SelectLayoutMode.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/SelectLayoutMode.vue new file mode 100644 index 0000000000000000000000000000000000000000..1127a00ec8dcf35e4b9101be58c44f12b6766850 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/SelectLayoutMode.vue @@ -0,0 +1,103 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..a7832440c0a816206aceb85bc45af09cf78679cd --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Settings/index.vue @@ -0,0 +1,86 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItem.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItem.vue new file mode 100644 index 0000000000000000000000000000000000000000..2863af6f017c033559f4b38aaa0dd0edcd5c6834 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItem.vue @@ -0,0 +1,101 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItemLink.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItemLink.vue new file mode 100644 index 0000000000000000000000000000000000000000..8df126ceed4590661a8f142529dbcecae2ad6c1f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/SidebarItemLink.vue @@ -0,0 +1,18 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..3b3ef514bcf16efcd4ac8799763a1d4c93f3b16b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/Sidebar/index.vue @@ -0,0 +1,353 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/ScrollPane.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/ScrollPane.vue new file mode 100644 index 0000000000000000000000000000000000000000..281e76fc01185465ece91c44d25e8f9f6c56698b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/ScrollPane.vue @@ -0,0 +1,155 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..6ffe80a3dbd0c68455767652a14720320ae5cbc8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/TagsView/index.vue @@ -0,0 +1,253 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2e02969c9fe1c41d08357049bf9a652490b4832 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/components/index.ts @@ -0,0 +1,7 @@ +export { default as AppMain } from './AppMain.vue'; +export { default as NavigationBar } from './NavigationBar/index.vue'; +export { default as Settings } from './Settings/index.vue'; +export { default as Sidebar } from './Sidebar/index.vue'; +export { default as TagsView } from './TagsView/index.vue'; +export { default as RightPanel } from './RightPanel/index.vue'; +export { default as Logo } from './Logo/index.vue'; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/hooks/useResize.ts b/timi_hok_game_translator/LQA_WMP/web/src/layouts/hooks/useResize.ts new file mode 100644 index 0000000000000000000000000000000000000000..d39607d908ebbd5599bfa124f698b60824fc075e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/hooks/useResize.ts @@ -0,0 +1,52 @@ +import { onBeforeMount, onMounted, onBeforeUnmount } from 'vue'; +import { useAppStore } from '@/store/modules/app'; +import { useRouteListener } from '@/hooks/useRouteListener'; +import { DeviceEnum } from '@/constants/app-key'; + +/** 参考 Bootstrap 的响应式设计将最大移动端宽度设置为 992 */ +const MAX_MOBILE_WIDTH = 992; + +/** 根据浏览器宽度变化,变换 Layout 布局 */ +export default () => { + const appStore = useAppStore(); + const { listenerRouteChange } = useRouteListener(); + + /** 用于判断当前设备是否为移动端 */ + const _isMobile = () => { + const rect = document.body.getBoundingClientRect(); + return rect.width - 1 < MAX_MOBILE_WIDTH; + }; + + /** 用于处理窗口大小变化事件 */ + const _resizeHandler = () => { + if (!document.hidden) { + const isMobile = _isMobile(); + appStore.toggleDevice(isMobile ? DeviceEnum.Mobile : DeviceEnum.Desktop); + isMobile && appStore.closeSidebar(true); + } + }; + /** 监听路由变化,根据设备类型调整布局 */ + listenerRouteChange(() => { + if (appStore.device === DeviceEnum.Mobile && appStore.sidebar.opened) { + appStore.closeSidebar(false); + } + }); + + /** 在组件挂载前添加窗口大小变化事件监听器 */ + onBeforeMount(() => { + window.addEventListener('resize', _resizeHandler); + }); + + /** 在组件挂载后根据窗口大小判断设备类型并调整布局 */ + onMounted(() => { + if (_isMobile()) { + appStore.toggleDevice(DeviceEnum.Mobile); + appStore.closeSidebar(true); + } + }); + + /** 在组件卸载前移除窗口大小变化事件监听器 */ + onBeforeUnmount(() => { + window.removeEventListener('resize', _resizeHandler); + }); +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/layouts/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/layouts/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..27f6163f81adc11e645633093edd34c09b44f76d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/layouts/index.vue @@ -0,0 +1,68 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/main.js b/timi_hok_game_translator/LQA_WMP/web/src/main.js new file mode 100644 index 0000000000000000000000000000000000000000..3d695c998d23c9e0a446109aba67fa04d5476e52 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/main.js @@ -0,0 +1,45 @@ +// core +import { createApp } from 'vue'; +import App from '@/App.vue'; +import store from '@/store'; +import router from '@/router'; +import '@/router/permission'; +// load +import { loadSvg } from '@/icons'; +import { loadPlugins } from '@/plugins'; +import { loadDirectives } from '@/directives'; +// css +import 'uno.css'; +import 'normalize.css'; +import 'element-plus/dist/index.css'; +import 'element-plus/theme-chalk/dark/css-vars.css'; +import 'vxe-table/lib/style.css'; +import 'vxe-table-plugin-element/dist/style.css'; +import '@/styles/index.scss'; + +import registerGlobalComponents from '@/components'; + +// fast-crud +import FastCrud from '@/fast-crud'; +import { registerGlobUtils } from '@/utils/register.js'; + +const app = createApp(App); + +/** 变量挂载 */ +registerGlobUtils(app); + +/** 加载插件 */ +loadPlugins(app); +/** 加载全局 SVG */ +loadSvg(app); +/** 加载自定义指令 */ +loadDirectives(app); +/** 加载 fast-crud */ +app.use(FastCrud); + +app.use(registerGlobalComponents); + +app.use(store).use(router); +router.isReady().then(() => { + app.mount('#app'); +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus-icon/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus-icon/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0da65c564ec09419004559b778622a63eb7ed114 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus-icon/index.ts @@ -0,0 +1,9 @@ +import { type App } from 'vue'; +import * as ElementPlusIconsVue from '@element-plus/icons-vue'; + +export function loadElementPlusIcon(app: App) { + /** 注册所有 Element Plus Icon */ + for (const [key, component] of Object.entries(ElementPlusIconsVue)) { + app.component(key, component); + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..4193e8f62d057a3dd506fb417406ce38c1ed38c9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/plugins/element-plus/index.ts @@ -0,0 +1,7 @@ +import { type App } from 'vue'; +import ElementPlus from 'element-plus'; + +export function loadElementPlus(app: App) { + /** Element Plus 组件完整引入 */ + app.use(ElementPlus); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/plugins/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/plugins/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..16f3d2402384df18cf8f91327a7209cc83174f77 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/plugins/index.ts @@ -0,0 +1,10 @@ +import { type App } from 'vue'; +import { loadElementPlus } from './element-plus'; +import { loadElementPlusIcon } from './element-plus-icon'; +import { loadVxeTable } from './vxe-table'; + +export function loadPlugins(app: App) { + loadElementPlus(app); + loadElementPlusIcon(app); + loadVxeTable(app); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/plugins/vxe-table/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/plugins/vxe-table/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9d11ef23e89cfc85a197ba865bb25b0c5b55e49a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/plugins/vxe-table/index.ts @@ -0,0 +1,66 @@ +import { type App } from 'vue'; +// https://vxetable.cn/#/table/start/install +import VXETable from 'vxe-table'; +// https://github.com/x-extends/vxe-table-plugin-element +import VXETablePluginElement from 'vxe-table-plugin-element'; + +VXETable.use(VXETablePluginElement); + +/** 全局默认参数 */ +VXETable.config({ + /** 全局尺寸 */ + size: 'medium', + /** 全局 zIndex 起始值,如果项目的的 z-index 样式值过大时就需要跟随设置更大,避免被遮挡 */ + zIndex: 9999, + /** 版本号,对于某些带数据缓存的功能有用到,上升版本号可以用于重置数据 */ + version: 0, + /** 全局 loading 提示内容,如果为 null 则不显示文本 */ + loadingText: null, + table: { + showHeader: true, + showOverflow: 'tooltip', + showHeaderOverflow: 'tooltip', + autoResize: true, + // stripe: false, + border: 'inner', + // round: false, + emptyText: '暂无数据', + rowConfig: { + isHover: true, + isCurrent: true, + }, + columnConfig: { + resizable: false, + }, + align: 'center', + headerAlign: 'center', + /** 行数据的唯一主键字段名 */ + rowId: '_VXE_ID', + }, + pager: { + // size: "medium", + /** 配套的样式 */ + perfect: false, + pageSize: 10, + pagerCount: 7, + pageSizes: [10, 20, 50], + layouts: ['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump'], + }, + modal: { + minWidth: 500, + minHeight: 400, + lockView: true, + mask: true, + // duration: 3000, + // marginSize: 20, + dblclickZoom: false, + showTitleOverflow: true, + transfer: true, + draggable: false, + }, +}); + +export function loadVxeTable(app: App) { + /** Vxe Table 组件完整引入 */ + app.use(VXETable); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/router/helper.ts b/timi_hok_game_translator/LQA_WMP/web/src/router/helper.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab75ff3d4b870727957880ff3cf464dad8ab5d70 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/router/helper.ts @@ -0,0 +1,68 @@ +import { + type Router, + type RouteRecordNormalized, + type RouteRecordRaw, + createRouter, + createWebHashHistory, + createWebHistory, +} from 'vue-router'; +import { cloneDeep, omit } from 'lodash-es'; + +/** 路由模式 */ +export const history = import.meta.env.VITE_ROUTER_HISTORY === 'hash' + ? createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH) + : createWebHistory(import.meta.env.VITE_PUBLIC_PATH); + +/** 路由降级(把三级及其以上的路由转化为二级路由) */ +export const flatMultiLevelRoutes = (routes: RouteRecordRaw[]) => { + const routesMirror = cloneDeep(routes); + routesMirror.forEach((route) => { + // 如果路由是三级及其以上路由,对其进行降级处理 + isMultipleRoute(route) && promoteRouteLevel(route); + }); + return routesMirror; +}; + +/** 判断路由层级是否大于 2 */ +const isMultipleRoute = (route: RouteRecordRaw) => { + const { children } = route; + if (children?.length) { + // 只要有一个子路由的 children 长度大于 0,就说明是三级及其以上路由 + return children.some(child => child.children?.length); + } + return false; +}; + +/** 生成二级路由 */ +const promoteRouteLevel = (route: RouteRecordRaw) => { + // 创建 router 实例是为了获取到当前传入的 route 的所有路由信息 + let router: Router | null = createRouter({ + history, + routes: [route], + }); + const routes = router.getRoutes(); + // 在 addToChildren 函数中使用上面获取到的路由信息来更新 route 的 children + addToChildren(routes, route.children || [], route); + router = null; + // 转为二级路由后,去除所有子路由中的 children + route.children = route.children?.map(item => omit(item, 'children') as RouteRecordRaw); +}; + +/** 将给定的子路由添加到指定的路由模块中 */ +const addToChildren = (routes: RouteRecordNormalized[], children: RouteRecordRaw[], routeModule: RouteRecordRaw) => { + children.forEach((child) => { + const route = routes.find(item => item.name === child.name); + if (route) { + // 初始化 routeModule 的 children + routeModule.children = routeModule.children || []; + // 如果 routeModule 的 children 属性中不包含该路由,则将其添加进去 + if (!routeModule.children.includes(route)) { + routeModule.children.push(route); + } + // 如果该子路由还有自己的子路由,则递归调用此函数将它们也添加进去 + if (child.children?.length) { + addToChildren(routes, child.children, routeModule); + } + } + }); +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/router/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/router/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ff199ff3d2572f2bccffd53abaecf8b463fc1a6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/router/index.ts @@ -0,0 +1,543 @@ +import { type RouteRecordRaw, createRouter } from 'vue-router'; +// import { history, flatMultiLevelRoutes } from './helper'; +import { history } from './helper'; +// import routeSettings from '@/config/route'; + +const Layouts = () => import('@/layouts/index.vue'); + +/** + * 常驻路由 + * 除了 redirect/403/404/login 等隐藏页面,其他页面建议设置 Name 属性 + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +export const constantRoutes: RouteRecordRaw[] = [ + { + path: '/redirect', + component: Layouts, + meta: { + hidden: true, + }, + children: [ + { + path: ':path(.*)', + component: () => import('@/views/redirect/index.vue'), + }, + ], + }, + { + path: '/403', + component: () => import('@/views/error-page/403.vue'), + meta: { + hidden: true, + }, + }, + { + path: '/404', + component: () => import('@/views/error-page/404.vue'), + meta: { + hidden: true, + }, + alias: '/:pathMatch(.*)*', + }, + { + path: '/login', + component: () => import('@/views/login/index.vue'), + meta: { + hidden: true, + title: '登录', + }, + }, + { + path: '/register', + component: () => import('@/views/login/register.vue'), + meta: { + hidden: true, + title: '注册', + }, + }, + // { + // path: '/', + // component: Layouts, + // redirect: '/dashboard', + // children: [ + // { + // path: 'dashboard', + // component: () => import('@/views/dashboard/index.vue'), + // name: 'Dashboard', + // meta: { + // title: '首页', + // svgIcon: 'dashboard', + // affix: true, + // }, + // }, + // ], + // }, + // { + // path: '/unocss', + // component: Layouts, + // redirect: '/unocss/index', + // children: [ + // { + // path: 'index', + // component: () => import('@/views/unocss/index.vue'), + // name: 'UnoCSS', + // meta: { + // title: 'UnoCSS', + // svgIcon: 'unocss', + // }, + // }, + // ], + // }, + // { + // path: '/link', + // meta: { + // title: '外链', + // svgIcon: 'link', + // }, + // children: [ + // { + // path: 'https://juejin.cn/post/7089377403717287972', + // component: () => {}, + // name: 'Link1', + // meta: { + // title: '中文文档', + // }, + // }, + // { + // path: 'https://juejin.cn/column/7207659644487139387', + // component: () => {}, + // name: 'Link2', + // meta: { + // title: '新手教程', + // }, + // }, + // ], + // }, + // { + // path: '/table', + // component: Layouts, + // redirect: '/table/element-plus', + // name: 'Table', + // meta: { + // title: '表格', + // elIcon: 'Grid', + // }, + // children: [ + // { + // path: 'element-plus', + // component: () => import('@/views/table/element-plus/index.vue'), + // name: 'ElementPlus', + // meta: { + // title: 'Element Plus', + // keepAlive: true, + // }, + // }, + // { + // path: 'vxe-table', + // component: () => import('@/views/table/vxe-table/index.vue'), + // name: 'VxeTable', + // meta: { + // title: 'Vxe Table', + // keepAlive: true, + // }, + // }, + // ], + // }, + // { + // path: '/menu', + // component: Layouts, + // redirect: '/menu/menu1', + // name: 'Menu', + // meta: { + // title: '多级路由', + // svgIcon: 'menu', + // }, + // children: [ + // { + // path: 'menu1', + // component: () => import('@/views/menu/menu1/index.vue'), + // redirect: '/menu/menu1/menu1-1', + // name: 'Menu1', + // meta: { + // title: 'menu1', + // }, + // children: [ + // { + // path: 'menu1-1', + // component: () => import('@/views/menu/menu1/menu1-1/index.vue'), + // name: 'Menu1-1', + // meta: { + // title: 'menu1-1', + // keepAlive: true, + // }, + // }, + // { + // path: 'menu1-2', + // component: () => import('@/views/menu/menu1/menu1-2/index.vue'), + // redirect: '/menu/menu1/menu1-2/menu1-2-1', + // name: 'Menu1-2', + // meta: { + // title: 'menu1-2', + // }, + // children: [ + // { + // path: 'menu1-2-1', + // component: () => import('@/views/menu/menu1/menu1-2/menu1-2-1/index.vue'), + // name: 'Menu1-2-1', + // meta: { + // title: 'menu1-2-1', + // keepAlive: true, + // }, + // }, + // { + // path: 'menu1-2-2', + // component: () => import('@/views/menu/menu1/menu1-2/menu1-2-2/index.vue'), + // name: 'Menu1-2-2', + // meta: { + // title: 'menu1-2-2', + // keepAlive: true, + // }, + // }, + // ], + // }, + // { + // path: 'menu1-3', + // component: () => import('@/views/menu/menu1/menu1-3/index.vue'), + // name: 'Menu1-3', + // meta: { + // title: 'menu1-3', + // keepAlive: true, + // }, + // }, + // ], + // }, + // { + // path: 'menu2', + // component: () => import('@/views/menu/menu2/index.vue'), + // name: 'Menu2', + // meta: { + // title: 'menu2', + // keepAlive: true, + // }, + // }, + // ], + // }, + // { + // path: '/hook-demo', + // component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + // name: 'HookDemo', + // meta: { + // title: 'Hook', + // elIcon: 'Menu', + // alwaysShow: true, + // }, + // children: [ + // { + // path: 'use-fetch-select', + // component: () => import('@/views/hook-demo/use-fetch-select.vue'), + // name: 'UseFetchSelect', + // meta: { + // title: 'useFetchSelect', + // }, + // }, + // { + // path: 'use-fullscreen-loading', + // component: () => import('@/views/hook-demo/use-fullscreen-loading.vue'), + // name: 'UseFullscreenLoading', + // meta: { + // title: 'useFullscreenLoading', + // }, + // }, + // { + // path: 'use-watermark', + // component: () => import('@/views/hook-demo/use-watermark.vue'), + // name: 'UseWatermark', + // meta: { + // title: 'useWatermark', + // }, + // }, + // ], + // }, +]; + +/** + * 系统路由 +*/ +export const systemRoute: RouteRecordRaw[] = [ + // 项目管理 + { + path: '/project', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'project', + meta: { + title: '项目管理', + }, + children: [ + { + path: '/project', + // @ts-ignore + component: () => import('@/views/system/project/index.vue'), + name: 'project', + meta: { + title: '项目管理', + fsIcon: 'lucide:audio-lines', + }, + }, + ], + }, + + // 用户管理 + { + path: '/user', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'user', + meta: { + title: '用户管理', + }, + children: [ + { + path: '/user', + // @ts-ignore + component: () => import('@/views/system/user/index.vue'), + name: 'user', + meta: { + title: '用户管理', + // elIcon: 'User', + fsIcon: 'ph:user', + }, + }, + ], + }, + + // 设置 + { + path: '/settings', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'setting', + meta: { + title: '设置', + }, + children: [ + { + path: '/settings', + // @ts-ignore + component: () => import('@/views/system/settings/index.vue'), + name: 'settings', + meta: { + title: '设置', + elIcon: 'Setting', + }, + }, + ], + }, +]; + +/** + * 动态路由 + * 用来放置有权限 (Roles 属性) 的路由 + * 必须带有 Name 属性 + */ +export const dynamicRoutes: RouteRecordRaw[] = [ + // demo + // { + // path: '/permission', + // component: Layouts, + // redirect: '/permission/page', + // name: 'Permission', + // meta: { + // title: '权限', + // svgIcon: 'lock', + // roles: ['admin', 'test'], // 可以在根路由中设置角色 + // alwaysShow: true, // 将始终显示根菜单 + // }, + // children: [ + // { + // path: '/page', + // component: () => import('@/views/permission/page.vue'), + // name: 'PagePermission', + // meta: { + // title: '页面级', + // roles: ['admin'], // 或者在子导航中设置角色 + // }, + // }, + // { + // path: '/directive', + // component: () => import('@/views/permission/directive.vue'), + // name: 'DirectivePermission', + // meta: { + // title: '按钮级1', // 如果未设置角色,则表示:该页面不需要权限,但会继承根路由的角色 + // }, + // }, + // ], + // }, + + // 设置 + { + path: '/settings', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'projectConfig', + meta: { + title: '项目设置', + elIcon: 'Setting', + alwaysShow: true, + }, + children: [ + // { + // path: '/project', + // // @ts-ignore + // component: () => import('@/views/system/project/index.vue'), + // name: 'project', + // meta: { + // title: '项目管理', + // }, + // }, + { + path: '/user', + // @ts-ignore + component: () => import('@/views/system/user/index.vue'), + name: 'projectUser', + meta: { + title: '用户管理', + roles: ['admin'], // 可以在根路由中设置角色 + }, + }, + { + path: '/basic', + // @ts-ignore + component: () => import('@/views/settings/index.vue'), + name: 'basicSettings', + meta: { + title: '基础配置', + }, + }, + ], + }, + // 任务管理 + { + path: '/task', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'task', + meta: { + title: '任务管理', + }, + children: [ + { + path: '/task', + // @ts-ignore + component: () => import('@/views/task/index.vue'), + name: 'task', + meta: { + title: '任务管理', + svgIcon: 'menu', + keepAlive: true, + // roles: ['admin'], // 可以在根路由中设置角色 + }, + }, + ], + }, + // 数据管理 + { + path: '/data', + component: Layouts, + // redirect: '/hook-demo/use-fetch-select', + name: 'data', + meta: { + title: '数据管理', + }, + children: [ + { + path: '/data', + // @ts-ignore + component: () => import('@/views/data/index.vue'), + name: 'data', + meta: { + title: '数据管理', + fsIcon: 'carbon:data-1', + // roles: ['admin'], // 可以在根路由中设置角色 + }, + }, + ], + }, + // 图片结果审核 + { + path: '/image-results', + // @ts-ignore + component: Layouts, + name: 'Audit', + meta: { + title: '结果审核', + hidden: true, + // roles: ['admin'], // 可以在根路由中设置角色 + }, + children: [ + { + path: '/image-results', + // @ts-ignore + component: () => import('@/views/task/audit/index.vue'), + name: 'Audit', + meta: { + title: '结果审核', + hidden: true, + activeMenu: '/task', + keepAlive: true, + // roles: ['admin'], // 可以在根路由中设置角色 + }, + }, + ], + }, + // 缺陷单 + { + path: '/bugs', + // @ts-ignore + component: Layouts, + name: 'Bugs', + meta: { + title: '缺陷单', + hidden: true, + // roles: ['admin'], // 可以在根路由中设置角色 + }, + children: [ + { + path: '/bugs', + // @ts-ignore + component: () => import('@/views/task/bugs/index.vue'), + name: 'Bugs', + meta: { + title: '缺陷单', + hidden: true, + // roles: ['admin'], // 可以在根路由中设置角色 + }, + }, + ], + }, +]; + +const router = createRouter({ + history, + // routes: routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(constantRoutes) : constantRoutes, + routes: constantRoutes, +}); + +/** 重置路由 */ +export function resetRouter() { + // 注意:所有动态路由路由必须带有 Name 属性,否则可能会不能完全重置干净 + try { + router.getRoutes().forEach((route) => { + const { name, meta } = route; + if (name && meta.roles?.length) { + router.hasRoute(name) && router.removeRoute(name); + } + }); + } catch { + // 强制刷新浏览器也行,只是交互体验不是很好 + window.location.reload(); + } +} + +export default router; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/router/permission.ts b/timi_hok_game_translator/LQA_WMP/web/src/router/permission.ts new file mode 100644 index 0000000000000000000000000000000000000000..367c396e34bffe792632d7746c30354c552b9a29 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/router/permission.ts @@ -0,0 +1,65 @@ +import router from '@/router'; +import { useUserStoreHook } from '@/store/modules/user'; +import { usePermissionStoreHook } from '@/store/modules/permission'; +import { setRouteChange } from '@/hooks/useRouteListener'; +import { useTitle } from '@/hooks/useTitle'; +import { getToken } from '@/utils/cache/cookies'; +import routeSettings from '@/config/route'; +import isWhiteList from '@/config/white-list'; +import NProgress from 'nprogress'; +import 'nprogress/nprogress.css'; + +const { setTitle } = useTitle(); +NProgress.configure({ showSpinner: false }); + +router.beforeEach(async (to, _from, next) => { + NProgress.start(); + const userStore = useUserStoreHook(); + const permissionStore = usePermissionStoreHook(); + + // 未登录 + if (!getToken()) { + if (isWhiteList(to)) return next(); + return next({ path: '/login', query: to.fullPath !== '/' ? { redirect: to.fullPath } : {} }); + } + + // 已登录访问登录/注册页,回到首页 + if (isWhiteList(to)) { + return next({ path: '/' }); + } + + // 已获取过用户信息 + if (userStore.roles.length !== 0) { + const { projects, superAdmin } = userStore; + if (to.path === '/') { + if (projects.length) return next({ path: `/project-${projects[0].value}/task` }); + return next({ path: superAdmin ? '/project' : '/403' }); + } + return next(); + } + + // 首次进入:获取用户信息与项目角色,生成可访问路由 + try { + await userStore.getInfo(); + // 注意:角色必须是一个数组! 例如: ["admin"] 或 ["developer", "editor"] + const { roles, superAdmin, projects } = userStore; + routeSettings.dynamic ? permissionStore.setRoutes(roles, superAdmin, projects) : permissionStore.setAllRoutes(); + permissionStore.addRoutes.forEach(route => router.addRoute(route)); + // 没有任何项目权限(如刚注册的用户),超级管理员可进入系统管理创建项目 + if (!projects.length && !superAdmin) { + return next({ path: '/403', replace: true }); + } + // 设置 replace: true, 因此导航将不会留下历史记录 + next({ ...to, replace: true }); + } catch (err: any) { + // 会话失效等错误:重置本地登录态并重新登录 + userStore.resetToken(); + next({ path: '/login', query: { redirect: to.fullPath } }); + } +}); + +router.afterEach((to) => { + setRouteChange(to); + setTitle(to.meta.title); + NProgress.done(); +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..02ae96a92f34dc375c7eb9fd4cd456002b4a5235 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/index.ts @@ -0,0 +1,5 @@ +import { createPinia } from 'pinia'; + +const store = createPinia(); + +export default store; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/modules/app.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb208ac72116fac8ed3adef14297d3567b6cdfcc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/app.ts @@ -0,0 +1,47 @@ +import { reactive, ref, watch } from 'vue'; +import { defineStore } from 'pinia'; +import { getSidebarStatus, setSidebarStatus } from '@/utils/cache/local-storage'; +import { DeviceEnum, SIDEBAR_OPENED, SIDEBAR_CLOSED } from '@/constants/app-key'; + +interface Sidebar { + opened: boolean + withoutAnimation: boolean +} + +/** 设置侧边栏状态本地缓存 */ +function handleSidebarStatus(opened: boolean) { + opened ? setSidebarStatus(SIDEBAR_OPENED) : setSidebarStatus(SIDEBAR_CLOSED); +} + +export const useAppStore = defineStore('app', () => { + /** 侧边栏状态 */ + const sidebar: Sidebar = reactive({ + opened: getSidebarStatus() !== SIDEBAR_CLOSED, + withoutAnimation: false, + }); + /** 设备类型 */ + const device = ref(DeviceEnum.Desktop); + + /** 监听侧边栏 opened 状态 */ + watch( + () => sidebar.opened, + opened => handleSidebarStatus(opened), + ); + + /** 切换侧边栏 */ + const toggleSidebar = (withoutAnimation: boolean) => { + sidebar.opened = !sidebar.opened; + sidebar.withoutAnimation = withoutAnimation; + }; + /** 关闭侧边栏 */ + const closeSidebar = (withoutAnimation: boolean) => { + sidebar.opened = false; + sidebar.withoutAnimation = withoutAnimation; + }; + /** 切换设备类型 */ + const toggleDevice = (value: DeviceEnum) => { + device.value = value; + }; + + return { device, sidebar, toggleSidebar, closeSidebar, toggleDevice }; +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/modules/permission.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/permission.ts new file mode 100644 index 0000000000000000000000000000000000000000..87be319e04553f24764e3a8fdb9a357d1b6a7914 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/permission.ts @@ -0,0 +1,90 @@ +import { ref } from 'vue'; +import store from '@/store'; +import { defineStore } from 'pinia'; +import { type RouteRecordRaw } from 'vue-router'; +import { constantRoutes, dynamicRoutes, systemRoute } from '@/router'; +import { flatMultiLevelRoutes } from '@/router/helper'; +import routeSettings from '@/config/route'; +import { SUPER_ADMIN_PROJECT_ID } from '@/constants/app-key'; + +const hasPermission = (roles: string[], route: RouteRecordRaw, superAdmin: number) => { + const routeRoles = route.meta?.roles || []; + if (superAdmin) { + return true; + } + return routeRoles.length ? roles.some(role => routeRoles.includes(role)) : true; +}; + +const filterSystemRoutes = (routes: RouteRecordRaw[], roles: string[], superAdmin: number) => { + const res: RouteRecordRaw[] = []; + routes.forEach((route) => { + const tempRoute = { + ...route, + meta: { ...route.meta, type: 'system', value: SUPER_ADMIN_PROJECT_ID }, + }; + if (hasPermission(roles, tempRoute, superAdmin)) { + if (tempRoute.children) { + tempRoute.children = filterSystemRoutes(tempRoute.children, roles, superAdmin); + } + res.push(tempRoute); + } + }); + return res; +}; + +const filterDynamicRoutes = (routes: RouteRecordRaw[], roles: string[], superAdmin: number, projects: number[]) => { + const res: RouteRecordRaw[] = []; + projects.forEach((item) => { + routes.forEach((route) => { + const tempRoute = { + ...route, name: `${item}-${route.name as string}`, path: `/project-${item}${route.path}`, + meta: { + ...route.meta, type: 'project', value: item, + activeMenu: route.meta!.activeMenu ? `/project-${item}${route.meta!.activeMenu}` : undefined, + // @ts-ignore + roles: (route.meta.roles || []).map(roleItem => `${item}:${roleItem}`), + }, + }; + if (hasPermission(roles, tempRoute, superAdmin)) { + if (tempRoute.children) { + tempRoute.children = filterDynamicRoutes(tempRoute.children, roles, superAdmin, [item]); + } + res.push(tempRoute); + } + }); + }); + return res; +}; + +export const usePermissionStore = defineStore('permission', () => { + /** 可访问的路由 */ + const routes = ref([]); + /** 有访问权限的动态路由 */ + const addRoutes = ref([]); + + /** 根据角色生成可访问的 Routes(可访问的路由 = 常驻路由 + 有访问权限的动态路由) */ + const setRoutes = (roles: string[], superAdmin: number, projects: LabelValueOptions) => { + const accessedRoutes = [ + ...filterSystemRoutes(systemRoute, roles, superAdmin), + ...filterDynamicRoutes(dynamicRoutes, roles, superAdmin, projects.map(item => item.value) as number[]), + ]; + _set(accessedRoutes); + }; + + /** 所有路由 = 所有常驻路由 + 所有动态路由 */ + const setAllRoutes = () => { + _set(dynamicRoutes); + }; + + const _set = (accessedRoutes: RouteRecordRaw[]) => { + routes.value = constantRoutes.concat(accessedRoutes); + addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes; + }; + + return { routes, addRoutes, setRoutes, setAllRoutes }; +}); + +/** 在 setup 外使用 */ +export function usePermissionStoreHook() { + return usePermissionStore(store); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/modules/settings.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/settings.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7959940eb2cd9574860efa65ee1f8c32ef302a7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/settings.ts @@ -0,0 +1,40 @@ +import { type Ref, ref, watch } from 'vue'; +import { defineStore } from 'pinia'; +import { type LayoutSettings, layoutSettings } from '@/config/layouts'; +import { setConfigLayout } from '@/utils/cache/local-storage'; + +type SettingsStore = { + // 使用映射类型来遍历 layoutSettings 对象的键 + [Key in keyof LayoutSettings]: Ref +}; + +type SettingsStoreKey = keyof SettingsStore; + +export const useSettingsStore = defineStore('settings', () => { + /** 状态对象 */ + const state = {} as SettingsStore; + // 遍历 layoutSettings 对象的键值对 + for (const [key, value] of Object.entries(layoutSettings)) { + // 使用类型断言来指定 key 的类型,将 value 包装在 ref 函数中,创建一个响应式变量 + const refValue = ref(value); + // @ts-ignore + state[key as SettingsStoreKey] = refValue; + // 监听每个响应式变量 + watch(refValue, () => { + // 缓存 + const settings = _getCacheData(); + setConfigLayout(settings); + }); + } + /** 获取要缓存的数据:将 state 对象转化为 settings 对象 */ + const _getCacheData = () => { + const settings = {} as LayoutSettings; + for (const [key, value] of Object.entries(state)) { + // @ts-ignore + settings[key as SettingsStoreKey] = value.value; + } + return settings; + }; + + return state; +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/modules/tags-view.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/tags-view.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbc10f8e75b59645407f6279c06c2babb57b47b4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/tags-view.ts @@ -0,0 +1,103 @@ +import { ref, watchEffect, nextTick } from 'vue'; +import { defineStore } from 'pinia'; +import { useSettingsStore } from './settings'; +import { type RouteLocationNormalized } from 'vue-router'; +import { getVisitedViews, setVisitedViews, getCachedViews, setCachedViews } from '@/utils/cache/local-storage'; + +export type TagView = Partial; + +export const useTagsViewStore = defineStore('tags-view', () => { + const { cacheTagsView } = useSettingsStore(); + const visitedViews = ref(cacheTagsView ? getVisitedViews() : []); + const cachedViews = ref(cacheTagsView ? getCachedViews() : []); + + /** 缓存标签栏数据 */ + watchEffect(() => { + setVisitedViews(visitedViews.value); + setCachedViews(cachedViews.value); + }); + + /** 设置当前 tag 页签标题 */ + async function setCurrentTabTitle(route: RouteLocationNormalized, title: string) { + await nextTick(); + const currentTag = visitedViews.value.find(v => v.fullPath === route.fullPath); + if (currentTag) { + currentTag.meta!.title = title; + } + } + + // #region add + const addVisitedView = (view: TagView) => { + // 检查是否已经存在相同的 visitedView + const index = visitedViews.value.findIndex(v => v.fullPath === view.fullPath); + if (index !== -1) { + // 防止 query 参数丢失 + visitedViews.value[index].fullPath !== view.fullPath && (visitedViews.value[index] = { ...view }); + } else { + // 添加新的 visitedView + visitedViews.value.push({ ...view }); + } + }; + + const addCachedView = (view: TagView) => { + if (typeof view.name !== 'string') return; + if (cachedViews.value.includes(view.name)) return; + if (view.meta?.keepAlive) cachedViews.value.push(view.name); + }; + // #endregion + + // #region del + const delVisitedView = (view: TagView) => { + const index = visitedViews.value.findIndex(v => v.fullPath === view.fullPath); + if (index !== -1) visitedViews.value.splice(index, 1); + }; + + const delCachedView = (view: TagView) => { + if (typeof view.name !== 'string') return; + const index = cachedViews.value.indexOf(view.name); + if (index !== -1) cachedViews.value.splice(index, 1); + }; + // #endregion + + // #region delOthers + const delOthersVisitedViews = (view: TagView) => { + visitedViews.value = visitedViews.value.filter(v => v.meta?.affix || v.path === view.path); + }; + + const delOthersCachedViews = (view: TagView) => { + if (typeof view.name !== 'string') return; + const index = cachedViews.value.indexOf(view.name); + if (index !== -1) { + cachedViews.value = cachedViews.value.slice(index, index + 1); + } else { + // 如果 index = -1, 没有缓存的 tags + cachedViews.value = []; + } + }; + // #endregion + + // #region delAll + const delAllVisitedViews = () => { + // 保留固定的 tags + visitedViews.value = visitedViews.value.filter(tag => tag.meta?.affix); + }; + + const delAllCachedViews = () => { + cachedViews.value = []; + }; + // #endregion + + return { + visitedViews, + cachedViews, + setCurrentTabTitle, + addVisitedView, + addCachedView, + delVisitedView, + delCachedView, + delOthersVisitedViews, + delOthersCachedViews, + delAllVisitedViews, + delAllCachedViews, + }; +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/src/store/modules/user.ts b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/user.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1d0bf8fdb38c693b4e1df38c7482e336f3b6aaf --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/store/modules/user.ts @@ -0,0 +1,140 @@ +import { ref } from 'vue'; +import store from '@/store'; +import { defineStore } from 'pinia'; +import { useTagsViewStore } from './tags-view'; +import { useSettingsStore } from './settings'; +import { getToken, removeToken, setToken } from '@/utils/cache/cookies'; +import { resetRouter } from '@/router'; +import routeSettings from '@/config/route'; +import { customRequest } from '@/utils/service'; +import Cookies from 'js-cookie'; +import CacheKey from '@/constants/cache-key'; + +export interface LoginForm { + username: string + password: string +} + +export interface RegisterForm extends LoginForm { + name_zh?: string + email?: string +} + +type UserEntity = { + user: { + id: number + name_zh: string + name: string + email: string + is_admin: number + access_token: string + }, +}; +type ProjectEntity = { + projects: { id: number, name: string, roles: string[] }[] +}; + +export const useUserStore = defineStore('user', () => { + /** 是否已登录的本地标记(真正的认证依赖 Session Cookie) */ + const token = ref(getToken() || ''); + const roles = ref([]); + const name = ref(''); + const username = ref(''); + const email = ref(''); + const superAdmin = ref(0); + const projects = ref([]); + + const tagsViewStore = useTagsViewStore(); + const settingsStore = useSettingsStore(); + + /** 账号密码登录 */ + const login = async (form: LoginForm) => { + await customRequest({ url: '/api/user/login', method: 'post', data: form, silent: true }); + setToken('web'); + token.value = 'web'; + }; + + /** 自助注册 */ + const register = async (form: RegisterForm) => customRequest({ + url: '/api/user/register', method: 'post', data: form, silent: true, + }); + + /** 获取当前用户信息及项目角色 */ + const getInfo = async () => { + const { data }: { data: UserEntity } = await customRequest({ + url: '/api/user/entity', + method: 'get', + params: { info_type: 1 }, + }); + const { data: projectData }: { data: ProjectEntity } = await customRequest({ + url: '/api/user/permission', + method: 'get', + }); + Cookies.set(CacheKey.USERNAME_CH, data.user.name_zh || data.user.name); + Cookies.set(CacheKey.USERNAME_EN, data.user.name); + name.value = data.user.name; + username.value = data.user.name_zh || data.user.name; + email.value = data.user.email || ''; + + // 角色:后端返回 `${project_id}_${role}`,前端路由使用 `${project_id}:${roleName}` + superAdmin.value = data.user.is_admin; + const roleMap: Record = { + 1: 'admin', + 2: 'test', + 3: 'dev', + }; + roles.value = [...routeSettings.defaultRoles]; + projectData.projects.forEach(item => item.roles.forEach((role) => { + const roleId = String(role).split('_').pop() as string; + roles.value.push(`${item.id}:${roleMap[roleId]}`); + })); + + // 项目 + projects.value = projectData.projects.map(item => ({ + label: item.name, value: item.id, ...item, + })); + }; + + /** 修改密码 */ + const changePassword = async (oldPassword: string, newPassword: string) => customRequest({ + url: '/api/user/password', + method: 'post', + data: { old_password: oldPassword, new_password: newPassword }, + }); + + /** 登出 */ + const logout = async () => { + try { + await customRequest({ url: '/api/user/logout', method: 'post', silent: true }); + } finally { + resetToken(); + resetRouter(); + _resetTagsView(); + } + }; + /** 重置本地登录态 */ + const resetToken = () => { + removeToken(); + token.value = ''; + roles.value = []; + projects.value = []; + superAdmin.value = 0; + }; + /** 重置 Visited Views 和 Cached Views */ + const _resetTagsView = () => { + if (!settingsStore.cacheTagsView) { + tagsViewStore.delAllVisitedViews(); + tagsViewStore.delAllCachedViews(); + } + }; + + return { + token, roles, name, username, email, superAdmin, projects, + login, register, getInfo, changePassword, logout, resetToken, + }; +}); + +/** 在 setup 外使用 */ +export function useUserStoreHook() { + return useUserStore(store); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.css b/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.css new file mode 100644 index 0000000000000000000000000000000000000000..6337bc19e03bf658b7baceb2ce4c183d6817362c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.css @@ -0,0 +1,90 @@ +/** + * dark-blue 主题模式下的 Element Plus CSS 变量 + * 在此查阅所有可自定义的变量:https://github.com/element-plus/element-plus/blob/dev/packages/theme-chalk/src/common/var.scss + * 也可以打开浏览器控制台选择元素,查看要覆盖的变量名 + */ + +/** 基础颜色 */ +html.dark-blue { + /** color-primary */ + --el-color-primary: #00bb99; + --el-color-primary-light-3: #00bb99b3; + --el-color-primary-light-5: #00bb9980; + --el-color-primary-light-7: #00bb994d; + --el-color-primary-light-8: #00bb9933; + --el-color-primary-light-9: #00bb991a; + --el-color-primary-dark-2: #00bb99; + /** color-success */ + --el-color-success: #67c23a; + --el-color-success-light-3: #67c23ab3; + --el-color-success-light-5: #67c23a80; + --el-color-success-light-7: #67c23a4d; + --el-color-success-light-8: #67c23a33; + --el-color-success-light-9: #67c23a1a; + --el-color-success-dark-2: #67c23a; + /** color-warning */ + --el-color-warning: #e6a23c; + --el-color-warning-light-3: #e6a23cb3; + --el-color-warning-light-5: #e6a23c80; + --el-color-warning-light-7: #e6a23c4d; + --el-color-warning-light-8: #e6a23c33; + --el-color-warning-light-9: #e6a23c1a; + --el-color-warning-dark-2: #e6a23c; + /** color-danger */ + --el-color-danger: #f56c6c; + --el-color-danger-light-3: #f56c6cb3; + --el-color-danger-light-5: #f56c6c80; + --el-color-danger-light-7: #f56c6c4d; + --el-color-danger-light-8: #f56c6c33; + --el-color-danger-light-9: #f56c6c1a; + --el-color-danger-dark-2: #f56c6c; + /** color-error */ + --el-color-error: #f56c6c; + --el-color-error-light-3: #f56c6cb3; + --el-color-error-light-5: #f56c6c80; + --el-color-error-light-7: #f56c6c4d; + --el-color-error-light-8: #f56c6c33; + --el-color-error-light-9: #f56c6c1a; + --el-color-error-dark-2: #f56c6c; + /** color-info */ + --el-color-info: #909399; + --el-color-info-light-3: #909399b3; + --el-color-info-light-5: #90939980; + --el-color-info-light-7: #9093994d; + --el-color-info-light-8: #90939933; + --el-color-info-light-9: #9093991a; + --el-color-info-dark-2: #909399; + /** text-color */ + --el-text-color-primary: #e5eaf3; + --el-text-color-regular: #cfd3dc; + --el-text-color-secondary: #a3a6ad; + --el-text-color-placeholder: #8d9095; + --el-text-color-disabled: #6c6e72; + /** border-color */ + --el-border-color-darker: #003380; + --el-border-color-dark: #003380; + --el-border-color: #003380; + --el-border-color-light: #003380; + --el-border-color-lighter: #003380; + --el-border-color-extra-light: #003380; + /** fill-color */ + --el-fill-color-darker: #002b6b; + --el-fill-color-dark: #002b6b; + --el-fill-color: #002b6b; + --el-fill-color-light: #002359; + --el-fill-color-lighter: #002359; + --el-fill-color-blank: #001b44; + --el-fill-color-extra-light: #001b44; + /** bg-color */ + --el-bg-color-page: #001535; + --el-bg-color: #001b44; + --el-bg-color-overlay: #002359; + /** mask-color */ + --el-mask-color: rgba(0, 0, 0, 0.5); + --el-mask-color-extra-light: rgba(0, 0, 0, 0.3); +} + +/** button */ +html.dark-blue .el-button { + --el-button-disabled-text-color: rgba(255, 255, 255, 0.5); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.scss new file mode 100644 index 0000000000000000000000000000000000000000..8564e9a0e970a6cdd9d094796c921360c2a5afe3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/element-plus.scss @@ -0,0 +1,217 @@ +/** 自定义 Element Plus 样式 */ + +// 卡片 +.el-card { + background-color: var(--el-bg-color); +} + +// 分页 +.el-pagination { + // 参考 Bootstrap 的响应式设计 WIDTH = 768 + @media screen and (max-width: 768px) { + .el-pagination__total, + .el-pagination__sizes, + .el-pagination__jump, + .btn-prev, + .btn-next { + display: none !important; + } + } +} + +.el-dropdown-link { + font-size: 12px; + cursor: pointer; + color: var(--el-color-primary); + display: flex; + align-items: center; +} + +.el-table th.el-table__cell { + background: rgb(245, 247, 250) !important; +} + +// 表格不省略样式 +.el-table .no-table-cell-text-ellipsis .cell { + text-overflow: unset; +} + +// 纯文本 tag +.only-text-tag { + .el-tag { + border: none !important; + background-color: transparent !important; + font-size: 13.5px; + padding: 0; + margin: 0; + } +} + +/** + * 消除 el-button 点击 / 悬停时的"文字闪烁"。 + * + * 成因(已用真机逐帧验证):Element Plus 的 el-button 对 color 挂了 0.1s 过渡,并在 + * :hover / :active / :focus 之间切换 color 变量(例如 default 按钮由 + * --el-text-color-regular 渐变到 --el-color-primary,primary 按钮内部文字白色也会 + * 随背景色过渡被重绘)。鼠标"点一下"会连续经历 hover→active→hover→(离开) 多个状态 + * 切换,每段都有 ~100ms 过渡,视觉上文字就会"闪一下"。 + * + * 处理:让所有按钮文字颜色在交互态保持恒定,交互反馈改由背景色 + 边框色承担 + * (保持 Element Plus 原有的浅蓝底 / 蓝边框 / 彩色按钮变浅效果),并取消 color 过渡。 + * 仅排除 is-link / is-text —— 它们没有背景与边框,文字色本身就是唯一的交互反馈。 + */ +.el-button:not(.is-link):not(.is-text) { + // 1) 关闭文字颜色的过渡动画,避免 100ms 内的逐帧重绘 + transition-property: background-color, border-color, outline-color, box-shadow; + + // 2) 冻结交互态下的文字颜色(继承各类按钮自身的 --el-button-text-color) + &:hover, + &:active, + &:focus, + &:focus-visible { + color: var(--el-button-text-color); + } +} + +// plain 彩色按钮(primary/success/warning/danger/info plain): +// hover 时 Element Plus 会把背景从浅色变成实心主题色,文字必须同步从主题色变为白色, +// 否则会出现"蓝字 + 蓝底"看不清。这里显式覆盖前一段"冻结文字色"的规则, +// 让 hover/active 文字直接用 Element Plus 的 hover 文字色(白色), +// 并把 color 过渡时长设为 0,既避免闪烁,又让切换瞬时完成。 +// 注意: +// 1) 必须排除 disabled 状态——disabled 的 plain 按钮背景保持白色,若把文字改成 +// 白色会出现"白底白字"整个按钮消失的情况。 +// 2) 不要在 :focus / :focus-visible 下保持白色文字——点击后浏览器会保留 focus 态 +// 但背景已经恢复为浅色,若文字还是白色就会出现"浅底白字"看不清,所以仅 +// 在真正有实色背景的 :hover / :active 下保持白色即可。 +.el-button.is-plain:not(.is-link):not(.is-text) { + // 仅去掉 color 过渡动画,但不冻结 color 值 + transition-property: color, background-color, border-color, outline-color, box-shadow; + transition-duration: 0s, var(--el-transition-duration), var(--el-transition-duration), var(--el-transition-duration), var(--el-transition-duration); + + &:not(.is-disabled):not(:disabled) { + &:hover, + &:active { + // 覆盖前面"冻结为 --el-button-text-color"的规则,使用 Element Plus 原生的 hover 文字色(白) + color: var(--el-button-hover-text-color); + } + } +} + +/** + * 补充修复:primary / success / warning / danger / info 等彩色按钮点击时文字"闪一下"。 + * + * 成因:Element Plus 把这些按钮的 --el-button-hover-bg-color 设成了 light-5(约 50% + * 透明度)的半透明主色,鼠标按下 / 悬停瞬间背景透明度骤降,白色文字下方透出了 + * 弹窗 / 页面的白色背景,造成"白字 + 白底 = 文字看起来淡掉"的闪烁错觉。松开后 + * 背景恢复不透明,文字又恢复清晰。 + * + * 处理:把 hover / active 的背景与边框 CSS 变量替换为不透明的 light-3 / dark-2 实色, + * 保持 Element Plus 原有的"变浅 / 变深"视觉反馈,但背景始终不透明,文字因此恒定。 + */ +@mixin wb-solid-color-btn($type) { + .el-button--#{$type}:not(.is-plain):not(.is-link):not(.is-text) { + --el-button-hover-bg-color: var(--el-color-#{$type}-light-3); + --el-button-hover-border-color: var(--el-color-#{$type}-light-3); + --el-button-active-bg-color: var(--el-color-#{$type}-dark-2); + --el-button-active-border-color: var(--el-color-#{$type}-dark-2); + } +} + +@include wb-solid-color-btn('primary'); +@include wb-solid-color-btn('success'); +@include wb-solid-color-btn('warning'); +@include wb-solid-color-btn('danger'); +@include wb-solid-color-btn('info'); + +/** + * 消除 Dialog 关闭瞬间"背景页面上的按钮文字闪烁"。 + * + * 成因:点击弹窗底部"确定"后,弹窗关闭会同时触发两段 Element Plus 原生过渡动画: + * 1) el-overlay 遮罩层(半透明黑色,覆盖整个页面)执行 opacity 1→0 的淡出; + * 2) el-dialog 弹窗容器执行 opacity 1→0 的淡出。 + * 在遮罩淡出的 ~300ms 期间,弹窗背后的"查询 / 重置"等按钮经历 + * 「被半透明黑色蒙住 → 蒙层逐帧变淡 → 完全露出」的过程,彩色文字(蓝/白) + * 在半透明黑覆盖下对比度变化明显,视觉上就是"文字闪一下"; + * 同理弹窗自身淡出时,底部"取消 / 重置 / 确定"白底蓝字在 opacity 过渡中 + * 也会被看到"渐隐"过程,产生二次闪烁。 + * + * 处理: + * 1) 让 el-overlay 遮罩直接"瞬时消失"(关闭 opacity 过渡),背景页按钮不再被 + * 渐变蒙层扫过; + * 2) 让弹窗关闭时底部按钮直接 visibility: hidden,不参与弹窗 opacity 淡出。 + * 弹窗本体的淡出动画保留,整体关闭依然自然柔和。 + */ +.el-overlay { + // 遮罩不再做淡出动画,直接出现 / 直接消失 + transition: none !important; + animation: none !important; +} + +// 弹窗离场动画期间,隐藏底部按钮,避免白底蓝字被看到渐隐 +.el-dialog.dialog-fade-leave-active, +.el-dialog.dialog-fade-leave-to { + .el-dialog__footer .el-button { + visibility: hidden; + } +} + +/** + * 让 v-loading 遮罩的淡入淡出"够短但够平滑"(选项 3:200ms 过渡)。 + * + * 背景:Element Plus 原生给 .el-loading-mask 的 opacity 过渡设为 0.3s。当请求时长 + * < 300ms(本地 / 测试环境常见)时,淡入还没结束就开始淡出,两段过渡交叠, + * mask 的 opacity 在 0→中间值→0 之间剧烈震荡,视觉上就是"按钮闪一下"。 + * 而线上环境请求通常 >1s,mask 稳定显示时间足够长,不会出现交叠闪烁。 + * + * 处理:把 opacity 过渡设为 200ms。 + * - 请求 > 400ms(200ms 淡入 + 200ms 淡出,两段不交叠):行为完全自然,接近原生 + * 300ms 的平滑质感; + * - 请求 < 400ms:虽会交叠,但 200ms 已避开原生 300ms 的敏感临界区,交叠峰值 + * 被压低,视觉上几乎看不到闪烁; + * - 线上长请求:进入 / 退出各 200ms,节奏接近原生,但略利落。 + * loading-mask 内部的 .el-loading-spinner(转圈图标)保留原有动画不变。 + */ +.el-loading-mask { + transition: opacity 200ms ease !important; +} + +/** + * 提单弹窗:限制整体高度不超过视口,让弹窗内部的表单区域自身滚动, + * 避免长内容把"提交 / 取消"按钮挤出屏幕。 + * + * 另外:描述区使用 scEditor(TinyMCE,异步加载 iframe),加载前仅渲染一个 + * 空 textarea,弹窗高度会"先小后大"闪一下。给外层容器一个最小高度,让 + * 骨架一开始就撑到接近最终尺寸,加载完成后不再出现跳变。 + */ +.bug-submit-dialog { + display: flex; + flex-direction: column; + max-height: 90vh; + margin-bottom: 0 !important; + + .el-dialog__body { + flex: 1 1 auto; + overflow-y: auto; + padding-top: 10px; + padding-bottom: 10px; + // 预留描述区编辑器加载前的占位高度,避免弹窗先小后大的抖动 + min-height: 560px; + } + + .el-dialog__footer { + flex-shrink: 0; + border-top: 1px solid var(--el-border-color-lighter); + } + + // 缺陷描述区域:TinyMCE 加载前先占位到接近实际高度 + .fs-form-item-description, + .el-form-item__content .el-textarea { + min-height: 420px; + } + + // TinyMCE 容器自身也给一个保底高度,避免 iframe 创建瞬间高度为 0 + .tox-tinymce { + min-height: 420px !important; + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/index.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/index.scss new file mode 100644 index 0000000000000000000000000000000000000000..b3442be239353e3466dbcf0fa724fca56a03d793 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/index.scss @@ -0,0 +1,61 @@ +// 全局 CSS 变量 +@import './variables.css'; +// Transition +@import './transition.scss'; +// Element Plus +@import './element-plus.css'; +@import './element-plus.scss'; +// Vxe Table +@import './vxe-table.css'; +@import './vxe-table.scss'; +// 注册多主题 +@import './theme/register.scss'; +// Mixins +@import './mixins.scss'; +// View Transition +@import './view-transition.scss'; +// vue3-json-viewer +@import 'vue3-json-viewer/dist/index.css'; + +// 业务页面几乎都应该在根元素上挂载 class="app-container",以保持页面美观 +.app-container { + padding: 20px; +} + +html { + height: 100%; +} + +body { + height: 100%; + color: var(--v3-body-text-color); + background-color: var(--v3-body-bg-color); + -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; + font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, + sans-serif; + + @extend %scrollbar; +} + +#app { + height: 100%; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +a, +a:focus, +a:hover { + color: inherit; + outline: none; + text-decoration: none; +} + +div:focus { + outline: none; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/mixins.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/mixins.scss new file mode 100644 index 0000000000000000000000000000000000000000..890dbab507af1f7223d6d755c9364ac56755a304 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/mixins.scss @@ -0,0 +1,44 @@ +/** 清除浮动 */ +%clearfix { + &::after { + content: ''; + display: table; + clear: both; + } +} + +/** 美化原生滚动条 */ +%scrollbar { + // 整个滚动条 + &::-webkit-scrollbar { + width: 8px; + height: 8px; + } + // 滚动条上的滚动滑块 + &::-webkit-scrollbar-thumb { + border-radius: 4px; + background-color: #90939955; + } + + &::-webkit-scrollbar-thumb:hover { + background-color: #90939977; + } + + &::-webkit-scrollbar-thumb:active { + background-color: #90939999; + } + // 当同时有垂直滚动条和水平滚动条时交汇的部分 + &::-webkit-scrollbar-corner { + background-color: transparent; + } +} + +/** 文本溢出时显示省略号 */ +%ellipsis { + // 隐藏溢出的文本 + overflow: hidden; + // 防止文本换行 + white-space: nowrap; + // 文本内容溢出容器时,文本末尾显示省略号 + text-overflow: ellipsis; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/element-plus.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/element-plus.scss new file mode 100644 index 0000000000000000000000000000000000000000..c718d340f1dd2f5b58e00b8acfddedc5d3cce7f6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/element-plus.scss @@ -0,0 +1,34 @@ +/** Element Plus 相关 */ + +// 侧边栏的 item 的 popper +.el-popper { + .el-menu { + background-color: var(--el-bg-color); + + .el-menu-item { + background-color: var(--el-bg-color); + + &.is-active, + &:hover { + background-color: var(--el-bg-color-overlay); + color: #fff; + } + } + + .el-sub-menu__title { + background-color: var(--el-bg-color); + } + + .el-sub-menu { + &.is-active { + > .el-sub-menu__title { + color: #fff; + } + } + } + } + + .el-menu--horizontal { + border: none; + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/index.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/index.scss new file mode 100644 index 0000000000000000000000000000000000000000..916b7718c8179d4377ec3aa6c320d0c1c043e7b2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/index.scss @@ -0,0 +1,4 @@ +.#{$theme-name} { + @import './layouts.scss'; + @import './element-plus.scss'; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/layouts.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/layouts.scss new file mode 100644 index 0000000000000000000000000000000000000000..39dd94a5ce6fe269806c966bdd5a6d324912acc6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/core/layouts.scss @@ -0,0 +1,39 @@ +/** Layout 相关 */ + +.app-wrapper { + // 侧边栏 + .sidebar-container { + background-color: var(--el-bg-color); + + .el-menu { + background-color: var(--el-bg-color); + + .el-menu-item { + background-color: var(--el-bg-color); + + &.is-active, + &:hover { + background-color: var(--el-bg-color-overlay); + color: #fff; + } + } + } + + .el-sub-menu__title { + background-color: var(--el-bg-color); + } + + .el-sub-menu { + &.is-active { + > .el-sub-menu__title { + color: #fff !important; + } + } + } + } +} + +// 右侧设置面板 +.handle-button { + background-color: lighten($theme-bg-color, 20%) !important; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/index.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/index.scss new file mode 100644 index 0000000000000000000000000000000000000000..ce89a62eee7ba327a756024ef31ab2397ba4dd89 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/index.scss @@ -0,0 +1,2 @@ +@import './variables.scss'; +@import '../core/index.scss'; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/variables.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/variables.scss new file mode 100644 index 0000000000000000000000000000000000000000..48fca7277e34b3a390693e292311096c2e9d8e2e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark-blue/variables.scss @@ -0,0 +1,6 @@ +/** dark-blue 主题下的变量 */ + +// 主题名称 +$theme-name: 'dark-blue'; +// 主题背景颜色 +$theme-bg-color: #001b44; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/index.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/index.scss new file mode 100644 index 0000000000000000000000000000000000000000..ce89a62eee7ba327a756024ef31ab2397ba4dd89 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/index.scss @@ -0,0 +1,2 @@ +@import './variables.scss'; +@import '../core/index.scss'; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/variables.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/variables.scss new file mode 100644 index 0000000000000000000000000000000000000000..df808e644611d3bd82886241ef184ea2a6451340 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/dark/variables.scss @@ -0,0 +1,6 @@ +/** dark 主题下的变量 */ + +// 主题名称 +$theme-name: 'dark'; +// 主题背景颜色 +$theme-bg-color: #141414; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/register.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/register.scss new file mode 100644 index 0000000000000000000000000000000000000000..c73e5528acb72f52d87ba5588890bcc3651baf61 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/theme/register.scss @@ -0,0 +1,3 @@ +// 注册多主题 +@import './dark/index.scss'; +@import './dark-blue/index.scss'; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/transition.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/transition.scss new file mode 100644 index 0000000000000000000000000000000000000000..7b31332d67ccd0e6b3d94a1659e058b608bbd896 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/transition.scss @@ -0,0 +1,28 @@ +// See https://cn.vuejs.org/guide/built-ins/transition.html for detail + +// fade-transform +.fade-transform-leave-active, +.fade-transform-enter-active { + transition: all .5s; +} + +.fade-transform-enter { + opacity: 0; + transform: translateX(-30px); +} + +.fade-transform-leave-to { + opacity: 0; + transform: translateX(30px); +} + +// layout-logo-fade +.layout-logo-fade-enter-active, +.layout-logo-fade-leave-active { + transition: opacity 1.5s; +} + +.layout-logo-fade-enter-from, +.layout-logo-fade-leave-to { + opacity: 0; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/variables.css b/timi_hok_game_translator/LQA_WMP/web/src/styles/variables.css new file mode 100644 index 0000000000000000000000000000000000000000..d97caca58a696e67964391f08abf345045f9d7d8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/variables.css @@ -0,0 +1,69 @@ +/** 全局 CSS 变量,这种变量不仅可以在 CSS 和 SCSS 中使用,还可以导入到 JS 中使用 */ + +:root { + /** Body */ + --v3-body-text-color: var(--el-text-color-primary); + --v3-body-bg-color: var(--el-bg-color-page); + /** Header 区域 = NavigationBar 组件 + TagsView 组件 */ + --v3-header-height: calc(var(--v3-navigationbar-height) + var(--v3-tagsview-height)); + --v3-header-bg-color: var(--el-bg-color); + --v3-header-box-shadow: var(--el-box-shadow-lighter); + --v3-header-border-bottom: 1px solid var(--el-fill-color); + /** NavigationBar 组件 */ + --v3-navigationbar-height: 50px; + --v3-navigationbar-text-color: var(--el-text-color-regular); + /** Sidebar 组件(左侧模式全部生效、顶部模式全部不生效、混合模式非颜色部分生效) */ + --v3-sidebar-width: 220px; + --v3-sidebar-hide-width: 58px; + --v3-sidebar-border-right: 1px solid var(--el-fill-color); + --v3-sidebar-menu-item-height: 60px; + --v3-sidebar-menu-tip-line-bg-color: var(--el-color-primary); + --v3-sidebar-menu-bg-color: #001428; + --v3-sidebar-menu-hover-bg-color: #409eff10; + --v3-sidebar-menu-text-color: #cfd3dc; + --v3-sidebar-menu-active-text-color: #ffffff; + /** TagsView 组件 */ + --v3-tagsview-height: 34px; + --v3-tagsview-text-color: var(--el-text-color-regular); + --v3-tagsview-tag-active-text-color: #ffffff; + --v3-tagsview-tag-bg-color: var(--el-bg-color); + --v3-tagsview-tag-active-bg-color: var(--el-color-primary); + --v3-tagsview-tag-border-radius: 2px; + --v3-tagsview-tag-border-color: var(--el-border-color-lighter); + --v3-tagsview-tag-active-border-color: var(--el-color-primary); + --v3-tagsview-tag-icon-hover-bg-color: #00000030; + --v3-tagsview-tag-icon-hover-color: #ffffff; + --v3-tagsview-contextmenu-text-color: var(--el-text-color-regular); + --v3-tagsview-contextmenu-hover-text-color: var(--el-text-color-primary); + --v3-tagsview-contextmenu-bg-color: var(--el-bg-color-overlay); + --v3-tagsview-contextmenu-hover-bg-color: var(--el-fill-color); + --v3-tagsview-contextmenu-box-shadow: var(--el-box-shadow); + /** Hamburger 组件 */ + --v3-hamburger-text-color: var(--el-text-color-primary); + /** RightPanel 组件 */ + --v3-rightpanel-button-bg-color: #001428; +} + +/** 内容区放大时,将不需要的组件隐藏 */ +body.content-large { + /** Header 区域 = TagsView 组件 */ + --v3-header-height: var(--v3-tagsview-height); + /** NavigationBar 组件 */ + --v3-navigationbar-height: 0px; + /** Sidebar 组件 */ + --v3-sidebar-width: 0px; + --v3-sidebar-hide-width: 0px; +} + +/** 内容区全屏时,将不需要的组件隐藏 */ +body.content-full { + /** Header 区域 */ + --v3-header-height: 0px; + /** NavigationBar 组件 */ + --v3-navigationbar-height: 0px; + /** Sidebar 组件 */ + --v3-sidebar-width: 0px; + --v3-sidebar-hide-width: 0px; + /** TagsView 组件 */ + --v3-tagsview-height: 0px; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/view-transition.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/view-transition.scss new file mode 100644 index 0000000000000000000000000000000000000000..a2fb41e6705805e891a54efbb24b13391e152f8c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/view-transition.scss @@ -0,0 +1,21 @@ +/** 控制切换主题时的动画效果(只在较新的浏览器上生效,例如 Chrome 111+) */ + +::view-transition-old(root) { + animation: none; + mix-blend-mode: normal; +} + +::view-transition-new(root) { + animation: .5s ease-in clip-animation; + mix-blend-mode: normal; +} + +@keyframes clip-animation { + from { + clip-path: circle(0px at var(--v3-theme-x) var(--v3-theme-y)); + } + + to { + clip-path: circle(var(--v3-theme-r) at var(--v3-theme-x) var(--v3-theme-y)); + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.css b/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.css new file mode 100644 index 0000000000000000000000000000000000000000..13bd1d4b9b146204c87373b11b5b8b01d70a6c68 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.css @@ -0,0 +1,97 @@ +/** + * 所有主题模式下的 Vxe Table CSS 变量 + * 用 Element Plus 的 CSS 变量来覆写 Vxe Table 的 CSS 变量,目的是使 Vxe Table 支持多主题模式且样式统一 + * 在此查阅所有可自定义的变量:https://github.com/x-extends/vxe-table/blob/master/styles/css-variable.scss + */ + +:root { + /*color*/ + --vxe-font-color: var(--el-text-color-regular); + --vxe-primary-color: var(--el-color-primary); + --vxe-success-color: var(--el-color-success); + --vxe-info-color: var(--el-color-info); + --vxe-warning-color: var(--el-color-warning); + --vxe-danger-color: var(--el-color-danger); + + --vxe-font-lighten-color: var(--el-text-color-primary); + --vxe-primary-lighten-color: var(--el-color-primary-light-3); + --vxe-success-lighten-color: var(--el-color-success-light-3); + --vxe-info-lighten-color: var(--el-color-info-light-3); + --vxe-warning-lighten-color: var(--el-color-warning-light-3); + --vxe-danger-lighten-color: var(--el-color-danger-light-3); + + --vxe-font-darken-color: var(--el-text-color-secondary); + --vxe-primary-darken-color: var(--el-color-primary-dark-2); + --vxe-success-darken-color: var(--el-color-success-dark-2); + --vxe-info-darken-color: var(--el-color-info-dark-2); + --vxe-warning-darken-color: var(--el-color-warning-dark-2); + --vxe-danger-darken-color: var(--el-color-danger-dark-2); + + --vxe-font-disabled-color: var(--el-text-color-disabled); + --vxe-primary-disabled-color: var(--el-color-primary-light-5); + --vxe-success-disabled-color: var(--el-color-success-light-5); + --vxe-info-disabled-color: var(--el-color-info-light-5); + --vxe-warning-disabled-color: var(--el-color-warning-light-5); + --vxe-danger-disabled-color: var(--el-color-danger-light-5); + + /*input/radio/checkbox*/ + --vxe-input-border-color: var(--el-border-color); + --vxe-input-disabled-color: var(--el-text-color-disabled); + --vxe-input-disabled-background-color: var(--el-fill-color-light); + --vxe-input-placeholder-color: var(--el-text-color-placeholder); + + /*popup*/ + --vxe-table-popup-border-color: var(--el-border-color); + + /*table*/ + --vxe-table-header-font-color: var(--el-text-color-regular); + --vxe-table-footer-font-color: var(--el-text-color-regular); + --vxe-table-border-color: var(--el-border-color-lighter); + --vxe-table-header-background-color: var(--el-bg-color); + --vxe-table-body-background-color: var(--el-bg-color); + --vxe-table-footer-background-color: var(--el-bg-color); + + --vxe-table-row-hover-background-color: var(--el-fill-color-light); + --vxe-table-row-current-background-color: var(--el-fill-color-light); + --vxe-table-row-hover-current-background-color: var(--el-fill-color-light); + + --vxe-table-checkbox-range-background-color: var(--el-fill-color-light); + + /*menu*/ + --vxe-table-menu-background-color: var(--el-bg-color-overlay); + + /*loading*/ + --vxe-loading-color: var(--el-color-primary); + --vxe-loading-background-color: var(--el-mask-color); + + /*validate*/ + --vxe-table-validate-error-color: var(--el-color-danger); + + /*toolbar*/ + --vxe-toolbar-background-color: var(--el-bg-color); + --vxe-toolbar-custom-active-background-color: var(--el-bg-color-overlay); + --vxe-toolbar-panel-background-color: var(--el-bg-color-overlay); + + /*pager*/ + --vxe-pager-background-color: var(--el-bg-color); + + /*modal*/ + --vxe-modal-header-background-color: var(--el-bg-color); + --vxe-modal-body-background-color: var(--el-bg-color); + --vxe-modal-border-color: var(--el-border-color); + + /*button*/ + --vxe-button-default-background-color: var(--el-bg-color-overlay); + + /*input*/ + --vxe-input-background-color: var(--el-fill-color-blank); + --vxe-input-panel-background-color: var(--el-fill-color-blank); + + /*form*/ + --vxe-form-background-color: var(--el-bg-color); + --vxe-form-validate-error-color: var(--el-color-danger); + + /*select*/ + --vxe-select-option-hover-background-color: var(--el-bg-color-overlay); + --vxe-select-panel-background-color: var(--el-bg-color); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.scss b/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.scss new file mode 100644 index 0000000000000000000000000000000000000000..7a7b84c1dab2e0ccdd207aff5bbfd9bd519e60c6 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/styles/vxe-table.scss @@ -0,0 +1,39 @@ +/** 自定义 Vxe Table 样式 */ + +.vxe-grid { + // 表单 + &--form-wrapper { + .vxe-form { + padding: 10px 20px !important; + margin-bottom: 20px !important; + } + } + + // 工具栏 + &--toolbar-wrapper { + .vxe-toolbar { + padding: 20px !important; + } + } + + // 分页 + &--pager-wrapper { + .vxe-pager { + height: 70px !important; + padding: 0 20px !important; + + &--wrapper { + // 参考 Bootstrap 的响应式设计 WIDTH = 768 + @media screen and (max-width: 768px) { + .vxe-pager--total, + .vxe-pager--sizes, + .vxe-pager--jump, + .vxe-pager--jump-prev, + .vxe-pager--jump-next { + display: none !important; + } + } + } + } + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/bind/date.js b/timi_hok_game_translator/LQA_WMP/web/src/utils/bind/date.js new file mode 100644 index 0000000000000000000000000000000000000000..bb98500734b71da54b29476324bce32a34e5bbde --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/bind/date.js @@ -0,0 +1,43 @@ +import dayjs from 'dayjs'; + +const dateRangeBind = { + clearable: false, + type: 'daterange', + align: 'left', + unlinkPanels: true, + rangeSeparator: '至', + startPlaceholder: '开始日期', + endPlaceholder: '结束日期', + valueFormat: 'YYYY-MM-DD', + shortcuts: [ + { + text: '最近一周', + value: () => [ + dayjs().subtract(1, 'week') + .format('YYYY-MM-DD'), + dayjs().format('YYYY-MM-DD'), + ], + }, + { + text: '最近一个月', + value: () => [ + dayjs().subtract(1, 'month') + .format('YYYY-MM-DD'), + dayjs().format('YYYY-MM-DD'), + ], + }, + { + text: '最近三个月', + value: () => [ + dayjs().subtract(3, 'month') + .format('YYYY-MM-DD'), + dayjs().format('YYYY-MM-DD'), + ], + }, + ], + disabledDate(time) { + return time > dayjs(); + }, +}; + +export { dateRangeBind }; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/cookies.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/cookies.ts new file mode 100644 index 0000000000000000000000000000000000000000..820e80b1f26a11871e59d2b6f5c3dcc643159818 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/cookies.ts @@ -0,0 +1,12 @@ +/** 统一处理 Cookie */ + +import CacheKey from '@/constants/cache-key'; +import Cookies from 'js-cookie'; + +export const getToken = () => Cookies.get(CacheKey.TOKEN); +export const setToken = (token: string) => { + Cookies.set(CacheKey.TOKEN, token); +}; +export const removeToken = () => { + Cookies.remove(CacheKey.TOKEN); +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/local-storage.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/local-storage.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e7489121d74fff0a4cc2ec0bfba0c834ed74876 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/cache/local-storage.ts @@ -0,0 +1,56 @@ +/** 统一处理 localStorage */ + +import CacheKey from '@/constants/cache-key'; +import { type SidebarOpened, type SidebarClosed } from '@/constants/app-key'; +import { type ThemeName } from '@/hooks/useTheme'; +import { type TagView } from '@/store/modules/tags-view'; +import { type LayoutSettings } from '@/config/layouts'; + +// #region 系统布局配置 +export const getConfigLayout = () => { + const json = localStorage.getItem(CacheKey.CONFIG_LAYOUT); + return json ? (JSON.parse(json) as LayoutSettings) : null; +}; +export const setConfigLayout = (settings: LayoutSettings) => { + localStorage.setItem(CacheKey.CONFIG_LAYOUT, JSON.stringify(settings)); +}; +export const removeConfigLayout = () => { + localStorage.removeItem(CacheKey.CONFIG_LAYOUT); +}; +// #endregion + +// #region 侧边栏状态 +export const getSidebarStatus = () => localStorage.getItem(CacheKey.SIDEBAR_STATUS); +export const setSidebarStatus = (sidebarStatus: SidebarOpened | SidebarClosed) => { + localStorage.setItem(CacheKey.SIDEBAR_STATUS, sidebarStatus); +}; +// #endregion + +// #region 正在应用的主题名称 +export const getActiveThemeName = () => localStorage.getItem(CacheKey.ACTIVE_THEME_NAME) as ThemeName | null; +export const setActiveThemeName = (themeName: ThemeName) => { + localStorage.setItem(CacheKey.ACTIVE_THEME_NAME, themeName); +}; +// #endregion + +// #region 标签栏 +export const getVisitedViews = () => { + const json = localStorage.getItem(CacheKey.VISITED_VIEWS); + return JSON.parse(json ?? '[]') as TagView[]; +}; +export const setVisitedViews = (views: TagView[]) => { + views.forEach((view) => { + // 删除不必要的属性,防止 JSON.stringify 处理到循环引用 + delete view.matched; + delete view.redirectedFrom; + }); + localStorage.setItem(CacheKey.VISITED_VIEWS, JSON.stringify(views)); +}; +export const getCachedViews = () => { + const json = localStorage.getItem(CacheKey.CACHED_VIEWS); + return JSON.parse(json ?? '[]') as string[]; +}; +export const setCachedViews = (views: string[]) => { + localStorage.setItem(CacheKey.CACHED_VIEWS, JSON.stringify(views)); +}; +// #endregion diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/dict.js b/timi_hok_game_translator/LQA_WMP/web/src/utils/dict.js new file mode 100644 index 0000000000000000000000000000000000000000..585891a450f335b5255ddcb8e55a058f7fbdd363 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/dict.js @@ -0,0 +1,97 @@ +import { dict } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; + +/** 用户 */ +export function getUserDict() { + return dict({ + url: '/api/user/list', + value: 'value', + label: 'label', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get', params: { + info_type: 0, // 简略信息 + page_size: 1000000000000000, + } }); + // 只返回 el-option 需要的 { value, label },避免把 updated_at / last_login_at / created_at + // 等后端原始字段作为 attrs 透传到 ,否则会触发 + // "[Vue warn]: Slot default invoked outside of the render function" 并导致页面白屏 + return data.list.map(item => ({ + value: item.id, + label: item.name_zh ? `${item.name}(${item.name_zh})` : item.name, + })); + }, + }); +} + +/** 区域语言 */ +export function getLanguageDict(projectId, filter = false) { + if (projectId) { + return dict({ + url: `/api/project/config?_=${Math.random()}`, + async getData() { + const res = await customRequest({ + url: '/api/project/config', + method: 'get', + params: { project_id: projectId, cate: 'Language' }, + }); + res.data.list.sort((a, b) => a.value - b.value); + if (filter) { + // 执行过滤:只保留已启用,并只返回 el-option 需要的字段, + // 避免把后端原始字段作为 attrs 透传到 ,否则会触发 + // "[Vue warn]: Slot default invoked outside of the render function" 警告 + return res.data.list + .filter(item => item.enable) + .map(item => ({ + value: item.value, + label: item.label, + name: item.name, + })); + } + // 展示未启用数据:同样仅返回必要字段 + return res.data.list.map(item => ({ + value: item.value, + label: item.enable ? item.label : `${item.label}(未启用)`, + name: item.name, + color: item.enable ? undefined : 'info', + effect: item.enable ? undefined : 'light', + disabled: !item.enable, + })); + }, + }); + } + return dict({ + url: `/api/system/enums/language?project_id=${projectId}`, + }); +} + +/** 缺陷类型 */ +export function getBugTypeDict(projectId) { + // 有项目 + if (projectId) { + return dict({ + url: `/api/project/config?_=${Math.random()}`, + async getData() { + const res = await customRequest({ + url: '/api/project/config', + method: 'get', + params: { project_id: projectId, cate: 'BugType' }, + }); + // 仅返回 el-option 需要的字段,避免把后端整条原始记录透传到 , + // 否则会触发 "[Vue warn]: Slot default invoked outside of the render function" + return res.data.list.map(item => ({ + value: item.value, + label: item.enable ? item.label : `${item.label}(未启用)`, + name: item.name, + color: item.enable ? undefined : 'info', + effect: item.enable ? undefined : 'light', + disabled: !item.enable, + })); + }, + }); + } + + // 没有项目 + return dict({ + url: '/api/system/enums/bug_type', + }); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/download.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/download.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9fb6f136b3bcaa30f9753e6e0f1dcd5f7a1ffd2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/download.ts @@ -0,0 +1,35 @@ +/** + * Download according to the background interface file stream + * @param {*} data + * @param {*} filename + * @param {*} mime + * @param {*} bom + */ +export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) { + const blobData = typeof bom !== 'undefined' ? [bom, data] : [data]; + const blob = new Blob(blobData, { type: mime || 'application/octet-stream' }); + + const blobURL = window.URL.createObjectURL(blob); + const tempLink = document.createElement('a'); + tempLink.style.display = 'none'; + tempLink.href = blobURL; + tempLink.setAttribute('download', filename); + if (typeof tempLink.download === 'undefined') { + tempLink.setAttribute('target', '_blank'); + } + document.body.appendChild(tempLink); + tempLink.click(); + document.body.removeChild(tempLink); + window.URL.revokeObjectURL(blobURL); +} + +/** + * 根据 URL 下载文件 + * @param {string} url - 链接 + */ +export function downloadByUrl(url: string) { + const a = document.createElement('a'); + a.href = url; + a.download = url.split('/').pop()!.split('?')[0]; + a.click(); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/env.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/env.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c4339f4856e6814520bef5bb45584eddf8eb6f9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/env.ts @@ -0,0 +1,7 @@ +export function isDevMode(): boolean { + return import.meta.env.DEV; +} + +export function isProdMode(): boolean { + return import.meta.env.PROD; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/index.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..876b21640def2837763a1464a3e9abde086b3093 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/index.ts @@ -0,0 +1,46 @@ +import dayjs from 'dayjs'; +import { removeConfigLayout } from '@/utils/cache/local-storage'; +import { cloneDeep } from 'lodash-es'; + +/** 格式化时间 */ +export const formatDateTime = (time: string | number | Date) => (time ? dayjs(new Date(time)).format('YYYY-MM-DD HH:mm:ss') : 'N/A'); + +/** 用 JS 获取全局 css 变量 */ +export const getCssVariableValue = (cssVariableName: string) => { + let cssVariableValue = ''; + try { + // 没有拿到值时,会返回空串 + cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName); + } catch (error) { + console.error(error); + } + return cssVariableValue; +}; + +/** 用 JS 设置全局 CSS 变量 */ +export const setCssVariableValue = (cssVariableName: string, cssVariableValue: string) => { + try { + document.documentElement.style.setProperty(cssVariableName, cssVariableValue); + } catch (error) { + console.error(error); + } +}; + +/** 重置项目配置 */ +export const resetConfigLayout = () => { + removeConfigLayout(); + location.reload(); +}; + +/** + * 覆盖 reactive 对象 + * @param obj: 数据对象 + * @param reactiveObj: 要覆盖的 reactive 对象 + */ +export function setReactiveObject(obj: ObjType, reactiveObj: ObjType) { + const cloneObj = cloneDeep(obj); + Object.keys(cloneObj).forEach((key) => { + // @ts-ignore + reactiveObj[key] = cloneObj[key]; + }); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/permission.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/permission.ts new file mode 100644 index 0000000000000000000000000000000000000000..f362ec7baa505533c09fbd844c0f7ab3016696c5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/permission.ts @@ -0,0 +1,14 @@ +import { useUserStoreHook } from '@/store/modules/user'; + +/** 全局权限判断函数,和权限指令 v-permission 功能类似 */ +export const checkPermission = (permissionRoles: string[]): boolean => { + if (Array.isArray(permissionRoles) && permissionRoles.length > 0) { + const { superAdmin, roles } = useUserStoreHook(); + if (superAdmin) { + return true; + } + return roles.some(role => permissionRoles.includes(role)); + } + console.error('need roles! Like checkPermission([\'admin\',\'editor\'])'); + return false; +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/register.js b/timi_hok_game_translator/LQA_WMP/web/src/utils/register.js new file mode 100644 index 0000000000000000000000000000000000000000..0845b703a2b537d23c864be21cc3e5ff311b19e1 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/register.js @@ -0,0 +1,9 @@ +import { isDevMode } from './env.ts'; + +export function registerGlobUtils(app) { + /* eslint-disable */ + app.config.globalProperties.isDevMode = isDevMode; + app.config.globalProperties.$log = console.log; + app.config.globalProperties.$sleep = time => new Promise(resolve => setTimeout(resolve, time)); + /* eslint-enable */ +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/runner.js b/timi_hok_game_translator/LQA_WMP/web/src/utils/runner.js new file mode 100644 index 0000000000000000000000000000000000000000..e2c22f3c0549316b53a4242cebc4edda74c77728 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/runner.js @@ -0,0 +1,76 @@ +/** + * 还原任务执行:由浏览器直接调用项目配置的 Webhook(Jenkins / GitLab CI / 自建服务等) + * 1. POST /api/job/action {action: start|retry} 后端校验任务状态并返回渲染好的 Webhook 请求 + * 2. 浏览器请求 Webhook(目标服务需允许平台域名跨域) + * 3. 成功后 POST /api/job/action {action: started} 任务置为执行中 + */ +import { customRequest } from '@/utils/service'; + +/** 从 Webhook 响应中尽量提取外部构建ID/链接,便于在任务详情中追溯 */ +function extractBuildId(resp, data) { + if (data && typeof data === 'object') { + const keys = ['build_id', 'buildId', 'web_url', 'url', 'id', 'number', 'pipeline_id']; + for (const k of keys) { + if (data[k] !== undefined && data[k] !== null && data[k] !== '') return String(data[k]); + } + } + // Jenkins 返回 201 + Location(需要目标服务 Access-Control-Expose-Headers: Location) + return resp.headers.get('Location') || ''; +} + +function encodeBody(body, headers) { + if (body === null || body === undefined) return undefined; + const contentType = Object.entries(headers || {}) + .find(([k]) => k.toLowerCase() === 'content-type')?.[1] || ''; + if (contentType.includes('application/x-www-form-urlencoded') && typeof body === 'object') { + const params = new URLSearchParams(); + Object.entries(body).forEach(([k, v]) => params.append(k, Array.isArray(v) ? v.join(',') : String(v))); + return params.toString(); + } + return typeof body === 'string' ? body : JSON.stringify(body); +} + +/** 浏览器发起 Webhook 请求 */ +export async function callWebhook(trigger) { + let resp; + try { + resp = await fetch(trigger.url, { + method: trigger.method, + headers: trigger.headers || {}, + body: trigger.method === 'GET' ? undefined : encodeBody(trigger.body, trigger.headers), + mode: 'cors', + credentials: 'omit', + }); + } catch (err) { + throw new Error(`无法访问 Webhook:网络不可达,或目标服务未允许跨域(CORS)。${err.message || ''}`); + } + const text = await resp.text().catch(() => ''); + if (!resp.ok) { + throw new Error(`Webhook 返回 HTTP ${resp.status}:${text.slice(0, 300)}`); + } + let data = null; + try { + data = text ? JSON.parse(text) : null; + } catch { + data = null; + } + return extractBuildId(resp, data); +} + +/** + * 开始/重试任务 + * @param {number} jobId + * @param {'start'|'retry'} action + * @returns {Promise} 提示信息 + */ +export async function runJob(jobId, action = 'start') { + const res = await customRequest({ url: '/api/job/action', method: 'post', data: { action, job_id: jobId } }); + const { trigger, regression } = res.data; + const buildId = await callWebhook(trigger); + await customRequest({ + url: '/api/job/action', + method: 'post', + data: { action: 'started', job_id: jobId, regression, build_id: buildId }, + }); + return buildId ? `已触发还原任务(${buildId})` : '已触发还原任务'; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/service.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/service.ts new file mode 100644 index 0000000000000000000000000000000000000000..92821ea9c70b6393d6c3197184ced500d8b4d82c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/service.ts @@ -0,0 +1,180 @@ +import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'; +import { useUserStoreHook } from '@/store/modules/user'; +import { ElMessage } from 'element-plus'; +import { get, merge } from 'lodash-es'; + +/** 后端约定:认证失败的业务码 */ +const AUTH_ERROR_CODE = 1003; + +/** 会话失效:清理本地登录态并跳转登录页(登录页本身的请求不跳转) */ +function logout() { + useUserStoreHook().resetToken(); + const { pathname, search } = window.location; + if (pathname.startsWith('/login') || pathname.startsWith('/register')) return; + const redirect = encodeURIComponent(`${pathname}${search}`); + window.location.href = `/login?redirect=${redirect}`; +} + +/** 创建请求实例 */ +function createService() { + // 创建一个 axios 实例命名为 service + const service = axios.create(); + // 请求拦截 + service.interceptors.request.use( + (config) => { + // 修改 get 请求 Content-Type,为 application/json 改为空 + if (config.method === 'get') { + if (config.headers['Content-Type'] === 'application/json') { + config.headers['Content-Type'] = null; + } + } + return config; + }, + // 发送失败 + error => Promise.reject(error), + ); + // 响应拦截(可根据具体业务作出相应的调整) + service.interceptors.response.use( + (response) => { + // apiData 是 api 返回的数据 + const apiData = response.data; + // 二进制数据则直接返回 + const responseType = response.request?.responseType; + if (responseType === 'blob' || responseType === 'arraybuffer') return apiData; + // 这个 code 是和后端约定的业务 code,0 表示成功 + const code = apiData?.code; + // 如果没有 code, 代表这不是项目后端开发的 api + if (code === undefined) { + ElMessage.error('非本系统的接口'); + return Promise.reject(new Error('非本系统的接口')); + } + if (code === 0) return apiData; + if (code === AUTH_ERROR_CODE) { + logout(); + return Promise.reject(new Error(apiData.msg || '未登录')); + } + const msg = apiData.message || apiData.msg || 'Error'; + if (!get(response, 'config.silent', false)) ElMessage.error(msg); + // 与 HTTP 错误保持一致:调用方可通过 err.response.data.msg 读取后端信息 + return Promise.reject(Object.assign(new Error(msg), { response })); + }, + (error) => { + // status 是 HTTP 状态码 + const status = get(error, 'response.status'); + // 业务错误后端返回 HTTP 500 + {code, msg},调用方按需读取 error.response.data + const silent = get(error, 'config.silent', false); + switch (status) { + case 400: + error.message = '请求错误'; + break; + case 401: + // 会话失效:登录接口本身的 401(账号或密码错误)交给调用方提示 + if (!String(get(error, 'config.url', '')).includes('/api/user/login')) { + logout(); + return Promise.reject(error); + } + break; + case 403: + error.message = '拒绝访问'; + break; + case 404: + error.message = '请求地址出错'; + break; + case 408: + error.message = '请求超时'; + break; + case 500: + error.message = '服务器内部错误'; + break; + case 501: + error.message = '服务未实现'; + break; + case 502: + error.message = '网关错误'; + break; + case 503: + error.message = '服务不可用'; + break; + case 504: + error.message = '网关超时'; + break; + case 505: + error.message = 'HTTP 版本不受支持'; + break; + default: + break; + } + if (!silent) { + ElMessage.error(error.response?.data?.msg || error.message); + } + return Promise.reject(error); + }, + ); + return service; +} + +/** + * GET 请求(列表 / 字典等)的最小返回时长(毫秒)。 + * + * 背景:测试环境请求通常 <100ms,fast-crud 的 loading 状态(按钮 is-loading、 + * 表格 v-loading 遮罩)持续时间太短,用户视觉上来不及感知就消失,看起来 + * 像是"点了没反应"。线上环境请求本来就 >500ms,此配置对其没有任何影响。 + * + * 行为:GET 请求的 Promise 至少等待 MIN_DELAY_MS 才 resolve。 + * - 真实请求 < 500ms:延迟到 500ms resolve → loading 清晰可见; + * - 真实请求 > 500ms:按真实时长 resolve → 和未加该机制时完全一致; + * - 非 GET 请求(表单提交 POST / PATCH / DELETE 等)不受影响,依然按真实 + * 速度返回,不影响表单响应感; + * - 业务侧可通过 config.minDelay 显式覆盖(例如传 0 关闭延迟)。 + * + * 例外:字典 / 枚举 / 项目配置 类接口(system/enums、project/config、 + * bug/tracker_meta)会自动跳过最小延迟。因为 fast-crud 的 dict-select + * 组件在字典未加载时会先把原始 value(如 "3")当成 label 展示出来, + * 等 500ms 后字典返回才切换为真实 label(如 "中"),造成明显的字段 + * "数字→文字"闪烁。字典本身的加载速度足够快,无需人为延迟。 + */ +const MIN_DELAY_MS = 500; + +/** 平台接口请求:浏览器使用 Session Cookie 认证 */ +function createCustomRequest(service: AxiosInstance) { + return function ( + config: AxiosRequestConfig & { silent?: boolean; minDelay?: number }, + ): Promise { + const defaultConfig = { + headers: { + // 'web' 表示使用 Session 认证;API 调用方可传入 access_token + 'LQA-Authorization': 'web', + 'Content-Type': 'application/json', + }, + withCredentials: true, + timeout: 0, + baseURL: import.meta.env.VITE_BASE_API, + data: {}, + }; + // 将默认配置 defaultConfig 和传入的自定义配置 config 进行合并成为 mergeConfig + const mergeConfig = merge(defaultConfig, config); + + // 仅对 GET 请求(列表查询 / 字典加载等)应用最小返回时长;非 GET 请求保持原速 + const method = String(mergeConfig.method || 'get').toLowerCase(); + // 字典 / 枚举 / 项目配置 类"打开表单必须等的加载请求"直接跳过最小延迟, + // 否则 fast-crud 的 dict-select 组件会先显示原始 value(如 "3")再切换为 + // label(如 "中"),造成明显的字段闪烁。 + const url = String(mergeConfig.url || ''); + const isDictLike = /\/api\/(system\/enums|project\/config|bug\/tracker_meta)/.test(url); + const minDelay = config.minDelay ?? (method === 'get' && !isDictLike ? MIN_DELAY_MS : 0); + if (minDelay <= 0) { + return service(mergeConfig); + } + + // Promise.all 等待"真实请求"与"最小延时"都完成,取请求结果返回 + const requestPromise = service(mergeConfig); + const delayPromise = new Promise(resolve => setTimeout(resolve, minDelay)); + return Promise.all([requestPromise, delayPromise]).then(([res]) => res) as Promise; + }; +} + +/** 用于网络请求的实例 */ +const service = createService(); +/** 用于网络请求的方法 */ +export const customRequest = createCustomRequest(service); +export const request = customRequest; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/tracker.js b/timi_hok_game_translator/LQA_WMP/web/src/utils/tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..2afe39e7d00a2a4fb69d93ad432567f0fd589044 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/tracker.js @@ -0,0 +1,37 @@ +/** + * 当前项目缺陷系统信息及提单下拉选项(发现版本/修复版本/发布计划) + * GET /api/bug/tracker_meta?project_id= + */ +import { customRequest } from '@/utils/service'; + +const cache = new Map(); + +export async function getTrackerMeta(projectId, force = false) { + if (!force && cache.has(projectId)) return cache.get(projectId); + const empty = { + type: 'none', label: '', remote: false, version_report_list: [], version_fix_list: [], release_id_list: [], error: '', + }; + let meta = empty; + try { + const res = await customRequest({ url: '/api/bug/tracker_meta', method: 'get', params: { project_id: projectId }, silent: true }); + meta = { ...empty, ...res.data }; + } catch (err) { + meta = { ...empty, error: err?.response?.data?.msg || err.message }; + } + cache.set(projectId, meta); + // 缓存 60 秒,配置修改后能较快生效 + setTimeout(() => cache.delete(projectId), 60 * 1000); + return meta; +} + +/** 转换为提单表单使用的 {params, options} */ +export function toBugFormOptions(meta) { + return { + params: { version_report: '', version_fix: '', release_id: '' }, + options: { + version_report: meta.version_report_list || [], + version_fix: meta.version_fix_list || [], + release_id: meta.release_id_list || [], + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/utils/validate.ts b/timi_hok_game_translator/LQA_WMP/web/src/utils/validate.ts new file mode 100644 index 0000000000000000000000000000000000000000..9637249ef83c7e7f076dcadb6c7bc7d6d768c51a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/utils/validate.ts @@ -0,0 +1,91 @@ +/** 判断是否为数组 */ +export const isArray = (arg: unknown) => (Array.isArray ? Array.isArray(arg) : Object.prototype.toString.call(arg) === '[object Array]'); + +/** 判断是否为字符串 */ +export const isString = (str: unknown) => typeof str === 'string' || str instanceof String; + +/** 判断是否为外链 */ +export const isExternal = (path: string) => { + const reg = /^(https?:|mailto:|tel:)/; + return reg.test(path); +}; + +/** 判断是否为网址(带协议) */ +export const isUrl = (url: string) => { + const reg = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/; + return reg.test(url); +}; + +/** 判断是否为网址或 IP(带端口) */ +export const isUrlPort = (url: string) => { + const reg = /^((ht|f)tps?:\/\/)?[\w-]+(\.[\w-]+)+:\d{1,5}\/?$/; + return reg.test(url); +}; + +/** 判断是否为域名(不带协议) */ +export const isDomain = (domain: string) => { + const reg = /^([0-9a-zA-Z-]{1,}\.)+([a-zA-Z]{2,})$/; + return reg.test(domain); +}; + +/** 判断版本号格式是否为 X.Y.Z */ +export const isVersion = (version: string) => { + const reg = /^\d+(?:\.\d+){2}$/; + return reg.test(version); +}; + +/** 判断时间格式是否为 24 小时制(HH:mm:ss) */ +export const is24H = (time: string) => { + const reg = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/; + return reg.test(time); +}; + +/** 判断是否为手机号(1 开头) */ +export const isPhoneNumber = (str: string) => { + const reg = /^(?:(?:\+|00)86)?1\d{10}$/; + return reg.test(str); +}; + +/** 判断是否为第二代身份证(18 位) */ +export const isChineseIdCard = (str: string) => { + const reg = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/; + return reg.test(str); +}; + +/** 判断是否为 Email(支持中文邮箱) */ +export const isEmail = (email: string) => { + const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/; + return reg.test(email); +}; + +/** 判断是否为 MAC 地址 */ +export const isMAC = (mac: string) => { + const reg = /^(([a-f0-9][0,2,4,6,8,a,c,e]:([a-f0-9]{2}:){4})|([a-f0-9][0,2,4,6,8,a,c,e]-([a-f0-9]{2}-){4}))[a-f0-9]{2}$/i; + return reg.test(mac); +}; + +/** 判断是否为 IPv4 地址 */ +export const isIPv4 = (ip: string) => { + const reg = /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/; + return reg.test(ip); +}; + +/** 判断是否为车牌(兼容新能源车牌) */ +export const isLicensePlate = (str: string) => { + const reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/; + return reg.test(str); +}; + +/** + * 宽松的文件/目录路径格式校验 + * 规则:必须包含 / 或 \,不能以数字开头,仅允许字母、数字、_、-、.、:、/、\ + */ +export const isValidPath = (val: unknown): boolean => { + if (typeof val !== 'string') return false; + const path = val.trim(); + if (!path) return false; + if (/^\d/.test(path)) return false; + if (!/[/\\]/.test(path)) return false; + if (!/^[A-Za-z0-9_\-./\\:]+$/.test(path)) return false; + return true; +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/data/common.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/data/common.jsx new file mode 100644 index 0000000000000000000000000000000000000000..ded0cac8ee4bd6c84f71ab79cbc50719266d154a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/data/common.jsx @@ -0,0 +1,200 @@ +import AutoPopover from '@/components/autoPopover.vue'; +import { customRequest } from '@/utils/service.ts'; +import { dateRangeBind } from '@/utils/bind/date.js'; +import { dict } from '@fast-crud/fast-crud'; +import { timeCols } from '@/fast-crud/common.ts'; +import dayjs from 'dayjs'; + +export function getCommonCols(projectId, versionDict) { + return { + // 任务 ID + job_id: { + title: '任务 ID', + type: 'number', + column: { width: 100, align: 'right' }, + form: { + component: { placeholder: '任务 ID' }, + }, + search: { + show: true, + component: { + name: 'fs-dict-select', + filterable: true, + allowCreate: true, + clearable: true, + defaultFirstOption: true, + renderLabel(e) { + return
+ {e.id} - + {e.name} + ({dayjs(e.created_at).format('YYYY-MM-DD HH:mm:ss')}) +
; + }, + dict: dict({ + url: '/api/job/list', + async getData({ url }) { + const res = await customRequest({ + url, + method: 'get', + params: { + project_id: projectId, + page_size: 10, + }, + }); + if (res.code === 0) { + return res.data.list.map(item => ({ + value: `${item.id}`, + // label: `${item.id} - ${item.name}1(${dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss')})`, + ...item, + })); + } + return []; + }, + }), + }, + }, + }, + + // 名称 + name: { + title: '名称', + type: 'text', + column: { + component: { + name: AutoPopover, + vModel: 'value', + }, + showOverflowTooltip: false, + }, + search: { + show: true, + component: { + placeholder: '模糊搜索', + }, + }, + }, + + // 采集图片 + shot_img_path: { + title: '采集图片', + type: 'image-uploader', + column: { + width: 300, + align: 'center', + component: { + buildUrl(val) { + return `${import.meta.env.VITE_RESOURCE_API}${val}`; + }, + }, + }, + }, + + // 还原图片 + revert_img_path: { + title: '还原图片', + type: 'image-uploader', + column: { + width: 300, + align: 'center', + component: { + buildUrl(val) { + return `${import.meta.env.VITE_RESOURCE_API}${val}`; + }, + }, + }, + }, + + // 资源版本 + resource_version: { + title: '资源版本', + type: 'dict-select', + column: { width: 150 }, + form: { + component: { + placeholder: '资源版本', + }, + }, + search: { + show: true, + component: { + dict: versionDict, + }, + }, + }, + // 模块 + module_id: { + title: '模块', + type: 'dict-select', + dict: dict({ + url: `/api/project/module/list?project_id=${projectId}&all=1`, + value: 'id', + label: 'show_name', + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + return data.modules; + }, + }), + column: { + width: 200, + align: 'center', + }, + form: { + component: { placeholder: '模块' }, + }, + search: { show: true }, + }, + // 数据审核状态(这条数据的原始标注框是否已被人工 review 过;注意:这不是用来手动添加 bug 的入口) + reviewed: { + title: '数据审核状态', + type: 'dict-select', + dict: dict({ + data: [ + { value: 0, label: '未审核' }, + { value: 1, label: '已审核' }, + ], + }), + column: { show: false }, + form: { + component: { placeholder: '数据审核状态' }, + }, + search: { show: true }, + }, + // 机器型号 + 'device.phone_type': { + title: '机器型号', + type: 'text', + column: { width: 300 }, + }, + ...timeCols, + // 创建时间 + time: { + title: '创建时间', + type: 'datetimerange', + column: { show: false }, + form: { show: false }, + search: { + show: true, + // value: [ + // dayjs().subtract(3, isDevMode() ? 'year' : 'month') + // .format('YYYY-MM-DD'), + // dayjs().format('YYYY-MM-DD'), + // ], + component: { + ...dateRangeBind, + clearable: true, + }, + valueResolve({ value, form }) { // <------注意这里是form,不是row + if (value && value.length === 2) { + form.begin_at = dayjs(value[0]).startOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + form.end_at = dayjs(value[1]).endOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + } + }, + // style: { width: '288px' }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/data/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/data/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..39ac1bf61b6a9751ff06a91736f393736c2caba9 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/data/crud.jsx @@ -0,0 +1,192 @@ +import { useCompute } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { useRoute } from 'vue-router'; +import { computed, ref, shallowRef } from 'vue'; +import { ElMessage } from 'element-plus'; +import pako from 'pako'; +import { pick } from 'lodash-es'; +import { downloadByData } from '@/utils/download.ts'; +import { getCommonCols } from '@/views/data/common.jsx'; +import numberRange from '@/components/numberRange.vue'; + +export default function ({ context }) { + const pageReviews = ref([]); + const route = useRoute(); + const { compute } = useCompute(); + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/api/data/list', + method: 'get', + params: { + project_id: route.meta.value, + ...params, + id: route.query.id || params.id || undefined, + job_id: params.job_id || undefined, + }, + }).then((res) => { + pageReviews.value = res.data.list.filter(item => item.reviewed).map(item => pick(item, ['id', 'revert_img_path'])); + return res; + }); + + const selectedIds = ref([]); + const onSelectionChange = (changed) => { + selectedIds.value = changed.map(item => item.id); + }; + + // 此处编辑 crudOptions 配置 + return { + selectedIds, + pageReviews, + crudOptions: { + request: { + pageRequest, + }, + pagination: { + pageSize: 10, // 默认pageSize + }, + actionbar: { + buttons: { + add: { + show: false, + }, + }, + }, + toolbar: { + buttons: { + export: { show: false }, + }, + }, + // search: { + // container: { + // col: { span: 6 }, // 默认列宽度配置 + // }, + // }, + table: { + border: false, + onSelectionChange, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '100px', + }, + rowHandle: { + buttons: { + edit: { show: false }, + remove: { show: false }, + // 数据 + data: { + size: 'small', + title: '', + type: 'warning', + plain: true, + link: true, + icon: 'tabler:cloud-download', + text: '数据', + style: { height: '30px' }, + disabled: compute(({ row }) => !row.file_path), + show: true, + order: 1, + click: ({ row }) => { + customRequest({ + url: row.file_path, + method: 'get', + responseType: row.file_path.endsWith('.gzip') ? 'arraybuffer' : undefined, // 确保接收的是二进制数据 + }).then((res) => { + /* eslint-disable */ + if (row.file_path.endsWith('.gzip')) { + // 解压缩 GZIP 数据 + const compressedData = new Uint8Array(res); + const decompressedData = pako.inflate(compressedData, { to: 'string' }); + + // 解析后会丢失精度 + context.jsonViewDialog.value = JSON.parse(decompressedData); + } else { + // json 数据 + context.jsonViewDialog.value = res; + } + + // 直接下载 + downloadByData(JSON.stringify(context.jsonViewDialog.value, null, 2), `job-${row.job_id} data-${row.id} 数据.json`); + + // context.jsonViewDialog.title = `${row.id} 数据`; + // context.jsonViewDialog.visible = true; + /* eslint-enable */ + }) + .catch((err) => { + if (err.response?.status === 403) { + ElMessage.error('无权限查看,请联系管理员'); + } else { + ElMessage.error('请求失败,请联系管理员'); + } + console.error(`${row.id} 数据调用失败: ${err}`); + }); + }, + }, + // 审核 + audit: { + size: 'small', + title: '', + // type: 'success', + type: 'danger', + plain: true, + link: true, + icon: 'icon-park-outline:audit', + text: '审核', + style: { height: '30px' }, + // tooltip: { content: '结果审核', enterable: false }, + show: true, + disabled: compute(({ row }) => !row.reviewed), + order: 1, + click: ({ row }) => { + context.imgDrawRef.value.open(row.id, row.revert_img_path); + }, + }, + }, + width: 140, + }, + columns: { + // 多选 + $checked: { + // title: '选择', + form: { show: false }, + column: { + type: 'selection', + align: 'center', + width: '60px', + reserveSelection: true, // 跨页选 + columnSetDisabled: true, // 禁止在列设置中选择 + showOverflowTooltip: false, + // selectable(row, index) { + // return row.id !== 1; // 设置第一行不允许选择 + // }, + }, + }, + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 100, align: 'right' }, + form: { + component: { placeholder: 'ID' }, + }, + search: { + show: computed(() => !route.query.id), + value: ['', ''], + component: { + name: shallowRef(numberRange), + }, + valueResolve(e) { + e.form.pk__gte = (e.form[e.key] || [])[0] ? e.form[e.key][0] : undefined; + e.form.pk__lte = (e.form[e.key] || [])[1] ? e.form[e.key][1] : undefined; + e.form[e.key] = undefined; + }, + }, + }, + + ...getCommonCols(route.meta.value, context.versionDict), + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/data/editCrud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/data/editCrud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..b6b576ba6fa28c52e42dacdcf2a67f916ca8ed36 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/data/editCrud.jsx @@ -0,0 +1,82 @@ +import { dict } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service.ts'; +import { ref } from 'vue'; + +export default function (route, selectedIds, clearRefresh) { + const submitDisabled = ref(false); + // 此处编辑 crudOptions 配置 + return { + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + form: { + watch({ form }) { + submitDisabled.value = Object.values(form).every(item => !item); + }, + wrapper: { + title: '批量编辑', + buttons: { + ok: { + disabled: submitDisabled, + }, + }, + }, + doSubmit: async ({ form }) => { + const res = await customRequest({ + url: '/api/data/list', + method: 'patch', + data: { ...form, ids: selectedIds.value }, + }) + .catch((err) => { + ElMessage.error('操作失败'); + console.log(`/data/project/${route.meta.value}/data 接口调用失败: ${err}`); + throw err; + }); + if (res.code === 0) { + ElMessage.success(res.msg); + clearRefresh(); + return true; + } + ElMessage.warning('操作失败'); + return false; + }, + }, + columns: { + // 资源版本 + resource_version: { + title: '资源版本', + type: 'text', + form: { + component: { + placeholder: '资源版本', + }, + }, + }, + // 模块 + module_id: { + title: '模块', + type: 'dict-select', + dict: dict({ + url: `/api/project/module/list?project_id=${route.meta.value}&all=1`, + value: 'id', + label: 'show_name', + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + return data.modules; + }, + }), + column: { align: 'center' }, + form: { + component: { placeholder: '模块' }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/data/imgDraw.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/data/imgDraw.vue new file mode 100644 index 0000000000000000000000000000000000000000..2d799e3abc8d430cab5fe609dae437e3eb8fc69b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/data/imgDraw.vue @@ -0,0 +1,794 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/data/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/data/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..4c0b46f826e0278fd4eac5ddb2f5bdef7f7aa089 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/data/index.vue @@ -0,0 +1,131 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/403.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/403.vue new file mode 100644 index 0000000000000000000000000000000000000000..082aa2ff5ba7062f40e5cfad9773efd2cab82b6e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/403.vue @@ -0,0 +1,35 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/404.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/404.vue new file mode 100644 index 0000000000000000000000000000000000000000..afe4a328c222a64587471a057c021d549cdb9bbd --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/404.vue @@ -0,0 +1,10 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/components/ErrorPageLayout.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/components/ErrorPageLayout.vue new file mode 100644 index 0000000000000000000000000000000000000000..315e570ccd3afea6d2bb742ce2bb3d073b4c4d6e --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/error-page/components/ErrorPageLayout.vue @@ -0,0 +1,24 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/login/components/Owl.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/login/components/Owl.vue new file mode 100644 index 0000000000000000000000000000000000000000..2a1f84216a0a42d02194a2b3fd749f4ab6d625bc --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/login/components/Owl.vue @@ -0,0 +1,92 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/login/hooks/useFocus.ts b/timi_hok_game_translator/LQA_WMP/web/src/views/login/hooks/useFocus.ts new file mode 100644 index 0000000000000000000000000000000000000000..32d102e93e548f84b3715bc161d478ddf36c5664 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/login/hooks/useFocus.ts @@ -0,0 +1,17 @@ +import { ref } from 'vue'; + +export function useFocus() { + /** 是否有焦点 */ + const isFocus = ref < boolean >(false); + + /** 失去焦点 */ + const handleBlur = () => { + isFocus.value = false; + }; + /** 获取焦点 */ + const handleFocus = () => { + isFocus.value = true; + }; + + return { isFocus, handleBlur, handleFocus }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/login/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/login/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..cf77c0d450743c07919f75e2480149f2dc2170cf --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/login/index.vue @@ -0,0 +1,181 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/login/register.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/login/register.vue new file mode 100644 index 0000000000000000000000000000000000000000..da6ca90438b49ba10152d15b5e5dcf77272f6eea --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/login/register.vue @@ -0,0 +1,183 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/login/rules.ts b/timi_hok_game_translator/LQA_WMP/web/src/views/login/rules.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d3dabbf43d7373404543897de995112a7c036eb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/login/rules.ts @@ -0,0 +1,19 @@ +import type { FormItemRule } from 'element-plus'; + +/** 与后端 apps/user/schemas.py 保持一致 */ +export const USERNAME_RULE: FormItemRule = { + pattern: /^[A-Za-z][A-Za-z0-9_.-]{2,31}$/, + message: '以字母开头,3~32位,只能包含字母、数字、下划线、点、中划线', + trigger: 'blur', +}; + +export const passwordRules = (required = true): FormItemRule[] => [ + { required, message: '请输入密码', trigger: 'blur' }, + { min: 8, max: 64, message: '密码长度需为 8~64 位', trigger: 'blur' }, + { + validator: (_r, value, cb) => (!value || (/[A-Za-z]/.test(value) && /\d/.test(value)) + ? cb() + : cb(new Error('密码需同时包含字母和数字'))), + trigger: 'blur', + }, +]; diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/redirect/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/redirect/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..432b678400b9a0399d1d07fd65f5210dff3263ac --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/redirect/index.vue @@ -0,0 +1,12 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/bugType.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/bugType.vue new file mode 100644 index 0000000000000000000000000000000000000000..f56e6e312097086685eaa6cd977b8cc633a7d0ac --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/bugType.vue @@ -0,0 +1,110 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..0e672546e4005b665adaeae1af4bb8e860ec6218 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/crud.jsx @@ -0,0 +1,245 @@ +import { customRequest } from '@/utils/service'; +import { useRoute } from 'vue-router'; +import { isValidPath } from '@/utils/validate'; +import langPathTable from './langPathTable.vue'; +import { shallowRef } from 'vue'; + +export default function ({ crudExpose, context }) { + const route = useRoute(); + + const addRequest = async ({ form }) => { + await customRequest({ + url: '/api/project/config?cate=ImgRevert', + method: 'post', + data: { + ...form, + lang_path: JSON.stringify(form.lang_path), + project_id: context.project_id, + }, + }).finally(() => { + crudExpose.doRefresh(); + }); + }; + const editRequest = async ({ form }) => { + await customRequest({ + url: '/api/project/config?cate=ImgRevert', + method: 'patch', + data: { + ...form, + lang_path: JSON.stringify(form.lang_path), + }, + }).finally(() => { + crudExpose.doRefresh(); + }); + }; + const delRequest = async ({ row }) => { + await customRequest({ + url: '/api/project/config?cate=ImgRevert', + method: 'delete', + data: { + ids: [row.id], + project_id: context.project_id, + }, + }).finally(() => { + crudExpose.doRefresh(); + }); + }; + + /** 文件根路径校验 */ + const validateRootPath = (rule, value, callback) => { + if (!value) { + callback(new Error('请填写文件根路径')); + return; + } + if (!isValidPath(value)) { + callback(new Error('路径格式不合法')); + return; + } + callback(); + }; + + /** 自定义校验 */ + const validateLangPath = (rule, value, callback) => { + for (let i = 0; i < value.length; i++) { + const allHasValue = Object.values(value[i]).every(item => !!item); + if (!allHasValue) { + callback(new Error('请填写必填字段')); + return; + } + // 校验每行的 配置路径(filePath) 格式 + if (!isValidPath(value[i].filePath)) { + callback(new Error(' ')); + return; + } + } + callback(); + }; + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + addRequest, + editRequest, + delRequest, + }, + // mode: { + // name: 'local', + // isMergeWhenUpdate: true, + // isAppendWhenAdd: true, + // }, + pagination: { + show: false, + }, + editable: { + enabled: false, + mode: 'row', + activeTrigger: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + group: { + groupType: 'collapse', // collapse, tabs + accordion: false, + groups: { + img: { + title: '图片还原', + columns: ['root_path', 'key', 'text', 'no_trans_text'], + }, + info: { + title: '翻译配置', + columns: ['lang_path'], + }, + // custom: { + // title: "自定义", + // collapsed: false, + // show(context) { + // console.log("custom context", context); + // return context.mode === "view"; + // }, + // disabled: false, + // icon: "el-icon-warning-outline", + // columns: ["custom", "custom2"] + // } + }, + }, + }, + search: { + show: false, + }, + columns: { + $expand: { + title: '', + form: { show: false }, + column: { + type: 'expand', + align: 'center', + width: '55px', + columnSetDisabled: true, // 禁止在列设置中选择 + exportable: false, // 不能导出 + }, + }, + // ID + // id: { + // title: 'ID', + // type: 'number', + // column: { width: 64, align: 'center' }, + // form: { show: false }, + // }, + // 根路径 + root_path: { + title: '文件根路径', + type: 'text', + form: { + component: { placeholder: '请填写文件根路径' }, + rules: [ + { required: true, message: '请填写文件根路径' }, + { validator: validateRootPath, trigger: 'blur' }, + ], + }, + }, + // key 列 + key: { + title: 'key 列', + type: 'text', + form: { + component: { placeholder: '请填写 key 列' }, + rules: [{ required: true, message: '请填写 key 列' }], + }, + }, + // 描述列 + text: { + title: '描述列', + type: 'text', + form: { + component: { placeholder: '请填写描述列' }, + rules: [{ required: true, message: '请填写描述列' }], + }, + }, + // 排除标识 + no_trans_text: { + title: '排除标识', + type: 'text', + form: { + component: { placeholder: '排除标识' }, + }, + }, + lang_path: { + title: '', + column: { show: false }, + form: { + col: { span: 24 }, + // labelWidth: '0px', + component: { + name: shallowRef(langPathTable), + projectId: route.meta.value, + vModel: 'modelValue', + addTemplate: { code_raw: '', code: '', filePath: '' }, + dragSort: true, + // slots: { + // default: () => ( + // [ + // // 语言 + // + // {scope => scope.row.code_raw = val} + // placeholder="请选择语言" + // > + // eslint-disable-next-line + // {langCodeOptions.value.map(item => )} + // + // } + // , + // // 列名 + // + // {scope => scope.row.code = val} + // placeholder="请输入列名" + // /> + // } + // , + // // 配置路径 + // + // {scope => scope.row.filePath = val} + // placeholder="请输入配置路径" + // /> + // } + // , + // ] + // ), + // }, + }, + rules: [ + { type: 'array', min: 1, required: true, message: '请添加翻译配置' }, + { validator: validateLangPath, trigger: 'blur' }, + ], + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..7d0ed0feaf677da763e33a977ff0632f6831f5a3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/index.vue @@ -0,0 +1,94 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/langPathTable.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/langPathTable.vue new file mode 100644 index 0000000000000000000000000000000000000000..15767e8c9bfaa1297698c0514e60c18565302949 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/img/langPathTable.vue @@ -0,0 +1,91 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..16cb101afec35347dac0041634c7d3b197a31eee --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/index.vue @@ -0,0 +1,79 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/language.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/language.vue new file mode 100644 index 0000000000000000000000000000000000000000..0fc71f6bce813176da3940d27daffa9e7735eec0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/language.vue @@ -0,0 +1,68 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..ecd4fcddd582cdf18d767230230742d7f264e149 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/crud.jsx @@ -0,0 +1,96 @@ +import { customRequest } from '@/utils/service'; +import { useRoute } from 'vue-router'; + +export default function () { + const route = useRoute(); + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/api/project/module/list', + method: 'get', + params: { project_id: route.meta.value, ...params }, + }); + // @ts-ignore + const addRequest = async ({ form }) => await customRequest({ + url: '/api/project/module', + method: 'post', + data: { project_id: route.meta.value, ...form }, + }); + // @ts-ignore + const editRequest = async ({ form, row }) => await customRequest({ + url: '/api/project/module', + method: 'patch', + data: { ...form, id: row.id, project_id: route.meta.value }, + }); + const delRequest = async ({ row }) => await customRequest({ + url: '/api/project/module', + method: 'delete', + data: { project_id: route.meta.value, module_id: row.id }, + }); + + function buildShowName(form) { + if (form.name && form.sub_module) { + form.show_name = `${form.name}-${form.sub_module}`; + } else if (form.name) { + form.show_name = form.name; + } + } + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + addRequest, + editRequest, + delRequest, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + columns: { + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 60, align: 'right', showOverflowTooltip: false }, + form: { show: false }, + }, + // 名称 + name: { + title: '名称', + type: 'text', + form: { + component: { placeholder: '请填写名称' }, + valueChange({ form }) { + buildShowName(form); + }, + rules: [{ required: true, message: '请填写名称' }], + }, + }, + // 子模块 + sub_module: { + title: '子模块', + type: 'text', + form: { + component: { placeholder: '子模块' }, + valueChange({ form }) { + buildShowName(form); + }, + }, + }, + // 显示名称 + show_name: { + title: '显示名称', + type: 'text', + form: { + component: { placeholder: '显示名称' }, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..9f85cb448a8b3252de47449ca80c64bb5d9c34b8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/module/index.vue @@ -0,0 +1,30 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/other/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/other/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..e224627b3ced99bd16e924a427378ebbf93e1c1a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/other/index.vue @@ -0,0 +1,166 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..b2efae781e9b9c9f550e244e5d79351e9bec84d0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/crud.jsx @@ -0,0 +1,232 @@ +import { customRequest } from '@/utils/service'; +import { useRoute } from 'vue-router'; +import { dict } from '@fast-crud/fast-crud'; +import { getBugTypeDict, getLanguageDict } from '@/utils/dict.js'; +import { computed } from 'vue'; + +export default function ({ context }) { + const route = useRoute(); + + const baseForm = { + bug_type: 0, // 缺陷类型 + language: 0, // 区域语言 + module: 0, // 模块 + }; + const keys = Object.keys(baseForm); + const addRequest = ({ form }) => { + customRequest({ + url: '/api/project/config?cate=BugBillUser', + method: 'post', + data: { + ...baseForm, + ...form, + project_id: context.project_id, + }, + }).finally(() => { + context.refresh(); + }); + }; + const editRequest = ({ form }) => { + // 构造要发往后端的 payload:空值补 0(后端存储的是数值) + // 注意:不要直接修改入参 form,因为它是 fast-crud 行数据的引用, + // 修改会触发列重新渲染,让字典里不存在的 value=0 短暂显示为"0",造成闪烁 + const payload = { ...form, project_id: context.project_id }; + keys.forEach((key) => { + if (!payload[key]) { + payload[key] = 0; + } + }); + customRequest({ + url: '/api/project/config?cate=BugBillUser', + method: 'patch', + data: payload, + }).finally(() => { + context.refresh(); + }); + }; + const delRequest = ({ row }) => { + customRequest({ + url: '/api/project/config?cate=BugBillUser', + method: 'delete', + data: { + ids: [row.id], + project_id: context.project_id, + }, + }).finally(() => { + context.refresh(); + }); + }; + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + addRequest, + editRequest, + delRequest, + }, + // mode: { + // name: 'local', + // isMergeWhenUpdate: true, + // isAppendWhenAdd: true, + // }, + pagination: { + show: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + editable: { + enabled: false, + mode: 'row', + activeTrigger: false, + }, + search: { + show: false, + }, + columns: { + // ID + // id: { + // title: 'ID', + // type: 'number', + // column: { width: 64, align: 'center' }, + // form: { show: false }, + // }, + // "/setting/BugClass/project/" + "{{projectId}}" + "/get_BugClass" + + // 缺陷类型 + bug_type: { + title: '缺陷类型', + type: 'dict-select', + dict: getBugTypeDict(route.meta.value), + column: { show: computed(() => !!context.props.form.bug_type_enable) }, + form: { + show: computed(() => !!context.props.form.bug_type_enable), + component: { placeholder: '请选择缺陷类型' }, + rules: [{ required: true, message: '请选择缺陷类型' }], + order: 1, + }, + }, + // 区域语言 + language: { + title: '区域语言', + type: 'dict-select', + dict: getLanguageDict(route.meta.value), + column: { + // show: !!context.props.form.language_enable + show: computed(() => !!context.props.form.language_enable), + }, + form: { + show: computed(() => !!context.props.form.language_enable), + component: { + dict: getLanguageDict(route.meta.value, true), + placeholder: '请选择区域语言', + }, + rules: [{ required: true, message: '请选择区域语言' }], + order: 2, + }, + }, + // 模块 + module: { + title: '模块', + type: 'dict-select', + dict: dict({ + url: `/api/project/module/list?project_id=${route.meta.value}&all=1`, + value: 'id', + label: 'show_name', + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + return data.modules; + }, + }), + column: { + show: computed(() => !!context.props.form.module_enable), + }, + form: { + show: computed(() => !!context.props.form.module_enable), + component: { placeholder: '请选择模块' }, + rules: [{ required: true, message: '请选择模块' }], + order: 3, + }, + }, + // 处理人 + user_names: { + title: '处理人', + type: 'dict-select', + dict: dict({ + url: '/api/user/list', + value: 'name', + label: 'format_name', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get', params: { + info_type: 0, // 简略信息 + page_size: 1000000000000000, + } }); + data.list.forEach((item) => { + let formatName = item.name; + if (item.name_zh) { + formatName = `${item.name}(${item.name_zh})`; + } + // eslint-disable-next-line no-param-reassign + item.format_name = formatName; + }); + return data.list; + }, + }), + form: { + col: { span: 24 }, + component: { + multiple: true, + allowCreate: true, + defaultFirstOption: true, + reserveKeyword: false, + placeholder: '请选择/填写处理人', + }, + rules: [{ required: true, message: '请选择/填写处理人' }], + order: 5, + }, + addForm: { value: [] }, + }, + // 生效 + enable: { + title: '生效', + type: 'dict-switch', + dict: dict({ + data: [ + { value: 1, label: '是', color: 'success' }, + { value: 0, label: '否', color: 'error' }, + ], + }), + column: { + component: { + name: 'fs-dict-switch', + vModel: 'modelValue', + on: { + change: editRequest, + }, + // on: { + // onChange: async (e) => { + // await customRequest({ + // url: `/setting/project/${route.meta.value}/bill_info/${e.row.id}`, + // method: 'patch', + // data: e.form, + // }); + // expose.doRefresh(); + // }, + // }, + }, + }, + form: { + order: 4, + }, + addForm: { + value: 1, // addForm默认值 是 + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..0d7a03fed927d7369755601abe203f4536d19f4a --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/index.vue @@ -0,0 +1,325 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/table.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/table.vue new file mode 100644 index 0000000000000000000000000000000000000000..20b72e52390309851fb67907934c593d43473318 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/submitBug/table.vue @@ -0,0 +1,47 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/settings/tracker/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/tracker/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..4924c4eb8596afec99d734d636ee7273fe9cddb4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/settings/tracker/index.vue @@ -0,0 +1,186 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/crud.ts b/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/crud.ts new file mode 100644 index 0000000000000000000000000000000000000000..713f550b57e675e657666d717513f35145a7b0c7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/crud.ts @@ -0,0 +1,228 @@ +import { dict, useCompute } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service'; +import { useRoute } from 'vue-router'; +import { timeCols } from '@/fast-crud/common'; + +export default function () { + const route = useRoute(); + const { compute } = useCompute(); + // @ts-ignore + const pageRequest = async params => { + // 游戏类型为多选,默认会以数组形式提交(axios 会序列化为 game_type[]=1&game_type[]=2), + // 后端可能无法正确解析数组参数;此处统一拼成逗号串(game_type=1,2)发给后端。 + const finalParams: any = { project_id: route.meta.value, ...params }; + if (Array.isArray(finalParams.game_type)) { + finalParams.game_type = finalParams.game_type.length ? finalParams.game_type.join(',') : undefined; + } + return await customRequest({ + url: '/api/project/list', + method: 'get', + params: finalParams, + }); + }; + // @ts-ignore + const addRequest = async ({ form }) => await customRequest({ + url: '/api/project/entity', + method: 'post', + data: form, + }); + // @ts-ignore + const editRequest = async ({ form, row }) => await customRequest({ + url: '/api/project/entity', + method: 'patch', + data: { ...form, project_id: row.id }, + }); + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + addRequest, + editRequest, + }, + rowHandle: { + buttons: { + // 查看 + view: { show: true }, + // 删除 + remove: { show: false }, + }, + align: 'center', + width: 110, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + display: 'grid', + labelWidth: '80px', + }, + columns: { + // ID + // id: { + // title: 'ID', + // type: 'number', + // column: { width: 64, align: 'center' }, + // form: { show: false }, + // }, + + // 所属团队 + team: { + title: '所属团队', + type: 'text', + search: { + show: true, + component: { placeholder: '模糊搜索' }, + }, + form: { + order: 1, + component: { placeholder: '所属团队/工作室(选填)' }, + }, + }, + + // 名称 + name: { + title: '名称', + type: 'text', + search: { + show: true, + component: { placeholder: '模糊搜索' }, + }, + form: { + order: 1, + component: { placeholder: '名称' }, + rules: [{ required: true, message: '请填写名称' }], + }, + }, + // 项目代号 + code: { + title: '项目代号', + type: 'text', + form: { + component: { placeholder: '英文代号,如 game_a' }, + rules: [ + { required: true, message: '请填写项目代号' }, + { pattern: /^[A-Za-z0-9_-]{2,100}$/, message: '只能包含字母、数字、下划线、中划线' }, + ], + helper: '创建后不可修改;提单模板目录 templates/spec2/<代号小写> 存在时使用自定义模板', + }, + editForm: { + show: false, // 编辑时隐藏 + component: { disabled: true }, + }, + }, + + // AI 识别项目名 + cvtest_project: { + title: 'AI识别项目名', + type: 'text', + column: { show: false }, + form: { + component: { placeholder: 'AI 识别服务中的项目标识' }, + rules: [{ required: true, message: '请填写 AI 识别项目名' }], + helper: '调用 AI 识别服务时以 "<项目名>_lqa" 作为 project-method,未填写时无法创建任务', + }, + }, + + // 项目图片 + // project_img: { + // title: '项目图片', + // type: 'cropper-uploader', + // form: { + // order: 0, + // col: { + // style: { gridRow: 'span 3' }, + // }, + // component: { + // limit: 1, + // }, + // helper: '图片比例 1:1,推荐尺寸为 60*60', + // }, + // }, + + // 项目类型 + project_type: { + title: '项目类型', + type: 'dict-select', + search: { show: true }, + dict: dict({ + data: [ + { value: 1, label: '平台级', effect: 'light' }, + { value: 2, label: '项目级', effect: 'light' }, + ], + }), + addForm: { value: 2 }, + form: { + component: { placeholder: '项目类型' }, + rules: [{ required: true, message: '请选择项目类型' }], + }, + }, + + // 游戏类型(可多选) + game_type: { + title: '游戏类型', + type: 'dict-select', + search: { + show: true, + component: { multiple: true, placeholder: '游戏类型(可多选)' }, + }, + dict: dict({ + data: [ + { value: 1, label: '手游', color: '', effect: 'light' }, // primary + { value: 2, label: '端游', color: 'danger', effect: 'light' }, + { value: 3, label: '页游', color: 'success', effect: 'plain' }, + { value: 4, label: 'app', color: 'danger', effect: 'plain' }, + { value: 5, label: '小游戏', color: 'warning', effect: 'light' }, + ], + }), + column: { align: 'center', minWidth: 140 }, + form: { + component: { multiple: true, placeholder: '游戏类型(可多选)' }, + rules: [{ required: true, message: '请选择游戏类型' }], + }, + }, + + // 研发阶段 + project_phase: { + title: '研发阶段', + type: 'dict-select', + search: { + show: true, + }, + dict: dict({ + data: [ + { value: 1, label: '上线运营', color: 'success', effect: 'light' }, + { value: 2, label: '下线', color: 'info', effect: 'light' }, + { value: 3, label: '研发期', color: 'warning', effect: 'light' }, + { value: 4, label: '保密', color: 'danger', effect: 'light' }, + ], + }), + form: { + component: { placeholder: '研发阶段' }, + rules: [{ required: true, message: '请选择研发阶段' }], + }, + }, + + // 测试经理 + test_manager: { + title: '测试经理', + type: 'text', + column: { + showOverflowTooltip: true, + }, + form: { + component: { placeholder: '测试经理' }, + rules: [{ required: true, message: '请填写项目测试经理' }], + }, + addForm: { + helper: '填写平台用户名,新增项目会为测试经理添加项目管理员角色,多名请用 ; 分割', + }, + }, + + ...timeCols, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..bd4d1845103fba73c450ef847c681c3c6cd9fdd5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/project/index.vue @@ -0,0 +1,36 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/crud.js b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/crud.js new file mode 100644 index 0000000000000000000000000000000000000000..cfd529f4dd92dfae04fd86560c8a22a1a45909bb --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/crud.js @@ -0,0 +1,127 @@ +import { customRequest } from '@/utils/service'; +import { useRoute } from 'vue-router'; + +export default function () { + const route = useRoute(); + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/system/setting/announcement', + method: 'get', + params: { project_id: route.meta.value, ...params }, + }).then(res => ({ ...res, page: 1, size: res.data.length, total: res.data.length })); + // @ts-ignore + const addRequest = async ({ form }) => await customRequest({ + url: `/system/setting/announcement?project_id=${route.meta.value}`, + method: 'post', + data: form, + }); + // @ts-ignore + const editRequest = async ({ form, row }) => await customRequest({ + url: `/system/setting/${row.id}/announcement?project_id=${route.meta.value}`, + method: 'patch', + data: form, + }); + // @ts-ignore + const delRequest = async ({ row }) => await customRequest({ + url: `/system/setting/${row.id}/announcement?project_id=${route.meta.value}`, + method: 'delete', + }); + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + addRequest, + editRequest, + delRequest, + }, + search: { show: false }, + pagination: { + show: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + display: 'grid', + labelWidth: '80px', + col: { span: 24 }, + }, + columns: { + // ID + // id: { + // title: 'ID', + // type: 'number', + // column: { width: 64, align: 'center', sorter: true }, + // form: { show: false }, + // }, + + // 内容 + info: { + title: '内容', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { minWidth: 300 }, + form: { + order: 1, + col: { span: 24 }, + component: { placeholder: '内容' }, + rules: [{ required: true, message: '请填写内容' }], + }, + }, + + // 创建人 + creator: { + title: '创建人', + type: 'text', + column: { width: 100 }, + form: { show: false }, + }, + + // 生效时间 + times: { + title: '生效时间', + type: 'datetimerange', + column: { + minWidth: 300, + align: 'center', + formatter({ value }) { + if (value && value.length === 2) { + return `${value[0]} ~ ${value[1]}`; + } + return ''; + }, + }, + valueBuilder({ row }) { + // value构建,就是把后台传过来的值转化为前端组件所需要的值 + // 在pageRequest之后执行转化,然后将转化后的数据放到table里面显示 + if (row.start_time && row.end_time) { + row.times = [row.start_time.replace('T', ' '), row.end_time.replace('T', ' ')]; + } + }, + valueResolve(context) { + // value解析,就是把组件的值转化为后台所需要的值 + // 在form表单点击保存按钮后,提交到后台之前执行转化 + if (context.form.times) { + const [startTime, endTime] = context.form.times; + context.form.start_time = startTime; + context.form.end_time = endTime; + context.form.times = []; + } + }, + form: { + component: { + format: 'YYYY-MM-DD HH:mm:ss', + valueFormat: 'YYYY-MM-DD HH:mm:ss', + }, + // component: dateRangeBind, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..4672de710c3a630bc698d457292e43af07123aea --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/announcement/index.vue @@ -0,0 +1,35 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..c8724d2acb51f0afa1430e556335b61e328d2db8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/crud.jsx @@ -0,0 +1,131 @@ +import { customRequest } from '@/utils/service'; + +export default function () { + // @ts-ignore + const pageRequest = async () => await customRequest({ + url: '/api/system/enums/bug_type', + method: 'get', + }); + // const edit = data => { + // customRequest({ + // url: '/api/project/config?cate=BugType', + // method: 'patch', + // data: data + // }).finally(() => { + // crudExpose.doRefresh(); + // }) + // } + // const isJson = str => { + // if(!str) return true + // try { + // const arr = JSON.parse(str) + // return Array.isArray(arr) + // } catch (e) { + // return false + // } + // } + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + }, + search: { show: false }, + pagination: { + show: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + labelWidth: '80px', + }, + actionbar: { + show: false, + }, + rowHandle: { + show: false, + }, + columns: { + // ID + value: { + title: 'ID', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { + align: 'right', + width: 50, + }, + }, + // 名称 + label: { + title: '名称', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { minWidth: 300 }, + form: { + order: 1, + col: { span: 24 }, + component: { placeholder: '名称' }, + rules: [{ required: true, message: '请填写名称' }], + }, + }, + // 编码 + name: { + title: '编码', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { minWidth: 300 }, + form: { + order: 1, + col: { span: 24 }, + component: { placeholder: '编码' }, + rules: [{ required: true, message: '请填写编码' }], + }, + }, + // trans_marks + // trans_marks: { + // title: '匹配标识', + // addForm: { + // col: { span: 24 }, + // }, + // column: { + // minWidth: 300, + // component: { + // show: compute(({ row }) => [1, 5].includes(row.value)), + // name: 'el-input', + // props: { + // type: 'input', + // class: { + // 'isError': compute(({ row }) => !isJson(row.trans_marks)) + // } + // }, + // vModle: "trans_marks", + // on: { + // onBlur: ({ form, row }) => { + // const { trans_marks } = row + // const flag = isJson(trans_marks); + // if(flag) { + // edit(row) + // ElMessage.success('更新成功'); + // } else { + // ElMessage.error('匹配标识格式有误,请重新输入!'); + // } + // } + // } + // } + // } + // } + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..702f02a7457f6b164b2f39a5d7a6e3b3c2ce98a5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/bug/index.vue @@ -0,0 +1,40 @@ + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..530cca985c0203ce265323cfaaae0fc443f4925c --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/index.vue @@ -0,0 +1,52 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/crud.js b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/crud.js new file mode 100644 index 0000000000000000000000000000000000000000..7d8e5dcd68f24b003aeb91aba5c2604dbbc93556 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/crud.js @@ -0,0 +1,82 @@ +import { customRequest } from '@/utils/service'; +import { SUPER_ADMIN_PROJECT_ID } from '@/constants/app-key.ts'; + +export default function () { + // @ts-ignore + const pageRequest = async () => await customRequest({ + url: '/api/system/enums/language', + method: 'get', + params: { project_id: SUPER_ADMIN_PROJECT_ID }, + }); + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + }, + search: { show: false }, + pagination: { + show: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + labelWidth: '80px', + }, + actionbar: { + show: false, + }, + rowHandle: { + show: false, + }, + columns: { + // ID + value: { + title: 'ID', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { + align: 'right', + width: 50, + }, + }, + // 名称 + label: { + title: '名称', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { minWidth: 300 }, + form: { + order: 1, + col: { span: 24 }, + component: { placeholder: '名称' }, + rules: [{ required: true, message: '请填写名称' }], + }, + }, + // 编码 + name: { + title: '编码', + type: 'text', + addForm: { + col: { span: 24 }, + }, + column: { minWidth: 300 }, + form: { + order: 1, + col: { span: 24 }, + component: { placeholder: '编码' }, + rules: [{ required: true, message: '请填写编码' }], + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..f36e4138106a6b58ed079257558484998a37d14d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/settings/language/index.vue @@ -0,0 +1,32 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..f94cc45caacab57e719d730dd2af71b1ac58e214 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/crud.jsx @@ -0,0 +1,362 @@ +import { ref } from 'vue'; +import { dict } from '@fast-crud/fast-crud'; +// import api from '@/api'; +import { useRoute } from 'vue-router'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service'; +import { checkPermission } from '@/utils/permission'; +import { SUPER_ADMIN_PROJECT_ID } from '@/constants/app-key.ts'; +import { timeCols } from '@/fast-crud/common.ts'; + +// eslint-disable-next-line no-unused-vars +export default function ({ crudExpose } = {}) { + const route = useRoute(); + const projectID = ref(route.meta.value); + + // const userAdminMap = {}; + const pageRequest = async params => await customRequest({ + url: '/api/user/list', + method: 'get', + params: { info_type: 2, ...params }, + }); + const addRequest = async ({ form }) => await customRequest({ + url: '/api/user/entity', + method: 'post', + data: { ...form, project_id: projectID.value }, + }); + const editRequest = async ({ form }) => + // const userIsAdmin = userAdminMap[form.id] || false; + // form.roles = form.roles || []; + // if (userIsAdmin) { + // if (!form.roles.includes('3')) { + // form.roles.push('3'); + // } + // } + await customRequest({ + url: '/api/user/entity', + method: 'patch', + data: { ...form, id: form.id, roles: form.roles, project_id: projectID.value }, + }) + ; + const delRequest = async ({ row }) => await customRequest({ + url: '/api/user/entity', + method: 'delete', + data: { id: row.id }, + }); + + const rolesDict = dict({ + isTree: true, + cache: true, + prototype: true, + label: 'cell_roles', + url: '/api/project/roles?project_id=0', + }); + + return { + projectID, + rolesDict, + crudOptions: { + request: { + pageRequest, + addRequest, + editRequest, + delRequest, + }, + // 右上「导出」按钮:默认实现直接把 roles 数组用 '|' join,导致导出结果是 1_2|1_3 这种原始编码; + // 这里覆盖 click 走自定义 CSV 导出:请求角色字典做翻译,输出 "演示项目/项目管理员|演示项目/测试人员" 的人类可读文本。 + toolbar: { + buttons: { + export: { + click: async () => { + try { + // 1) 取字典:project_id_role_id -> 'xx项目/xx角色' + const { data: rolesData } = await customRequest({ + url: '/api/project/roles?project_id=0', + method: 'get', + }); + const rolesMap = {}; + (rolesData?.list || []).forEach((proj) => { + (proj.children || []).forEach((role) => { + rolesMap[role.value] = role.cell_roles; + }); + }); + + // 2) 取当前表格的数据(已经按用户筛选过的列表) + const rows = crudExpose?.getTableData?.() || []; + if (rows.length === 0) { + ElMessage.warning('没有可导出的数据'); + return; + } + + // 3) 组装 CSV(UTF-8 BOM + 用 Excel 友好的 \r\n 换行,字段按需转义) + const headers = ['英文名', '中文名', '所属部门', '角色', '创建时间', '更新时间']; + const esc = (val) => { + const s = val === null || val === undefined ? '' : String(val); + return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; + }; + const lines = [headers.join(',')]; + rows.forEach((row) => { + const rolesText = (row.roles || []) + .map(code => rolesMap[code] || code) + .join('|'); + lines.push([ + esc(row.name), + esc(row.name_zh), + esc(row.department), + esc(rolesText), + esc(row.created_at), + esc(row.updated_at), + ].join(',')); + }); + const csv = '\uFEFF' + lines.join('\r\n'); + + // 4) 触发浏览器下载 + const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = `用户列表_${new Date().toISOString().slice(0, 19).replace(/[-:T]/g, '')}.csv`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + } catch (err) { + ElMessage.error('导出失败'); + throw err; + } + }, + }, + }, + }, + rowHandle: { + buttons: { + // 刷新 + // refresh: { + // size: 'small', + // title: '', + // icon: 'Refresh', + // text: null, + // style: { height: '30px' }, + // tooltip: { content: '刷新', enterable: false }, + // click: async ({ row }) => { + // await customRequest({ + // url: `/users/${row.id}?project_id=${projectID.value}`, + // method: 'patch', + // }); + // ElMessage.success(`更新 ${row.user_name} 信息成功`); + // }, + // // show: proxy.$hasPermissions('user:del'), + // order: 1, + // }, + + edit: { + disabled: !checkPermission([`${projectID.value}:admin`]), + }, + + // 删除 + remove: { + disabled: projectID.value !== 0, + }, + }, + align: 'center', + width: 150, + }, + table: { + border: false, + }, + columns: { + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 64, align: 'center', sorter: true, show: false }, + form: { order: 0, show: false }, + }, + // 英文名 + name: { + title: '英文名', + type: 'text', + column: { width: 150 }, + search: { + show: true, + component: { + name: 'fs-dict-select', + filterable: true, + clearable: true, + placeholder: '英文名', + dict: dict({ + url: '/api/user/list', + value: 'name', + label: 'name', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get', params: { + info_type: 0, // 简略信息 + page_size: 1000000000000000, + } }); + return data.list; + }, + }), + }, + }, + form: { + component: { + style: { width: '100%' }, + placeholder: '请填写英文名', + }, + rules: [{ required: true, message: '请填写英文名' }], + }, + addForm: { col: { span: 24 } }, + editForm: { component: { disabled: true } }, + }, + // 中文名 + name_zh: { + title: '中文名', + type: 'text', + column: { width: 120 }, + search: { + show: true, + component: { + name: 'fs-dict-select', + filterable: true, + clearable: true, + placeholder: '中文名', + dict: dict({ + url: '/api/user/list', + value: 'name_zh', + label: 'name_zh', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get', params: { + info_type: 0, // 简略信息 + page_size: 1000000000000000, + } }); + return data.list; + }, + }), + }, + }, + addForm: { show: false }, + editForm: { component: { disabled: true } }, + }, + // 所属项目 + project_id: { + title: '所属项目', + type: 'text', + column: { show: false }, + form: { show: false }, + search: { + // 仅在"系统管理 → 用户管理"(超管全局视角)下显示;具体项目视角下该下拉只有一个选项,无筛选意义,隐藏 + show: projectID.value === SUPER_ADMIN_PROJECT_ID, + component: { + name: 'fs-dict-select', + filterable: true, + clearable: true, + placeholder: '所属项目', + dict: dict({ + url: '/api/project/list', + value: 'id', + label: 'name', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get', params: { + page_size: 1000000000000000, + } }); + return data.list; + }, + }), + }, + }, + }, + // 所属部门 + department: { + title: '所属部门', + type: 'text', + column: { width: 550 }, + search: { + show: true, + component: { + placeholder: '模糊搜索', + }, + }, + form: { + col: { span: 24 }, + component: { + placeholder: '请填写所属部门', + }, + }, + addForm: { show: false }, + editForm: { component: { disabled: true } }, + }, + // // 是否管理员 + // isAdmin: { + // title: '系统管理员', + // column: { + // width: 100, + // align: 'center', + // cellRender({ row }) { + // const isAdmin = row.roles.includes('3'); + // return {isAdmin ? '是' : '否'}; + // }, + // }, + // form: { show: false }, + // }, + is_admin: { + title: '管理员', + type: 'dict-select', + column: { show: false }, + form: { show: false }, + dict: dict({ + data: [ + { value: 1, label: '是' }, + { value: 0, label: '否' }, + ], + }), + search: { + show: true, + component: { + placeholder: '是否管理员', + clearable: true, + }, + }, + }, + // 角色 + roles: { + title: '角色', + type: 'dict-cascader', + search: { + show: false, + }, + column: { + minWidth: 300, + component: { + dict: rolesDict, + }, + }, + form: { + col: { span: 24 }, + component: { + dict: dict({ + isTree: true, + label: 'cell_roles', + prototype: true, + url: '/api/project/roles?project_id=0', + async getData({ url }) { + const { data } = await customRequest({ url, method: 'get' }); + if (projectID.value !== SUPER_ADMIN_PROJECT_ID) { + return data.list.filter(item => item.project_id === projectID.value); + } + return data.list; + }, + }), + style: 'width: 100%', + filterable: true, + placeholder: '角色', + // popperClass 作为 JS 事件代理(点击 label 文字也能勾选)的作用域锚点,见 index.vue + popperClass: 'user-roles-cascader-popper', + props: { props: { multiple: true, emitPath: false } }, + }, + }, + }, + ...timeCols, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..da7d22d56f95648936c6708bfdc358797232ac92 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/system/user/index.vue @@ -0,0 +1,126 @@ + + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/common.js b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/common.js new file mode 100644 index 0000000000000000000000000000000000000000..b1e4975b632266c495797e112110f0fce88f9073 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/common.js @@ -0,0 +1,39 @@ +import { customRequest } from '@/utils/service.ts'; +import { ElMessage } from 'element-plus'; + +export async function getBasicInfo(projectId, imageId, form) { + await customRequest({ + url: '/api/bug/build_info', + method: 'get', + params: { + project_id: projectId, + image_id: imageId, + bug_types: (form.bug_types || []).join(','), + }, + }) + .then((res) => { + if (res.code === 0) { + /* eslint-disable */ + form.title = res.data.title; + form.description = res.data.description; + form.current_owner = res.data.current_owner; + form.Key_in_bug = res.data.keyInBugDict || ''; + // 标题前缀 + if (res.data.title_pre) { + form.fix_title = res.data.title_pre; + } + // 发现版本 + if (res.data.version_report) { + form.version_report_value = res.data.version_report; + } + /* eslint-enable */ + } else { + ElMessage.warning(res.msg); + // this.show_bug_dialog_fail_show(row) + } + }) + .catch((err) => { + ElMessage.error('请求失败,请联系管理员'); + console.log(`/api/bug/build_info?project_id=${projectId}&image_id=${imageId} 接口调用失败: ${err}`); + }); +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/crud.js b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/crud.js new file mode 100644 index 0000000000000000000000000000000000000000..bf4881703bebb01cd2e05a3e8ae2c130b01435e3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/crud.js @@ -0,0 +1,844 @@ +import { dict, useCompute, useColumns } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { useRoute, useRouter } from 'vue-router'; +import { ElMessage, ElMessageBox } from 'element-plus'; +import { dateRangeBind } from '@/utils/bind/date.js'; +import dayjs from 'dayjs'; +import createBugCrudOptions from './submitBug/crud'; +import createBatchBugCrudOptions from './submitBug/batchCrud.jsx'; +import { cloneDeep, debounce } from 'lodash-es'; +import { ref, computed, shallowRef } from 'vue'; +import { getBugTypeDict, getLanguageDict } from '@/utils/dict.js'; +import { useTagsViewStore } from '@/store/modules/tags-view.ts'; +import { getBasicInfo } from '@/views/task/audit/common.js'; +import numberRange from '@/components/numberRange.vue'; +import { getTrackerMeta } from '@/utils/tracker.js'; + +export default function ({ crudExpose, context }) { + const route = useRoute(); + const router = useRouter(); + const { compute } = useCompute(); + const tagsViewStore = useTagsViewStore(); + + if (route.query.data_id) { + tagsViewStore.setCurrentTabTitle(route, `${route.query.data_id}-多语言对比`); + } + + const debounceDoSearch = debounce(form => crudExpose.doSearch({ form }), 250); + + let searchBugTypes = []; + const pageData = ref([]); + const previewImgs = ref([]); + + // @ts-ignore + const pageRequest = async (params) => { + searchBugTypes = cloneDeep(params.ai_bug_types || []); + pageData.value = []; + previewImgs.value = []; + return await customRequest({ + url: '/api/image/list', + // url: `/images/project/${route.meta.value}/get_images`, + method: 'get', + params: { + job_id: route.query.job_id, + ...params, + id: params.id || route.query.id || undefined, + data_id: route.query.data_id || undefined, + rect_location: params.rect_location || undefined, + ai_bug_types: + (params.ai_bug_types && params.ai_bug_types.length) ? params.ai_bug_types.join(',') : undefined, + }, + }).then((res) => { + pageData.value = res.data.list; + const tempPreviewImgs = []; + res.data.list.forEach((item) => { + context.imgKeys.forEach((key) => { + tempPreviewImgs.push(`${context.imgPrefix}${item[key]}`); + }); + }); + previewImgs.value = tempPreviewImgs; + return res; + }); + }; + + const delRequest = async ({ row }) => await customRequest({ + url: '/api/image/entity', + method: 'delete', + data: { image_ids: [row.id], project_id: route.meta.value }, + }); + + const selectedIds = ref([]); + // 保存当前勾选的完整行数据,批量提单前要据此过滤未识别/已提单的图片 + const selectedRows = ref([]); + const jobId = ref(); + const onSelectionChange = (changed) => { + selectedIds.value = changed.map(item => item.id); + selectedRows.value = changed; + if (changed.length) { + jobId.value = changed[0].job_id; + } + }; + + const commonSubmitObj = { + priority: 3, // 中 - 优先级 + severity: 3, // 一般 - 严重程度 + // 发现版本 + version_report_options: [], + version_report_value: '', + version_report: '', + // 发布计划 + release_id_options: [], + release_id_value: '', + release_id_label: '', + // 合入版本 + version_fix_options: [], + version_fix_value: '', + }; + const submitDataObj = { + title: '', + fix_title: '', + image_name: '', + current_owner: '', + raw_image_path: '', + AI_image_path: '', + description: '', + image_id: '', + job_id: '', + Key_in_bug: '', + }; + const batchDataForm = { + bug_type: [], + }; + + // 判断单行图片不能提单的原因;返回空串表示该图片可以提单 + // 共三种不可提单情形,前端据此给出针对性建议: + // 1) '已提单' → bill_status === 0 + // 2) 'AI 识别失败' → ai_sign_suc === 2(后端标记为识别失败) + // 3) 'AI 识别未完成' → ai_sign_suc === 0 且 ai_mark_img_path 为空(还没识别过) + // 4) 'AI 未发现缺陷' → ai_sign_suc === 1 但 ai_bug_types 为空(识别成功但没检出 bug) + function getUnbillableReason(row) { + if (row.bill_status === 0) return '已提单'; + if (row.ai_sign_suc === 2) return 'AI 识别失败'; + if (!row.ai_mark_img_path && (!row.ai_bug_types || !row.ai_bug_types.length)) return 'AI 识别未完成'; + if (!row.ai_bug_types || !row.ai_bug_types.length) return 'AI 未发现缺陷'; + return ''; + } + + // 不可提单原因 → 可读颜色(表格里着色,橙=提示类,红=错误类) + function getReasonColor(reason) { + if (reason === '已提单' || reason === 'AI 未发现缺陷') return '#E6A23C'; + return '#F56C6C'; + } + + // 根据实际出现过的原因,返回 HTML 建议段落 + function getActionAdviceHtml(invalidRows) { + const reasons = new Set(invalidRows.map(getUnbillableReason)); + const lines = []; + if (reasons.has('AI 识别未完成')) { + lines.push('• AI 识别未完成:请先点击该行的 识别 按钮完成识别,再提单。'); + } + if (reasons.has('AI 识别失败')) { + lines.push('• AI 识别失败:请点击该行的 识别 按钮重新识别;若多次失败,可能是图片本身异常(如抽帧失败),建议删除或更换图片。'); + } + if (reasons.has('AI 未发现缺陷')) { + lines.push('• AI 未发现缺陷:AI 识别已完成,但该图片未检出任何 bug,当前版本不支持为此类图片手动提单。'); + } + if (reasons.has('已提单')) { + lines.push('• 已提单:可从 缺陷管理 页面查看,无需重复提单。'); + } + lines.push('• 或先取消勾选这些图片,再对其他可提单的图片进行批量提单。'); + return `
+ 建议:
${lines.join('
')} +
`; + } + + // 防止弹窗重复打开 + let unbillableBoxOpen = false; + + // HTML 转义,避免文件名里带 < > & 等字符破坏弹窗内容 + function esc(s) { + return String(s == null ? '' : s) + .replace(/&/g, '&').replace(//g, '>') + .replace(/"/g, '"').replace(/'/g, '''); + } + + // 构建“不可提单”明细表格 HTML + function buildUnbillableTable(invalidRows) { + const rows = invalidRows.map((r) => { + const reason = getUnbillableReason(r); + const reasonColor = getReasonColor(reason); + return ` + ${esc(r.id)} + ${esc(r.file_name || '-')} + ${esc(reason)} + `; + }).join(''); + return `
+ + + + + + + + + ${rows} +
图片 ID文件名原因
+
`; + } + + async function batchBill() { + // 过滤勾选行:未完成 AI 识别(ai_bug_types 为空)或已提单(bill_status === 0)的图片都无法提单, + // 若直接把它们提交到 /api/bug/list,后端会把 ai_check_detail 当 JSON 解析而抛 + // "Input is a zero-length, empty document" 等错误,前端只能看到一串英文异常。 + const rows = selectedRows.value || []; + const validRows = []; + const invalidRows = []; + rows.forEach((row) => { + if (getUnbillableReason(row)) invalidRows.push(row); + else validRows.push(row); + }); + + // 情况 1:全部不可提单——用 alert 弹窗列出明细 + 建议 + if (validRows.length === 0) { + if (unbillableBoxOpen) return; + unbillableBoxOpen = true; + const tip = `
以下 ${invalidRows.length} 张图片都无法提单:
` + + buildUnbillableTable(invalidRows) + + getActionAdviceHtml(invalidRows); + try { + await ElMessageBox.alert(tip, '无法批量提单', { + dangerouslyUseHTMLString: true, + confirmButtonText: '知道了', + customClass: 'batch-bill-unbillable-dialog', + type: 'warning', + }); + } catch (e) { /* 用户关闭 */ } finally { + unbillableBoxOpen = false; + } + return; + } + + // 情况 2:部分不可提单——confirm 弹窗,列出明细,让用户决定是否跳过它们继续 + if (invalidRows.length > 0) { + if (unbillableBoxOpen) return; + unbillableBoxOpen = true; + const tip = `
以下 ${invalidRows.length} 张图片无法提单,将被自动跳过:
` + + buildUnbillableTable(invalidRows) + + `
是否继续对剩余 ${validRows.length} 张图片提单?
`; + try { + await ElMessageBox.confirm(tip, '部分图片无法提单', { + dangerouslyUseHTMLString: true, + type: 'warning', + confirmButtonText: `继续对剩余 ${validRows.length} 张提单`, + cancelButtonText: '取消', + customClass: 'batch-bill-unbillable-dialog', + }); + } catch (e) { + unbillableBoxOpen = false; + return; // 用户取消 + } finally { + unbillableBoxOpen = false; + } + } + + const useBatchDataForm = cloneDeep({ + image_ids: validRows.map(r => r.id), + ...commonSubmitObj, + ...batchDataForm, + job_id: jobId.value, + }); + + await getExtraInfo(useBatchDataForm); + + // 自定义表单配置 + const { buildFormOptions } = useColumns(); + // 使用crudOptions结构来构建自定义表单配置 + const formOptions = ( + buildFormOptions(createBatchBugCrudOptions(route, useBatchDataForm, context.clearRefresh)) + ); + formOptions.initialForm = useBatchDataForm; + context.formWrapperRef.value.open(formOptions); + } + + /** 缺陷系统提单选项(发现版本/发布计划/修复版本) */ + async function getExtraInfo(obj) { + const meta = await getTrackerMeta(route.meta.value); + if (meta.error) { + ElMessage.warning(`缺陷系统配置有误,提单可能失败:${meta.error}`); + } + obj.tracker_label = meta.type === 'none' ? '平台内记录' : meta.label; + // 发现版本 + obj.version_report_options = meta.version_report_list; + obj.version_report_value = ''; + // 发布计划 + obj.release_id_options = meta.release_id_list; + obj.release_id_value = ''; + obj.release_id_label = ''; + // 修复版本 + obj.version_fix_options = meta.version_fix_list; + obj.version_fix_value = ''; + } + + // 此处编辑 crudOptions 配置 + return { + pageData, + previewImgs, + selectedIds, + crudOptions: { + request: { + pageRequest, + delRequest, + }, + pagination: { + pageSize: 10, // 默认pageSize + }, + // pagination: { + // onChange() { + // console.log('page change'); + // }, + // }, + // 屏蔽 fast-crud 右上角内置的"导出"按钮。 + // 该页面(结果审核 / 多语言对比,共用本 crud.js)内置导出按钮点击无响应, + // 容易引起误解,这里统一关掉;其他页面不受影响。 + toolbar: { + buttons: { + export: { show: false }, + }, + }, + actionbar: { + buttons: { + add: { show: false }, + submitBugs: { + // size: 'small', + title: '', + type: 'warning', + // plain: true, + text: '批量提单', + show: true, + // order: 0, + disabled: computed(() => !selectedIds.value.length), + click: batchBill, + }, + }, + }, + rowHandle: { + buttons: { + edit: { show: false }, // 编辑隐藏 + remove: { + plain: true, + link: true, + text: '删除', + tooltip: null, + click: async ({ row }) => { + // 没查到,二次确认删除 + ElMessageBox.confirm('确认删除该数据吗?', '温馨提示', { + type: 'warning', + }).then(async () => { + await delRequest({ row }); + ElMessage.success('操作成功'); + context.clearRefresh(); + }); + }, + }, + // 多语种 + languages: { + size: 'small', + title: '', + type: 'warning', + plain: true, + link: true, + icon: 'ci:image-01', + text: '多语种', + // style: { height: '30px', width: '32px' }, + // tooltip: { content: '提单', enterable: false }, + show: true, + order: 1, + click: async ({ row }) => { + const url = router.resolve({ + path: route.path, + query: { + job_id: route.query.job_id, + data_id: row.data_id, + }, + }).href; + router.push(url); + }, + }, + // 提单 + submitBugs: { + size: 'small', + title: '', + type: 'warning', + plain: true, + link: true, + icon: compute(({ row }) => (row.bill_status === 0 ? '' : 'cil:bug')), + text: compute(({ row }) => (row.bill_status === 0 ? '提单中' : '提单')), + // style: { height: '30px', width: '32px' }, + // tooltip: { content: '提单', enterable: false }, + disabled: compute(({ row }) => !row.ai_bug_types.length || row.bill_status === 0), + show: true, + order: 1, + click: async ({ row }) => { + const useSubmitDataObj = cloneDeep({ ...commonSubmitObj, ...submitDataObj }); + useSubmitDataObj.bug_types = cloneDeep(searchBugTypes.length ? searchBugTypes : row.ai_bug_types || []); + + useSubmitDataObj.image_name = row.file_name; + useSubmitDataObj.raw_image_path = row.file_path; + useSubmitDataObj.AI_image_path = row.ai_mark_img_path; + useSubmitDataObj.job_id = row.job_id; + useSubmitDataObj.image_id = row.id; + + // 获取描述模板 + const billMethodRes = await customRequest({ + url: '/api/project/config', + method: 'get', + params: { project_id: route.meta.value, cate: 'BugBillMethod' }, + }); + let descTemplate = ''; + if (billMethodRes.code === 0 && billMethodRes.data.list.length) { + descTemplate = billMethodRes.data.list[0].description_template || ''; + } + + if (descTemplate) { + // 使用配置的模板,替换变量 + let rendered = descTemplate + .replace(/\{image_id\}/g, row.id) + .replace(/\{image_name\}/g, row.file_name) + .replace(/\{job_id\}/g, row.job_id) + .replace(/\{create_time\}/g, row.create_time || ''); + // 如果模板不包含HTML标签,按行转换为

+ if (!rendered.includes('<')) { + rendered = rendered.split('\n').map(line => `

${line}

`) + .join(''); + } + useSubmitDataObj.description = rendered; + } else { + // 默认模板 + useSubmitDataObj.description = '

[测试环境](Version & Test environment)

' + + '

测试包(Installation package):

' + + '

服务器名(Server name):

' + + '

测试机型(Device):

' + + '

[操作步骤](Steps)

' + + '

1.自动化LQA单中列出了缺陷所在的蓝图和控件信息,未列出步骤,如需要步骤,请联系提单人

' + + '

[问题描述](Current result)

' + + '

1、

' + + '

[文本信息](Text information)

' + + '

翻译key (TextKey):

' + + '

1、

' + + '

翻译原文 (SourceText):

' + + '

1、

' + + '

翻译译文 (Translation in text file):

' + + '

1、

' + + '

文本控件名(Widget Name):

' + + '

1、

' + + '

文本父蓝图(Parent Widget):

' + + '

1、

' + + '

[截图](Screenshots)

' + + '

' + + '

[备注](Notes)

'; + } + // 保护前端已渲染好的 description:仅当项目在"设置→提单"里配置了自定义模板时, + // getBasicInfo 回来后把 description 还原为前端模板,否则 /api/bug/build_info 返回的 + // 后端默认模板(BugBuildComm.description_tpl)会把前端的渲染结果覆盖掉。 + const useCustomDescTpl = !!descTemplate; + const preRenderedDesc = useSubmitDataObj.description; + await getBasicInfo(route.meta.value, row.id, useSubmitDataObj); + if (useCustomDescTpl) { + useSubmitDataObj.description = preRenderedDesc; + } + + await getExtraInfo(useSubmitDataObj); + + // 获取自定义提单字段配置 + const customFieldRes = await customRequest({ + url: '/api/project/config', + method: 'get', + params: { project_id: route.meta.value, cate: 'CustomField' }, + }); + useSubmitDataObj.customFields = customFieldRes.code === 0 ? (customFieldRes.data.list || []) : []; + + // 生成名称前缀 + if (!useSubmitDataObj.fix_title) { + if (useSubmitDataObj.image_name.split('_').length === 3) { + const language = useSubmitDataObj.image_name.split('_')[1]; + const language2 = useSubmitDataObj.image_name.split('_')[2].split('.')[0]; + console.log(`language2====${language2}`); + useSubmitDataObj.fix_title = `【GRN-${language}-${language2}】【LQA-Tools】-`; + console.log(`language====${language}----language2====${language2}-----v====${useSubmitDataObj.fix_title}`); + } else { + console.error('fix_title:image_name 命名不符合规范'); + useSubmitDataObj.fix_title = '【LQA-Tools】-'; + } + } + // 自定义表单配置 + const { buildFormOptions } = useColumns(); + // 使用crudOptions结构来构建自定义表单配置 + const formOptions = buildFormOptions(createBugCrudOptions(route, useSubmitDataObj, crudExpose, useSubmitDataObj.bug_types)); + formOptions.initialForm = useSubmitDataObj; + context.formWrapperRef.value.open(formOptions); + }, + }, + }, + align: 'center', + width: 166, + }, + table: { + // border: false, + onSelectionChange, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '90px', + }, + columns: { + // 多选 + $checked: { + // title: '选择', + form: { show: false }, + column: { + type: 'selection', + align: 'center', + width: '60px', + fixed: 'left', + // reserveSelection: true, // 跨页选 + columnSetDisabled: true, // 禁止在列设置中选择 + showOverflowTooltip: false, + selectable(row) { + return row.bill_status !== 0; + }, + }, + }, + // 图片 ID + id: { + title: '图片 ID', + type: 'number', + column: { width: 180, align: 'right' }, + form: { + component: { placeholder: 'ID' }, + }, + search: { + show: computed(() => !route.query.id), + value: ['', ''], + component: { + name: shallowRef(numberRange), + }, + valueResolve(e) { + e.form.pk__gte = (e.form[e.key] || [])[0] ? e.form[e.key][0] : undefined; + e.form.pk__lte = (e.form[e.key] || [])[1] ? e.form[e.key][1] : undefined; + e.form[e.key] = undefined; + }, + }, + }, + // 模块 + module_id: { + title: '模块', + type: 'dict-select', + dict: dict({ + url: `/api/project/module/list?project_id=${route.meta.value}&all=1`, + value: 'id', + label: 'show_name', + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + // 仅返回 el-option 需要的字段,避免把后端整条 module 记录(含 checked/ + // file_name/container 等字段)透传到 ,否则会触发 + // "[Vue warn]: Slot default invoked outside of the render function" + return (data.modules || []).map(item => ({ + id: item.id, + show_name: item.show_name, + })); + }, + }), + column: { width: 200 }, + search: { + show: true, + component: { + multiple: true, + }, + valueResolve(e) { + e.form.module_ids = (e.form[e.key] && e.form[e.key].length) ? e.form[e.key].join(',') : undefined; + e.form[e.key] = undefined; + }, + }, + }, + // 图片名称 + file_name: { + title: '图片名称', + type: 'text', + column: { width: 240 }, + search: { + show: true, + component: { placeholder: '模糊搜索' }, + }, + }, + // 图片名称 + name: { + title: '图片名称', + type: 'text', + column: { show: false }, + }, + // 采集图片 + shot_img_path: { + title: '采集图片', + type: 'image-uploader', + column: { + align: 'center', + width: 300, + }, + }, + // 还原图片 + file_path: { + title: '还原图片', + type: 'image-uploader', + column: { + align: 'center', + width: 300, + }, + }, + // 图像检测结果 + ai_mark_img_path: { + title: '图像检测结果', + type: 'image-uploader', + column: { + align: 'center', + width: 300, + }, + }, + // 图像检测 Debug + ai_rect_img_path: { + title: '图像检测 Debug', + type: 'image-uploader', + column: { + align: 'center', + width: 300, + }, + }, + // 区域语言 + language: { + title: '区域语言', + type: 'dict-select', + dict: getLanguageDict(route.meta.value), + column: { width: 100 }, + form: { + component: { + dict: getLanguageDict(route.meta.value, true), + }, + }, + search: { + show: true, + valueResolve(e) { + e.form.languages = (e.form[e.key] && e.form[e.key].length) ? e.form[e.key].join(',') : undefined; + e.form[e.key] = undefined; + }, + component: { + multiple: true, + // 监听 dict-change事件 + // 默认选中第一个 + onDictChange({ dict, form, key }) { + if (!route.query.data_id) { + if (dict.data !== null && !form[key]) { + if (dict.data[0].name === 'DEFAULT') { + if (dict.data.length > 1) { + form[key] = [dict.data[1].value]; + } + } else { + form[key] = [dict.data[0].value]; + } + } + } + debounceDoSearch(form); + }, + }, + }, + }, + // 缺陷类型 + ai_bug_types: { + title: '缺陷类型', + type: 'dict-select', + dict: getBugTypeDict(route.meta.value), + column: { width: 120 }, + search: { + show: true, + component: { + multiple: true, + }, + }, + }, + // 人工审核 + // will_review: { + // title: '人工审核', + // type: 'dict-select', + // column: { width: 84 }, + // dict: dict({ + // data: [ + // { value: 1, label: '需要', color: 'danger', effect: 'light' }, + // { value: 0, label: '不需要', color: '', effect: 'light' }, + // ], + // }), + // form: { + // component: { placeholder: '人工审核' }, + // }, + // search: { show: true }, + // }, + // 审核(这条图片的"数据审核"状态;非"手动打 bug 位置") + reviewed: { + title: '审核', + type: 'dict-select', + column: { width: 84 }, + dict: dict({ + data: [ + { value: 1, label: '已审核', color: 'success', effect: 'light' }, + { value: 0, label: '未审核', color: 'danger', effect: 'light' }, + ], + }), + form: { + component: { placeholder: '数据审核状态' }, + }, + search: { show: true }, + }, + // 缺陷单 + bug_num: { + title: '缺陷单', + column: { + align: 'right', + width: 70, + component: { + name: 'el-button', + type: 'primary', + link: true, + slots: { + default: compute(e => e.value), + }, + on: { + click(e) { + const currentRouteArr = route.path.split('/').slice(0, -1); + currentRouteArr.push(`bugs?job_id=${e.row.job_id}&image_id=${e.row.id}`); + router.push(currentRouteArr.join('/')); + }, + }, + style: { + marginBottom: '3px', + }, + }, + }, + }, + // 错误类型 + err_type: { + title: '错误类型', + type: 'dict-select', + dict: dict({ + data: [ + { value: 0, label: '没有失败', color: 'info' }, + { value: 1, label: '识别失败', color: 'error' }, + { value: 2, label: '提单失败', color: 'error' }, + { value: 3, label: '回归失败', color: 'error' }, + ], + }), + column: { + width: 100, + component: { + class: 'only-text-tag', + }, + }, + form: { + component: { placeholder: '错误类型' }, + }, + search: { show: true }, + }, + // 检测文本 + rect_location: { + title: '检测文本', + type: 'text', + column: { width: 84 }, + search: { + show: true, + component: { + disabled: compute(({ form }) => !(form.language && form.language.length)), + placeholder: '模糊搜索', + }, + }, + }, + + // 创建时间 + created_at: { + title: '创建时间', + type: 'datetimerange', + column: { + align: 'center', + width: 158, + component: { name: 'fs-date-format' }, + }, + form: { + component: { + ...dateRangeBind, + clearable: true, + }, + show: false, + }, + search: { + show: true, + order: 0, + // value: [ + // dayjs().subtract(3, isDevMode() ? 'year' : 'month') + // .format('YYYY-MM-DD'), + // dayjs().format('YYYY-MM-DD'), + // ], + valueResolve({ value, form }) { // <------注意这里是form,不是row + if (value && value.length === 2) { + // eslint-disable-next-line no-param-reassign + form.created_begin_at = dayjs(value[0]).startOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + // eslint-disable-next-line no-param-reassign + form.created_end_at = dayjs(value[1]).endOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + } + }, + // style: { width: '288px' }, + }, + }, + // 更新时间 + updated_at: { + title: '更新时间', + type: 'datetimerange', + column: { + align: 'center', + width: 158, + component: { + name: 'fs-date-format', + // formatter: datetimerangeFormatter, + }, + }, + form: { + component: { + ...dateRangeBind, + clearable: true, + }, + show: false, + }, + search: { + show: true, + order: 0, + // value: [ + // dayjs().subtract(3, isDevMode() ? 'year' : 'month') + // .format('YYYY-MM-DD'), + // dayjs().format('YYYY-MM-DD'), + // ], + valueResolve({ value, form }) { // <------注意这里是form,不是row + if (value && value.length === 2) { + form.updated_begin_at = dayjs(value[0]).startOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + form.updated_end_at = dayjs(value[1]).endOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + } + }, + // style: { width: '288px' }, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..74db1b569a151f48a14a82abb7d9d6217258faa5 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/index.vue @@ -0,0 +1,388 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/recognizeDialog.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/recognizeDialog.vue new file mode 100644 index 0000000000000000000000000000000000000000..5430f30dcb45915f334cbafd4a067b60a9317c17 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/recognizeDialog.vue @@ -0,0 +1,99 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/batchCrud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/batchCrud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..91c7e5ecf2d79a5edf2a49e4b56ff99e5d207349 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/batchCrud.jsx @@ -0,0 +1,135 @@ +import { dict } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { useUserStoreHook } from '@/store/modules/user'; +import { customRequest } from '@/utils/service.ts'; +import { getBugTypeDict } from '@/utils/dict.js'; + +export default function (route, params, clearRefresh) { + // 此处编辑 crudOptions 配置 + return { + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + form: { + wrapper: { + title: `批量提单${params.tracker_label ? `(${params.tracker_label})` : ''}`, + }, + doSubmit: async ({ form }) => { + console.log('form submit:', form); + const data = { + project_id: route.meta.value, + image_ids: form.image_ids, + version_report: form.version_report_value, // 发现版本 + release_id: form.release_id_label, // 发布计划 + version_fix: form.version_fix_value, // 修复版本 + severity: form.severity, // 严重程度 + priority: form.priority, // 优先级 + reporter: useUserStoreHook().name, // 提单人 + bug_types: form.bug_type, + job_id: params.job_id, + }; + const res = await customRequest({ + url: '/api/bug/list', + method: 'post', + data, + }) + .catch((err) => { + ElMessage.error('请求失败,请联系管理员'); + // this.$loading.hide(); + console.log(`batch_create_bug 接口调用失败:${err}`); + throw err; + }); + if (res.code === 0) { + ElMessage.success(res.msg || '操作成功'); + clearRefresh(); + return true; + } + ElMessage.warning(res.msg); + return false; + }, + }, + columns: { + // 缺陷类型 + bug_type: { + title: '缺陷类型', + type: 'dict-select', + dict: getBugTypeDict(route.meta.value), + form: { + component: { + multiple: true, + }, + }, + }, + // 优先级 + priority: { + title: '优先级', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_priority', + }), + form: { + component: { placeholder: '优先级' }, + }, + }, + // 严重程度 + severity: { + title: '严重程度', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_severity', + }), + form: { + component: { placeholder: '严重程度' }, + }, + }, + // 发现版本 + version_report_value: { + title: '发现版本', + type: 'dict-select', + dict: dict({ + data: params.version_report_options, + }), + form: { + component: { placeholder: '发现版本' }, + }, + }, + // 修复版本 + version_fix_value: { + title: '修复版本', + type: 'dict-select', + dict: dict({ + data: params.version_fix_options, + }), + form: { + component: { placeholder: '修复版本' }, + }, + }, + // 发布计划 + // release_id_value: { + release_id_label: { + title: '发布计划', + type: 'dict-select', + dict: dict({ + data: params.release_id_options, + }), + form: { + component: { placeholder: '发布计划' }, + }, + }, + // 处理人 + current_owner: { + title: '处理人', + type: 'text', + form: { + component: { + name:
根据配置自动生成
, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..5d4684a8bd7ffa73268fec57e0479a141f0633f8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/audit/submitBug/crud.jsx @@ -0,0 +1,277 @@ +import { dict, useCompute } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { useUserStoreHook } from '@/store/modules/user'; +import { customRequest } from '@/utils/service.ts'; +import { cloneDeep, debounce } from 'lodash-es'; +import { getBasicInfo } from '@/views/task/audit/common.js'; +import { shallowRef } from 'vue'; +import scEditor from '@/components/scEditor/index.vue'; + +export default function (route, params, parentCrudExpose, bugTypes) { + const { compute } = useCompute(); + + // [新增] 根据配置动态构建自定义字段的 columns + // params.customFields 来自基础配置页面的 ProjectConfigCustomField 表 + // 每个启用的自定义字段会在提单表单中渲染为一个可搜索的下拉选择框 + // + // options 元素约定两种格式(在设置页写入): + // 1) "中文|英文" —— 用户看到"中文",选中后提交"英文"(如禅道的 "代码错误|codeerror") + // 2) "值" —— label 与 value 相同(用户手输场景或缺陷系统本就无中文映射) + // 这里统一拆成 { value, label } 对象供 dict-select 渲染 + const parseOption = (opt) => { + if (typeof opt !== 'string') { + return { value: String(opt), label: String(opt) }; + } + const idx = opt.indexOf('|'); + if (idx > 0) { + return { label: opt.slice(0, idx), value: opt.slice(idx + 1) }; + } + return { value: opt, label: opt }; + }; + const customFieldColumns = {}; + if (params.customFields && params.customFields.length) { + params.customFields.forEach((field) => { + if (field.enable) { + // fieldKey 加 custom_ 前缀避免与内置字段冲突 + const fieldKey = `custom_${field.field_key}`; + customFieldColumns[fieldKey] = { + title: field.field_name, // 显示的标题 + type: 'dict-select', + dict: dict({ + data: (field.options || []).map(parseOption), + }), + form: { + component: { + placeholder: '搜索', + filterable: true, // 支持搜索过滤 + allowCreate: true, // 允许手动输入新值 + defaultFirstOption: true, + clearable: true, + }, + }, + }; + } + }); + } + + return { + table: { + border: false, + }, + search: { + show: false, + }, + form: { + wrapper: { + title: `${params.image_name} 提单${params.tracker_label ? `(${params.tracker_label})` : ''}`, + zIndex: 1003, + top: '5vh', + width: '70%', + draggable: true, + customClass: 'bug-submit-dialog', + }, + doSubmit: async ({ form }) => { + console.log('form submit:', form); + const data = { + project_id: route.meta.value, + title: params.fix_title + form.title, + description: form.description, + version_report: form.version_report_value !== undefined ? form.version_report_value : undefined, + release_id: form.release_id_label !== undefined ? form.release_id_label : undefined, + version_fix: form.version_fix_value !== undefined ? form.version_fix_value : undefined, + severity: form.severity !== undefined ? form.severity : undefined, + priority: form.priority !== undefined ? form.priority : undefined, + reporter: useUserStoreHook().name, + current_owner: form.current_owner, + raw_image_path: params.raw_image_path, + image_id: params.image_id, + job_id: params.job_id, + ai_image_path: params.AI_image_path, + key_in_bug: params.Key_in_bug, + }; + // 收集自定义字段值,组装为 {field_key: 选中的值} 格式 + // 后端会将这些字段原样附加到缺陷系统创建 Bug 的请求体中 + const customFieldValues = {}; + if (params.customFields && params.customFields.length) { + params.customFields.forEach((field) => { + if (field.enable) { + const fieldKey = `custom_${field.field_key}`; + // 修复:使用 !== undefined 判断,避免将 0、false、空字符串等合法值错误排除 + if (form[fieldKey] !== undefined) { + customFieldValues[field.field_key] = form[fieldKey]; + } + } + }); + } + if (Object.keys(customFieldValues).length > 0) { + data.custom_fields = customFieldValues; + } + + const res = await customRequest({ + url: '/api/bug/entity', + method: 'post', + data, + }) + .catch((err) => { + ElMessage.error('创建 bug 失败,请确认图片正常显示'); + console.log(`/bug/project/${route.meta.value}/create 接口调用失败: ${err}`); + throw err; + }); + if (res.code === 0) { + ElMessage.success(res.msg || '创建成功'); + parentCrudExpose.doRefresh(); + return true; + } + ElMessage.warning('创建bug失败'); + return false; + }, + }, + columns: { + // 缺陷类型 + bug_types: { + title: '缺陷类型', + type: 'dict-select', + dict: dict({ + url: `/api/project/config?_=${Math.random()}`, + async getData() { + const res = await customRequest({ + url: '/api/project/config', + method: 'get', + params: { project_id: route.meta.value, cate: 'BugType' }, + }); + return res.data.list.filter(item => cloneDeep(bugTypes).includes(item.value)).map(item => ({ + ...item, label: item.enable ? item.label : `${item.label}(未启用)`, + color: item.enable ? undefined : 'info', + effect: item.enable ? undefined : 'light', + disabled: !item.enable, + })); + }, + }), + form: { + col: { span: 24 }, + helper: '用于生成基础信息', + component: { + multiple: true, + placeholder: '请选择缺陷类型', + }, + valueChange: debounce(async ({ form }) => { + await getBasicInfo(route.meta.value, params.image_id, form); + }, 1000), + }, + }, + // 名称 + title: { + title: '名称', + type: 'text', + form: { + col: { span: 24 }, + component: { + placeholder: '请填写名称', + slots: { + prepend: compute(e => e.form.fix_title), + }, + }, + rules: [{ required: true, message: '请填写名称' }], + }, + }, + // 优先级 + priority: { + title: '优先级', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_priority', + }), + form: { + component: { placeholder: '优先级' }, + }, + }, + // 严重程度 + severity: { + title: '严重程度', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_severity', + }), + form: { + component: { placeholder: '严重程度' }, + }, + }, + // 发现版本 + version_report_value: { + title: '发现版本', + type: 'dict-select', + dict: dict({ + data: params.version_report_options, + }), + form: { + component: { + allowCreate: true, + defaultFirstOption: true, + placeholder: '发现版本', + }, + }, + }, + // 修复版本 + version_fix_value: { + title: '修复版本', + type: 'dict-select', + dict: dict({ + data: params.version_fix_options, + }), + form: { + component: { + allowCreate: true, + defaultFirstOption: true, + placeholder: '修复版本', + }, + }, + }, + // 发布计划 + release_id_label: { + title: '发布计划', + type: 'dict-select', + dict: dict({ + data: params.release_id_options, + }), + form: { + component: { + allowCreate: true, + defaultFirstOption: true, + placeholder: '发布计划', + }, + }, + }, + // 动态自定义字段(插入在发布计划和处理人之间) + ...customFieldColumns, + // 处理人 + current_owner: { + title: '处理人', + type: 'text', + form: { + component: { + placeholder: '缺陷系统中的账号(Bugzilla 为邮箱),多个用逗号分隔', + }, + rules: [{ required: true, message: '请填写处理人' }], + }, + }, + // 缺陷描述 + description: { + title: '缺陷描述', + type: 'textarea', + form: { + col: { span: 24 }, + component: { + name: shallowRef(scEditor), + placeholder: '请填写缺陷描述', + maxlength: 5000, + showWordLimit: true, + autosize: { + minRows: 20, + }, + }, + rules: [{ required: true, message: '请填写缺陷描述' }], + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/crud.js b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/crud.js new file mode 100644 index 0000000000000000000000000000000000000000..753d739379031c47f87cab3552f884ef716d23ce --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/crud.js @@ -0,0 +1,363 @@ +import { dict, useCompute, useColumns } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { useRoute, useRouter } from 'vue-router'; +import { computed, ref } from 'vue'; +import createRegressCrudOptions from './regress.jsx'; +import { timeCols } from '@/fast-crud/common.ts'; + +export default function ({ context }) { + const route = useRoute(); + const router = useRouter(); + const { compute } = useCompute(); + const delKey = 'is_delete'; + // @ts-ignore + const pageRequest = async params => await customRequest({ + // url: `/bug/project/${route.meta.value}/get_bugs`, + url: '/api/bug/list', + method: 'get', + params: { + ...params, + job_id: route.query.job_id, + image_id: route.query.image_id, + }, + }); + + // 平台内记录 / Bugzilla / 禅道 的常见状态 + const statusLabels = { + open: '打开', + closed: '关闭', + // Bugzilla + UNCONFIRMED: '未确认', + CONFIRMED: '已确认', + IN_PROGRESS: '处理中', + RESOLVED: '已解决', + VERIFIED: '已验证', + // 禅道 + active: '激活', + resolved: '已解决', + }; + const isClosed = row => row.tracker_open === false || row.status === 'closed'; + const trackerDict = dict({ url: '/api/system/enums/bug_tracker' }); + + const selectedIds = ref([]); + const onSelectionChange = (changed) => { + selectedIds.value = changed.map(item => item.id); + }; + + // 自定义表单配置 + const { buildFormOptions } = useColumns(); + + // 此处编辑 crudOptions 配置 + return { + selectedIds, + crudOptions: { + request: { + pageRequest, + }, + // 仅在本页面屏蔽 fast-crud 右上角内置的"导出"按钮。 + // 本页面已经在左上角提供了自定义的"导出"按钮(后端生成 Excel,带超链接), + // 内置的那个按钮点击无响应,容易引起误解,这里单独关掉。 + // 其他页面不受影响。 + toolbar: { + buttons: { + export: { show: false }, + }, + }, + actionbar: { + buttons: { + add: { + show: false, + }, + regress: { + // size: 'small', + title: '', + type: 'warning', + // plain: true, + text: '批量回归', + show: true, + // order: 0, + disabled: computed(() => !selectedIds.value.length), + click: () => { + const formOptions = buildFormOptions(( + createRegressCrudOptions(route, selectedIds.value, context.clearRefresh) + )); + context.formWrapperRef.value.open(formOptions); + }, + }, + }, + }, + rowHandle: { + buttons: { + edit: { show: false }, // 编辑隐藏 + remove: { show: false }, // 删除隐藏 + // 任务详情 + task: { + size: 'small', + title: '', + // type: 'success', + type: 'primary', + link: true, + plain: true, + icon: 'svg:icon-menu', + text: '任务', + style: { height: '30px' }, + // tooltip: { content: '结果审核', enterable: false }, + show: true, + order: 1, + click: ({ row }) => { + const currentRouteArr = route.path.split('/').slice(0, -1); + currentRouteArr.push(`task?id=${row.job_id}`); + router.push(currentRouteArr.join('/')); + }, + }, + // 结果审核 + audit: { + size: 'small', + title: '', + // type: 'success', + type: 'danger', + plain: true, + link: true, + icon: 'icon-park-outline:audit', + text: '审核', + style: { height: '30px' }, + // tooltip: { content: '结果审核', enterable: false }, + show: true, + order: 1, + click: ({ row }) => { + const currentRouteArr = route.path.split('/').slice(0, -1); + currentRouteArr.push(`image-results?id=${row.image_id}`); + router.push(currentRouteArr.join('/')); + }, + }, + // 回归 + regress: { + size: 'small', + title: '', + type: 'denger', + plain: true, + link: true, + icon: 'line-md:backup-restore', + text: '回归', + style: { height: '30px' }, + show: true, + disabled: compute(({ row }) => row[delKey]), + click: ({ row }) => { + const formOptions = buildFormOptions(createRegressCrudOptions(route, [row.id], context.clearRefresh)); + context.formWrapperRef.value.open(formOptions); + }, + }, + }, + align: 'center', + width: 190, + }, + table: { + border: false, + onSelectionChange, + // rowClassName: ({ row }) => 'decoration-line-through', + rowStyle: ({ row }) => (row[delKey] ? { 'text-decoration': 'line-through', opacity: '.6' } : {}), + // rowStyle: ({ row }) => (row[delKey] ? { opacity: '.5' } : {}), + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '90px', + }, + columns: { + // 多选 + $checked: { + // title: '选择', + form: { show: false }, + column: { + type: 'selection', + align: 'center', + width: '54px', + reserveSelection: true, // 跨页选 + columnSetDisabled: true, // 禁止在列设置中选择 + showOverflowTooltip: false, + selectable(row) { + return !row[delKey]; + }, + }, + }, + // ID + // id: { + // title: 'ID', + // type: 'number', + // column: { width: 100, align: 'center' }, + // form: { + // component: { placeholder: 'ID' }, + // }, + // search: { + // show: true, + // component: { + // name: 'el-input', + // type: 'number', + // }, + // }, + // }, + + // 标题 + title: { + title: '标题', + column: { + minWidth: 360, + component: { + name: compute(({ row }) => (row[delKey] ? 'div' : 'el-link')), + type: 'primary', + // link: true, + href: compute(e => e.row.external_url || undefined), + target: '_blank', + slots: { + default: compute(e => e.row.title), + }, + // style: { + // marginBottom: '3px', + // }, + }, + }, + search: { + show: true, + component: { placeholder: '模糊搜索' }, + }, + }, + // 严重程度 + severity: { + title: '严重程度', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_severity', + }), + column: { + align: 'center', + component: { + type: compute(({ row }) => (row[delKey] ? 'text' : 'tag')), + }, + }, + form: { + component: { placeholder: '严重程度' }, + }, + // search: { + // show: true, + // }, + }, + // 缺陷系统 + tracker: { + title: '缺陷系统', + type: 'dict-select', + dict: trackerDict, + column: { align: 'center', width: 110 }, + }, + // 缺陷ID + external_id: { + title: '缺陷ID', + type: 'text', + column: { align: 'center', width: 90 }, + }, + // 缺陷状态(优先显示缺陷系统中的实时状态) + status_text: { + title: '缺陷状态', + type: 'text', + valueBuilder({ row }) { + let text; + if (row.bill_status === 2) { + text = '提单失败'; + } else if (row.bill_status === 0) { + text = '提单中'; + } else { + const raw = row.tracker_status || row.status || ''; + text = statusLabels[raw] || raw; + } + // eslint-disable-next-line no-param-reassign + row.status_text = text; + }, + column: { + align: 'center', + sortable: true, + showOverflowTooltip: true, + component: { + name: 'el-tooltip', + content: compute(({ row }) => row.bill_text || row.status_text || ''), + disabled: compute(({ row }) => !row.bill_text), + slots: { default: compute(({ row }) => row.status_text) }, + }, + }, + }, + // 提单人 + reporter: { + title: '提单人', + type: 'text', + }, + // 处理人 + current_owner: { + title: '处理人', + type: 'text', + }, + // 发现版本 + version_report: { + title: '发现版本', + type: 'text', + }, + // 合入版本 + version_fix: { + title: '修复版本', + type: 'text', + }, + // 发布计划 + release_id: { + title: '发布计划', + type: 'text', + }, + // 回归状态 + human_local_bug_status: { + title: '回归状态', + type: 'dict-select', + dict: dict({ + data: [ + { value: '无需回归', label: '无需回归', color: 'info' }, + { value: '等待回归', label: '等待回归', color: '' }, + { value: '回归中', label: '回归中', color: 'warning' }, + { value: '回归成功', label: '回归成功', color: 'success' }, + { value: '回归失败', label: '回归失败', color: 'error' }, + ], + }), + valueBuilder({ row }) { + let humanText = ''; + if (row.regress_status === 1 && isClosed(row)) { + humanText = '无需回归'; + } else if (row.regress_status === 1 && !isClosed(row)) { + humanText = '等待回归'; + } else if (row.regress_status === 2) { + humanText = '回归中'; + } else if (row.regress_status === 3) { + humanText = '回归成功'; + } else if (row.regress_status === 4) { + humanText = '回归失败'; + } + // eslint-disable-next-line no-param-reassign + row.human_local_bug_status = humanText; + }, + column: { + sortable: true, + component: { + name: 'fs-values-format', + }, + }, + }, + + ...timeCols, + + // 回归任务 + regress_job_ids: { + title: '回归任务', + type: 'text', + column: { + width: 180, + showOverflowTooltip: false, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/editRedu.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/editRedu.jsx new file mode 100644 index 0000000000000000000000000000000000000000..b8ba9c19684ae0a53f4ef240e2fef6c0ab7d9850 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/editRedu.jsx @@ -0,0 +1,76 @@ +import { dict } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service.ts'; +import { ref } from 'vue'; + +export default function (route, selectedIds, clearRefresh) { + const submitDisabled = ref(false); + // 此处编辑 crudOptions 配置 + return { + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + form: { + watch({ form }) { + submitDisabled.value = Object.values(form).every(item => !item); + }, + wrapper: { + title: '批量编辑', + style: { + justifyContent: 'center', + // height: '22vh', // 使容器高度占满整个视口 + weights: '3vh', + }, + buttons: { + ok: { + disabled: submitDisabled, + }, + }, + }, + doSubmit: async ({ form }) => { + const res = await customRequest({ + url: '/api/bug/list', + method: 'patch', + data: { ...form, bug_ids: selectedIds.value }, + }) + .catch((err) => { + ElMessage.error('操作失败'); + console.log(`/data/project/${route.meta.value}/data 接口调用失败: ${err}`); + throw err; + }); + + if (res.code === 0) { + ElMessage.success('操作成功'); + clearRefresh(); + return true; + } + ElMessage.warning('操作失败'); + return false; + }, + }, + columns: { + // 资源版本 + status: { + columnStyle: { + className: 'center', + }, + title: '回归状态', + type: 'dict-select', + dict: dict({ + data: [ + { value: '1', label: '初始' }, + { value: '2', label: '回归中' }, + { value: '3', label: '回归成功' }, + { value: '4', label: '回归失败' }, + ], + }), + }, + }, + }; +} + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..616b47dbe741d875189ab7fa7cfda10ec6ca9435 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/index.vue @@ -0,0 +1,189 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/regress.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/regress.jsx new file mode 100644 index 0000000000000000000000000000000000000000..8f3502742cb535ad6f0fdfbf493879641dfdacea --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/bugs/regress.jsx @@ -0,0 +1,109 @@ +import { dict } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service.ts'; + +export default function (route, bugIdList, clearRefresh) { + // 此处编辑 crudOptions 配置 + return { + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + form: { + labelWidth: '100px', + wrapper: { + title: '回归', + }, + doSubmit: async ({ form }) => { + const res = await customRequest({ + url: '/api/job/bug_regress', + method: 'post', + data: { + bug_ids: bugIdList, + ...form, + }, + }).catch((err) => { + console.error(`regressionBug 接口调用失败:${err}`); + return; + }); + if (!res) { + return false; + } + if (res.code === 0) { + ElMessage.success('提交成功'); + clearRefresh(); + return true; + } + ElMessage.warning(res.data.msg); + return true; + }, + }, + columns: { + // 任务类型 + discern: { + title: '任务类型', + type: 'dict-radio', + form: { + value: 0, + }, + dict: dict({ + data: [ + { value: 1, label: '差异识别' }, + { value: 0, label: '全量识别' }, + ], + }), + }, + // 译文资源 + translate_resource: { + title: '译文资源', + form: { + col: { span: 24 }, + valueBuilder(context) { + // 构建时 + const keys = [ + 'trans_res_type', 'trans_res_repo', 'trans_res_br', 'trans_res_ver', 'trans_res_file_path', + ]; + const temp = {}; + keys.forEach((key) => { + if (context.form[key]) { + if (key === 'trans_res_file_path') { + // 文件数据组装 + temp[key] = [ + { + url: context.form[key], + name: context.form[key].split('/').pop(), + }, + ]; + } else { + temp[key] = context.form[key]; + } + } + }); + context.form[context.key] = JSON.stringify(temp); + }, + valueResolve(context) { + // 提交时 + const temp = JSON.parse(context.form[context.key]); + Object.entries(temp).forEach(([key, value]) => { + context.form[key] = value; + }); + }, + }, + }, + // 说明信息 + helper: { + title: '', + form: { + col: { span: 24 }, + component: { + name: 'div', + }, + helper: '回归时间受配置更新时间影响,配置更新内容多,回归时间就会较长', + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/crud.js b/timi_hok_game_translator/LQA_WMP/web/src/views/task/crud.js new file mode 100644 index 0000000000000000000000000000000000000000..3862fd103c70f437219556e50a69aef7b70fd972 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/crud.js @@ -0,0 +1,526 @@ +import { dict, useCompute } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { useRoute, useRouter } from 'vue-router'; +import { getLanguageDict, getUserDict } from '@/utils/dict.js'; +import { dateRangeBind } from '@/utils/bind/date.js'; +import dayjs from 'dayjs'; +import { isDevMode } from '@/utils/env.ts'; +import { computed, ref, nextTick } from 'vue'; +import { ElMessageBox, ElMessage } from 'element-plus'; +import { timeCols } from '@/fast-crud/common.ts'; +import { runJob } from '@/utils/runner.js'; + +export default function ({ expose, context }) { + const route = useRoute(); + const router = useRouter(); + const dataLen = ref(0); + const expandSingleKey = ref(); + const { compute } = useCompute(); + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/api/job/list', + method: 'get', + params: { + project_id: route.meta.value, + ...params, + id: route.query.id || params.id || undefined, + module_id: params.module_ids || undefined, + }, + }).then((res) => { + dataLen.value = res.data.list.length; + if (dataLen.value > 1) { + res.data.list.forEach(item => item.hasChildren = !!item.regress_num); + } + nextTick(() => { + if (dataLen.value === 1 && res.data.list[0].regress_num) { + expandSingleKey.value = res.data.list[0].id; + } else { + expandSingleKey.value = undefined; + } + }); + return res; + }); + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + }, + actionbar: { + buttons: { + add: { + show: false, + }, + }, + }, + rowHandle: { + buttons: { + // 查看 + view: { + show: true, + link: true, + // text: '查看', + style: { height: '30px', width: 'auto' }, + // tooltip: null, + // style: { + // scale: 0.75, + // }, + click: context.openViewTask, + }, + // 编辑 + edit: { + link: true, + style: { height: '30px', width: 'auto' }, + click: context.openEditTask, + order: 1, + // 1 - 未执行 - 编辑 + // 2 - 执行中 - 追加 + disabled: compute(({ row }) => ![1, 2].includes(row.status)), + tooltip: compute(({ row }) => ( + [1, 2].includes(row.status) ? { content: '编辑', enterable: false } : null + )), + }, + // 执行进度 + progress: { + size: 'small', + title: '', + type: 'primary', + plain: true, + link: true, + icon: 'uil:process', + text: '', + style: { height: '30px' }, + tooltip: { content: '执行进度', enterable: false }, + click: context.openProgress, + }, + // 删除隐藏 + remove: { show: false }, + // 开始 + start: { + size: 'small', + title: '', + type: 'primary', + plain: true, + link: true, + icon: 'akar-icons:play', + text: '', + style: { height: '30px' }, + tooltip: compute(({ row }) => ( + row.status === 1 ? { content: '开始', enterable: false } : null + )), + loading: compute(({ row }) => row.loading), + // 未执行展示 + show: compute(({ row }) => row.status === 1), + order: 1, + click: (scope) => { + scope.row.loading = true; + runJob(scope.row.id, 'start') + .then((msg) => { + ElMessage.success(msg); + expose.doRefresh(); + }) + .catch((err) => { + // 后端业务错误已由请求拦截器提示,这里只提示 Webhook 调用失败 + if (!err?.response) ElMessageBox.alert(err.message, '启动失败', { type: 'error' }); + console.log(`任务开始调用失败: ${err}`); + }) + .finally(() => { + scope.row.loading = false; + }); + }, + }, + // 结束 + stop: { + size: 'small', + title: '', + type: 'danger', + plain: true, + link: true, + icon: 'ph:stop-circle-bold', + text: '', + style: { height: '30px' }, + tooltip: { content: '结束', enterable: false }, + loading: compute(({ row }) => row.loading), + // 仅执行中展示 + show: compute(({ row }) => row.status === 2), + order: 1, + click: (scope) => { + scope.row.loading = true; + customRequest({ + url: '/api/job/action', + method: 'post', + data: { + action: 'stop', + job_id: scope.row.id, + }, + }) + .then((res) => { + if (res.code === 0) { + ElMessage.success(res.msg || '操作成功'); + expose.doRefresh(); + } else { + ElMessage.warning(res.msg); + } + }) + .catch((err) => { + console.log(`任务结束调用失败: ${err}`); + }) + .finally(() => { + scope.row.loading = false; + }); + }, + }, + // 重试 + retry: { + size: 'small', + title: '', + type: 'primary', + plain: true, + link: true, + icon: 'mdi:reload', + text: '', + style: { height: '30px' }, + tooltip: { content: '重试', enterable: false }, + loading: compute(({ row }) => row.loading), + show: true, + order: 1, + click: (scope) => { + ElMessageBox.confirm( + `${scope.row.status === 2 ? '任务运行中,是否需要重试?' : '任务重试,未生成图片的数据继续生成,是否需要执行?'}`, + '提示', + { + confirmButtonText: '确定', + cancelButtonText: '取消', + type: 'warning', + }, + ).then(() => { + scope.row.loading = true; + runJob(scope.row.id, 'retry') + .then((msg) => { + ElMessage.success(msg); + expose.doRefresh(); + }) + .catch((err) => { + if (!err?.response) ElMessageBox.alert(err.message, '重试失败', { type: 'error' }); + console.log(`任务重试调用失败: ${err}`); + }) + .finally(() => { + scope.row.loading = false; + }); + }); + }, + }, + // 结果审核 + audit: { + size: 'small', + title: '', + // type: 'success', + type: 'primary', + link: true, + plain: true, + icon: 'icon-park-outline:audit', + text: '审核', + style: { height: '30px' }, + // tooltip: { content: '结果审核', enterable: false }, + show: true, + order: 1, + click: ({ row }) => { + const currentRouteArr = route.path.split('/').slice(0, -1); + currentRouteArr.push(`image-results?job_id=${row.id}`); + router.push(currentRouteArr.join('/')); + }, + }, + // 缺陷单 + bugs: { + size: 'small', + title: '', + type: 'danger', + plain: true, + link: true, + icon: 'cil:bug', + text: '缺陷', + style: { height: '30px' }, + show: true, + order: 1, + click: ({ row }) => { + const currentRouteArr = route.path.split('/').slice(0, -1); + currentRouteArr.push(`bugs?job_id=${row.id}`); + router.push(currentRouteArr.join('/')); + }, + }, + }, + align: 'center', + width: 260, + }, + table: { + border: false, + lazy: computed(() => dataLen.value > 1), + load: (row, treeNode, resolve) => { + customRequest({ + url: '/api/job/list', + method: 'get', + params: { + project_id: route.meta.value, + id: row.id, + }, + }).then((res) => { + resolve(res.data.list[0].children); + }); + }, + defaultExpandAll: computed(() => dataLen.value === 1), + expandRowKeys: computed(() => (expandSingleKey.value ? [expandSingleKey.value] : undefined)), + // defaultExpandAll: true454 + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '100px', + }, + columns: { + // 时间范围 + times: { + title: '时间', + type: 'daterange', + column: { + show: false, + }, + form: { + component: { + ...dateRangeBind, + clearable: true, + }, + show: false, + }, + search: { + show: computed(() => !route.query.id), + value: [ + dayjs() + .subtract(3, isDevMode() ? 'year' : 'month') + .format('YYYY-MM-DD'), + dayjs().format('YYYY-MM-DD'), + ], + valueResolve({ value, form }) { + // <------注意这里是form,不是row + if (value && value.length === 2) { + form.begin_at = dayjs(value[0]).startOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + form.end_at = dayjs(value[1]).endOf('day') + .format('YYYY-MM-DD HH:mm:ss'); + } + }, + // style: { width: '288px' }, + }, + }, + + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 100, align: 'center' }, + form: { + component: { placeholder: 'ID' }, + }, + search: { + show: computed(() => !route.query.id), + component: { + name: 'el-input', + type: 'number', + }, + }, + }, + + // 名称 + name: { + title: '名称', + type: 'text', + column: { + width: 180, + }, + search: { + show: true, + component: { placeholder: '模糊搜索' }, + }, + }, + // 模块(任务管理页暂未落地任务-模块关联,先隐藏列表列与顶部筛选,仅此页面隐藏,不影响其他页面) + module_ids: { + title: '模块', + type: 'dict-select', + dict: dict({ + url: `/api/project/module/list?project_id=${route.meta.value}&all=1`, + value: 'id', + label: 'show_name', + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get' }); + return data.modules; + }, + }), + column: { show: false, align: 'center' }, + form: { + component: { + multiple: true, + placeholder: '模块', + }, + }, + search: { + show: false, + component: { + multiple: false, + }, + }, + }, + // 区域语言 + languages: { + title: '区域语言', + type: 'dict-select', + dict: getLanguageDict(route.meta.value), + column: { + align: 'center', + width: '200px', + showOverflowTooltip: false, + }, + form: { + component: { + dict: getLanguageDict(route.meta.value, true), + placeholder: '区域语言', + }, + }, + search: { + show: true, + valueResolve(e) { + e.form.language = e.form[e.key]; + }, + }, + }, + // 状态 + status: { + title: '状态', + type: 'dict-select', + search: { show: true }, + dict: context.statusDict, + column: { align: 'center' }, + form: { + component: { placeholder: '状态' }, + }, + }, + + // 进度 + progress_rate: { + title: '进度', + type: 'text', + column: { show: false }, + }, + // 缺陷数 + bug_num: { + title: '缺陷数', + type: 'text', + column: { align: 'right' }, + }, + // 是否回归 + is_parent: { + title: '回归', + type: 'dict-select', + dict: dict({ + data: [ + { label: '否', value: 0 }, + { label: '是', value: 1 }, + ], + }), + column: { show: false }, + search: { + show: true, + value: 0, + component: { + clearable: false, + }, + }, + }, + // 回归任务数 + regress_num: { + title: '回归任务数', + type: 'number', + column: { align: 'right' }, + valueBuilder({ row }) { + // value构建,就是把后台传过来的值转化为前端组件所需要的值 + // 在pageRequest之后执行转化,然后将转化后的数据放到table里面显示 + row.regress_num = row.regress_num || 0; + }, + }, + // 创建人 + creator_id: { + title: '创建人', + type: 'dict-select', + dict: getUserDict(), + column: { + component: { + type: 'text', + }, + }, + search: { + show: true, + component: { + allowCreate: true, + defaultFirstOption: true, + placeholder: '创建人', + }, + }, + }, + + ...timeCols, + + // 版本号 + resource_version: { + title: '版本号', + type: 'text', + column: { show: false }, + }, + // 外部构建(Webhook 返回) + build_id: { + title: '外部构建', + type: 'text', + column: { show: false }, + }, + // 选取的数据 id + data_ids: { + title: '选取的数据 id', + type: 'text', + column: { show: false }, + form: { col: { span: 24 } }, + valueBuilder({ row }) { + // value构建,就是把后台传过来的值转化为前端组件所需要的值 + // 在pageRequest之后执行转化,然后将转化后的数据放到table里面显示 + if (row.type === 'GeneratePictureByVersion') { + row.data_ids = []; + } + }, + }, + // SVN 地址 + svn_url: { + title: 'SVN 地址', + type: 'text', + column: { show: false }, + form: { col: { span: 24 } }, + }, + // SVN 版本号 + svn_version: { + title: 'SVN 版本号', + type: 'text', + column: { show: false }, + form: { col: { span: 24 } }, + }, + + /** 执行信息 */ + infoTable: { + title: '', + form: { + labelWidth: '0px', + col: { span: 24 }, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/index.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/index.vue new file mode 100644 index 0000000000000000000000000000000000000000..d9a1581808460de2eeba82c2fd92eed8b22921e8 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/index.vue @@ -0,0 +1,245 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..c1bd09c199d1f83c39d05a739f5ec8714d08aeed --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/crud.jsx @@ -0,0 +1,442 @@ +import { dict, useCompute } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service.ts'; +// import { cloneDeep, pick } from 'lodash-es'; +import { getBugTypeDict, getLanguageDict } from '@/utils/dict.js'; +import { dateRangeBind } from '@/utils/bind/date.js'; +import dayjs from 'dayjs'; +import createCrudOptions from '@/views/task/runTask/data/crud.jsx'; +import { ref } from 'vue'; + +const basicColumns = ['discern', 'name', 'plan_time', 'languages', 'sign_bug_types', 'ocr_detect']; +const testDataColumn = ['data_ids']; +// 注:当前后端未消费资源配置相关字段(test_app_file_path / test_case_file_path / proj_res_* / trans_res_*), +// 暂时整个「资源配置」分组隐藏。字段定义保留以便后续恢复或兼容老任务数据回显。 +const resourceColumns = []; +const bugColumns = [ + 'bill_bug_types', 'priority', 'severity', 'version_report', 'version_fix', 'release_id', 'current_owner', +]; + +export default function ({ + route, trackerMeta, bugOptions, doRefresh, projectSourceRef, translateResourceRef, +}) { + const { compute } = useCompute(); + const tracker = trackerMeta?.value || { type: 'none' }; + const trackerTitle = tracker.type === 'none' ? '平台内记录' : tracker.label; + + const languageDict = ref(getLanguageDict(route.meta.value)); + const languageDictNoDisable = ref(getLanguageDict(route.meta.value, true)); + // 此处编辑 crudOptions 配置 + return { + pagination: { + show: false, + }, + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + form: { + labelWidth: '110px', + wrapper: { + title: '创建任务', + onOpened(e) { + setTimeout(() => { + e.formRef.formRef.clearValidate(); + }, 500); + }, + }, + beforeValidate: () => { + // 「资源配置」分组已隐藏,对应 ref 可能未挂载,需做空值防御 + // 项目资源校验 + projectSourceRef.value?.validate?.(); + // 译文资源校验 + translateResourceRef.value?.$refs?.form?.validate?.(); + }, + doSubmit: async ({ form }) => { + console.log('=>(crud.jsx:44) formatForm', form); + // 生成参数 + const params = { + project_id: route.meta.value, ...form, + }; + // FIXME + // if (form.dataSource === 'filter') { + // // 条件筛选 + // params = { ...params, ...pick(form, dataSourceColumns) }; + // } else { + // // 选中数据 + // params.data_ids = selectedIds.value; + // } + // if (form.bug_types.length) { + // // 有缺陷类型则有提单配置 + // params = { ...params, ...pick(form, bugColumns) }; + // } + // 执行请求 + const res = await customRequest({ + url: '/api/job/entity', + method: params.id ? 'patch' : 'post', + data: params, + }); + if (res.code === 0) { + ElMessage.success(res.msg || '创建成功'); + languageDict.value = await getLanguageDict(route.meta.value).reloadDict(); + languageDictNoDisable.value = await getLanguageDict(route.meta.value, true); + doRefresh(); + return true; + } + ElMessage.error(res.msg); + return false; + }, + group: { + groupType: 'collapse', // collapse, tabs + accordion: false, + groups: { + basic: { + title: '基础配置', + columns: basicColumns, + }, + test_data: { + title: '测试数据', + columns: testDataColumn, + }, + resource: { + title: '资源配置', + columns: resourceColumns, + }, + submitBugs: { + title: `提单配置(${trackerTitle}${tracker.error ? ',配置有误' : ''})`, + columns: bugColumns, + }, + }, + }, + }, + columns: { + /** 基础配置 */ + // 任务类型 + discern: { + title: '任务类型', + type: 'dict-radio', + form: { + col: { span: 24 }, + value: 1, + }, + dict: dict({ + data: [ + { value: 1, label: '差异识别' }, + { value: 0, label: '全量识别' }, + ], + }), + }, + // 名称 + name: { + title: '名称', + type: 'text', + form: { + component: { placeholder: '请填写任务名' }, + rules: [{ required: true, message: '请填写任务名' }], + }, + }, + // 预约测试时间 + plan_time: { + title: '预约测试时间', + type: 'daterange', + form: { + component: { + ...dateRangeBind, + shortcuts: undefined, + disabledDate(time) { + return dayjs(time).startOf('day') < dayjs().startOf('day'); + }, + clearable: true, + }, + rules: [{ required: true, message: '请选择预约测试时间' }], + valueBuilder(context) { + // 构建时 + if (context.form.plan_start_at && context.form.plan_end_at) { + context.form[context.key] = [context.form.plan_start_at, context.form.plan_end_at]; + } + }, + valueResolve(context) { + // 提交时 + context.form.plan_start_at = context.form[context.key][0]; + context.form.plan_end_at = context.form[context.key][1]; + }, + }, + }, + // 语言 + languages: { + title: '区域语言', + type: 'dict-select', + // dict: getLanguageDict(route.meta.value), + dict: languageDict.value, + form: { + col: { span: 24 }, + component: { + // dict: getLanguageDict(route.meta.value, true), + dict: languageDictNoDisable.value, + multiple: true, placeholder: '请选择区域语言', + }, + rules: [{ required: true, message: '请选择区域语言' }], + }, + }, + // 识别缺陷类型 + sign_bug_types: { + title: '识别缺陷类型', + type: 'dict-select', + dict: getBugTypeDict(route.meta.value), + form: { + col: { span: 24 }, + component: { + multiple: true, + placeholder: '请选择识别缺陷类型', + }, + rules: [{ required: true, message: '请选择识别缺陷类型' }], + }, + }, + // OCR 检测文本位置 + ocr_detect: { + title: '检测文本位置', + type: 'dict-switch', + form: { + value: 0, + helper: '是否需要 OCR 检测文本在文本框内的实际位置', + }, + }, + + /** 测试数据 */ + data_ids: { + title: '数据添加', + search: { show: true }, + type: 'table-select', + dict: dict({ + value: 'id', + label: 'id', + // getNodesByValues: async (values: any[]) => await textTableApi.GetByIds(values), + }), + form: { + col: { span: 24 }, + component: { + select: { + placeholder: '数据添加', + }, + multiple: true, + crossPage: true, + showCurrent: false, // 回显 tag 点击删除有问题,先屏蔽掉 + createCrudOptions: () => createCrudOptions(route.meta.value), + }, + }, + }, + + /** 资源配置 */ + // 测试应用 + test_app_file_path: { + title: '测试应用', + type: 'file-uploader', + form: { + // 「资源配置」整组暂未被后端消费,表单隐藏 + show: false, + component: { + limit: 1, + accept: '.apk,.ipa,.hap,.zip', + }, + valueBuilder(context) { + // 构建时 + if (context.form[context.key]) { + context.form[context.key] = `${import.meta.env.VITE_RESOURCE_API}${context.form[context.key]}`; + } + }, + valueResolve(context) { + // 提交时 + if (context.form[context.key]) { + const regex = new RegExp(`^${import.meta.env.VITE_RESOURCE_API}`); // 创建一个正则表达式,匹配开头的 "hello" + context.form[context.key] = context.form[context.key].replace(regex, ''); + } else { + // 移除文件后值可能为 null/undefined,归一化为空串避免后端 schema 报错 + context.form[context.key] = ''; + } + }, + }, + }, + // 测试用例 + test_case_file_path: { + title: '测试用例', + type: 'file-uploader', + form: { + // 「资源配置」整组暂未被后端消费,表单隐藏 + show: false, + component: { + limit: 1, + accept: '.xlsx', + }, + valueBuilder(context) { + // 构建时 + if (context.form[context.key]) { + context.form[context.key] = `${import.meta.env.VITE_RESOURCE_API}${context.form[context.key]}`; + } + }, + valueResolve(context) { + // 提交时 + if (context.form[context.key]) { + const regex = new RegExp(`^${import.meta.env.VITE_RESOURCE_API}`); // 创建一个正则表达式,匹配开头的 "hello" + context.form[context.key] = context.form[context.key].replace(regex, ''); + } else { + // 移除文件后值可能为 null/undefined,归一化为空串避免后端 schema 报错 + context.form[context.key] = ''; + } + }, + }, + }, + // 项目资源 + project_resource: { + title: '项目资源', + form: { + // 「资源配置」整组暂未被后端消费,表单隐藏 + show: false, + col: { span: 24 }, + valueBuilder(context) { + // 构建时 + const keys = ['proj_res_type', 'proj_res_repo', 'proj_res_br', 'proj_res_ver']; + const temp = {}; + keys.forEach((key) => { + if (context.form[key]) { + temp[key] = context.form[key]; + } + }); + context.form[context.key] = JSON.stringify(temp); + }, + valueResolve(context) { + // 提交时 + const temp = JSON.parse(context.form[context.key] || '{}'); + Object.entries(temp).forEach(([key, value]) => { + context.form[key] = value; + }); + }, + }, + }, + // 译文资源 + translate_resource: { + title: '译文资源', + form: { + // 「资源配置」整组暂未被后端消费,表单隐藏;同时移除必填校验避免按「确定」时被卡住 + show: false, + col: { span: 24 }, + valueBuilder(context) { + // 构建时 + const keys = [ + 'trans_res_type', 'trans_res_repo', 'trans_res_br', 'trans_res_ver', 'trans_res_file_path', + ]; + const temp = {}; + keys.forEach((key) => { + if (context.form[key]) { + if (key === 'trans_res_file_path') { + // 文件数据组装 + temp[key] = [ + { + url: context.form[key], + name: context.form[key].split('/').pop(), + }, + ]; + } else { + temp[key] = context.form[key]; + } + } + }); + context.form[context.key] = JSON.stringify(temp); + }, + valueResolve(context) { + // 提交时 + const temp = JSON.parse(context.form[context.key]); + Object.entries(temp).forEach(([key, value]) => { + context.form[key] = value; + }); + }, + }, + }, + + /** 提单配置 */ + // 缺陷类型 + bill_bug_types: { + title: '缺陷类型', + type: 'dict-select', + dict: getBugTypeDict(route.meta.value), + form: { + component: { + multiple: true, + placeholder: '识别出这些缺陷类型时自动提单,不选则不提单', + }, + }, + }, + // 优先级 + priority: { + title: '优先级', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_priority', + }), + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { placeholder: '优先级' }, + }, + }, + // 严重程度 + severity: { + title: '严重程度', + type: 'dict-select', + dict: dict({ + url: '/api/system/enums/bug_severity', + }), + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { placeholder: '严重程度' }, + }, + }, + // 发现版本 + version_report: { + title: '发现版本', + type: 'dict-select', + dict: dict({ + data: bugOptions.value.version_report || [], + }), + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { placeholder: '发现版本' }, + }, + }, + // 合入版本 + version_fix: { + title: '修复版本', + type: 'dict-select', + dict: dict({ + data: bugOptions.value.version_fix || [], + }), + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { placeholder: '修复版本' }, + }, + }, + // 发布计划 + // release_id_value: { + release_id: { + title: '发布计划', + type: 'dict-select', + dict: dict({ + data: bugOptions.value.release_id || [], + }), + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { placeholder: '发布计划' }, + }, + }, + // 处理人 + current_owner: { + title: '处理人', + type: 'text', + form: { + show: compute(({ form }) => !!form.bill_bug_types.length), + component: { + name:
根据配置自动生成
, + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..54b3e1cc2b9619584bcd3e7f03bebb8488d69080 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/crud.jsx @@ -0,0 +1,87 @@ +import { dict } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { getCommonCols } from '@/views/data/common.jsx'; +import { shallowRef } from 'vue'; +import numberRange from '@/components/numberRange.vue'; + +export default function (projectId) { + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/api/data/list', + method: 'get', + params: { + project_id: projectId, + ...params, + id: params.id || undefined, + job_id: params.job_id || undefined, + }, + }); + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + }, + pagination: { + pageSize: 10, // 默认pageSize + }, + actionbar: { + buttons: { + add: { + show: false, + }, + }, + }, + table: { + showOverflowTooltip: false, + border: false, + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '100px', + }, + rowHandle: { + show: false, + }, + columns: { + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 100, align: 'right' }, + form: { + component: { placeholder: 'ID' }, + }, + search: { + show: true, + value: ['', ''], + component: { + name: shallowRef(numberRange), + }, + valueResolve(e) { + e.form.pk__gte = (e.form[e.key] || [])[0] ? e.form[e.key][0] : undefined; + e.form.pk__lte = (e.form[e.key] || [])[1] ? e.form[e.key][1] : undefined; + e.form[e.key] = undefined; + }, + }, + }, + + ...getCommonCols( + projectId, + dict({ + url: '/api/data/resource_version/list', + cache: false, + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get', params: { project_id: projectId } }); + return data.list.map(item => ({ label: item, value: item })); + }, + }), + ), + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/dialog.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/dialog.vue new file mode 100644 index 0000000000000000000000000000000000000000..6ea005d6628ad2d8968b11d463ebae5500a7432d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/data/dialog.vue @@ -0,0 +1,56 @@ + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/info.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/info.vue new file mode 100644 index 0000000000000000000000000000000000000000..f603fa1db4f1c357f024798fb9ba97d2b6e6f0e3 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/info.vue @@ -0,0 +1,85 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/projectResource.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/projectResource.vue new file mode 100644 index 0000000000000000000000000000000000000000..a27a28f86f37bd639db213d4a3b2fc8842e374b0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/projectResource.vue @@ -0,0 +1,91 @@ + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/translateResource.vue b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/translateResource.vue new file mode 100644 index 0000000000000000000000000000000000000000..2d42929dce2e0ac900083e1322e01ef18ba14fbd --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runTask/translateResource.vue @@ -0,0 +1,166 @@ + + + + + + diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..ba0a4b392e6f6a88fdc4c4dab3587c778462a831 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/crud.jsx @@ -0,0 +1,97 @@ +import { dict } from '@fast-crud/fast-crud'; +import { ElMessage } from 'element-plus'; +import { customRequest } from '@/utils/service.ts'; +import createCrudOptions from './data/crud.jsx'; +import { ref } from 'vue'; +import { getLanguageDict } from '@/utils/dict.js'; + +export default function ({ + route, selectedLanguages, selectedDataIds, doRefresh, +}) { + const submitDisabled = ref(false); + // 此处编辑 crudOptions 配置 + return { + table: { + border: false, + // defaultSort: {prop: 'create_time', order: 'descending'} + }, + search: { + show: false, + }, + form: { + watch({ form }) { + submitDisabled.value = !Object.values(form).some(item => item.length); + }, + wrapper: { + buttons: { + ok: { + disabled: submitDisabled, + }, + }, + }, + doSubmit: async ({ form }) => { + const res = await customRequest({ + url: '/api/job/entity', + method: 'patch', + data: { + ...form, + languages: [...form.languages, ...selectedLanguages], + data_ids: [...form.data_ids, ...selectedDataIds], + }, + }); + if (res.code === 0) { + ElMessage.success(res.msg || '追加成功'); + doRefresh(); + return true; + } + ElMessage.error(res.msg); + return false; + }, + }, + columns: { + // 语言 + languages: { + title: '区域语言', + type: 'dict-select', + dict: getLanguageDict(route.meta.value, true), + form: { + col: { span: 24 }, + component: { + multiple: true, + onDictChange: ({ dict }) => { + (dict.data || []).forEach((item) => { + if (selectedLanguages.includes(item.value)) { + item.disabled = true; + } + }); + }, + placeholder: '区域语言', + }, + }, + }, + // 测试数据 + data_ids: { + title: '数据添加', + search: { show: true }, + type: 'table-select', + dict: dict({ + value: 'id', + label: 'id', + // getNodesByValues: async (values: any[]) => await textTableApi.GetByIds(values), + }), + form: { + col: { span: 24 }, + component: { + select: { + placeholder: '数据添加', + }, + multiple: true, + crossPage: true, + showCurrent: false, // 回显 tag 点击删除有问题,先屏蔽掉 + createCrudOptions: () => createCrudOptions(route.meta.value, selectedDataIds), + }, + }, + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/data/crud.jsx b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/data/crud.jsx new file mode 100644 index 0000000000000000000000000000000000000000..ab6dda0222eca2bd555fee519e4b2e418a10f26b --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/src/views/task/runningAdd/data/crud.jsx @@ -0,0 +1,92 @@ +import { dict } from '@fast-crud/fast-crud'; +import { customRequest } from '@/utils/service.ts'; +import { getCommonCols } from '@/views/data/common.jsx'; +import { shallowRef } from 'vue'; +import numberRange from '@/components/numberRange.vue'; + +export default function (projectId, selectedIds) { + // @ts-ignore + const pageRequest = async params => await customRequest({ + url: '/api/data/list', + method: 'get', + params: { + project_id: projectId, + ...params, + id: params.id || undefined, + job_id: params.job_id || undefined, + }, + }); + + // 此处编辑 crudOptions 配置 + return { + crudOptions: { + request: { + pageRequest, + }, + pagination: { + pageSize: 10, // 默认pageSize + }, + actionbar: { + buttons: { + add: { + show: false, + }, + }, + }, + table: { + showOverflowTooltip: false, + border: false, + }, + form: { + // 具体可配置请参考 grid 布局: http://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html + // display: 'grid', + labelWidth: '100px', + }, + rowHandle: { + show: false, + }, + columns: { + $checked: { + column: { + selectable: row => !(selectedIds || []).includes(row.id), + }, + }, + // ID + id: { + title: 'ID', + type: 'number', + column: { width: 100, align: 'right' }, + form: { + component: { placeholder: 'ID' }, + }, + search: { + show: true, + value: ['', ''], + component: { + name: shallowRef(numberRange), + }, + valueResolve(e) { + e.form.pk__gte = (e.form[e.key] || [])[0] ? e.form[e.key][0] : undefined; + e.form.pk__lte = (e.form[e.key] || [])[1] ? e.form[e.key][1] : undefined; + e.form[e.key] = undefined; + }, + }, + }, + + ...getCommonCols( + projectId, + dict({ + url: '/api/data/resource_version/list', + cache: false, + async getData({ url }) { + // 获取字典请求 + // @ts-ignore + const { data } = await customRequest({ url, method: 'get', params: { project_id: projectId } }); + return data.list.map(item => ({ label: item, value: item })); + }, + }), + ), + }, + }, + }; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/tests/components/Notify.test.ts b/timi_hok_game_translator/LQA_WMP/web/tests/components/Notify.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fbcc98d47560dcbaeb6347140b086b342e1be901 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/tests/components/Notify.test.ts @@ -0,0 +1,34 @@ +import { shallowMount } from '@vue/test-utils'; +import { describe, expect, it } from 'vitest'; +import Notify from '@/components/Notify/index.vue'; +import NotifyList from '@/components/Notify/NotifyList.vue'; + +describe('Notify', () => { + it('正常渲染', () => { + const wrapper = shallowMount(Notify); + expect(wrapper.classes('notify')).toBe(true); + }); +}); + +describe('NotifyList', () => { + it('List 长度为 0', () => { + const wrapper = shallowMount(NotifyList, { + props: { + list: [], + }, + }); + expect(wrapper.find('el-empty').exists()).toBe(true); + }); + it('List 长度不为 0', () => { + const wrapper = shallowMount(NotifyList, { + props: { + list: [ + { + title: '', + }, + ], + }, + }); + expect(wrapper.find('el-empty').exists()).toBe(false); + }); +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/tests/demo.test.ts b/timi_hok_game_translator/LQA_WMP/web/tests/demo.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..66769fba4cb389bc40315e956206671e951514c7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/tests/demo.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; + +/** + * @description 该文件所有示例均是为了向你演示 Vitest 最基本的用法 + * @link https://cn.vitest.dev/api + * @api describe: 形成一个作用域 + * @api test/it: 定义了一组关于测试期望的方法,它接收测试名称和一个含有测试期望的函数 + * @api expect: 用来创建断言 + * @api toBe: 可以用于断言原始类型是否相等,或者对象是否共享相同的引用 + * @api toEqual: 断言实际值是否等于接收到的值或具有相同的结构(如果是对象,则递归比较它们) + */ + +const author1 = { + name: 'demo-user', + email: 'demo@example.com', + url: 'https://example.com', +}; + +const author2 = { + name: 'demo-user', + email: 'demo@example.com', + url: 'https://example.com', +}; + +describe('这里填写作用域名称', () => { + it('测试基础数据类型', () => { + expect(1 + 1).toBe(2); + }); + it('测试引用类型', () => { + expect(author1).toEqual(author2); + }); +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/tests/utils/validate.test.ts b/timi_hok_game_translator/LQA_WMP/web/tests/utils/validate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6237633336521092bce0afcc6922dde1180ff06 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/tests/utils/validate.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { isArray } from '@/utils/validate'; + +describe('isArray', () => { + it('String', () => { + expect(isArray('')).toBe(false); + }); + it('Number', () => { + expect(isArray(1)).toBe(false); + }); + it('Boolean', () => { + expect(isArray(true)).toBe(false); + }); + it('Null', () => { + expect(isArray(null)).toBe(false); + }); + it('Undefined', () => { + expect(isArray(undefined)).toBe(false); + }); + it('Symbol', () => { + expect(isArray(Symbol())).toBe(false); + }); + it('BigInt', () => { + expect(isArray(BigInt(1))).toBe(false); + }); + it('Object', () => { + expect(isArray({})).toBe(false); + }); + it('Array Object', () => { + expect(isArray([])).toBe(true); + }); +}); diff --git a/timi_hok_game_translator/LQA_WMP/web/tsconfig.json b/timi_hok_game_translator/LQA_WMP/web/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..238f217f56680b55ad14b54441d586158b7428b7 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + "target": "esnext", + /** https://cn.vitejs.dev/guide/features.html#typescript-compiler-options */ + "useDefineForClassFields": true, + "module": "esnext", + "moduleResolution": "bundler", + /** TS 严格模式 */ + "strict": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "importHelpers": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "sourceMap": true, + "resolveJsonModule": true, + /** https://cn.vitejs.dev/guide/features.html#typescript-compiler-options */ + "isolatedModules": true, + "esModuleInterop": true, + "lib": ["esnext", "dom"], + "skipLibCheck": true, + "types": [ + "node", + "vite/client", + /** Element Plus 的 Volar 插件支持 */ + "element-plus/global", + "vitest" + ], + /** baseUrl 用来告诉编译器到哪里去查找模块,使用非相对模块时必须配置此项 */ + "baseUrl": ".", + /** 非相对模块导入的路径映射配置,根据 baseUrl 配置进行路径计算 */ + "paths": { + "@/*": ["src/*"] + } + }, + "include": [ + "src/**/*.ts", + "src/**/*.d.ts", + "src/**/*.tsx", + "src/**/*.vue", + "tests/**/*.ts", + "types/**/*.d.ts", + "vite.config.ts", + "vitest.config.ts", + "node_modules/.pnpm/preact@10.20.2/node_modules/preact/src/internal.d.ts", + ], + /** 编译器默认排除的编译文件 */ + "exclude": ["node_modules", "dist"] +} diff --git a/timi_hok_game_translator/LQA_WMP/web/types/api.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ab5c240521bc8a7106b16efc684941b2d04219f --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/api.d.ts @@ -0,0 +1,6 @@ +/** 所有 api 接口的响应数据都应该准守该格式 */ +interface ApiResponseData { + code: number + data: T + message: string +} diff --git a/timi_hok_game_translator/LQA_WMP/web/types/common.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5b207019909a0dbb598c5f7f293df2da005f5ca --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/common.d.ts @@ -0,0 +1,9 @@ +declare type LabelValueOptions = { + label: string; + value: any; + [key: string]: string | number | boolean | any[]; +}[]; + +declare type ObjType = { + [key: string]: any[]; +}[]; diff --git a/timi_hok_game_translator/LQA_WMP/web/types/env.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..085362749c00551d5bdde5362827d1e4414a20c2 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/env.d.ts @@ -0,0 +1,14 @@ +/** 声明 vite 环境变量的类型(如果未声明则默认是 any) */ +interface ImportMetaEnv { + readonly VITE_APP_TITLE: string + readonly VITE_BASE_API: string + readonly VITE_ROUTER_HISTORY: 'hash' | 'html5' + readonly VITE_PUBLIC_PATH: string + readonly VITE_PROXY_TARGET?: string + readonly VITE_ADMIN_CONTACT?: string + readonly VITE_RESOURCE_API: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} diff --git a/timi_hok_game_translator/LQA_WMP/web/types/global-components.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/global-components.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e136b718f879859faceb5c2331a49a3e14282de --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/global-components.d.ts @@ -0,0 +1,10 @@ +import SvgIcon from '@/components/SvgIcon/index.vue'; + +/** 由 app.component 全局注册的组件需要在这里声明 TS 类型才能获得 Volar 插件提供的类型提示) */ +declare module 'vue' { + export interface GlobalComponents { + SvgIcon: typeof SvgIcon + } +} + +export {}; diff --git a/timi_hok_game_translator/LQA_WMP/web/types/shims-vue.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/shims-vue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..72b47ccdc846033a4f952d16d2efe26e2dc83f0d --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/shims-vue.d.ts @@ -0,0 +1,4 @@ +declare module '*.scss' { + const scss: Record; + export default scss; +} diff --git a/timi_hok_game_translator/LQA_WMP/web/types/vue-router.d.ts b/timi_hok_game_translator/LQA_WMP/web/types/vue-router.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..550846eb27f7090f3e62cfd622abbfb6da793bde --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/types/vue-router.d.ts @@ -0,0 +1,52 @@ +import 'vue-router'; + +declare module 'vue-router' { + interface RouteMeta { + /** + * 设置该路由在侧边栏和面包屑中展示的名字 + */ + title?: string + /** + * 设置该路由的图标,记得将 svg 导入 @/icons/svg + */ + svgIcon?: string + /** + * 设置该路由的图标,直接使用 Element Plus 的 Icon(与 svgIcon 同时设置时,svgIcon 将优先生效) + */ + elIcon?: string + /** + * 默认 false,设置 true 的时候该路由不会在侧边栏出现 + */ + hidden?: boolean + /** + * 设置能进入该路由的角色,支持多个角色叠加 + */ + roles?: string[] + /** + * 默认 true,如果设置为 false,则不会在面包屑中显示 + */ + breadcrumb?: boolean + /** + * 默认 false,如果设置为 true,它则会固定在 tags-view 中 + */ + affix?: boolean + /** + * 当一个路由下面的 children 声明的路由大于 1 个时,自动会变成嵌套的模式, + * 只有一个时,会将那个子路由当做根路由显示在侧边栏, + * 若想不管路由下面的 children 声明的个数都显示你的根路由, + * 可以设置 alwaysShow: true,这样就会忽略之前定义的规则,一直显示根路由 + */ + alwaysShow?: boolean + /** + * 示例: activeMenu: "/xxx/xxx", + * 当设置了该属性进入路由时,则会高亮 activeMenu 属性对应的侧边栏。 + * 该属性适合使用在有 hidden: true 属性的路由上 + */ + activeMenu?: string + /** + * 是否缓存该路由页面 + * 默认为 false,为 true 时代表需要缓存,此时该路由和该页面都需要设置一致的 Name + */ + keepAlive?: boolean + } +} diff --git a/timi_hok_game_translator/LQA_WMP/web/unocss.config.ts b/timi_hok_game_translator/LQA_WMP/web/unocss.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5a561ac5109a7f3227c7668afee5126a903ecb4 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/unocss.config.ts @@ -0,0 +1,20 @@ +import { defineConfig, presetAttributify, presetUno } from "unocss" + +export default defineConfig({ + /** 预设 */ + presets: [ + /** 属性化模式 & 无值的属性模式 */ + presetAttributify(), + /** 默认预设 */ + presetUno() + ], + /** 自定义规则 */ + rules: [["uno-padding-20", { padding: "20px" }]], + /** 自定义快捷方式 */ + shortcuts: { + "uno-wh-full": "w-full h-full", + "uno-flex-center": "flex justify-center items-center", + "uno-flex-x-center": "flex justify-center", + "uno-flex-y-center": "flex items-center" + } +}) diff --git a/timi_hok_game_translator/LQA_WMP/web/vite.config.ts b/timi_hok_game_translator/LQA_WMP/web/vite.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..07d4e31c156d47bb119c5f05abf9a126627ed520 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/vite.config.ts @@ -0,0 +1,115 @@ +/// + +import { type ConfigEnv, type UserConfigExport, loadEnv } from 'vite'; +import path, { resolve } from 'path'; +import vue from '@vitejs/plugin-vue'; +import vueJsx from '@vitejs/plugin-vue-jsx'; +import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'; +import viteCompression from 'vite-plugin-compression'; +import svgLoader from 'vite-svg-loader'; +import UnoCSS from 'unocss/vite'; + +/** 配置项文档:https://cn.vitejs.dev/config */ +export default ({ mode }: ConfigEnv): UserConfigExport => { + const viteEnv = loadEnv(mode, process.cwd()) as ImportMetaEnv; + const { VITE_PUBLIC_PATH, VITE_PROXY_TARGET } = viteEnv; + return { + /** 打包时根据实际情况修改 base */ + base: VITE_PUBLIC_PATH, + resolve: { + alias: { + /** @ 符号指向 src 目录 */ + '@': resolve(__dirname, './src'), + }, + }, + server: { + /** 设置 host: true 才可以使用 Network 的形式,以 IP 访问项目 */ + host: true, // host: "0.0.0.0" + /** 端口号 */ + port: 3333, + /** 是否自动打开浏览器 */ + open: false, + /** 跨域设置允许 */ + cors: true, + /** 端口被占用时,是否直接退出 */ + strictPort: false, + /** 接口代理 */ + proxy: { + // 后端接口:/api-pro/api/xxx -> {VITE_PROXY_TARGET}/api/xxx + '/api-pro/': { + target: VITE_PROXY_TARGET || 'http://127.0.0.1:8000/', + ws: true, + rewrite: path => path.replace('/api-pro/', ''), + /** 是否允许跨域 */ + changeOrigin: true, + }, + }, + /** 预热常用文件,提高初始页面加载速度 */ + warmup: { + clientFiles: ['./src/layouts/**/*.vue'], + }, + }, + build: { + /** 单个 chunk 文件的大小超过 2048KB 时发出警告 */ + chunkSizeWarningLimit: 2048, + /** 禁用 gzip 压缩大小报告 */ + reportCompressedSize: false, + /** 打包后静态资源目录 */ + assetsDir: 'static', + rollupOptions: { + output: { + /** + * 分块策略 + * 1. 注意这些包名必须存在,否则打包会报错 + * 2. 如果你不想自定义 chunk 分割策略,可以直接移除这段配置 + */ + manualChunks: { + vue: ['vue', 'vue-router', 'pinia'], + element: ['element-plus', '@element-plus/icons-vue'], + vxe: ['vxe-table', 'vxe-table-plugin-element', 'xe-utils'], + }, + }, + }, + }, + /** 混淆器 */ + esbuild: + mode === 'development' + ? undefined + : { + /** 打包时移除 console.log */ + pure: ['console.log'], + /** 打包时移除 debugger */ + drop: ['debugger'], + /** 打包时移除所有注释 */ + legalComments: 'none', + }, + /** Vite 插件 */ + plugins: [ + vue(), + vueJsx(), + /** 将 SVG 静态图转化为 Vue 组件 */ + svgLoader({ defaultImport: 'url' }), + /** SVG */ + createSvgIconsPlugin({ + iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')], + symbolId: 'icon-[dir]-[name]', + }), + /** UnoCSS */ + UnoCSS(), + // gzip 压缩 + viteCompression({ + // 可选配置 + verbose: true, // 是否在控制台输出压缩结果 + disable: false, // 是否禁用压缩 + threshold: 10240, // 只处理大于此大小的资源(单位:字节) + algorithm: 'gzip', // 使用 gzip 压缩 + ext: '.gz', // 文件扩展名 + }), + ], + /** Vitest 单元测试配置:https://cn.vitest.dev/config */ + test: { + include: ['tests/**/*.test.ts'], + environment: 'jsdom', + }, + }; +}; diff --git a/timi_hok_game_translator/LQA_WMP/web/vue.code-snippets b/timi_hok_game_translator/LQA_WMP/web/vue.code-snippets new file mode 100644 index 0000000000000000000000000000000000000000..e0a2e4b33e4ef44ab4ea404153feb00995e3afd0 --- /dev/null +++ b/timi_hok_game_translator/LQA_WMP/web/vue.code-snippets @@ -0,0 +1,14 @@ +{ + "Vue3 SFC 代码结构一键生成": { + "prefix": "Vue3 SFC", + "body": [ + "\n", + "\n", + "", + "$1" + ], + "description": "Vue3 SFC" + } +} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/.gitignore b/timi_hok_game_translator/TiMi_HOK_Game_Translator/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..aa142cbaa740286d2e1768c0fbded275c9d26e94 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/.gitignore @@ -0,0 +1,92 @@ +# ---- Python ---- +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# ---- Virtual environments ---- +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# ---- Testing / Coverage ---- +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +htmlcov/ + +# ---- Type checkers ---- +.mypy_cache/ +.dmypy.json +dmypy.json +.pyre/ +.pytype/ + +# ---- IDE ---- +.idea/ +.vscode/ +*.iml +*.swp +*.swo +.DS_Store +Thumbs.db + +# ---- Project runtime artifacts ---- +logs/ +*.log +data/ +!docs/examples/data/ +workspace/ +*.local.yaml +*.local.yml + +# ---- Business assets that must never ship ---- +utils/dtxml_data/ +docs/*.xlsx +docs/*.docx +scripts/*.xlsx +scripts/*.docx +*.dtxml +!docs/examples/data/**/*.dtxml +*.xliff +!docs/examples/data/**/*.xliff + +# ---- MkDocs ---- +site/ + +# ---- Compiled translations ---- +*.mo +*.pot + +# ---- Internal / local-only archive (credentials, bench results, private notes) ---- +archive_internal/ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/README.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00fea09725e9a273f5209dcec5daa020304db79d --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/README.md @@ -0,0 +1,277 @@ +

TiMiHOKGameTranslator

+ +

+ 面向游戏出海的工业级本地化自动化流水线
+ Bridge your game to the world — automated, auditable, extensible. +

+ +

+ Python 3.8+ + Architecture + License +

+ +

+ 拉取源文 → AI 预翻译 → 多轮审校 → 合并回写 → 提交发布 → 通知 +

+ +--- + +## 🎯 Why TiMiHOKGameTranslator? + +游戏本地化不是"调一次 ChatGPT 就能发版"的事。**TiMiHOKGameTranslator** 专门为中国游戏厂商 +出海场景打造,解决传统方案无法覆盖的真实痛点: + +- 🏭 **工业级 ≠ 玩具** —— 支持**断点续跑**、**跨天尾巴任务续审**、**线程安全持久化**, + 一次性跑完一周的增量翻译且崩溃可恢复,不是"run 一次 translate 一次"的脚手架; +- 🔀 **双平台双轮审校** —— 一审 Phrase、二审 Crowdin 可以同时跑,所有已审 approved + 精准路由到"该走的下一个阶段",而不是无差别回炉; +- 🎮 **游戏场景原生** —— 内置术语注入、兄弟行广播(同源文一译多扩散)、 + TM 回灌、小语种两步枢纽翻译(中→英→目标),针对游戏文案痛点深度优化; +- 🔌 **真·可插拔** —— VCS(svn/git/perforce)、源文件格式(6+ 种)、LLM、翻译平台、 + 通知渠道,每个层都是**协议 + 工厂 + 装饰器注册**三件套,加新后端零改框架; +- 📝 **YAML-first 配置** —— 新增语种、切换策略、调整审校流程全部走 YAML, + 运维/测试同学无需碰代码。 + +## 👥 适合谁 / 不适合谁 + +| ✅ 适合 | ❌ 不适合 | +|---|---| +| 多语种游戏(10+ locales)的持续迭代本地化 | 一次性翻译一份 README 的小需求(用 ChatGPT 更快)| +| 已有 Phrase/Crowdin 等平台但想接 AI 预译的团队 | 对翻译质量零容忍且不愿人工审校的场景 | +| 需要 TM 积累 + 增量翻译 + 跨天审校的生产流水线 | 没有 VCS、也不走审校的个人 side-project | +| 要在 SVN/Git/Perforce 多仓协同的大型项目 | 完全离线、无 LLM API 预算的场景(可用 mock 跑通但无实际翻译)| + +## 🔧 平台支持矩阵 + +| 层 | 内置实现 | 可扩展 | +|---|---|---| +| **VCS** | `svn` / `git` / `perforce` / `mock` | ✅ 继承 `VcsClient` | +| **源文件格式** | `json` / `yaml` / `xml` / `csv` / `dtxml` / `xliff` / `xlsx` | ✅ `@register_source("myfmt")` | +| **LLM 提供方** | `mock`(零依赖)/ `openai` / `openai_compatible` / `anthropic` / `venus` / `hunyuan_translation` | ✅ 实现 `LLMClient` 协议 | +| **翻译平台** | **Phrase TMS**(原 Memsource)/ **Crowdin API v2** / `none` | ✅ `@register_platform("myp")` | +| **翻译策略** | `generic`(直译)/ `two_step`(枢纽翻译)| ✅ `@register_translation_strategy("vi")` | +| **通知渠道** | `console` / `webhook` | ✅ 实现 `Notifier` 协议 | + +--- + +## 🚀 快速开始(1 分钟 mock demo) + +跑通一个**零依赖、零凭据**的 demo,验证安装无误: + +```bash +# 1. 克隆 + 进入项目目录 +git clone https://github.com//TiMi_HOK_Game_Translator.git +cd TiMi_HOK_Game_Translator + +# 2. 创建虚拟环境(要求 Python 3.8+) +python -m venv .venv +# Linux / macOS:source .venv/bin/activate +# Windows PowerShell:.venv\Scripts\Activate.ps1 + +# 3. 安装依赖 +pip install -r requirements.txt + +# 4. 跑一个全 mock 的 demo(不需要任何外部服务) +python main.py run --config docs/examples/demo.yaml + +# 5. 查看最终生效配置(敏感字段自动脱敏为 ***) +python main.py config dump --config docs/examples/demo.yaml +``` + +> 💡 跑过一次想从头再来:加 `--fresh` +> 续跑指定批次:`--batch `(与 `--fresh` 互斥) + +完整的 demo 教程见 [`docs/quickstart.md`](./docs/quickstart.md)。 + +--- + +## 🧭 真实项目接入 5 步 + +跑通 mock demo 后,接入自己的真实项目按以下 5 步落地。每一步都给了跳转链接, +**全程不改一行代码**。 + +### Step 1 · 准备源文件(增量 / 全量) + +支持 **xlsx / json / yaml / xml / csv / xliff / dtxml** 7 种格式,统一映射到 `Entry`。 + +- 📁 把增量文件放到 VCS 工作副本的 `fixtures//99.incr.`; +- 📖 完整字段 schema 和每种格式的示例:→ [配置详解 源文件格式](./docs/configuration.md#4-源文件格式source参考) +- 💡 不确定选哪种格式?游戏项目**强烈推荐 xlsx**(审校员最熟 + 支持 EnTerms/Terms 术语列)。 + +### Step 2 · 接入 VCS + +改 `conf/config.yaml` 的 `vcs` 块,支持 `svn` / `git` / `perforce` / `mock`。 + +- 📖 四种后端的完整示例:→ [配置详解 VCS 配置示例](./docs/configuration.md#12-vcs--版本控制) +- 🔒 **凭据走环境变量**:`GAME_TRANS_TOOLCHAIN__VCS__USERNAME` / `GAME_TRANS_TOOLCHAIN__VCS__PASSWORD`,严禁明文提交。 + +### Step 3 · 配置 LLM 模型 + +在 `conf/llm.yaml` 的 `profiles` 下**按名字**注册一个 profile,然后在 `conf/config.yaml` +或 `conf/languages/.yaml` 用 `llm_profile: ` 引用它。 + +- 📖 字段逐项 + extra 键说明:→ [配置详解 llm.yaml](./docs/configuration.md#2-confllmyaml--llm-profile-注册表) +- 🔒 **API Key 走环境变量**:`GAME_TRANS_TOOLCHAIN__LLM__API_KEY` +- 🧪 零预算调试:profile 用 `provider: mock` 即可,不发一次网络请求。 + +### Step 4 · 配置审校平台 Token + +在 `conf/languages/.yaml` 的 `reviews.first` / `reviews.second` 分别选平台, +一审 Phrase + 二审 Crowdin 可以**同时跑**。 + +- 📖 一审 / 二审解耦机制:→ [配置详解](./docs/configuration.md#6-为什么-platform-不区分一审--二审) +- 📖 Phrase 鉴权 / 字段 / 排错:→ [Phrase 平台专项](./docs/platforms/phrase.md) +- 🔒 常用环境变量: + - `GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN` —— Crowdin / Phrase ApiToken 模式 + - `GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN` —— Phrase 推荐的 Subject Token 模式 + +### Step 5 · 启用翻译记忆库(TM)回灌(可选) + +在语种 profile 的 `workflow` 列表里加入 `update_tm` / `update_grn_tm`, +工作流会**在正式审校前**把历史 approved 自动灌回审校平台的默认 TM 库。 + +- 🧭 **TM 本身请直接在审校平台(Phrase / Crowdin)后台创建并绑定到项目**, + 框架只负责把历史 approved 以 `(source, target)` 形式回灌到项目默认 TM。 +- ✅ 默认 Phrase 内置支持;Crowdin / 自定义平台不实现 `upload_tm` 时**自动跳过**, + 不阻塞主流程。 +- 💤 不想做 TM 回灌?从 `workflow` 列表里删掉这两个状态即可。 + +### 跑起来 + +```bash +python main.py run --language vi +``` + +想一步到位理解全部字段,直接看 [`docs/getting_started.md`](./docs/getting_started.md) 的 +"一张清单接入一个语种"章节。 + +--- + +## 🎯 翻译策略选择指南 + +本框架支持**三级优先**的策略绑定:**YAML 配置 → 装饰器 → Generic 兜底**。 +推荐使用 YAML 方式,运维/测试同学无需改代码即可切换策略。 + +### 一、内置策略类 + +| 短名 | 行为 | 用到的术语列 | 适用场景 | +|---|---|---|---| +| `GenericTranslationStrategy`
或 `generic` | **一步直译**(中 → 目标) | `Terms` | 中文到目标语种模型效果稳定的语种(vi/th/id/ja 等) | +| `TwoStepTranslationStrategy`
或 `two_step` | **两步枢纽**(中 → 英 → 目标) | `EnTerms` + `Terms` | 直译效果不稳定的小语种(de/fr/ru/tr/ar/es/pt-BR 等);
Step 1 注入 EnTerms,Step 2 用两列做 inner-join 后以"英→目标"术语对注入 | + +### 二、三种配置方式(优先级从高到低) + +**方式一(推荐):YAML 声明式** + +在 `conf/languages/.yaml` 的 `strategy_config` 加一行: + +```yaml +strategy_config: + class: TwoStepTranslationStrategy # 短名;或完整 import 路径 + pivot_locale: en # 两步策略专属:中转语种,默认 en + display_name: 越南语翻译 +``` + +想回退一步直译?注释掉 `class:` 这一行即可。 + +**方式二:代码装饰器注册** + +适合策略类需要重写 `filter` / `post_translate` 等方法的深度定制场景: + +```python +# src/TiMi_HOK_Game_Translator/strategies/my_strategy.py +from TiMi_HOK_Game_Translator.translation.factory import register_translation_strategy +from TiMi_HOK_Game_Translator.strategies.minor_language_strategy import TwoStepTranslationStrategy + + +@register_translation_strategy("ru") +class RussianStrategy(TwoStepTranslationStrategy): + display_name = "Russian" + # ... 自定义 filter / translate 等 +``` + +**方式三:第三方包 import 路径** + +`class` 带 `.` 时,走 `importlib` 动态加载,不碰框架代码: + +```yaml +strategy_config: + class: my_company.strategies.RussianDialectStrategy +``` + +### 三、术语列(EnTerms / Terms)填法 + +增量 xlsx 的两列术语单元格内,每行一个 `源文=译文`,Alt+Enter 换行分隔: + +``` +艾薇塔=Evita +护盾=shield +噬源兽=Essence Devourer +``` + +- **一步策略**:只读 `Terms` 列(中→目标语术语),`EnTerms` 可留空; +- **两步策略**:两列都读,Step 2 会把 EnTerms/Terms 按中文源文做 inner-join + 映射为"英→目标语"术语对注入,命中率比直接用"中→目标"更高。 + +### 四、运行时日志自检 + +工厂首次创建策略时会打 INFO 日志,便于确认实际用的是哪个类: + +``` +[INFO] Translation strategy for 'vi' resolved via YAML strategy_config.class → TwoStepTranslationStrategy +``` + +错配置(如写错短名)不会炸——会打 WARNING 并降级到装饰器或 Generic: + +``` +[WARN] strategy_config.class='TwoStep' is not a known builtin short name + (available: ['GenericTranslationStrategy', 'TwoStepTranslationStrategy', + 'generic', 'two_step']); falling back to decorator registry +``` + +## 🧩 架构总览 + +``` +┌───────────────┐ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ +│ ingest │──▶│ translate │──▶│ review │──▶│ merge │ +│ (VCS + 源) │ │ (LLMClient)│ │ (Platform) │ │ (Source.dump)│ +└───────────────┘ └───────────────┘ └───────────────┘ └───────┬───────┘ + ▼ + ┌───────────────┐ + │ publish │ + │ (VCS 提交 │ + │ + 通知) │ + └───────────────┘ +``` + +完整架构见 [`docs/architecture.md`](./docs/architecture.md)。 + +## 📚 文档 + +**入门** +- [快速开始(JSON demo)](./docs/quickstart.md) · 5 分钟端到端跑通 +- [完整入门指南](./docs/getting_started.md) · 详细教程,涵盖所有配置项 +- [架构总览](./docs/architecture.md) · 核心抽象 + 分层设计 + +**配置参考** +- [配置详解](./docs/configuration.md) · `config.yaml` / `llm.yaml` / `languages/*.yaml` 字段逐项说明,含源文件格式参考 +- [状态机状态表](./docs/state_registry.md) · 所有工作流状态一览 + +**扩展指南** +- [扩展 VCS 后端](./docs/extending_vcs.md) · 接入自定义版本控制系统 +- [扩展源文件格式](./docs/extending_sources.md) · 新增 Properties/.resx 等格式 +- [扩展 LLM 提供方](./docs/extending_llm.md) · 对接内网/私有大模型 +- [扩展翻译平台](./docs/extending_platforms.md) · 接入新的 TMS +- [扩展翻译策略](./docs/extending_translation.md) · 自定义语种专属翻译逻辑 + +**运维参考** +- [Phrase TMS 平台专项](./docs/platforms/phrase.md) · 鉴权 / 字段 / 排错 +- [E2E 测试指南](./docs/e2e_test_guide.md) · 完整联调手册 +- [常见问题 FAQ](./docs/faq.md) + +--- + +

+ Built with ❤️ for game localization teams. +

diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5287f4567b1fe9a7724a84d128defa2aaceba4bd --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/__init__.py @@ -0,0 +1,15 @@ +"""conf 包:业务层运行配置与 LLM 粘合器。 + +对外暴露: + load_config_with_llm_profiles —— 读取 conf/config.yaml 并把其中/ + 语种 profile 中的 llm_profile 名称展开成完整 LLMConfig。 + +说明: + ``dtxml_merge`` 工作流状态已作为内置能力迁入 + :mod:`TiMi_HOK_Game_Translator.workflow.states`,无需在此导入即可被 + 语种 profile 的 workflow 列表直接引用。 +""" + +from ._bootstrap import load_config_with_llm_profiles + +__all__ = ["load_config_with_llm_profiles"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/_bootstrap.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/_bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..cff39ce1fafdf1b45d8b39c95002a96af3618b06 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/_bootstrap.py @@ -0,0 +1,395 @@ +"""conf 层的 LLM profile 粘合器。 + +作用: + 1) 把 config.yaml / 语种 profile 里的 ``llm_profile: `` 字符串 + 展开成 conf/llm.yaml 中对应 profile 的完整 LLM 参数; + 2) 对 ``vcs`` / ``source`` 做**字段级合并**(而不是 src/TiMi_HOK_Game_Translator/cli.py + 的「整段替换」):全局 config 提供项目恒定字段(vcs.type、vcs.username、 + source.format、source.encoding 等),语种 profile 只写按语种差异的字段 + (vcs.url、vcs.local_path、source.path)。 + +设计目标: + - 不修改 src/TiMi_HOK_Game_Translator/ 任何代码; + - 对框架透明——粘合完成后,``Config``/``LanguageProfile`` 的字段 + 与直接写满参数的效果完全等价; + - 项目上线/开源时 ``conf/`` 目录保留(_bootstrap 等粘合代码运行时使用), + 仅清理 ``config.yaml`` / ``languages/*.json`` 中的真实敏感值 + (账号密码、API token、分支 URL 等),替换为占位符或改为环境变量注入。 + +使用方式: + from conf._bootstrap import load_config_with_llm_profiles + config = load_config_with_llm_profiles("conf/config.yaml") +""" + +from __future__ import annotations + +from dataclasses import fields +from pathlib import Path +from typing import Any, Dict, Optional + +from TiMi_HOK_Game_Translator.commons import ConfigFileError +from TiMi_HOK_Game_Translator.config.loader import load as _framework_load +from TiMi_HOK_Game_Translator.config.schema import ( + Config, + LanguageProfile, + LLMConfig, + SourceConfig, + VcsConfig, +) + +_DEFAULT_LLM_REGISTRY = Path(__file__).resolve().parent / "llm.yaml" +_DEFAULT_CONFIG_YAML = Path(__file__).resolve().parent / "config.yaml" + + +def _read_llm_registry(path: Path) -> Dict[str, Any]: + """读取并解析 llm.yaml 注册表。 + + 参数: + path: llm.yaml 的绝对路径。 + 返回: + 包含 ``default`` 与 ``profiles`` 两个键的 dict。 + """ + if not path.exists(): + raise ConfigFileError(f"LLM registry not found: {path}") + import yaml # 延迟导入,避免引入副作用 + with path.open("r", encoding="utf-8") as fh: + data = yaml.safe_load(fh) or {} + if not isinstance(data, dict): + raise ConfigFileError(f"Top-level value in {path} must be a mapping.") + profiles = data.get("profiles") or {} + if not isinstance(profiles, dict): + raise ConfigFileError(f"'profiles' in {path} must be a mapping.") + return {"default": data.get("default", ""), "profiles": profiles} + + +def _dict_to_llm_config(name: str, raw: Dict[str, Any]) -> LLMConfig: + """把 YAML 中的一段 profile dict 转成 ``LLMConfig`` 实例。 + + 参数: + name: profile 名称,仅用于错误提示。 + raw: 从 llm.yaml 读到的参数字典。 + 返回: + 填充好字段的 ``LLMConfig``;未识别的键进入 ``extra``。 + """ + if not isinstance(raw, dict): + raise ConfigFileError(f"LLM profile '{name}' must be a mapping.") + field_names = {f.name for f in fields(LLMConfig)} + known = {k: v for k, v in raw.items() if k in field_names and k != "extra"} + unknown = {k: v for k, v in raw.items() if k not in field_names} + cfg = LLMConfig(**known) + base_extra = raw.get("extra") or {} + if isinstance(base_extra, dict): + cfg.extra.update(base_extra) + if unknown: + cfg.extra.update(unknown) + return cfg + + +def _resolve_profile_name( + registry: Dict[str, Any], + requested: str, + *, + scope: str, +) -> LLMConfig: + """按名在注册表里找 profile;找不到抛明确错误。 + + 参数: + registry: ``_read_llm_registry`` 返回的 dict。 + requested: 配置里出现的 profile 名称。 + scope: 调用位置描述(如 ``'global config'`` 或 ``'profile vi'``), + 用于错误信息。 + 返回: + 对应的 ``LLMConfig``。 + """ + profiles = registry["profiles"] + if requested not in profiles: + available = sorted(profiles.keys()) + # 用 difflib 给出相似名建议——用户常见拼错(漏写 _plus / 多余后缀 / + # 大小写等),这里把"你是不是想写 xxx"直接写进错误消息,省得翻 YAML。 + import difflib + suggestions = difflib.get_close_matches(requested, available, n=3, cutoff=0.6) + hint = ( + f" 你是不是想写:{suggestions}?" + if suggestions else "" + ) + raise ConfigFileError( + f"[{scope}] llm_profile '{requested}' not found in conf/llm.yaml.{hint} " + f"Available: {available}" + ) + return _dict_to_llm_config(requested, profiles[requested]) + + +def _apply_global_llm(config: Config, registry: Dict[str, Any]) -> None: + """把全局 llm_profile 展开写入 ``config.llm``。 + + 参数: + config: 已由框架加载完成的 ``Config``。 + registry: llm 注册表。 + 返回: + None(就地修改)。 + """ + # 顶层未识别字段 llm_profile 会被 loader 收进 Config.extra + name = str(config.extra.pop("llm_profile", "") or registry["default"] or "") + if not name: + return # 用户没指定、也没有 default,保持 src 默认值 + config.llm = _resolve_profile_name(registry, name, scope="global config") + + +def _apply_language_llm( + profile: LanguageProfile, registry: Dict[str, Any], fallback: LLMConfig, +) -> None: + """为单个语种 profile 展开 llm_profile;没写则沿用全局配置。 + + 参数: + profile: 单语种 profile。 + registry: llm 注册表。 + fallback: 全局 llm 配置(当语种未指定 llm_profile 时直接复用)。 + 返回: + None(就地修改)。 + """ + name = str(profile.extra.pop("llm_profile", "") or "") + if name: + profile.llm = _resolve_profile_name( + registry, name, scope=f"profile {profile.id}", + ) + else: + # 关键:显式复制一份全局 llm 给 profile,避免 cli.py 的 + # fallback 分支因 profile.llm.provider 默认 'echo' 而被误判。 + profile.llm = _copy_llm(fallback) + + # 把语种 JSON 顶层的 locale_names 透传进 profile.llm.extra, + # 供 provider 构造提示词时覆盖内置的中/英文语种名字典。 + if profile.locale_names: + profile.llm.extra["locale_names"] = dict(profile.locale_names) + + +def _copy_llm(src: LLMConfig) -> LLMConfig: + """浅拷贝 ``LLMConfig``(含 extra dict)。""" + copy = LLMConfig( + provider=src.provider, + model=src.model, + temperature=src.temperature, + max_tokens=src.max_tokens, + batch_size=src.batch_size, + timeout_seconds=src.timeout_seconds, + retries=src.retries, + retry_interval_seconds=src.retry_interval_seconds, + api_key=src.api_key, + api_base=src.api_base, + ) + copy.extra.update(src.extra) + return copy + + +# --------------------------------------------------------------------------- +# VCS / Source 的字段级合并 +# --------------------------------------------------------------------------- +# cli.py 对 profile.vcs / profile.source 是「整段替换」(全有或全无): +# 一旦 profile.vcs.type / profile.source.path 为空就整段丢弃。那种模式 +# 要求每个语种 profile 把 vcs.type / source.format 等项目恒定字段重复 +# 写一遍,噪声且易错。 +# +# 这里改为:先拿全局配置做基线,再把 profile 里显式写了的字段叠加上去。 +# 这样 vi.json 只需写 { "vcs": {"url": "..."} } 就能复用全局的 type/username +# 等参数。 +_VCS_DEFAULTS = VcsConfig() +_SOURCE_DEFAULTS = SourceConfig() + + +def _merge_vcs(global_vcs: VcsConfig, profile_vcs: VcsConfig) -> VcsConfig: + """按字段把 ``profile_vcs`` 的非默认值叠加到 ``global_vcs`` 之上。 + + 参数: + global_vcs: 来自 config.yaml 的全局 vcs 配置。 + profile_vcs: 来自语种 profile 的 vcs 配置(可能只写了部分字段)。 + 返回: + 合并后的新 ``VcsConfig``;原始对象均不被修改。 + """ + merged = VcsConfig( + type=global_vcs.type, + url=global_vcs.url, + revision=global_vcs.revision, + local_path=global_vcs.local_path, + username=global_vcs.username, + password=global_vcs.password, + cli_timeout_seconds=global_vcs.cli_timeout_seconds, + default_commit_message=global_vcs.default_commit_message, + ) + merged.extra.update(global_vcs.extra) + + for f in fields(VcsConfig): + if f.name == "extra": + continue + profile_value = getattr(profile_vcs, f.name) + default_value = getattr(_VCS_DEFAULTS, f.name) + # 仅当 profile 显式写了(即与 schema 默认值不同)才覆盖。 + if profile_value != default_value: + setattr(merged, f.name, profile_value) + if profile_vcs.extra: + merged.extra.update(profile_vcs.extra) + return merged + + +def _merge_source( + global_source: SourceConfig, profile_source: SourceConfig, +) -> SourceConfig: + """按字段把 ``profile_source`` 叠加到 ``global_source`` 之上。 + + 参数: + global_source: 来自 config.yaml 的全局 source 配置。 + profile_source: 来自语种 profile 的 source 配置。 + 返回: + 合并后的新 ``SourceConfig``。 + + .. note:: + **扩展名推断兜底**:由于 ``SourceConfig`` 的字段级合并用 + "值 != dataclass 默认值" 判断是否覆盖,当 profile 显式写 + ``"format": "json"`` 而 schema 默认值恰好也是 ``"json"`` 时,会被误 + 判为"没显式写",导致全局 ``format: dtxml`` 继续生效 —— + 造成"读 json 文件却用 DtxmlSource 解析"的致命错误。 + + 修复:合并完成后,若 ``merged.path`` 与 ``merged.format`` 的扩展名 + 明显不符(例如 ``path="...99.incr.json"`` 但 ``format="dtxml"``), + 用 ``path`` 的扩展名重新推断 format。这既是对配置漂移的兜底,也 + 让 "切 profile.source.path 后缀就能切 format" 成为真实能力。 + """ + merged = SourceConfig( + format=global_source.format, + path=global_source.path, + encoding=global_source.encoding, + ) + merged.extra.update(global_source.extra) + for f in fields(SourceConfig): + if f.name == "extra": + continue + profile_value = getattr(profile_source, f.name) + default_value = getattr(_SOURCE_DEFAULTS, f.name) + # 仅当 profile 显式写了(即与 schema 默认值不同)才覆盖。 + if profile_value != default_value: + setattr(merged, f.name, profile_value) + if profile_source.extra: + merged.extra.update(profile_source.extra) + + # 关键兜底:按 merged.path 的扩展名重新推断 format, + # 当 (path 扩展名有对应 format) 且 (该推断值与当前 merged.format 不同) + # 时触发——避免"path 换了但 format 字段因 dataclass 默认值陷阱保留旧值"。 + inferred = _infer_format_from_path(merged.path) + if inferred and inferred != merged.format: + merged.format = inferred + return merged + + +#: 常见 source 文件扩展名 → format 名的映射。 +#: 源于 ``TiMi_HOK_Game_Translator.sources`` 已注册的 format 工厂。 +_EXT_TO_SOURCE_FORMAT: Dict[str, str] = { + ".dtxml": "dtxml", + ".json": "json", + ".xliff": "xliff", + ".xlf": "xliff", + ".xlsx": "xlsx", + ".csv": "csv", + ".yaml": "yaml", + ".yml": "yaml", + ".xml": "xml", +} + + +def _infer_format_from_path(path: str) -> Optional[str]: + """按文件扩展名推断 source format;无法识别时返回 ``None``。 + + 参数: + path: ``source.path`` 字段值(可能带目录前缀)。 + 返回: + format 名(如 ``"json"``)或 ``None``。 + """ + if not path: + return None + ext = Path(path).suffix.lower() + return _EXT_TO_SOURCE_FORMAT.get(ext) + + +def _apply_language_vcs_source( + profile: LanguageProfile, config: Config, +) -> None: + """为单个语种 profile 合并 vcs 与 source。 + + 参数: + profile: 单语种 profile(就地修改)。 + config: 全局配置,提供基线字段。 + 返回: + None。 + """ + profile.vcs = _merge_vcs(config.vcs, profile.vcs) + profile.source = _merge_source(config.source, profile.source) + + +def load_config_with_llm_profiles( + config_path: Optional[str | Path] = None, + *, + llm_registry_path: Optional[Path] = None, + cli_args: Any = None, + environ: Optional[Dict[str, str]] = None, +) -> Config: + """加载 config 并把 llm_profile 名称展开成完整参数。 + + 参数: + config_path: ``conf/config.yaml`` 路径;为 ``None`` 时按以下顺序兜底: + ① ``cli_args.config``(``-c/--config`` 命令行参数); + ② ``GAME_TRANS_TOOLCHAIN_CONFIG`` 环境变量; + ③ 本仓库同目录下的 ``conf/config.yaml``。 + llm_registry_path: 自定义 llm.yaml 位置;默认 conf/llm.yaml。 + cli_args: 可选,透传给框架 loader。 + environ: 可选,透传给框架 loader(测试用)。 + 返回: + 经过 llm_profile 展开的 ``Config``;可直接交给 + ``TiMi_HOK_Game_Translator.cli._run`` 使用。 + """ + resolved = _resolve_config_path(config_path, cli_args, environ) + config = _framework_load( + config_path=str(resolved) if resolved else None, + cli_args=cli_args, + environ=environ, + ) + registry = _read_llm_registry(llm_registry_path or _DEFAULT_LLM_REGISTRY) + _apply_global_llm(config, registry) + for profile in config.languages.values(): + _apply_language_llm(profile, registry, fallback=config.llm) + _apply_language_vcs_source(profile, config) + return config + + +def _resolve_config_path( + explicit: Optional[str | Path], + cli_args: Any, + environ: Optional[Dict[str, str]], +) -> Optional[Path]: + """按优先级选出要加载的 config.yaml 路径;均缺失时返回 ``None``。 + + 参数: + explicit: 调用方显式传入的路径。 + cli_args: argparse namespace;读取其中的 ``config`` 属性。 + environ: 可选自定义环境变量字典。 + 返回: + 实际存在的 YAML 路径,或 ``None`` 让框架 loader 自己回落默认行为。 + """ + import os + + if explicit: + return Path(explicit).expanduser().resolve() + + if cli_args is not None: + cli_path = getattr(cli_args, "config", None) + if cli_path: + return Path(cli_path).expanduser().resolve() + + src = environ if environ is not None else os.environ + env_path = src.get("GAME_TRANS_TOOLCHAIN_CONFIG") + if env_path: + return Path(env_path).expanduser().resolve() + + if _DEFAULT_CONFIG_YAML.exists(): + return _DEFAULT_CONFIG_YAML + return None + + +__all__ = ["load_config_with_llm_profiles"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/config.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..539a873b3946c995c99558277118bef38483940a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/config.yaml @@ -0,0 +1,112 @@ +# ============================================================================= +# TiMi_HOK_Game_Translator — 主运行配置(示例) +# ============================================================================= +# 用法: +# python main.py run -c conf/config.yaml --language vi --stage trunk_week +# +# 规范: +# 本文件只保留**非敏感的 profile 结构**(URL、项目名、模型 profile 名等)。 +# 所有敏感字段(SVN 密码、Phrase/Crowdin token、企业微信 webhook key、LLM API key) +# 走环境变量注入,字段保留为空字符串 "" 并注明对应环境变量名。 +# ============================================================================= + +project_code: TiMi_HOK_Game_Translator_e2e + +# 当前阶段:exp_week | trunk_week | pub_week | hot_week(可被 --stage 覆盖) +stage: trunk_week + +# 源语种恒定为简体中文;目标语种由各语种 profile(conf/languages/.yaml) +# 的 target_locale 决定,命令行 `--language vi` 会定位到 conf/languages/vi.yaml。 +source_locale: zh-CN + +# ------------------------------ 版本控制 ------------------------------ +# 支持 type: local | svn | perforce | git(更多示例见 docs/configuration.md 的"VCS 配置示例")。 +# * local —— 无版本控制,直接读写 local_path 下的本地文件;适合单机 / demo。 +# * svn / git / perforce —— 真实项目使用,必须填 url。 +# local_path 可填绝对路径(推荐 local 场景)或相对路径(会自动拼接 workspace 根)。 +vcs: + type: local + url: "" # TODO: 使用 svn/git/perforce 时必填,local 可留空 + revision: HEAD + local_path: "" # TODO: 本地工作副本路径,例如 svn/test_translation 或 D:/workspace/game-i18n + # 敏感字段:**请通过环境变量注入**,不要把真实账号密码写进本文件。 + # GAME_TRANS_TOOLCHAIN__VCS__USERNAME / GAME_TRANS_TOOLCHAIN__VCS__PASSWORD + username: "" + password: "" + cli_timeout_seconds: 600 + default_commit_message: "[TiMi_HOK_Game_Translator] commit translation data" + +# ------------------------------ 本地化源 ------------------------------ +# 各语种具体的 source.path 一般在 conf/languages/.yaml 中覆盖; +# 这里给一个全局默认值供新建语种借鉴。路径相对于 vcs.local_path(VCS 工作副本根)。 +# 约定:fixtures 下按语种拆子目录(``fixtures//99.incr.``), +# 文件名使用英文避免 cmd.exe / svn.exe 中文 argv 编码坑。 +source: + format: json + path: "" # TODO: 填入源文件相对路径,例如 vi/json/99.incr.json + encoding: utf-8 + +# -------------------------------- LLM -------------------------------- +# LLM 实际参数集中在 conf/llm.yaml 管理(支持多 profile)。 +# 这里按名引用 conf/llm.yaml 的 profiles.;单个语种可在 +# conf/languages/.yaml 的 llm_profile 覆盖。 +# 默认指向本地零依赖的 echo provider,首次启动无需任何凭据即可跑通流程。 +llm_profile: echo + +# ------------------------- 翻译 / 审核平台 ------------------------- +# 支持 type: crowdin | phrase(更多平台见 docs/extending_platforms.md)。 +# 各语种可在 conf/languages/.yaml 的 reviews.* 覆盖 project_id/project_name。 +# 敏感字段均通过环境变量注入,字段保留为空字符串。 +# +# 示例一:Crowdin(当前启用) +# 环境变量:GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN —— Crowdin Personal Access Token +platform: + type: crowdin + api_base: "https://api.crowdin.com/api/v2" + api_token: "" # 通过环境变量 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN 注入 + project_id: "" # TODO: 填入 Crowdin 项目 ID + extra: {} + +# 示例二:Phrase TMS(原 Memsource)—— 如需启用,注释掉上面的 crowdin 块,取消下面注释 +# 认证模式(推荐 Subject Token Exchange): +# 环境变量:GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN +# - 来源:Phrase UI → Settings → API tokens → Generate token +# - 适配器会用 subject_token 向 IDM 端点换取短期 Bearer,自动缓存与刷新 +# 环境变量:GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN —— 仅遗留 ApiToken 模式使用 +# 区域(EU / US 二选一):extra.region: eu | us;默认 eu +# 私有部署:可用 extra.idm_base / api_base 覆盖 +# platform: +# type: phrase +# api_base: "https://cloud.memsource.com/web/api2" +# api_token: "" # 遗留 ApiToken 模式使用,subject_token 模式留空 +# project_id: "" # Phrase project UID(URL /web/project2/show/) +# extra: +# subject_token: "" # 走环境变量 GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN +# region: eu # EU 账户走 eu.phrase.com,US 账户走 us.phrase.com +# # idm_base: "https://eu.phrase.com" # 私有部署覆盖 +# # workflow_step_uid: "" # 把新建 job 绑定到指定 workflow step + +# ------------------------------ 通知 ------------------------------ +# 支持 type: none | wecom(企业微信群机器人)。 +# wecom 的 webhook 请通过环境变量注入 GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK +notification: + type: none # none | wecom;wecom 时填 webhook + webhook: "" # 通过环境变量 GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK 注入 webhook 完整 URL + mentioned: [] + +# ------------------------------ 语种 profile 目录 ------------------------------ +# attach_language_profiles 会扫描该目录下所有 *.yaml / *.json +languages_dir: conf/languages + +# ------------------------------ 工作区 ------------------------------ +workspace: + root: "" # 空 → ${CWD}/workspace + subdir: workspace + state_filename: workflow_state.json + +# ------------------------------ 日志 ------------------------------ +logging: + level: INFO + directory: logs + filename: TiMi_HOK_Game_Translator.log + console: true diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/de_example.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/de_example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c33d1a85a16f31031bf5dfba812158f75a406aee --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/de_example.yaml @@ -0,0 +1,87 @@ +# 德语语种 profile +# 用于验证 GenericTranslationStrategy(中 → 德)一步直译策略 + 术语注入。 +# 本阶段**跳过审校**,workflow 仅包含「pull_vcs → translate → merge_data → push_vcs」, +# 用来专注验证一步直译与 Terms 术语注入效果。 +# 审校功能对齐 vi.yaml 的编排即可。 + +id: de_example +display_name: 德语 +source_locale: zh-CN +target_locale: de + +locale_names: + cn: 德语 + en: German + +# 源文件格式和路径(相对于 ``vcs.local_path`` 下的 svn 工作副本根) +# svn 实际布局:trunk/tests/fixtures/de/99.incr.xlsx +source: + format: csv + path: trunk/tests/fixtures/de/99.incr.xlsx + +# VCS 配置:留空(走 config.yaml 的 svn 配置,与 vi 共用 svn 工作副本) +# 如需本语种独立 VCS,取消下方注释并填入;extra.username/password 建议用环境变量。 +# vcs: +# url: "svn://..." +# local_path: svn/test_translation + +# 使用混元翻译模型。多语种通用,底层根据 target_locale 自动切换。 +# 这里指向 conf/llm.yaml 的模板示例 profile(带 _example 后缀)。 +# 真实项目请把模板复制一份、填好凭据、重命名为 hunyuan_mt2_prod 之类,再引用。 +llm_profile: hunyuan_mt2_plus_example + +# 跳过审校阶段:使用 console 通知,避免误发企业微信 +notification: + type: console + +# 审校配置先占位,但本轮 workflow 不启用;保留结构便于以后接入 +reviews: + light: + platform: crowdin + project_name: DE_LightReview + first: + platform: crowdin + project_id: "your_project_id" # Phrase project UID(URL /web/project2/show/) + project_name: DE First Review (Phrase) + target_language_id: de # Phrase 项目 targetLangs[0].code + poll_interval_seconds: 60 + stop_time: "17:00" # 支持 "HH:MM" 绝对格式或 "+Nm/Nh" 相对格式 + extra: + region: eu # EU 账户走 eu.phrase.com + second: + platform: crowdin + project_name: DE_SecondReview(Phrase) + +# 工作流状态编排——【只保留翻译链路,跳过所有审校】 +# 验证重点: +# 1. 翻译策略默认走 GenericTranslationStrategy(一步直译); +# 2. 注入 Terms(中→德语术语); +# 3. 最终 xlsx 的 Target 列有德语译文。 +workflow: + - pull_vcs + - last_first_review + - last_second_review + - last_merge_data + - translate + - update_tm + - update_grn_tm + - light_review + - first_review + - second_review + - validate_data + - merge_data + - push_vcs +merge_start_time: "" + +strategy_config: + # 两步直译策略:中 → 英(pivot) → 德 + # 若想改为一步直译:删除 class 字段,让系统走 GenericTranslationStrategy + class: TwoStepTranslationStrategy + pivot_locale: en # Step 1 的中转语种,默认 en + display_name: 德语翻译 + use_concurrent_by_default: true + default_max_workers: 32 + # 进度日志:每完成 1 条就打印一次,便于逐条跟踪翻译链路 + # (10 条量级下看每条 key 的 zh→de 明细;量大时可改为 5 或 10) + progress_log_interval: 100 + diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/vi_example.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/vi_example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..468edc25a5e643da650e6aa905223d76ea40e202 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/languages/vi_example.yaml @@ -0,0 +1,90 @@ +# 越南语语种 profile +id: vi_example +display_name: 越南语 +source_locale: zh-CN +target_locale: vi + +locale_names: + cn: 越南语 + en: Vietnamese + +# 源文件:路径相对于 ``vcs.local_path`` 下的 VCS 工作副本根。 +# 对应 full 表自动推断为同目录下的 98.full.,无需显式配置。 +source: + format: json + path: trunk/tests/fixtures/vi/99.incr.json + +# VCS 配置留空 → 走 conf/config.yaml 的 vcs 段。 +# 如需本语种独立 VCS,取消下方注释并填入;敏感字段建议走环境变量。 +# vcs: +# url: "svn://..." +# local_path: svn/vi_dedicated + +llm_profile: llama3_1_70b_example + +# 通知渠道:企业微信群机器人 +# 敏感字段:webhook 请通过环境变量注入 GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK +# mentioned 可填企业微信用户名,审校任务关键节点会 @ 这些人 +notification: + type: wecom + webhook: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx" + mentioned: + - curry + +# 审校配置 +# ⚠️ Phrase 平台特性与已知限制详见 docs/platforms/phrase.md。 +reviews: + light: + platform: crowdin + project_name: VI_LightReview + + # 一审:Phrase TMS + # 敏感字段:subject_token 不要写在这里,请走环境变量 + # GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN + # (来源:Phrase UI → Settings → API tokens → Generate token) + first: + platform: crowdin + project_id: "your_project_id" # Phrase project UID(URL /web/project2/show/) + project_name: VI First Review (Crowdin) + target_language_id: vi # Phrase 项目 targetLangs[0].code + poll_interval_seconds: 60 + stop_time: "17:00" # 支持 "HH:MM" 绝对格式或 "+Nm/Nh" 相对格式 + extra: + region: eu # EU 账户走 eu.phrase.com + + # 二审:Crowdin + # 敏感字段:api_token 走 config.yaml 的 platform.api_token(env 注入) + second: + platform: crowdin + project_id: "your_project_id" + project_name: VI Second Review (Crowdin) + target_language_id: vi + poll_interval_seconds: 60 + stop_time: "18:00" + +# 工作流状态编排(按声明顺序执行) +workflow: + - pull_vcs + - last_first_review + - last_second_review + - last_merge_data + - translate + - update_tm + - first_review + - validate_data + - merge_data +merge_start_time: "" + +# 翻译策略配置 +# - class 可填短名 "TwoStepTranslationStrategy" / "two_step",或完整 import 路径; +# - 省略 class 则走装饰器注册表,再兜底 GenericTranslationStrategy(一步直译)。 +# +# 两步翻译(中 → 英 → 越): +# - Step 1 注入中→英术语;Step 2 用英→越术语对注入,充分利用增量表的 +# en_terms / vi_terms 两列。 +strategy_config: + class: GenericTranslationStrategy + display_name: 越南语翻译 + use_concurrent_by_default: true + default_max_workers: 32 + progress_log_interval: 100 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/llm.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/llm.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f7e8fcba53097ffd88697747c4da9da3811182e --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/conf/llm.yaml @@ -0,0 +1,120 @@ +# ============================================================================= +# conf/llm.yaml — LLM 模型注册表(跨业务项目共享) +# ============================================================================= +# config.yaml / conf/languages/*.yaml 用 `llm_profile: ` 按名引用。 +# 敏感字段 api_key / secret_* 建议走环境变量 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 注入。 +# +# 命名约定: +# - 带 `_example` 后缀的均为**模板示例**,使用前请复制一份、重命名为自己的 +# 业务 profile(如 `openai_gpt4o_mini_prod`),再把 TODO 字段填好。 +# - `echo` 是真正可用的本地零依赖 provider,用于联调/演示,无需凭据。 +# ============================================================================= + +default: echo + +profiles: + # ---------- Echo(本地零依赖调试:直接把原文带 [locale] 标签回显) ---------- + # 无需任何凭据,适合首次启动 / 流程联调 / CI 测试。 + echo: + provider: echo + model: echo-dev + temperature: 0.0 + max_tokens: 2048 + batch_size: 32 + + # ---------- OpenAI 官方(示例) ---------- + # 常用 model:gpt-4o-mini / gpt-4o / gpt-4-turbo + # 常用 api_base:https://api.openai.com/v1 + openai_gpt4o_mini_example: + provider: openai + model: "" # TODO: 填入模型 ID,例如 gpt-4o-mini + api_base: "" # 走 OpenAI 官方可留空;企业网关填完整 URL + api_key: "" + temperature: 0.2 + max_tokens: 1024 + batch_size: 32 + timeout_seconds: 30 + retries: 3 + retry_interval_seconds: 30 + + # ---------- Venus 内网 SDK(示例 provider) ---------- + # 凭据:GAME_TRANS_TOOLCHAIN__LLM__API_KEY=: + # 常用 api_base:http://v2.open.venus.oa.com/chat/single + llama3_1_70b_example: + provider: venus + model: "llama3.1-70B" # TODO: 填入 Venus 平台的模型路由名 + api_base: "http://v2.open.venus.oa.com/chat/single" # TODO: Venus API 入口 + temperature: 0.1 + timeout_seconds: 180 # Venus 大模型推理较慢,建议 ≥120s + retries: 3 + retry_interval_seconds: 10 + extra: + server_id: 252029 # TODO: Venus 平台模型路由 ID(整数) + app_group_id: 2777 # TODO: Venus 平台应用组 ID(整数) + secret_id: "" # TODO: Venus 平台认证 secret_id + secret_key: "" # TODO: Venus 平台认证 secret_key + model_params: # 透传到 Venus 请求体的解码参数(可选) + repetition_penalty: 1.1 + do_sample: false + + # ---------- Google Gemini(Google AI Studio generateContent API) ---------- + # 鉴权:GAME_TRANS_TOOLCHAIN__LLM__API_KEY 或 GOOGLE_API_KEY + # 常用模型:gemini-2.5-flash(快)/ gemini-2.5-pro(强) + gemini_flash_example: + provider: gemini + model: gemini-2.5-flash + api_base: "https://generativelanguage.googleapis.com" + api_key: "" + temperature: 0.2 + max_tokens: 2048 + batch_size: 16 + timeout_seconds: 60 + retries: 3 + retry_interval_seconds: 10 + + # ---------- 混元 HY-MT 翻译模型(OpenAI chat.completions 变体 + Wsid 头) ---------- + # extra.wsid 为 HY-MT 工作空间 ID(必填) + hunyuan_mt2_plus_example: + provider: hunyuan_translation + model: "" # TODO: 填入混元 HY-MT 模型名 + api_base: "" # TODO: 填入混元 HY-MT API 入口(必填) + api_key: "" + temperature: 0.7 + max_tokens: 4096 + batch_size: 16 + timeout_seconds: 3000 + extra: + wsid: "" # TODO: 填入混元 HY-MT 工作空间 ID(必填) + top_p: 1.0 + top_k: -1 + repetition_penalty: 1.0 + system_prompt: "" + stream: false + reasoning_effort: "no_think" + + # ---------- OpenAI 兼容协议(DeepSeek / Kimi / GLM / Qwen / Hy4 等通用) ---------- + # 常用 api_base: + # DeepSeek: https://api.deepseek.com/v1 + # Kimi: https://api.moonshot.cn/v1 + # GLM: https://open.bigmodel.cn/api/paas/v4 + # Qwen: https://dashscope.aliyuncs.com/compatible-mode/v1 + openai_compatible_example: + provider: openai_compatible + model: "" # TODO: 填入模型 ID,例如 deepseek-chat + api_base: "" # TODO: 对应厂商的兼容协议入口(必填) + api_key: "" + temperature: 0.2 + max_tokens: 4096 + batch_size: 16 + + # ---------- Anthropic Claude(原生 endpoint) ---------- + # 常用 model:claude-3-5-sonnet-20241022 / claude-3-5-haiku-20241022 + # 默认 api_base:https://api.anthropic.com(可留空走官方) + claude_example: + provider: anthropic + model: "" # TODO: 填入 Claude 模型 ID + api_base: "" # 走官方可留空;企业网关填完整 URL + api_key: "" + temperature: 0.2 + max_tokens: 4096 + batch_size: 8 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/architecture.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..b1e9cd02ac0c66e7894f1e59dcb3a1642cddffa2 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/architecture.md @@ -0,0 +1,82 @@ +# 架构 + +TiMi_HOK_Game_Translator 有**三大骨架**、**六个可插拔层**。任何一次运行都是它们协作的结果。 + +## 概览 + +``` + +-----------------------------+ + | WorkflowRunner | + | 按 profile.workflow 编排 | + +--------------+--------------+ + | + +------------------------------+------------------------------+ + | | | + +-------v-------+ +--------v---------+ +--------v---------+ + | StatesManager | | WorkflowContext | | AutoSaveDict | + | 状态位持久化 | | 运行时上下文 | | 业务数据自动落盘 | + +---------------+ +------------------+ +------------------+ + | + +-------------+----------+---------------+-----------+--------------+--------------+ + | | | | | | | ++-----v----+ +-----v----+ +---v------+ +-----v----+ +---v----+ +-----v-----+ +-----v-----+ +| VcsClient| | LocalSrc | | LLMClient| | Trans- | |Trans- | | Notifier | | ... | +| svn/git | | json/... | | mock/ | | Strategy | |lation | | wecom/... | | | +| perforce | | yaml/xml | | openai | | (语种) | |Platform| | | | | ++----------+ +----------+ +----------+ +----------+ |Phrase/ | +-----------+ +-----------+ + |Crowdin | + +--------+ +``` + +## 三大骨架 + +### 1. `translation/` 独立于 `llm/`:编排层 vs 调用层 + +- **`translation.BaseTranslationStrategy`(编排层)**:负责 `filter` + `translate` + `process` 三段式、串行/并发执行、去重、兄弟行广播、`post_translate` 钩子、进度回调; +- **`llm.LLMClient`(调用层)**:负责把 prompt 送给具体后端(Mock / OpenAI / 自定义); +- 语种可以通过 `@register_translation_strategy("vi")` 装饰器自定义策略,也可以只在 JSON 里写 `strategy_config` 就用通用 `GenericTranslationStrategy`。 + +### 2. `workflow/`:17 个状态族 + JSON 驱动 workflow + +- 状态由 `state_registry.register_state("name", cls)` 注册,`build_workflow(profile.workflow)` 按 profile 里的名字列表逐个实例化; +- 每个语种的 pipeline 在 [`conf/languages/.yaml`](../conf/languages/) 里声明,例如越南语走 11 步双轮审校、日语走 7 步单轮审校; +- 完整状态列表见 [state_registry.md](./state_registry.md)。 + +### 3. `platforms/`:`review_stage` 首次成为一等公民 + +- `TranslationPlatform` 的每个方法都接受关键字 `review_stage`(`light` / `first` / `second`); +- `build_review_tool(profile, "first")` 会按 `profile.reviews["first"].platform` 选择平台实例; +- 内置两个平台:**Phrase TMS**(原 Memsource)与 **Crowdin API v2**; +- 一审二审可以走**完全不同的后端**(例如一审 Phrase、二审 Crowdin)。 + +## 断点续跑 + +两个文件承担不同的持久化职责: + +| 文件 | 内容 | 由谁写 | +|---|---|---| +| `workspace/workflow_state.json` | 每个状态的完成标记(`{status: {name: True/False}, metadata: {...}}`)| `StatesManager` | +| `workspace/project_run_data.json` | 业务数据(`task_id / approved_path / stats / errors`)| `AutoSaveDict`(每次变更即落盘) | + +不带 `--fresh` 再次运行时: +- 已完成状态自动跳过; +- `AutoSaveDict` 已保存的 `task_id` 会被 `FirstReviewState / SecondReviewState` 识别并复用,不会重复上传。 + +## 六个可插拔层 + +| 层 | 抽象基类 | 内置实现 | 用户如何扩展 | +|---|---|---|---| +| VCS | `vcs.VcsClient` | `svn / git / perforce / mock` | 继承基类实现 `checkout / update / commit / cleanup` | +| 源文件 | `sources.LocalizationSource` | `json / yaml / xml / csv / dtxml / xliff` | `@register_source("format")` | +| LLM | `llm.LLMClient` | `mock / openai` | `@register_llm("provider")` | +| 翻译策略 | `translation.BaseTranslationStrategy` | `GenericTranslationStrategy` | `@register_translation_strategy("lang")` | +| 审校平台 | `platforms.TranslationPlatform` | `none / phrase / crowdin` | `@register_platform("name")` | +| 通知 | `notify.Notifier` | `wecom / slack / email / console` | `@register_notifier("type")` | + +## 关键约束 + +1. **零私密信息**:所有敏感字段(`api_token / password / webhook`)通过 `.env` 或 CLI 传入;`config dump` 自动脱敏。 +2. **状态即位图**:`StatesManager` 只记录布尔完成位,不夹带业务;业务全部走 `AutoSaveDict`。 +3. **`review_stage` 决定平台**:state 类通过 `build_review_tool(profile, stage)` 拿平台实例,不直接依赖具体 SDK。 +4. **一切名字可注册**:`register_state / register_platform / register_translation_strategy / register_llm / register_source / register_notifier` 六个装饰器让整个框架可被外部完全扩展,无需 fork 源码。 + diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/configuration.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..e028d536df57b3dd03e30bde6a96264a9f833b55 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/configuration.md @@ -0,0 +1,640 @@ +# 配置详解 + +本页集中介绍 `TiMi_HOK_Game_Translator` 的三份 YAML 配置: + +``` +conf/ +├── config.yaml # 主运行配置(VCS / platform / notification / workspace / logging) +├── llm.yaml # LLM 模型注册表(跨业务项目共享的模型 profile) +└── languages/ + ├── .yaml # 单个语种 profile(source / reviews / workflow / strategy) + └── ... +``` + +> 📌 整体心智模型:**全局 `config.yaml` 定下框架默认值,语种 profile 可覆盖/新增,`llm.yaml` 以 "profile 名" 形式被前两者按名引用。** + +- [1. `conf/config.yaml` — 主运行配置](#1-confconfigyaml--主运行配置) +- [2. `conf/llm.yaml` — LLM profile 注册表](#2-confllmyaml--llm-profile-注册表) +- [3. `conf/languages/.yaml` — 语种 profile](#3-conflanguageslangyaml--语种-profile) +- [4. 源文件格式(source)参考](#4-源文件格式source参考) +- [5. 敏感字段与环境变量注入](#5-敏感字段与环境变量注入) +- [6. 为什么 `platform` 不区分一审 / 二审?](#6-为什么-platform-不区分一审--二审) + +--- + +## 1. `conf/config.yaml` — 主运行配置 + +**作用**:定义**全局默认**的 VCS、翻译/审校平台、通知渠道、workspace 位置与日志,供所有语种 profile 继承。 +**运行时覆盖优先级**:`环境变量` > `命令行参数` > `conf/languages/.yaml` > `conf/config.yaml`。 + +### 1.1 顶层字段 + +| 字段 | 类型 | 必填 | 默认值 | 说明 | +|---|---|---|---|---| +| `project_code` | str | ✅ | - | 产品 slug,出现在日志前缀、通知标题、状态文件名 | +| `stage` | enum | ❌ | `trunk_week` | 运行阶段,可选 `exp_week` / `trunk_week` / `pub_week` / `hot_week`,可被 `--stage` 覆盖 | +| `source_locale` | str | ❌ | `zh-CN` | 源语种 BCP-47 代码;目标语种由各语种 profile 的 `target_locale` 决定 | +| `languages_dir` | str | ❌ | `conf/languages` | 扫描语种 profile 的目录(支持 `*.yaml` / `*.json`) | + +### 1.2 `vcs` — 版本控制 + +| 字段 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `type` | enum | ✅ | `svn` / `git` / `perforce` / `mock`;用 `mock` 做零依赖试跑 | +| `url` | str | ✅ | 远端仓库地址 | +| `revision` | str | ❌ | 签出修订号,默认 `HEAD` | +| `local_path` | str | ✅ | **相对路径**,factory 自动拼接 `workspace` 根;**不要加 "workspace/" 前缀** | +| `username` / `password` | str | 🔒 | 凭据,**走环境变量 `GAME_TRANS_TOOLCHAIN__VCS__USERNAME` / `GAME_TRANS_TOOLCHAIN__VCS__PASSWORD`** | +| `cli_timeout_seconds` | int | ❌ | 单条 CLI 调用超时,默认 600 | +| `default_commit_message` | str | ❌ | `push_vcs` 阶段提交消息兜底 | + +> SVN 遇 `wc locked / E155004` 时跑 `svn cleanup `;**不要用 `svn status` 判断是否锁定**,`svn update` 或 `svn info` 更可靠。 + +#### VCS 配置示例 + +
+Git + +```yaml +vcs: + type: git + url: https://github.com/YOUR_ACCOUNT/game-i18n.git + local_path: workspace/repo + # revision: main # 可选,默认 HEAD + default_commit_message: "chore(i18n): TiMi_HOK_Game_Translator auto commit" +``` + +
+ +
+SVN + +```yaml +vcs: + type: svn + url: https://svn.example.com/game-i18n/trunk + local_path: workspace/repo + # username: your-svn-user # 🔒 GAME_TRANS_TOOLCHAIN__VCS__USERNAME + # password: your-svn-pass # 🔒 GAME_TRANS_TOOLCHAIN__VCS__PASSWORD + revision: HEAD + default_commit_message: "chore(i18n): TiMi_HOK_Game_Translator auto commit" +``` + +
+ +
+Perforce + +```yaml +vcs: + type: perforce + url: "perforce.example.com:1666" # P4PORT + local_path: workspace/repo # 本地映射目录(client root) + # username / password 🔒 走环境变量 + extra: + client: game-i18n-workspace # p4 client 名 + stream: "//depot/game-i18n/main" # 流式仓库 + charset: utf8 +``` + +
+ +
+Mock(零依赖试跑) + +```yaml +vcs: + type: mock + url: mock://local + local_path: "." # 相对 cwd;不实际克隆 +``` + +该模式配合 `platform.type: none` + `llm.provider: mock` 即可无网络跑通 +整条流水线,适合首次验证安装。见 [快速开始](./quickstart.md)。 + +
+ + +### 1.3 `source` — 全局源文件默认 + +多数情况下这段**只做新建语种的"复制起点"**,真实路径以 `conf/languages/.yaml` 的 `source` 为准。 + +```yaml +source: + format: json # xlsx | json | yaml | xml | csv | dtxml | xliff + path: "vi/json/99.incr.json" # 相对 vcs.local_path + encoding: utf-8 +``` + +### 1.4 `llm_profile` — 默认 LLM + +```yaml +llm_profile: hunyuan_mt2_plus # 必须在 conf/llm.yaml 的 profiles 下存在 +``` + +单个语种若需换模型,到 `conf/languages/.yaml` 覆盖同名字段即可。 + +### 1.5 `platform` — **全局默认审校平台** + +```yaml +platform: + type: crowdin # crowdin | phrase | none | <自定义名> + api_base: "https://api.crowdin.com/api/v2" + api_token: "" # 🔒 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN + project_id: "" + extra: {} # 平台专属扩展 +``` + +> ⚠️ 本配置**不区分一审 / 二审** —— 它只是全局兜底。真正的"一审走 Phrase + 二审走 Crowdin"配置在 +> `conf/languages/.yaml` 的 `reviews.first` / `reviews.second`。详情见第 6 节。 + +### 1.6 `notification` — 通知渠道 + +```yaml +notification: + type: none # none | wecom | console + webhook: "" # 🔒 GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK +``` + +### 1.7 `workspace` 与 `logging` + +```yaml +workspace: + root: "" # 空 → ${CWD}/workspace + subdir: workspace + state_filename: workflow_state.json # 断点续跑状态持久化文件名 + +logging: + level: INFO # DEBUG | INFO | WARNING | ERROR + directory: logs + filename: TiMi_HOK_Game_Translator.log + console: true +``` + +--- + +## 2. `conf/llm.yaml` — LLM profile 注册表 + +**作用**:集中维护所有可用模型 "profile",业务配置按名引用,避免每个语种重复写一遍 `api_base` / `temperature` 等。 + +### 2.1 顶层结构 + +```yaml +default: openai_gpt4o_mini # config.yaml / 语种 profile 都没指定时的兜底 +profiles: + : + provider: openai # openai | openai_compatible | anthropic | venus | hunyuan_translation | mock + model: gpt-4o-mini + api_base: "" + api_key: "" # 🔒 GAME_TRANS_TOOLCHAIN__LLM__API_KEY + temperature: 0.2 + max_tokens: 1024 + batch_size: 32 + timeout_seconds: 30 + retries: 3 + retry_interval_seconds: 30 + extra: {} # provider 专属字段 +``` + +### 2.2 字段逐项 + +| 字段 | 必填 | 说明 | +|---|---|---| +| `provider` | ✅ | 决定走哪个 `LLMClient` 实现;详见 [`docs/extending_llm.md`](./extending_llm.md) | +| `model` | ✅ | 模型名;venus / hunyuan_translation 走的是服务端模型 ID | +| `api_base` | ⚠️ | OpenAI 系省略即走官方 endpoint,其它必填 | +| `api_key` | 🔒 | 走环境变量注入;venus 用 `secret_id:secret_key` 形式 | +| `temperature` | ❌ | 翻译建议 `0.1 ~ 0.3` 之间 | +| `max_tokens` | ❌ | 单次响应上限;长文本可设 4096 | +| `batch_size` | ❌ | 单次打包多少条 Entry(框架按此分批) | +| `timeout_seconds` | ❌ | 单次 HTTP 超时 | +| `retries` / `retry_interval_seconds` | ❌ | 网络抖动重试 | +| `extra` | ❌ | provider 专属,常见键见下表 | + +### 2.3 常用 `extra` 键 + +| provider | 键 | 说明 | +|---|---|---| +| `venus` | `server_id` / `app_group_id` | Venus 平台模型路由 | +| `venus` | `secret_id` / `secret_key` | 鉴权(也可合并到 `api_key`) | +| `venus` | `model_params.top_p / top_k / repetition_penalty / do_sample` | 解码参数 | +| `hunyuan_translation` | `wsid` | HY-MT 工作空间 ID(必填) | +| `hunyuan_translation` | `top_p / top_k / repetition_penalty / reasoning_effort / system_prompt / stream` | HY-MT 解码参数 | + +--- + +## 3. `conf/languages/.yaml` — 语种 profile + +**作用**:接入一门新语种的**唯一**入口。日常改动最多的文件。 + +### 3.1 基础字段 + +```yaml +id: vi # 必填:语种短 ID(与文件名一致) +display_name: 越南语 # 日志 / 通知使用的中文名 +source_locale: zh-CN +target_locale: vi +locale_names: + cn: 越南语 # 用于提示词 + en: Vietnamese +``` + +### 3.2 `source` — 本语种源文件 + +```yaml +source: + format: json # 覆盖全局 config.yaml 的 source.format + path: trunk/tests/fixtures/vi/99.incr.json # 相对 vcs.local_path + encoding: utf-8 +``` + +> 👉 可用的 `format` 值与各格式的字段约定见 [第 4 节](#4-源文件格式source参考)。 + +### 3.3 `vcs` — 可选,覆盖全局 + +多数语种共用一个 svn 工作副本时留空;需要本语种独立 VCS 时填: + +```yaml +vcs: + url: "svn://..." + local_path: svn/vi_dedicated +``` + +### 3.4 `llm_profile` 与 `strategy_config` — 翻译 + +```yaml +llm_profile: hunyuan_mt2_plus # 必须在 conf/llm.yaml 中存在 + +strategy_config: + # ① 短名 —— GenericTranslationStrategy / TwoStepTranslationStrategy / generic / two_step + # ② 完整导入路径 —— my_pkg.strategies.MyStrategy + # 省略 class 字段 → 走装饰器注册表,再兜底 Generic + class: TwoStepTranslationStrategy + pivot_locale: en # 两步策略专属,默认 en + display_name: 越南语翻译 + use_concurrent_by_default: true + default_max_workers: 32 + progress_log_interval: 100 +``` + +详细说明见 [`README.md`](../README.md#-翻译策略选择指南) 的"翻译策略选择指南"。 + +### 3.5 `reviews` — **一审 / 二审 / 轻校对配置** + +这是语种 profile 里**最容易踩坑**的一段。核心约定: + +- **每个审校阶段独立选择平台**,互不影响; +- `platform: none`(或字段省略)即跳过该阶段; +- 阶段级 `api_token` / `api_base` 为空且**全局 `platform.type` 等于本阶段 `platform`** 时,自动继承全局的凭据(避免跨平台污染); +- `extra.target_language_id` 是**平台侧**的语种 ID(与 BCP-47 可能不同,比如 Phrase 用 `vi`、Crowdin 用 `vi`,但有的平台会用数字 ID)。 + +```yaml +reviews: + light: + platform: none + project_name: VI_LightReview + + first: # 一审 + platform: phrase + project_id: "" # Phrase project UID + project_name: VI First Review (Phrase) + target_language_id: vi + poll_interval_seconds: 60 + stop_time: "17:00" # "HH:MM" 绝对或 "+5m"/"+2h" 相对 + extra: + region: eu # Phrase 专属:eu / us + subject_token: "" # 🔒 可改走 GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN + + second: # 二审 + platform: crowdin + project_id: "" + project_name: VI Second Review (Crowdin) + target_language_id: vi + poll_interval_seconds: 60 + stop_time: "18:00" +``` + +### 3.6 `notification` — 覆盖全局通知 + +```yaml +notification: + type: wecom + webhook: "" # 🔒 GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK + mentioned: # 审校关键节点 @ 的企业微信用户 + - some_user_id +``` + +### 3.7 `workflow` — 工作流编排 + +按声明顺序执行;每个条目都是已注册的状态名。常见组合: + +```yaml +# 完整链路(一审 + 二审) +workflow: + - last_first_review # 续审昨日未完成的一审任务 + - last_second_review # 续审昨日未完成的二审任务 + - pull_vcs + - last_merge_data # 续审任务到位后先合并 + - translate + - light_review # 轻校对(可省) + - update_tm # 一审 TM 回灌 + - first_review + - update_grn_tm # 二审 TM 回灌 + - second_review + - validate_data + - merge_data + - push_vcs + +# 仅翻译 + 推送(跳过所有审校),例如 ar.yaml +workflow: + - pull_vcs + - translate + - merge_data + - push_vcs +``` + +内置状态清单见 [`state_registry.md`](./state_registry.md)。 + +### 3.8 `merge_start_time` + +```yaml +merge_start_time: "" # 空 → 立即执行;"08:30" → 等到当日 08:30 之后再合并 +``` + +--- + +## 4. 源文件格式(source)参考 + +内置支持 **7 种**源文件格式,统一映射到 `Entry`: + +```python +@dataclass +class Entry: + key: str # 稳定标识,惯例 "ui.mainmenu.play" + source_text: str # 源语文本 + target_text: str = "" # 目标语译文(未翻译时为空) + context: str = "" # 自由形式上下文 + comment: str = "" # 术语/占位符提醒 + en_terms: list = [] # [(zh, en), ...] 中→英术语对 + terms: list = [] # [(zh, target), ...] 中→目标语术语对 + metadata: dict = {} # 后端自定义字段(往返保留) +``` + +| 格式 | 后缀 | 适合场景 | 术语列 | 备注 | +|---|---|---|---|---| +| `json` | `.json` | 现代 Web / Unity 项目 | ❌ 不建议 | 结构见 4.1 | +| `yaml` | `.yaml` / `.yml` | 可读性高、人工维护 | ❌ 不建议 | 和 JSON 同 schema | +| `xml` | `.xml` | 遗留 Flash / Unreal | ❌ 不建议 | 结构见 4.3 | +| `csv` | `.csv` | Excel 导出首选 | ❌ 不建议 | UTF-8 BOM 可选 | +| `xliff` | `.xliff` / `.xlf` | 标准化翻译交付 | ❌ 不建议 | OASIS XLIFF 1.2 | +| `dtxml` | `.dtxml` | 内部 metalib 格式 | ❌ 不建议 | 保留 struct 名 | +| `xlsx` | `.xlsx` | **一审/二审上传的首选**;LLM 翻译链路 | ✅ `EnTerms` / `Terms` | 结构见 4.7 | + +### 4.1 JSON + +```json +{ + "meta": { + "project_code": "example_game", + "source_locale": "en", + "target_locale": "zh-CN" + }, + "entries": [ + { + "key": "ui.mainmenu.play", + "source_text": "Play", + "context": "Main menu — start a new game.", + "comment": "Short action button." + } + ] +} +``` + +必填字段:`entries[].key` / `entries[].source_text`。 +`target_text` / `context` / `comment` 可省略,缺省为空串。 + +### 4.2 YAML + +同 JSON schema,缩进+注释更友好: + +```yaml +meta: + project_code: example_game + source_locale: en + target_locale: zh-CN + +entries: + - key: ui.mainmenu.play + source_text: Play + context: "Main menu — start a new game." + comment: "" +``` + +### 4.3 XML + +```xml + + + + Play + + + +``` + +### 4.4 CSV + +```csv +key,source_text,context,comment +ui.mainmenu.play,Play,Main menu — start a new game.,Short action button. +hud.health,"HP: {value}/{max}",HUD label.,"Placeholders must be preserved." +``` + +- 首行**必须**是表头,列名大小写不敏感; +- 包含逗号的字段需用双引号包裹; +- UTF-8 推荐带 BOM 保证 Excel 直接双击可读。 + +### 4.5 XLIFF(OASIS 1.2) + +```xml + + + + + + Play + Chơi + + + + +``` + +`state` / 自定义属性会被塞进 `Entry.metadata`,`load → dump` 往返保留。 + +### 4.6 DTXML(内部 metalib 格式) + +```xml + + + + + Play + Main menu — start a new game. + Short action button. + + + +``` + +> 这是示意版 schema;真实业务里的 DTXML 列定义是私有的,接入时请覆盖 `DtxmlSource` 的 `load` / `dump`。 + +### 4.7 XLSX(审校/翻译首选) + +**固定表头,顺序即列顺序**: + +| 列 | 必填 | 说明 | +|---|---|---| +| `Key` | ✅ | 稳定标识 | +| `Source` | ✅ | 源语文本 | +| `Target` | ❌ | 译文(增量表翻译前为空) | +| `Context` | ❌ | 上下文 | +| `Comment` | ❌ | 备注 / 占位符提醒 | +| `EnTerms` | ❌ | **中→英术语对**,一个单元格内多行,格式:`艾薇塔=Evita` | +| `Terms` | ❌ | **中→目标语术语对**,格式同上,如 `艾薇塔=Evita` 或 `护盾=khiên` | +| `EnglishSide` | ❌ | 两步翻译 Step 1 的英文中间结果(框架自动写入) | + +``` +┌───────────────────┬────────┬────────┬─────────┬─────────┬──────────────┬──────────────┬─────────────┐ +│ Key │ Source │ Target │ Context │ Comment │ EnTerms │ Terms │ EnglishSide │ +├───────────────────┼────────┼────────┼─────────┼─────────┼──────────────┼──────────────┼─────────────┤ +│ ui.mainmenu.play │ 开始 │ │ 主菜单 │ │ │ │ │ +│ hud.health │ 血量 │ │ HUD │ │ 血量=HP │ 血量=Máu │ │ +└───────────────────┴────────┴────────┴─────────┴─────────┴──────────────┴──────────────┴─────────────┘ +``` + +术语列每行一个 `源文=译文`,用**单元格内换行**(Alt+Enter)分隔。 +一步策略只读 `Terms`,两步策略两列都读并做 inner-join 映射。 + +### 4.8 可用列名容错 + +JSON/YAML 的 `source` / `source_text` / `original` 都识别;XLSX 的 `EnTerms` / `en_terms` / `ENTERMS` 都认,不区分大小写与下划线。 + +--- + +## 5. 敏感字段与环境变量注入 + +**所有标注 🔒 的字段**都应走环境变量注入,严禁明文写进仓库 YAML。 + +### 命名规则 + +``` +GAME_TRANS_TOOLCHAIN__
__ +``` + +两层下划线分隔,`
` 对应 YAML 顶层键。 + +### 常用环境变量清单 + +| 环境变量 | 对应配置路径 | +|---|---| +| `GAME_TRANS_TOOLCHAIN__VCS__USERNAME` / `GAME_TRANS_TOOLCHAIN__VCS__PASSWORD` | `vcs.username` / `vcs.password` | +| `GAME_TRANS_TOOLCHAIN__LLM__API_KEY` | `llm_profile` 指向的 profile 的 `api_key` | +| `GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN` | `platform.api_token`(全局) | +| `GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN` | Phrase 一审的 `reviews.first.extra.subject_token` | +| `GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK` | `notification.webhook` | + +### 验证 + +```bash +python main.py config dump --config conf/config.yaml --language vi +``` + +敏感字段应打印为 `***`。若还看到原文,立刻排查注入是否生效。 + +--- + +## 6. 为什么 `platform` 不区分一审 / 二审? + +一句话:**`config.yaml.platform` 是全局兜底;一审 / 二审的真正差异靠 `reviews.first.platform` / `reviews.second.platform` 做阶段级独立选择。** + +### 为什么这样设计? + +- **常见场景**:单平台(例如全部走 Crowdin)—— 只在 `config.yaml.platform.api_token` 填一次,一审 / 二审都用; +- **游戏出海典型场景**:**一审 Phrase + 二审 Crowdin** —— 两份凭据分别放 `reviews.first.extra.subject_token` 与 `platform.api_token`,各走各的; +- **跨平台污染保护**:工厂 `build_review_tool` 在回退到全局 `platform` 时,仅当全局 `type` 与阶段 `platform` 相同时才共享 `api_base/api_token/project_id`,避免 "Phrase 用了 Crowdin 的 token / 请求打到对方 nginx" 的 404; +- **扩展友好**:新接入第三家 TMS 时,只需在**阶段**里写 `platform: lokalise` 即可,不用动全局。 + +### 配置解析优先级(`build_review_tool`) + +``` +reviews[stage].platform (非 none) + └── 用该平台 +reviews[stage].platform == "none" / 空 + └── fallback 参数(内部调用方指定) + └── 全局 platform.type(如果非 none) + └── NoopPlatform(无操作兜底) +``` + +详细代码:[`src/TiMi_HOK_Game_Translator/platforms/factory.py#build_review_tool`](../src/TiMi_HOK_Game_Translator/platforms/factory.py)。 + +### 场景示例 + +**场景 A:全局单平台** + +```yaml +# config.yaml +platform: + type: crowdin + api_token: "" + project_id: "123" +# 语种 profile 两阶段都省略 → 都走全局 Crowdin +``` + +**场景 B:一审 Phrase + 二审 Crowdin** + +```yaml +# config.yaml +platform: + type: crowdin # 二审用它的 api_token / project_id 做兜底 + api_token: "" # 🔒 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN +# conf/languages/vi.yaml +reviews: + first: + platform: phrase # 阶段级覆盖,强制走 Phrase + extra: + region: eu + subject_token: "" # 🔒 GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN + second: + platform: crowdin # 跟全局同名 → 自动继承 api_token / project_id + project_id: "" # 若此处留空,会从 config.yaml 的 platform.project_id 继承 +``` + +**场景 C:只做翻译不走审校** + +```yaml +# 语种 profile 直接从 workflow 里移除 first_review / second_review: +workflow: + - pull_vcs + - translate + - merge_data + - push_vcs +reviews: + first: { platform: none } # 显式声明 none(可省,但显式更安全) + second: { platform: none } +``` + +--- + +## 相关文档 + +- 项目总览:[`../README.md`](../README.md) +- 架构详解:[`architecture.md`](./architecture.md) +- 工作流状态清单:[`state_registry.md`](./state_registry.md) +- 平台扩展:[`extending_platforms.md`](./extending_platforms.md) +- Phrase 专项:[`platforms/phrase.md`](./platforms/phrase.md) +- 源文件扩展:[`extending_sources.md`](./extending_sources.md) +- LLM 扩展:[`extending_llm.md`](./extending_llm.md) +- VCS 扩展:[`extending_vcs.md`](./extending_vcs.md) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/e2e_test_guide.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/e2e_test_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..0fdcd8ffa44257cca5f650d4c7c90f14b85132f0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/e2e_test_guide.md @@ -0,0 +1,665 @@ +# TiMi_HOK_Game_Translator 端到端测试指南 + +> 本文档帮你证明整套系统在**真实环境**下畅通:按**9 级端到端验证**顺序推进 —— 环境 → VCS 连通 → 源文件解析 → LLM 调用 → 审校平台 → 单语种 workflow → 多语种批处理 → 断点续跑 → 通知。 + +> 📌 **使用说明**: +> - 入口命令统一使用 `python main.py ...`(项目根的 `main.py` 已内置 `sys.path` 引导,无需安装成包); +> - 示例源文件统一使用 [`docs/examples/data/`](./examples/data/) 下的 5 种格式(`example_game.en.{json,yaml,xml,csv,dtxml}`); +> - 示例配置使用 [`docs/examples/demo.yaml`](./examples/demo.yaml) 或项目根 [`conf/config.yaml`](../conf/config.yaml); +> - 语种 profile 使用 [`conf/languages/`](../conf/languages/) 下的 **YAML** 文件(如 `vi.yaml`),不是旧版的 JSON 文件。 + +--- + +## 目录 + +- [0. 前置准备](#0-前置准备) +- [1. 环境自检](#1-环境自检) +- [2. VCS 连通性测试](#2-vcs-连通性测试) +- [3. 源文件格式自检](#3-源文件格式自检) +- [4. LLM 连通性测试](#4-llm-连通性测试) +- [5. 审校平台连通性测试](#5-审校平台连通性测试) +- [6. 单语种端到端测试](#6-单语种端到端测试) +- [7. 多语种批处理测试](#7-多语种批处理测试) +- [8. 断点续跑验证](#8-断点续跑验证) +- [9. 通知渠道验证](#9-通知渠道验证) +- [附录 A:故障排查速查表](#附录-a故障排查速查表) +- [附录 B:如何准备一个可直接使用的测试仓库](#附录-b如何准备一个可直接使用的测试仓库) + +--- + +## 0. 前置准备 + +### 0.1 装依赖 + +```bash +cd gpt/TiMi_HOK_Game_Translator + +# 创建并激活虚拟环境(要求 Python 3.8+) +python -m venv .venv +# Linux/macOS:source .venv/bin/activate +# Windows PowerShell:.venv\Scripts\Activate.ps1 + +# 安装运行时依赖 +pip install -r requirements.txt +``` + +### 0.2 准备测试数据 + +本仓库在 [`docs/examples/data/`](./examples/data/) 下自带 5 种格式的同一批词条样例: +`example_game.en.{json, yaml, xml, csv, dtxml}`,可直接用于 VCS / 源文件 / LLM 等各级探针。 + +如需在 Git / SVN / Perforce 远端仓库里铺这些数据,自行建一个 `locales/` 目录并把 +`docs/examples/data/*` 复制进去即可: + +```bash +mkdir -p my_i18n_test/locales +cp docs/examples/data/example_game.en.* my_i18n_test/locales/ +``` + +### 0.3 环境变量三级注入 + +**永远不要**把凭据写到 YAML!用环境变量: + +```bash +# VCS 凭据 +export GAME_TRANS_TOOLCHAIN__VCS__USERNAME=your-username +export GAME_TRANS_TOOLCHAIN__VCS__PASSWORD=your-secret + +# LLM 凭据 +export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=sk-xxxxx + +# 审校平台凭据 +export GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN=phrase_or_crowdin_token + +# 通知凭据 +export GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK=https://qyapi.weixin.qq.com/... +``` + +**PowerShell 语法**:`$env:GAME_TRANS_TOOLCHAIN__VCS__USERNAME="your-username"` + +--- + +## 1. 环境自检 + +**目的**:验证 Python 与 CLI 装对了。 + +```bash +python --version # >= 3.8 +python main.py --help # 应该列出 run / config 子命令 +python main.py config dump --config docs/examples/demo.yaml +``` + +**期望输出**:一份完整的 YAML,敏感字段(`password / api_token / webhook`)应显示为 `***`。 + +**✅ 通过标准**:`config dump` 打印结束,退出码 0,且**未看到任何原始凭据**。 + +--- + +## 2. VCS 连通性测试 + +分四种后端讲,每种都有**独立命令 + TiMi_HOK_Game_Translator 侧的连通性测试**。 + +### 2.1 Git + +#### 2.1.1 系统层探针 + +```bash +git --version # 确认装了 git +git ls-remote https://github.com/YOUR_ACCOUNT/game-i18n-test.git # 无凭据探测公开仓库 +git clone https://github.com/YOUR_ACCOUNT/game-i18n-test.git /tmp/probe && rm -rf /tmp/probe +``` + +如果是**私有仓库**,用以下任一凭据方式确认: + +```bash +# SSH:确认 ssh key 已加到 GitHub +ssh -T git@github.com + +# HTTPS + Personal Access Token +git ls-remote https://oauth2:${GITHUB_PAT}@github.com/YOUR_ACCOUNT/game-i18n-test.git +``` + +#### 2.1.2 TiMi_HOK_Game_Translator 侧探针 + +```bash +# 复制项目自带的最小配置做修改 +cp conf/config.yaml my_config.yaml +# 把 vcs.type 改为 git,vcs.url 指向你的仓库,vcs.local_path 填 "git/test_translation" + +# 只跑 pull_vcs 一个状态(打印后立即停止): +python -c " +from TiMi_HOK_Game_Translator.config import load +from TiMi_HOK_Game_Translator.vcs import create_vcs_client +cfg = load(config_path='my_config.yaml') +client = create_vcs_client(cfg.vcs, workspace='workspace') +status = client.checkout() +print('OK, files pulled:', status.files_touched) +" +``` + +**✅ 通过标准**:上述脚本打印 `OK, files pulled: N` 且 `workspace//locales/en.json` 已经存在。 + +**❌ 常见错误**: + +| 错误 | 原因 | 处理 | +|---|---|---| +| `fatal: Authentication failed` | PAT 过期 / SSH key 未配置 | 到 GitHub Settings → Developer settings → PAT 重新生成 | +| `Repository not found` | 仓库名写错 / 权限不足 | 复核 `vcs.url` | +| `SSL certificate problem` | 企业代理拦 HTTPS | 设 `GIT_SSL_NO_VERIFY=true` 临时排查(**上线时切勿保留**) | + +### 2.2 SVN + +#### 2.2.1 系统层探针 + +```bash +svn --version # 需 CLI 装了 +svn info https://svn.example.com/game-i18n-test/trunk # 匿名探测 +svn info https://svn.example.com/game-i18n-test/trunk \ + --username $GAME_TRANS_TOOLCHAIN__VCS__USERNAME \ + --password $GAME_TRANS_TOOLCHAIN__VCS__PASSWORD \ + --non-interactive --trust-server-cert +``` + +**⚠️ 关键提示**:`svn status` **不能**可靠判断工作副本是否处于 `wc locked / needs cleanup` 状态。更可靠的方式是: +- 直接 `svn cleanup` (或较新版本支持的 `svn cleanup --dry-run`); +- 或用 `svn update` / `svn info` 触发锁错误 `E155004`; +- 需区分**工作副本锁**(E155004,`svn cleanup` 修)与**版本库文件锁**(`svn lock/unlock` 用)。 + +#### 2.2.2 TiMi_HOK_Game_Translator 侧探针 + +```bash +# 项目根的 conf/config.yaml 默认即为 svn 模板,只需改 vcs.url / local_path +cp conf/config.yaml my_config.yaml +python -c " +from TiMi_HOK_Game_Translator.config import load +from TiMi_HOK_Game_Translator.vcs import create_vcs_client +cfg = load(config_path='my_config.yaml') +client = create_vcs_client(cfg.vcs, workspace='workspace') +print('checkout:', client.checkout().files_touched) +print('update:', client.update().revision) +" +``` + +**✅ 通过标准**:打印两行数字,`workspace/` 下有 `locales/en.json`。 + +### 2.3 Perforce + +```bash +p4 -p perforce.example.com:1666 -u YOUR_USER info # 系统层探针 +p4 -c game-i18n-test-workspace sync //depot/game-i18n-test/main/... # 拉一次 +``` + +TiMi_HOK_Game_Translator 侧探针与 Git 相同,复制 `conf/config.yaml` 后将 `vcs.type` 改为 `perforce`。 +配置字段清单详见 [`configuration.md` → VCS 配置示例](./configuration.md#vcs-配置示例)。 + +### 2.4 Mock(快速本地验证) + +```bash +python main.py run --config docs/examples/demo.yaml --language vi --fresh +``` + +零依赖,用来在**任何 VCS 都不可用时**验证 TiMi_HOK_Game_Translator 本身正确(`demo.yaml` 已把 `vcs.type` 设为 `mock`)。 + +--- + +## 3. 源文件格式自检 + +**目的**:在真调 LLM 之前,先证明你的源文件能被正确解析。 + +```bash +python -c " +from TiMi_HOK_Game_Translator.sources import create_source +from TiMi_HOK_Game_Translator.config.schema import SourceConfig + +for fmt, path in [ + ('json', 'docs/examples/data/example_game.en.json'), + ('yaml', 'docs/examples/data/example_game.en.yaml'), + ('xml', 'docs/examples/data/example_game.en.xml'), + ('csv', 'docs/examples/data/example_game.en.csv'), + ('dtxml', 'docs/examples/data/example_game.en.dtxml'), +]: + src = create_source(SourceConfig(format=fmt, path=path)) + entries = src.load(path) + print(f'{fmt:8} {len(entries):3} entries first key={entries[0].key if entries else \"(empty)\"}') +" +``` + +**✅ 通过标准**:5 行都打印 `entries > 0` 且 `first key` 是合理字符串。 + +> 💡 内置源码还支持 `xliff` / `xlsx` / `properties`,可将这些格式的样例文件丢到 +> `docs/examples/data/` 下并把路径加到循环中测通。 + +**如果你的项目用自定义格式**: + +- 参考 `docs/extending_sources.md` +- 实现 `LocalizationSource.load / dump` +- 用 `@register_source("your_format")` 装饰器注册 +- 把上面的循环加你的 format 就能立即测通 + +--- + +## 4. LLM 连通性测试 + +### 4.1 Mock LLM(默认) + +无需任何配置。用它验证 pipeline 完整性。 + +```bash +python -c " +from TiMi_HOK_Game_Translator.llm import create_llm_client +from TiMi_HOK_Game_Translator.config.schema import LLMConfig +c = create_llm_client(LLMConfig(provider='mock')) +print(c.translate('Hello', source_locale='en', target_locale='vi').text) +" +``` + +**期望输出**:`[vi] Hello` + +### 4.2 OpenAI + +```bash +export GAME_TRANS_TOOLCHAIN__LLM__API_KEY="sk-xxxxx" +python -c " +import os +from TiMi_HOK_Game_Translator.llm import create_llm_client +from TiMi_HOK_Game_Translator.config.schema import LLMConfig +c = create_llm_client(LLMConfig(provider='openai', model='gpt-4o-mini', + api_key=os.environ['GAME_TRANS_TOOLCHAIN__LLM__API_KEY'])) +r = c.translate('Hello, world.', source_locale='en', target_locale='vi', + context='UI greeting') +print('OpenAI 返回:', r.text) +" +``` + +> 💡 bash 中含双下划线的环境变量用 `export KEY="value"` 定义没问题,但在 Python 代码 +> 内读取时必须用 `os.environ['...']`,不能用 `$VAR` 直接插值(shell 解析不会穿透 +> `python -c` 的字符串字面量)。 + +**❌ 常见错误**: + +| 错误 | 原因 | 处理 | +|---|---|---| +| `AuthenticationError: 401` | key 错 / 项目未绑定支付 | 到 platform.openai.com 换 key | +| `RateLimitError: 429` | 免费额度用完 | 加信用卡、或用 `time.sleep` 拉低并发 | +| 中文乱码 | Windows CMD 编码 | `chcp 65001` 或改用 PowerShell | + +### 4.3 自定义 LLM + +例如你想接 Azure OpenAI / 内部部署 LLaMA: + +```python +from TiMi_HOK_Game_Translator.llm import LLMClient, register_llm_provider + + +@register_llm_provider("my_llama") +class MyLlamaClient(LLMClient): + def translate(self, text, *, source_locale, target_locale, context=""): + # 你的 HTTP 调用 + ... +``` + +写完立刻能用:`llm.provider: my_llama` 加到 config.yaml。 + +--- + +## 5. 审校平台连通性测试 + +### 5.1 Phrase TMS(Phrase Platform) + +Phrase 现在推荐的鉴权模式是**Subject Token Exchange**(RFC 8693):从 UI 生成的 token 需要先向 IDM 端点换成 Bearer 短期 access token,再拿去调 TMS API。详见 。 + +#### 5.1.1 最省事:`--whoami` 一键探针(推荐) + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN="your_phrase_token" +python scripts/probe_platform.py \ + --platform phrase --region eu --whoami +``` + +期望输出: + +``` +[INFO] PhrasePlatform: exchanged subject token for Bearer via https://eu.phrase.com/idm/oauth/token (expires in 14399s) +[OK] whoAmI -> user=your-username role=ADMIN org=your-org (uid=xxx) +``` + +看到 `[OK] whoAmI` 就说明整条链路(IDM 交换 → Bearer 缓存 → TMS `whoAmI`)全通。**这一步不需要任何 project_id,只要 token 有效就能跑**。 + +#### 5.1.2 手动 curl 验证(若脚本不方便) + +```bash +# 1) IDM 交换 —— 注意 region!EU 账户用 eu.phrase.com,US 账户用 us.phrase.com +curl -s -X POST https://eu.phrase.com/idm/oauth/token \ + -H 'Content-Type: application/x-www-form-urlencoded' \ + -d 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \ + -d "subject_token=${GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN}" +# → {"access_token":"eyJ...","expires_in":14399,"token_type":"Bearer",...} + +# 2) 用返回的 access_token 调 TMS whoAmI +curl -s https://cloud.memsource.com/web/api2/v1/auth/whoAmI \ + -H "Authorization: Bearer eyJ..." +# → {"user":{"userName":"...","role":"ADMIN"}, "organization":{...}} +``` + +#### 5.1.3 用适配器写一个最小自检脚本 + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN="your_phrase_token" +python -c " +import os +from TiMi_HOK_Game_Translator.platforms import PhrasePlatform +p = PhrasePlatform( + api_base='https://cloud.memsource.com/web/api2', + api_token='', + project_id='YOUR_PROJECT_UID', + extra={'subject_token': os.environ['GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN'], + 'region': 'eu'}, +) +print('project name:', p.get_project_name()) +" +``` + +**✅ 通过标准**:打印非空的 project 名称。 + +**❌ 常见错误**: + +| 错误 | 原因 | 处理 | +|---|---|---| +| IDM `invalid_grant` | 区域错了(EU / US 弄反) | 改 `--region` 或 `extra.region` | +| TMS `auth: not logged` | 用了 `ApiToken` 头去调 subject_token 换出的 Bearer,或反之 | 让适配器自动选头,不要手动组装 | +| `AuthInvalidCredentials` | 直接把 subject_token 当用户名密码送去 `/auth/login` | 切换到 subject_token 模式(`extra.subject_token`) | +| `Not Found` 项目 UID | UID 拼错 / 项目在别的组织 | 到 Phrase UI 复制 URL 里的 UID 段 | + +#### 5.1.4 遗留 ApiToken 模式(早期 Memsource 账号) + +如果你的账号仍然能在 UI 里直接看到长期 ApiToken(无 base64 结构),可以走遗留模式: + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN="phrase_xxx" +python scripts/probe_platform.py \ + --platform phrase --project-id YOUR_UID \ + --file docs/examples/data/example_game.en.json --target vi +``` + +### 5.2 Crowdin + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN="your_crowdin_pat" +python -c " +import os +from TiMi_HOK_Game_Translator.platforms import CrowdinPlatform +p = CrowdinPlatform( + api_base='https://api.crowdin.com/api/v2', + api_token=os.environ['GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN'], + project_id='YOUR_PROJECT_ID', +) +print('project name:', p.get_project_name()) +" +``` + +企业版租户请把 `api_base` 换成 `https://.api.crowdin.com/api/v2`。 + +### 5.3 上传 / 建 job / 查状态 / 下载 —— 完整回路 + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN="your_token" +python scripts/probe_platform.py \ + --platform phrase \ + --project-id YOUR_PROJECT_UID \ + --file docs/examples/data/example_game.en.json \ + --target vi +``` + +这个脚本会: +1. `upload_source(en.json)` → 打印 `file_id`; +2. `create_task([file_id], "vi", review_stage="first")` → 打印 `task_id`; +3. `get_task_status(task_id)` → 打印 `status` 与 `percent`; +4. `download_translations(...)` → 保存到 `workspace/probe_out.json`; +5. `delete_task(task_id)` → 清理,避免占用配额。 + +任何一步失败都会打印**完整 HTTP 请求 + 响应** 供排查(尚未真上传前**先在 UI 里手动删掉遗留 job**)。 + +--- + +## 6. 单语种端到端测试 + +跑一次**最小四步 workflow**:`pull_vcs → translate → validate_data → push_vcs` + +```bash +python main.py run \ + --config docs/examples/demo.yaml \ + --language vi \ + --fresh +``` + +**✅ 通过标准**(3 个都要满足): + +1. 退出码 0; +2. `workspace/vcs/en.json`(或你配的 `source.path`)里所有 entry 的 `target_text` 都以 `[vi] ` 开头(因为用了 mock LLM); +3. `workspace/workflow_state.json` 里所有状态 `status = true`。 + +### 6.1 加入真实审校平台 + +改你的 `config.yaml` 中的 `platform` 段: + +```yaml +platform: + type: phrase + api_base: https://cloud.memsource.com/web/api2 + project_id: YOUR_PROJECT_UID + api_token: "" # 走环境变量 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN +``` + +> ℹ️ 配置模型中 **`platform` 段只有一个**,不区分一审/二审。真正的一审/二审路由在**语种 +> profile** 的 `reviews.first` / `reviews.second` 中声明,由 `first_review` / `second_review` +> 两个工作流状态分别拾取。顶层 `platform` 只是“默认连接池”:profile 的 `reviews.*` +> 里省略的字段(如 `api_base`、`api_token`)会从顶层回填。详见 +> [`docs/configuration.md`](./configuration.md)。 + +准备一份 `conf/languages/vi.yaml`(本仓库已自带,这里是最小示例): + +```yaml +id: vi +target_locale: vi +source: + format: json + path: trunk/tests/fixtures/vi/99.incr.json +reviews: + first: + platform: phrase + project_id: YOUR_PROJECT_UID + target_language_id: vi + extra: + region: eu +workflow: + - pull_vcs + - translate + - first_review + - validate_data + - push_vcs +``` + +```bash +python main.py run \ + --config my_config.yaml \ + --language vi \ + --languages-dir conf/languages/ \ + --fresh +``` + +--- + +## 7. 多语种批处理测试 + +仓库自带的 `conf/languages/` 目录下已经有 14 份 YAML profile: + +``` +conf/languages/ +├── vi.yaml +├── ja.yaml +├── ko.yaml +├── ar.yaml +└── ...(de / es / fr / id / pt-BR / ru / th / tr / zh-Hant / en) +``` + +然后循环运行: + +```bash +for lang in vi ja ko; do + python main.py run --config my_config.yaml --language "$lang" --fresh +done +``` + +**✅ 通过标准**:每语种一个独立的 `workspace/_workflow_state.json`(如果你 `workspace.root: workspace/{language}`)或者共享的 `workflow_state.json` 都全部完成。 + +--- + +## 8. 断点续跑验证 + +**目的**:证明真的可以恢复。 + +```bash +# 1. 起一次任务但故意中途 kill +python main.py run --config my_config.yaml --language vi --fresh & +sleep 2 +kill -9 $! + +# 2. 检查状态文件(部分状态应该已完成,部分未完成) +cat workspace/workflow_state.json + +# 3. 不带 --fresh 再跑一次 +python main.py run --config my_config.yaml --language vi + +# 4. 现在所有 status 都应该 = true,且未完成的部分从上次断点继续 +``` + +**✅ 通过标准**:第二次运行只处理**未完成**的状态,日志里能看到大量 `already completed — skipping` 行。 + +--- + +## 9. 通知渠道验证 + +### 9.1 Console(默认) + +`python main.py run ...` 结束时直接 stdout 打印一行 "pipeline finished"。 + +### 9.2 企业微信 + +```bash +export GAME_TRANS_TOOLCHAIN__NOTIFICATION__TYPE="wecom" +export GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY" +python main.py run --config my_config.yaml --language vi --fresh +``` + +**通知失败永远不会阻塞主流水线** —— 这是 TiMi_HOK_Game_Translator 的强约定。所以即使 webhook 写错,`python main.py run` 也不会失败,你需要**看日志**里是否有 `Notifier failed:` 警告。 + +### 9.3 Slack / Email + +同理,见 `docs/architecture.md` 中"六个可插拔层"章节。 + +--- + +## 附录 A:故障排查速查表 + +| 错误关键字 | 出现位置 | 处理 | +|---|---|---| +| `Authentication failed` | git/svn/p4 拉代码 | 检查 PAT / 密码 / 是否被墙 | +| `SSL certificate problem` | https 请求 | 企业代理 → 走 `HTTPS_PROXY` 或 `SSL_CERT_FILE` | +| `E155004 working copy is locked` | svn | `svn cleanup` 然后重试 | +| `auth: not logged` | Phrase TMS | 用错认证模式:把 subject_token 当 ApiToken 直接发。切到 `extra.subject_token` 让适配器自动换 Bearer | +| `invalid_grant` | Phrase IDM | 区域错了:EU 账户走 `eu.phrase.com`,US 走 `us.phrase.com` | +| `401 Unauthorized` | Crowdin/OpenAI | token 错 / 配额用尽 | +| `429 Too Many Requests` | LLM | 调低并发 `default_max_workers` | +| `File not found` | source.load | 相对路径基于 `vcs.local_path`,不是当前目录 | +| `KeyError: source_text` | csv/xml 解析 | 确认列名/元素名,参考 `docs/examples/data/example_game.en.*` | +| `pipeline failed` 但没 traceback | runner | 加 `--log-level DEBUG` 或直接看 `workspace/workflow_state.json` 的 error 字段 | + +--- + +## 附录 B:如何准备一个可直接使用的测试仓库 + +**目标**:复用仓库自带的样例数据与 profile,三步就能跑通最小端到端链路。 + +### B.1 用 `docs/examples/data/` 作为源文件库 + +仓库自带 5 种格式的同一批样例词条: + +``` +docs/examples/data/ +├── example_game.en.json +├── example_game.en.yaml +├── example_game.en.xml +├── example_game.en.csv +└── example_game.en.dtxml +``` + +如果需要在远端 VCS 中验证,自行建一个仓库并把这些文件复制过去: + +```bash +# 示例:git 远端仓库 +mkdir -p my-i18n-test/locales +cp docs/examples/data/example_game.en.* my-i18n-test/locales/ +cd my-i18n-test && git init && git add -A \ + && git commit -m "chore: initial i18n fixtures" \ + && git remote add origin https://github.com/YOUR_ACCOUNT/my-i18n-test.git \ + && git push -u origin main +``` + +### B.2 复制项目配置并指向你的仓库 + +在 TiMi_HOK_Game_Translator 项目根: + +```bash +cp conf/config.yaml my_config.yaml +# 编辑 my_config.yaml: +# vcs.type: git +# vcs.url: https://github.com/YOUR_ACCOUNT/my-i18n-test.git +# vcs.local_path: git/my-i18n-test +# source.format: json +# source.path: locales/example_game.en.json +python main.py run --config my_config.yaml --language vi --fresh +``` + +> 💡 想完全离线验证(不连任何 VCS),把 `vcs.type` 改为 `mock` 即可,相当于直接使用 +> 已经准备好的本地文件。参见 [`docs/examples/demo.yaml`](./examples/demo.yaml)。 + +### B.3 想要多语种? + +参考 [`conf/languages/`](../conf/languages/) 下已有的 14 份语种 profile(如 +`vi.yaml` / `ja.yaml`),复制一份改 `id / target_locale / reviews / workflow` +即可。或者用脚本一键生成: + +```bash +python scripts/generate_language_profiles.py ko ja th # 批量生成占位 profile +``` + +按需编辑后运行: + +```bash +python main.py run --config my_config.yaml --language vi \ + --languages-dir conf/languages/ --fresh +``` + +### B.4 加真实审校平台 + +- **Phrase**:见 [`docs/platforms/phrase.md`](./platforms/phrase.md) +- **Crowdin**:见 [`docs/extending_platforms.md`](./extending_platforms.md) + +只需在 `conf/languages/vi.yaml` 的 `reviews.first` / `reviews.second` 段填 `project_id + target_language_id`,把 API Token 通过环境变量注入。**一审二审可以走完全不同的后端**。 + +--- + +## 结束语 + +通过本文档的 9 级测试,你可以确认: + +- ✅ Python / CLI / VCS / 网络四大基础环境; +- ✅ VCS 后端(Git / SVN / Perforce)真实连通; +- ✅ 5 种源文件格式全部可解析; +- ✅ LLM 与审校平台真实调通; +- ✅ 单语种端到端流水线可完成; +- ✅ 多语种批处理可并发运行; +- ✅ 断点续跑真的能恢复; +- ✅ 通知渠道不会阻塞主流水线。 + +每一步都通过后,你的 TiMi_HOK_Game_Translator 环境就**具备了正式接入真实业务项目的能力**。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.csv b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.csv new file mode 100644 index 0000000000000000000000000000000000000000..87872cbe62691e56a720032a92ceef2fb6672bae --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.csv @@ -0,0 +1,8 @@ +key,source_text,context,comment +ui.mainmenu.play,Play,Main menu — start a new game.,Short action button. +ui.mainmenu.settings,Settings,Main menu — open the settings panel., +ui.mainmenu.quit,Quit,Main menu — exit the application., +hud.health,HP: {value}/{max},HUD label for current and maximum health.,Placeholders {value} and {max} must be preserved. +dialog.tutorial.welcome,"Welcome, brave adventurer! Your journey starts here.",Tutorial NPC greeting at the start of the game., +achievement.first_win.name,First Blood,Achievement title for winning the first battle., +error.network.offline,You are currently offline. Please check your connection.,Displayed when the client cannot reach the server., diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.dtxml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.dtxml new file mode 100644 index 0000000000000000000000000000000000000000..105c9e522a40a83a5bf691d3b7dd397299843a62 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.dtxml @@ -0,0 +1,30 @@ + + + + + + Play + Main menu — start a new game. + Short action button. + + + Settings + Main menu — open the settings panel. + + + + HP: {value}/{max} + HUD label. + Placeholders must be preserved. + + + Welcome, brave adventurer! Your journey starts here. + Tutorial NPC greeting. + + + + diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.json b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.json new file mode 100644 index 0000000000000000000000000000000000000000..9db4cac1693e54932636c79c2cf1431862fd198c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.json @@ -0,0 +1,71 @@ +{ + "$schema": "../schema/localization.schema.json", + "meta": { + "project_code": "example_game", + "source_locale": "en", + "target_locale": "zh-CN", + "note": "Fully fictional demo strings for TiMi_HOK_Game_Translator showcase. No real product data." + }, + "entries": [ + { + "key": "ui.mainmenu.play", + "source_text": "Play", + "context": "Main menu — start a new game.", + "comment": "Short action button." + }, + { + "key": "ui.mainmenu.settings", + "source_text": "Settings", + "context": "Main menu — open the settings panel.", + "comment": "" + }, + { + "key": "ui.mainmenu.quit", + "source_text": "Quit", + "context": "Main menu — exit the application.", + "comment": "" + }, + { + "key": "hud.health", + "source_text": "HP: {value}/{max}", + "context": "HUD label for current and maximum health.", + "comment": "Placeholders {value} and {max} must be preserved." + }, + { + "key": "dialog.tutorial.welcome", + "source_text": "Welcome, brave adventurer! Your journey starts here.", + "context": "Tutorial NPC greeting at the start of the game.", + "comment": "" + }, + { + "key": "dialog.tutorial.instructions", + "source_text": "Use the arrow keys to move and press [SPACE] to attack.", + "context": "Tutorial NPC control instructions.", + "comment": "Keep [SPACE] in English as it refers to a physical key." + }, + { + "key": "achievement.first_win.name", + "source_text": "First Blood", + "context": "Achievement title for winning the first battle.", + "comment": "" + }, + { + "key": "achievement.first_win.desc", + "source_text": "Win your first battle.", + "context": "Achievement description shown below the title.", + "comment": "" + }, + { + "key": "error.network.offline", + "source_text": "You are currently offline. Please check your connection.", + "context": "Displayed when the client cannot reach the server.", + "comment": "" + }, + { + "key": "error.save.failed", + "source_text": "Failed to save the game. Retry?", + "context": "Modal dialog when a save operation fails.", + "comment": "" + } + ] +} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.xml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.xml new file mode 100644 index 0000000000000000000000000000000000000000..d7e788cb759405ccef93d2f128c8cb6450c4bf17 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.xml @@ -0,0 +1,25 @@ + + + + + Play + + + Settings + + + Quit + + + HP: {value}/{max} + + + Welcome, brave adventurer! Your journey starts here. + + + First Blood + + diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9cb2a4d0180248b233d5d432a7b527d7f03be45d --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.en.yaml @@ -0,0 +1,33 @@ +# Fully fictional demo strings for TiMi_HOK_Game_Translator showcase. +# No real product data. Format mirrors ``docs/examples/data/example_game.en.json``. +meta: + project_code: example_game + source_locale: en + target_locale: zh-CN + note: "YAML demo — same schema as the JSON variant." + +entries: + - key: ui.mainmenu.play + source_text: Play + context: "Main menu — start a new game." + comment: "Short action button." + - key: ui.mainmenu.settings + source_text: Settings + context: "Main menu — open the settings panel." + comment: "" + - key: ui.mainmenu.quit + source_text: Quit + context: "Main menu — exit the application." + comment: "" + - key: hud.health + source_text: "HP: {value}/{max}" + context: "HUD label for current and maximum health." + comment: "Placeholders {value} and {max} must be preserved." + - key: dialog.tutorial.welcome + source_text: "Welcome, brave adventurer! Your journey starts here." + context: "Tutorial NPC greeting at the start of the game." + comment: "" + - key: achievement.first_win.name + source_text: "First Blood" + context: "Achievement title for winning the first battle." + comment: "" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.zh-CN.json b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.zh-CN.json new file mode 100644 index 0000000000000000000000000000000000000000..b7e9ff904f21fe4e59386eb1ccf43fc56d6639fe --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/data/example_game.zh-CN.json @@ -0,0 +1,311 @@ +{ + "$schema": "../schema/localization.schema.json", + "meta": { + "project_code": "example_game", + "source_locale": "zh-CN", + "target_locale": "en", + "note": "完全虚构的 TiMi_HOK_Game_Translator 示例文案,不包含任何真实产品数据。" + }, + "entries": [ + { + "key": "ui.mainmenu.play", + "source_text": "开始游戏", + "context": "主菜单——开启一局新游戏。", + "comment": "简短的动作按钮。" + }, + { + "key": "ui.mainmenu.settings", + "source_text": "设置", + "context": "主菜单——打开设置面板。", + "comment": "" + }, + { + "key": "ui.mainmenu.quit", + "source_text": "退出", + "context": "主菜单——退出应用。", + "comment": "" + }, + { + "key": "hud.health", + "source_text": "生命值:{value}/{max}", + "context": "HUD 中显示当前及最大生命值。", + "comment": "占位符 {value} 和 {max} 必须保留。" + }, + { + "key": "dialog.tutorial.welcome", + "source_text": "欢迎你,勇敢的冒险者!你的旅程从这里开始。", + "context": "新手引导 NPC 在游戏开始时的问候。", + "comment": "" + }, + { + "key": "dialog.tutorial.instructions", + "source_text": "使用方向键移动,按 [空格] 键攻击。", + "context": "新手引导 NPC 的操作说明。", + "comment": "[空格] 指物理按键,译文中请保持直观易懂。" + }, + { + "key": "achievement.first_win.name", + "source_text": "首胜", + "context": "赢得第一场战斗的成就标题。", + "comment": "" + }, + { + "key": "achievement.first_win.desc", + "source_text": "赢得你的第一场战斗。", + "context": "成就标题下方展示的描述。", + "comment": "" + }, + { + "key": "error.network.offline", + "source_text": "当前处于离线状态,请检查你的网络连接。", + "context": "客户端无法连接服务器时显示。", + "comment": "" + }, + { + "key": "error.save.failed", + "source_text": "保存游戏失败,是否重试?", + "context": "保存操作失败时弹出的模态对话框。", + "comment": "" + }, + { + "key": "ui.mainmenu.continue", + "source_text": "继续游戏", + "context": "主菜单——从最近的存档继续。", + "comment": "" + }, + { + "key": "ui.mainmenu.load", + "source_text": "读取存档", + "context": "主菜单——打开存档列表。", + "comment": "" + }, + { + "key": "ui.mainmenu.multiplayer", + "source_text": "多人联机", + "context": "主菜单——进入多人大厅。", + "comment": "" + }, + { + "key": "ui.mainmenu.credits", + "source_text": "制作名单", + "context": "主菜单——查看制作团队名单。", + "comment": "" + }, + { + "key": "ui.button.confirm", + "source_text": "确认", + "context": "通用确认按钮。", + "comment": "尽量使用简短的译词。" + }, + { + "key": "ui.button.cancel", + "source_text": "取消", + "context": "通用取消按钮。", + "comment": "" + }, + { + "key": "ui.button.back", + "source_text": "返回", + "context": "通用返回上一级按钮。", + "comment": "" + }, + { + "key": "ui.button.close", + "source_text": "关闭", + "context": "通用关闭弹窗按钮。", + "comment": "" + }, + { + "key": "hud.mana", + "source_text": "法力值:{value}/{max}", + "context": "HUD 中显示当前及最大法力值。", + "comment": "占位符 {value} 和 {max} 必须保留。" + }, + { + "key": "hud.stamina", + "source_text": "体力值:{value}/{max}", + "context": "HUD 中显示当前及最大体力值。", + "comment": "占位符 {value} 和 {max} 必须保留。" + }, + { + "key": "hud.level", + "source_text": "等级 {level}", + "context": "HUD 中显示角色等级。", + "comment": "占位符 {level} 必须保留。" + }, + { + "key": "hud.exp", + "source_text": "经验值:{value}/{max}", + "context": "HUD 中显示当前及升级所需经验。", + "comment": "占位符 {value} 和 {max} 必须保留。" + }, + { + "key": "hud.gold", + "source_text": "金币:{amount}", + "context": "HUD 中显示当前金币数量。", + "comment": "占位符 {amount} 必须保留。" + }, + { + "key": "dialog.npc.merchant.greeting", + "source_text": "欢迎光临,想要买点什么?", + "context": "商人 NPC 打招呼。", + "comment": "" + }, + { + "key": "dialog.npc.merchant.farewell", + "source_text": "一路顺风,冒险者!", + "context": "玩家结束与商人交谈时的告别语。", + "comment": "" + }, + { + "key": "dialog.npc.blacksmith.greeting", + "source_text": "需要我为你的装备打磨一番吗?", + "context": "铁匠 NPC 打招呼。", + "comment": "" + }, + { + "key": "dialog.quest.accept", + "source_text": "我接受这个任务。", + "context": "任务对话——玩家接受任务时的选项。", + "comment": "" + }, + { + "key": "dialog.quest.decline", + "source_text": "现在还不是时候。", + "context": "任务对话——玩家婉拒任务时的选项。", + "comment": "" + }, + { + "key": "quest.main.chapter1.title", + "source_text": "第一章:失落的星图", + "context": "主线任务章节标题。", + "comment": "" + }, + { + "key": "quest.main.chapter1.objective", + "source_text": "前往古代神殿寻找失落的星图。", + "context": "主线任务目标描述。", + "comment": "" + }, + { + "key": "quest.side.lost_cat.title", + "source_text": "寻找走失的小猫", + "context": "支线任务标题。", + "comment": "" + }, + { + "key": "quest.side.lost_cat.objective", + "source_text": "帮助村民找回走失的小猫,奖励:{reward} 金币。", + "context": "支线任务目标描述。", + "comment": "占位符 {reward} 必须保留。" + }, + { + "key": "item.potion.health.name", + "source_text": "生命药水", + "context": "道具名称——生命药水。", + "comment": "" + }, + { + "key": "item.potion.health.desc", + "source_text": "饮用后立即恢复 {value} 点生命值。", + "context": "道具描述——生命药水效果。", + "comment": "占位符 {value} 必须保留。" + }, + { + "key": "item.potion.mana.name", + "source_text": "法力药水", + "context": "道具名称——法力药水。", + "comment": "" + }, + { + "key": "item.potion.mana.desc", + "source_text": "饮用后立即恢复 {value} 点法力值。", + "context": "道具描述——法力药水效果。", + "comment": "占位符 {value} 必须保留。" + }, + { + "key": "item.weapon.ironsword.name", + "source_text": "铁剑", + "context": "武器名称——铁剑。", + "comment": "" + }, + { + "key": "item.weapon.ironsword.desc", + "source_text": "一把结实耐用的铁剑,适合初出茅庐的冒险者。", + "context": "武器描述——铁剑。", + "comment": "" + }, + { + "key": "achievement.level10.name", + "source_text": "初露锋芒", + "context": "角色升至 10 级的成就标题。", + "comment": "" + }, + { + "key": "achievement.level10.desc", + "source_text": "角色等级达到 10 级。", + "context": "成就描述。", + "comment": "" + }, + { + "key": "achievement.explorer.name", + "source_text": "无畏探险家", + "context": "探索成就标题。", + "comment": "" + }, + { + "key": "achievement.explorer.desc", + "source_text": "解锁地图上的 {count} 个区域。", + "context": "探索成就描述。", + "comment": "占位符 {count} 必须保留。" + }, + { + "key": "settings.audio.master", + "source_text": "主音量", + "context": "设置界面——主音量滑条标签。", + "comment": "" + }, + { + "key": "settings.audio.music", + "source_text": "音乐音量", + "context": "设置界面——音乐音量滑条标签。", + "comment": "" + }, + { + "key": "settings.audio.sfx", + "source_text": "音效音量", + "context": "设置界面——音效音量滑条标签。", + "comment": "" + }, + { + "key": "settings.graphics.fullscreen", + "source_text": "全屏模式", + "context": "设置界面——全屏模式切换项。", + "comment": "" + }, + { + "key": "settings.graphics.resolution", + "source_text": "分辨率", + "context": "设置界面——分辨率下拉菜单标签。", + "comment": "" + }, + { + "key": "settings.language", + "source_text": "语言", + "context": "设置界面——语言下拉菜单标签。", + "comment": "" + }, + { + "key": "error.server.timeout", + "source_text": "服务器响应超时,请稍后再试。", + "context": "服务器响应超时时弹出的错误提示。", + "comment": "" + }, + { + "key": "error.auth.invalid", + "source_text": "账号或密码错误,请重新输入。", + "context": "登录失败时的错误提示。", + "comment": "" + } + ] +} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/demo.yaml b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/demo.yaml new file mode 100644 index 0000000000000000000000000000000000000000..153dbc91c267809e60974bc95a52bfd8548fb143 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/examples/demo.yaml @@ -0,0 +1,47 @@ +# ============================================================================= +# TiMi_HOK_Game_Translator — end-to-end demo configuration +# ============================================================================= +# 从项目根目录运行: +# python main.py run --config docs/examples/demo.yaml +# +# All backends are set to the built-in mocks so no external service is +# required. 把 source.path 换成同目录下 data/ 的其他格式即可切换源文件格式。 +# ============================================================================= + +project_code: example_game +stage: trunk_week +source_locale: en +target_locale: zh-CN + +vcs: + type: mock + url: mock://demo + # 相对 workspace.root(默认 ${CWD}/workspace)。mock VCS 不实际克隆, + # 只要 source.path 能在 cwd 下找到即可。 + local_path: vcs + +source: + format: json + # 相对项目根(通过 workspace 根再加 vcs.local_path 展开)。 + # 这里直接指向 docs/examples/data/ 下的样例数据,无需额外复制。 + path: ../../docs/examples/data/example_game.en.json + encoding: utf-8 + +llm: + provider: mock + temperature: 0.2 + batch_size: 8 + +platform: + type: none + +notification: + type: console + +workspace: + root: "" + subdir: workspace + +logging: + level: INFO + console: true diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_llm.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_llm.md new file mode 100644 index 0000000000000000000000000000000000000000..7ef255a6ade4283b0005c0c92c8458edc86e624e --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_llm.md @@ -0,0 +1,87 @@ +# 扩展指南:新增一种 LLM 提供方 + +框架内置的 LLM 提供方: + +- `LocalMockLLM`(默认,provider 名 `echo`,老别名 `mock`)——不联网、结果可预测,把原文带 `[locale]` 标签回显,测试专用; +- `OpenAILLM`——可选(`pip install "TiMi_HOK_Game_Translator[openai]"`)。 + +下面演示如何以插件形式接入另一家——比如 Anthropic 的 Claude。 + +## 1. 继承 `LLMClient` + +```python +# my_project/claude_llm.py +import os +from TiMi_HOK_Game_Translator.llm import LLMClient, LLMResponse +from TiMi_HOK_Game_Translator.commons import LLMProviderMissingError + + +class ClaudeLLM(LLMClient): + provider_name = "claude" + + def _client(self): + try: + import anthropic # type: ignore + except ImportError as exc: + raise LLMProviderMissingError( + "请先安装:pip install anthropic" + ) from exc + api_key = self.api_key or os.getenv("ANTHROPIC_API_KEY", "") + if not api_key: + raise LLMProviderMissingError("未配置 ANTHROPIC_API_KEY") + return anthropic.Anthropic(api_key=api_key) + + def translate(self, text, *, source_locale="", target_locale="", context=""): + client = self._client() + model = self.model or "claude-3-5-sonnet-latest" + prompt = ( + f"请把下面的文本从 {source_locale or 'auto'} " + f"翻译到 {target_locale or 'unspecified'},保留占位符不动。\n\n" + f"文本:{text}" + ) + response = client.messages.create( + model=model, + max_tokens=self.max_tokens, + messages=[{"role": "user", "content": prompt}], + ) + translated = response.content[0].text.strip() + return LLMResponse(text=translated, provider=self.provider_name, model=model) +``` + +## 2. 注册 + +```python +from TiMi_HOK_Game_Translator.llm import register_llm_provider +from .claude_llm import ClaudeLLM + +register_llm_provider("claude", ClaudeLLM) +``` + +## 3. 配置 + +```yaml +llm: + provider: claude + model: claude-3-5-sonnet-latest + temperature: 0.2 + # api_key 会从 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 或 ANTHROPIC_API_KEY 读取。 +``` + +## 批量效率 + +默认的 `batch_translate()` 会循环调用 `translate()`。如果你的提供方有 +原生 batch 接口(或者一次性把多条内容拼进同一 prompt 更便宜), +请直接重写这个方法: + +```python +def batch_translate(self, texts, *, source_locale="", target_locale="", context=""): + # 把多个 texts 拼成一个 prompt,再把返回的编号列表解析回来。 + ... +``` + +## 测试 + +- 单元测试**绝对不要**打真实 API。参考 + `tests/unit/test_llm.py::TestOpenAILLM`,通过 `sys.modules` + 注入 fake 模块; +- 至少覆盖:SDK 未安装、API key 缺失、正常返回、重试后恢复等路径。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_platforms.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_platforms.md new file mode 100644 index 0000000000000000000000000000000000000000..5f3d14c829f528a731aacd11eb42df13490c3e3c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_platforms.md @@ -0,0 +1,307 @@ +# 扩展指南:接入一个新的翻译 / 审校平台 + +假设你希望把 [Lokalise](https://lokalise.com/) 接进来,让一审或二审走它的 +项目工作流。本指南演示如何通过**约 100 行代码** + 一行注册把它接入 `TiMi_HOK_Game_Translator`, +无需改动框架本身。 + +> 本框架内置两种平台适配器可供参考:[`PhrasePlatform`](../src/TiMi_HOK_Game_Translator/platforms/phrase_platform.py) +> 与 [`CrowdinPlatform`](../src/TiMi_HOK_Game_Translator/platforms/crowdin_platform.py),`NoopPlatform` 则是 `platform.type: none` 的最小兜底实现。 + +--- + +## 1. 继承 `TranslationPlatform` + +框架为平台定义了一组极简的协议(见 [`src/TiMi_HOK_Game_Translator/platforms/base.py`](../src/TiMi_HOK_Game_Translator/platforms/base.py))。 +一个合格的平台适配器只需要实现这 5 个必覆盖方法: + +| 方法 | 做什么 | +|---|---| +| `upload_source(file_path, *, remote_path)` | 把本地源文件上传成平台上的 "file / job",返回 `UploadResult(file_id=...)` | +| `create_task(file_ids, target_locale, *, review_stage, title, description)` | 为上传的文件集创建审校任务,返回 `TaskInfo(task_id=...)` | +| `get_task_status(task_id, *, review_stage)` | 轮询任务状态,映射到 `TaskStatus.PENDING/IN_PROGRESS/APPROVED/REJECTED/UNKNOWN` | +| `import_approved(task_id, dest_path, *, review_stage)` | 下载**已批准**译文到本地文件,返回落地路径 | +| `download_translations(file_id, target_locale, dest_path, *, review_stage)` | 按文件维度下载全部译文(无论是否已批准) | +| `export_review_report(task_id, dest_path, *, review_stage)` | 导出可读的审校报告(无 Analytics 接口时可写一个简短 txt) | + +另外三个方法已有默认实现,按需覆盖即可: + +| 方法 | 默认行为 | +|---|---| +| `split_approved_data(task_id, ...)` | 仅返回 `import_approved` 的结果;平台若能按段级(segment)区分 approved/pending,强烈建议重写 | +| `delete_task(task_id, ...)` / `delete_file(file_id, ...)` | 空实现;若想避免平台项目堆积,覆盖它调用对应 REST DELETE | +| `get_project_name(project_id)` | 回传 `project_id`;想显示人类可读名称可覆盖 | + +### 骨架代码 + +```python +# my_plugin/lokalise_platform.py +from __future__ import annotations + +from typing import Sequence +import requests + +from TiMi_HOK_Game_Translator.commons import PlatformError, ReviewStage +from TiMi_HOK_Game_Translator.platforms import ( + TranslationPlatform, + TaskInfo, + TaskStatus, + UploadResult, +) + + +class LokalisePlatform(TranslationPlatform): + """最小可用的 Lokalise 适配器。""" + + platform_name = "lokalise" + # 空元组 = 不限制 review_stage;需要只支持某些阶段时填 ("first", "second")。 + supports_stages: tuple = () + + _STATUS_MAP = { + "queued": TaskStatus.PENDING, + "in_progress": TaskStatus.IN_PROGRESS, + "completed": TaskStatus.APPROVED, + "cancelled": TaskStatus.REJECTED, + } + + def _headers(self) -> dict: + if not self.api_token: + raise PlatformError("Lokalise api_token is empty") + return {"X-Api-Token": self.api_token, "Content-Type": "application/json"} + + def _url(self, path: str) -> str: + base = self.api_base.rstrip("/") or "https://api.lokalise.com/api2" + return f"{base}{path}" + + # ---- 必覆盖 ---- + def upload_source(self, file_path, *, remote_path=""): + with open(file_path, "rb") as f: + data = f.read() + resp = requests.post( + self._url(f"/projects/{self.project_id}/files/upload"), + headers=self._headers(), + json={"data": data.decode("utf-8"), "filename": remote_path or file_path}, + timeout=60, + ) + resp.raise_for_status() + return UploadResult(file_id=str(resp.json()["process"]["id"])) + + def create_task(self, file_ids, target_locale, *, + review_stage=ReviewStage.FIRST.value, title="", description=""): + payload = { + "title": title or "TiMi_HOK_Game_Translator review", + "description": description, + "languages": [{"language_iso": target_locale, "users": []}], + "source_language_iso": "zh_CN", + "project_id": self.project_id, + } + resp = requests.post( + self._url(f"/projects/{self.project_id}/tasks"), + headers=self._headers(), json=payload, timeout=60, + ) + resp.raise_for_status() + task = resp.json()["task"] + return TaskInfo( + task_id=str(task["task_id"]), + status=self._STATUS_MAP.get(task.get("status", ""), TaskStatus.UNKNOWN), + target_locale=target_locale, + project_id=self.project_id, + review_stage=review_stage, + ) + + def get_task_status(self, task_id, *, review_stage=ReviewStage.FIRST.value): + resp = requests.get( + self._url(f"/projects/{self.project_id}/tasks/{task_id}"), + headers=self._headers(), timeout=30, + ) + resp.raise_for_status() + task = resp.json()["task"] + return TaskInfo( + task_id=task_id, + status=self._STATUS_MAP.get(task.get("status", ""), TaskStatus.UNKNOWN), + percent_completed=float(task.get("progress", 0)), + review_stage=review_stage, + ) + + def import_approved(self, task_id, dest_path, *, review_stage=ReviewStage.FIRST.value): + # Lokalise 没有直接的 "下载 task approved 文件" 接口; + # 这里演示:先从 task 查到关联 file,再按 file 导出 JSON。 + # 真实实现建议走 /files/download,并过滤 translation.is_reviewed=True。 + with open(dest_path, "w", encoding="utf-8") as f: + f.write("{}") # 省略:真实 HTTP + JSON 落盘 + return dest_path + + def download_translations(self, file_id, target_locale, dest_path, *, + review_stage=ReviewStage.FIRST.value): + # 类似 import_approved,不过不过滤 is_reviewed。 + with open(dest_path, "w", encoding="utf-8") as f: + f.write("{}") + return dest_path + + def export_review_report(self, task_id, dest_path, *, + review_stage=ReviewStage.FIRST.value): + info = self.get_task_status(task_id, review_stage=review_stage) + with open(dest_path, "w", encoding="utf-8") as f: + f.write(f"task {task_id} progress={info.percent_completed}%\n") + return dest_path +``` + +--- + +## 2. 注册平台名 + +在包的 `__init__.py` 里一行注册,确保 `TiMi_HOK_Game_Translator` 在工厂构造时能找到它: + +```python +# my_plugin/__init__.py +from TiMi_HOK_Game_Translator.platforms import register_platform +from .lokalise_platform import LokalisePlatform + +register_platform("lokalise", LokalisePlatform) +``` + +> 📌 名称大小写不敏感。重复 `register_platform` 以替换内置实现也是允许的 +> (适合你需要**覆盖**官方 Phrase 适配器时)。 + +--- + +## 3. 让插件被 import 到 + +和 VCS 扩展一样,`TiMi_HOK_Game_Translator` 并不知道你的插件存在。两种常见做法: + +- **自建 CLI 入口**:在自己的 console-script 里 `import my_plugin` 后再调 `TiMi_HOK_Game_Translator.cli.main`; +- **`.pth` 文件**:随 wheel 发一个 `my_plugin.pth`,内容是 `import my_plugin`,解释器启动时自动加载。 + +--- + +## 4. 在 YAML 中启用 + +### 方案 A:全局单一平台 + +```yaml +# conf/config.yaml +platform: + type: lokalise + api_base: https://api.lokalise.com/api2 + api_token: "" # 走 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN 环境变量 + project_id: "123456789" +``` + +然后在语种 profile 里让某阶段**显式继承**(`platform` 字段省略或填 `""`): + +```yaml +# conf/languages/vi.yaml +reviews: + first: + platform: "" # 空 → 回退到全局 platform.type=lokalise + project_name: VI First +``` + +### 方案 B:一审 + 二审走不同后端(最常用) + +框架为**每个 `review_stage` 独立选择平台**,这是 `build_review_tool` 的核心机制 +(见 [`src/TiMi_HOK_Game_Translator/platforms/factory.py`](../src/TiMi_HOK_Game_Translator/platforms/factory.py)): + +```yaml +reviews: + first: + platform: phrase # 一审走 Phrase + project_id: "" + target_language_id: vi + extra: + region: eu + second: + platform: lokalise # 二审走你新接的 Lokalise + project_id: "123456789" + target_language_id: vi +``` + +框架会分别用两个工厂实例,互不干扰。**跨平台保护**: +`build_review_tool` 在回退到全局 `platform` 时,仅当全局 `type` 与阶段 +`platform` 相同时才共享 `api_base/api_token/project_id`,避免 "Phrase 用了 Crowdin +token / 请求打到对方 nginx" 这种污染。 + +### 方案 C:阶段级 fallback(内部状态机使用) + +工作流状态可以给 `build_review_tool` 传 `fallback` 参数——当阶段级 `platform` +填 `"none"` 时才启用 fallback 名称。多数业务不需要关心。 + +--- + +## 5. 可选:覆盖 `split_approved_data` + +默认实现只把 `import_approved` 的结果塞进 `approved_path`,`pending_path` 为空。 +如果你的平台能按段级(segment)区分 approved/pending(比如 Crowdin 的 +`ApprovalStatus` 列),强烈建议重写: + +```python +from TiMi_HOK_Game_Translator.platforms import SplitResult + + +class LokalisePlatform(TranslationPlatform): + ... + + def split_approved_data(self, task_id, *, + save_approved_path, save_pending_path="", + review_stage=ReviewStage.FIRST.value): + # 1. 拉取 task 全部译文 + 每段 is_reviewed 标记 + rows = self._fetch_task_rows(task_id) + approved_rows = [r for r in rows if r["is_reviewed"]] + pending_rows = [r for r in rows if not r["is_reviewed"]] + + self._write_rows(save_approved_path, approved_rows) + if save_pending_path: + self._write_rows(save_pending_path, pending_rows) + + return SplitResult( + approved_path=save_approved_path, + pending_path=save_pending_path if pending_rows else "", + should_continue=bool(approved_rows), + is_complete=not pending_rows, + ) +``` + +状态机 `FirstReviewState` / `SecondReviewState` 根据 `is_complete` 判断是否 +需要**跨天续审**,`should_continue` 决定要不要把当批已 approved 合并回主表。 + +--- + +## 6. 可选:删除平台残留文件 / 任务 + +`delete_task` 和 `delete_file` 默认都是空实现。生产长时间运行时,平台项目目录 +很容易被几百份已 split 掉的 xlsx / xml 塞满——建议至少实现 `delete_file`: + +```python +def delete_file(self, file_id, *, review_stage=ReviewStage.FIRST.value): + requests.delete( + self._url(f"/projects/{self.project_id}/files/{file_id}"), + headers=self._headers(), timeout=30, + ).raise_for_status() +``` + +> ⚠️ **调用顺序**:删 task 之后再删 file。顺序颠倒容易触发平台的 +> "文件被 task 引用无法删除" 409 响应。 + +--- + +## 7. 测试你的平台 + +参考 [`tests/unit/test_platform_phrase.py`](../tests/unit/test_platform_phrase.py) +与 [`tests/unit/test_platform_crowdin.py`](../tests/unit/test_platform_crowdin.py): + +- **不要调真实 API**:通过 `extra["session_factory"] = lambda: FakeSession(...)` 注入自定义 + `requests.Session`,`FakeSession` 用 `MagicMock` 返回构造好的响应; +- 至少覆盖:鉴权(含 401 自动刷新)、`upload_source` 成功路径、`get_task_status` + 状态映射、`import_approved` 文件落地、`split_approved_data` 的 approved/pending 拆分、 + 网络错误重试; +- 用 `tests/unit/test_platform_factory.py` 的模式检查**工厂级跨平台保护逻辑** + (全局 Crowdin + 阶段 Lokalise 时不污染 `api_base`)。 + +--- + +## 8. 其它参考 + +- 协议细节:[`src/TiMi_HOK_Game_Translator/platforms/base.py`](../src/TiMi_HOK_Game_Translator/platforms/base.py) +- 工厂与注册表:[`src/TiMi_HOK_Game_Translator/platforms/factory.py`](../src/TiMi_HOK_Game_Translator/platforms/factory.py) +- 内置实现:[`phrase_platform.py`](../src/TiMi_HOK_Game_Translator/platforms/phrase_platform.py) / [`crowdin_platform.py`](../src/TiMi_HOK_Game_Translator/platforms/crowdin_platform.py) +- 平台专项:[Phrase TMS 快速接入](./platforms/phrase.md) +- 快速验证令牌:[`scripts/probe_platform.py`](../scripts/probe_platform.py) 的 `--whoami` 探针 \ No newline at end of file diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_sources.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_sources.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a162370d6037ded3168fd4c49a623f9985e305 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_sources.md @@ -0,0 +1,62 @@ +# 扩展指南:新增一种源文件格式 + +假设你使用 [Fluent](https://projectfluent.org/)(`.ftl`), +希望 `TiMi_HOK_Game_Translator` 能读写它。 + +## 1. 继承 `LocalizationSource` + +```python +# my_project/fluent_source.py +from typing import List, Sequence + +from TiMi_HOK_Game_Translator.sources import Entry, LocalizationSource, register_source + + +@register_source("fluent") +class FluentSource(LocalizationSource): + """Fluent 格式的最小实现示例。""" + + file_extensions = (".ftl",) + + def load(self, path: str) -> List[Entry]: + text = self._read_text(path, self.encoding) + entries: List[Entry] = [] + for line in text.splitlines(): + if not line or line.startswith("#"): + continue + if "=" not in line: + continue + key, value = (part.strip() for part in line.split("=", 1)) + entries.append(Entry(key=key, source_text=value)) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + lines = [f"{e.key} = {e.target_text or e.source_text}" for e in entries] + self._write_text(path, "\n".join(lines) + "\n", self.encoding) +``` + +`@register_source("fluent")` 装饰器会把这个类接入工厂,此后 +`TiMi_HOK_Game_Translator` 就能识别 `source.format: fluent` 了。 + +## 2. 保留元数据以支持往返读写 + +每个 `Entry` 都有一个可选的 `metadata: dict` 字段。凡是无法直接 +用你的文件格式表达的信息(例如审校状态、译者 ID、修订号), +都建议放进 `metadata`,从而在多次 `load → dump` 之间保留下来。 +真实示例可看 `xliff_source.py`。 + +## 3. 合并语义 + +默认的 `merge()` 方法(见 `LocalizationSource.merge`)按 key 做合并: +`patch` 会覆盖同名 key,并追加新增的 key。如果你的格式支持更精细的 +合并语义(例如 Fluent 的 attribute / variant),请重写 `merge()`。 + +## 4. 测试清单 + +参考 `tests/unit/test_sources_json_yaml.py` 的模式: + +- **正常加载**:解析一个小文件并检查 key / 文本; +- **空文件**:`load()` 必须返回 `[]`,而不是抛异常; +- **格式错误**:`load()` 必须抛 `SourceError`,且信息足以定位; +- **往返一致**:`dump()` 之后再 `load()`,得到的 entries 应一致; +- **元数据保留**:特定后端字段应能在往返后依旧存在。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_translation.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_translation.md new file mode 100644 index 0000000000000000000000000000000000000000..6ab2d94b296a92d2304bcf6423218591ffe5eb35 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_translation.md @@ -0,0 +1,115 @@ +# 扩展翻译策略 + +`TiMi_HOK_Game_Translator.translation` 是**编排层**:负责三段式(`filter → translate → process`)、串行/并发、去重、兄弟行广播、进度回调。而 `TiMi_HOK_Game_Translator.llm` 是**调用层**:负责把 prompt 送给具体后端。 + +## 两种扩展方式 + +### 方式 1:纯配置(零代码) + +只需在 `configs/languages/.json` 写 `strategy_config`,框架会自动使用 `GenericTranslationStrategy`: + +```json +{ + "id": "es", + "target_locale": "es", + "workflow": ["pull_vcs", "translate", "validate_data", "push_vcs"], + "strategy_config": { + "display_name": "Spanish translator", + "prompt_template": "Translate to Spanish. Preserve placeholders like {value}: {text}", + "returns_english_data": false, + "use_concurrent_by_default": true, + "default_max_workers": 4, + "allow_empty": false + } +} +``` + +### 方式 2:Python 子类 + +当你需要**语种专属**的 filter(如"越南语时过滤含日文/泰文/韩文的原文")或 translate 逻辑(如"越南语自身直返原文,否则调 llama3-70B"),继承 `BaseTranslationStrategy` 并用装饰器注册: + +```python +from typing import Optional, Tuple +from TiMi_HOK_Game_Translator.translation import ( + BaseTranslationStrategy, Entry, + register_translation_strategy, +) + + +@register_translation_strategy("vi") +class VietnameseStrategy(BaseTranslationStrategy): + default_max_workers = 5 + returns_english_data = False + + def filter(self, source_text: str, *, entry: Entry) -> bool: + # 只翻译不含日文/泰文/韩文的原文 + for ch in source_text: + code = ord(ch) + if 0x3040 <= code <= 0x30FF: # 假名 + return False + if 0x0E00 <= code <= 0x0E7F: # 泰文 + return False + if 0xAC00 <= code <= 0xD7AF: # 韩文 + return False + return True + + def translate(self, source_text, *, entry, source_locale, target_locale, context): + response = self.llm.translate( + source_text, + source_locale=source_locale, + target_locale=target_locale, + context=context or "Translate to Vietnamese", + ) + return response.text, None +``` + +## `process()` 提供的能力(无需子类实现) + +- **去重**:同 `source_text` 只送 LLM 一次,其余 sibling 行自动广播翻译; +- **并发/串行**:由 `use_concurrent_by_default` 决定,独立 `_lock` 保证共享 list 安全; +- **异常收集**:`translate` 抛异常时不会中断整个批次,错误落到 `TranslationResult.errors[key]`; +- **空返回处理**:`translate` 返回 `""` 视为失败,进入 `untranslated`; +- **进度回调**:`process(..., progress_callback=lambda done, total: ...)`; +- **post_translate 钩子**:翻译流程结束后可注入质量校验、术语检查。 + +## `strategy_config` 支持的键 + +| 键 | 类型 | 说明 | +|---|---|---| +| `display_name` | str | 日志前缀 | +| `use_concurrent_by_default` | bool | 默认走并发执行器 | +| `default_max_workers` | int | 线程池大小 | +| `batch_size` | int | 推荐批处理大小 | +| `progress_log_interval` | int | 每 N 条打印一次进度 | +| `returns_english_data` | bool | 是否请求 LLM 返回英文侧翻译 | +| `prompt_template` | str | `{text}` / `{context}` 变量替换 | +| `allow_empty` | bool | 是否翻译空字符串 | +| `skip_predicate` | callable | `(text, entry) -> bool`;返回 True 则跳过 | + +未列出的键会原样保留在 `self.strategy_config` 里,供子类自行读取。 + +## 兄弟行广播 + +场景:源文件里 3 行不同 key 共用同一 `source_text`。默认行为: + +1. 只有 1 行送 LLM; +2. 得到翻译后,其余 2 行的 `target_text` 也被自动填上。 + +如需触发**外部**副作用(把广播事件写入 Excel、通知统计),实现 `SiblingBroadcaster` 协议: + +```python +from TiMi_HOK_Game_Translator.translation import BaseTranslationStrategy, SiblingBroadcaster, Entry + + +class ExcelBroadcaster: + def broadcast(self, translated: Entry, all_entries) -> int: + # ... 写 Excel,返回被触碰的兄弟行数 + return 3 + + +strategy = get_translation_strategy("vi", sibling_broadcaster=ExcelBroadcaster()) +``` + +## 测试友好 + +仓库内置的 `tests/unit/test_translation.py`(可选参考)展示了如何注入 mock LLM(`_RaisingLLM`)验证异常路径、如何断言并发执行器保序、如何用 `progress_callback` 验证进度节奏——直接照抄即可。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_vcs.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_vcs.md new file mode 100644 index 0000000000000000000000000000000000000000..12ac2f7ec0eb794821e636154167b998500b66fb --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/extending_vcs.md @@ -0,0 +1,95 @@ +# 扩展指南:新增一种 VCS 后端 + +假设你在使用 [Fossil](https://fossil-scm.org),希望 `TiMi_HOK_Game_Translator` 也能驱动它。 +下面演示如何用约 30 行代码接入一个新后端。 + +## 1. 继承 `VcsClient` + +在 `my_project/fossil_client.py` 中: + +```python +from TiMi_HOK_Game_Translator.vcs import VcsClient, VcsStatus + + +class FossilClient(VcsClient): + """Fossil SCM 的 VcsClient 实现。""" + + cli_name = "fossil" # TiMi_HOK_Game_Translator 会检查 PATH 中是否存在此可执行文件。 + + def checkout(self) -> VcsStatus: + self._run(["fossil", "clone", self.url, self.local_path]) + return VcsStatus(revision=self.get_revision()) + + def update(self, revision=None) -> VcsStatus: + cmd = ["fossil", "update"] + if revision: + cmd.append(revision) + self._run(cmd) + return VcsStatus(revision=self.get_revision()) + + def add(self, paths): + self._run(["fossil", "add", *paths]) + + def commit(self, paths, message=None): + self._run(["fossil", "commit", "-m", message or self.default_commit_message, *paths]) + return VcsStatus(revision=self.get_revision(), modified_paths=list(paths)) + + def revert(self, paths): + self._run(["fossil", "revert", *paths]) + + def status(self, paths=None): + out = self._run(["fossil", "changes"], check=False).stdout + modified = [line.split()[-1] for line in out.splitlines() if line] + return VcsStatus(revision=self.get_revision(), modified_paths=modified) + + def cleanup(self): + self._run(["fossil", "revert"], check=False) + + def get_revision(self) -> str: + return self._run(["fossil", "info"], check=False).stdout.strip().split()[0] +``` + +## 2. 注册后端 + +在包被 import 时注册一次即可,通常放在你的 `__init__.py` 里: + +```python +# my_project/__init__.py +from TiMi_HOK_Game_Translator.vcs import register_vcs_client +from .fossil_client import FossilClient + +register_vcs_client("fossil", FossilClient) +``` + +## 3. 在 `config.yaml` 中指向它 + +```yaml +vcs: + type: fossil + url: https://fossil.example.com/myrepo + local_path: "" # → 解析为 {workspace}/vcs +``` + +## 4. 在运行前 import 你的插件 + +`TiMi_HOK_Game_Translator` 并不知道 `my_project` 的存在,所以你需要确保它被 import 到, +常见两种做法: + +- **console-script 包装器**:在自己的 CLI 入口里 import 该插件后再调用 + `TiMi_HOK_Game_Translator.cli.main`; +- **`PYTHONSTARTUP` / `.pth` 文件**:随包分发一个 `.pth` 文件,其中 + `import my_project` 一行让解释器启动时自动加载。 + +至此,`PullVcsState` 与 `PushVcsState` 都会调用你的 `fossil` 客户端, +而 `TiMi_HOK_Game_Translator` 的所有单元测试仍然通过——因为框架从不假设某个具体后端。 + +## 测试你的插件 + +参考 `tests/unit/test_vcs_git.py` 的写法: + +- **不要**调用真实 CLI,改为 patch `VcsClient._run` 并返回构造好的 + `VcsCommandResult` 对象; +- 至少覆盖:`checkout`、带/不带消息的 `commit`、`status` 解析、 + `cleanup` 与 至少一条重试/异常路径。 + +完整示例可看 `tests/unit/test_vcs_*.py`。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/faq.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/faq.md new file mode 100644 index 0000000000000000000000000000000000000000..ad25372b0430c5515d4da01d5aeb83d017579889 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/faq.md @@ -0,0 +1,90 @@ +# 常见问题(FAQ) + +## 安装与环境 + +**Q:安装依赖在 Python 3.7 上失败。** +A:`TiMi_HOK_Game_Translator` 需要 **Python 3.8 或更高版本**。可通过 +`pyenv install 3.11.9` 升级(或使用系统包管理器)。 + +**Q:`pip install -r requirements.txt` 很慢。** +A:启用 wheel 缓存:`pip config set global.cache-dir ~/.cache/pip`。 +CI 上使用 `actions/setup-python` 自带的 `cache: pip` 参数 +(`.github/workflows/ci.yml` 已经启用)。 + +## 运行流水线 + +**Q:CLI 打印 `Workflow finished`,但没有翻译任何内容。** +A:很可能你连着运行了两次。流水线是**可恢复的**:一旦跑到 `finished`, +状态文件(`workspace/workflow_state.json`)就记录它已完成,再次运行会直接返回。 +加 `--fresh` 参数即可从头开始,或手动删除该 state 文件。 + +**Q:如何从某个特定状态恢复?** +A:编辑 `workspace/workflow_state.json`,把 `current_state` +改成你想**重新进入**的状态名,再次运行 CLI。Manager 会在每步执行后 +持久化新快照,这一改法是安全的。 + +**Q:`require_valid` 抱怨 `target_locale`。** +A:框架拒绝在没有目标语种时运行。请通过下列任一方式设置: +`--target-locale zh-CN`、`GAME_TRANS_TOOLCHAIN__TARGET_LOCALE=zh-CN`、 +或在 `config.yaml` 中填 `target_locale:` 字段。 + +## 密钥与敏感信息 + +**Q:我什么都没加,`scan_secrets` 却在 CI 上失败?** +A:扫描器会同时拦截**内部标识符**(主机名、真实用户名、旧 webhook 等) +和常见密钥模式。请看报错信息,它会给出命中的规则名和行号。 +如果确实是误报,请把该文件同时加入 `.gitleaks.toml` 的 `[allowlist]` +以及 `scripts/scan_secrets.py` 中的 `ALLOWLIST_PATHS` 集合。 + +**Q:`config dump` 里还是能看到我的密码!** +A:仅当你显式加了 `--no-mask` 时才会输出原文,这是为本机调试专用。 +不加该参数时,每个敏感字段都会被替换成 `***`。 + +## VCS + +**Q:SVN 客户端每次都提示我信任证书。** +A:`SvnClient` 已经以 `--non-interactive` 方式运行。请在你的工作机上 +手动信任一次证书:`svn info --trust-server-cert`,之后 CI 上 +就不会再打扰。 + +**Q:Git 在 CI 上 push 报"authentication required"。** +A:使用短期部署令牌 / SSH 密钥,通过 +`GAME_TRANS_TOOLCHAIN__VCS__PASSWORD` 注入。`GitClient` 从不打印其值。 + +**Q:Perforce 命令卡住不返回。** +A:先在同一 shell 里执行过 `p4 login`。`PerforceClient` 不会自动做 SSO。 + +## LLM + +**Q:如何在不改代码的情况下从 mock 切到 OpenAI?** +A: + +```bash +pip install openai +export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=openai +export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=sk-... +python main.py run --config config.yaml --fresh +``` + +**Q:翻译结果里 `{value}` 这类占位符被吃掉了。** +A:`OpenAILLM` 的 system prompt 已经要求模型保留占位符, +但没有任何 LLM 能保证 100% 可靠。如果你的 key 中占位符很多, +建议在 `TiMi_HOK_Game_Translator.strategies/` 下加一个"占位符校验"的后置策略。 + +## 扩展 + +**Q:私有策略/扩展在哪里发布,团队才能 import?** +A:把它做成独立 PyPI 包(公共或私有源都行)。把 `register_*` 调用 +放在包的 `__init__.py`,只需 `import 你的包` 即可完成注册。 + +## 参与贡献 + +**Q:我的 PR 至少要兼容哪些 Python 版本?** +A:3.8 – 3.12。CI 矩阵会强制校验。请避免 `list[int]` / `dict[str, X]` / +`X | None` 语法,改用 `typing` 里的 `List[int]` 等。 + +**Q:我的 PR 里合法的 `Any` 边界被 `mypy` 挡了。** +A:使用带明确错误码和简短说明的 +`# type: ignore[error-code]`。**不允许**大段 `# type: ignore`。 + +其它问题?请开一条打了 `question` 标签的 issue。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/getting_started.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/getting_started.md new file mode 100644 index 0000000000000000000000000000000000000000..98ea7183478cbdc4af882bf68c22b87ba60a521f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/getting_started.md @@ -0,0 +1,271 @@ +# TiMi_HOK_Game_Translator 接入指南 + +> 面向内部开发/运维的实战文档。看完本篇你应该能够:接 1 种新语种、换 1 种 VCS、换 1 种审校平台、换 1 种 LLM,全程**不改代码**。 + +--- + +## 一、这是什么? + +一个**可插拔、基于状态机**的游戏本地化自动化框架: + +``` +拉源文(VCS) → AI 预翻译(LLM) → 多轮审校(Platform) → 合并回写 → 推送发布 + 通知 +``` + +一句话:**接入靠配置、扩展靠装饰器、状态可回放**。 + +--- + +## 二、能力矩阵(都能换,不改代码) + +| 维度 | 当前支持 | 对应配置字段 | 想换 / 加? | +|---|---|---|---| +| **VCS** | `svn`、`git`、`perforce`、`mock` | `vcs.type` | 改 `conf/config.yaml` 的 `vcs` 块 | +| **文件格式** | `xlsx`、`json`、`yaml`、`xml`、`csv`、`dtxml`、`xliff` | `source.format` | 改 `conf/languages/.yaml` 的 `source.format` | +| **审校平台** | `phrase`、`crowdin`、`none` | `reviews..platform` | 一审走 Phrase、二审走 Crowdin,可自由组合 | +| **LLM 模型** | OpenAI/Anthropic/Venus/HY-MT/DeepSeek/GLM/Qwen/mock | `llm_profile` | 全部在 `conf/llm.yaml` 维护,用名字引用 | +| **翻译策略** | 一步直译 / 两步枢纽(中→英→目标) | `strategy_config.class` | YAML 一行切换,详见 README "翻译策略选择指南" | +| **通知渠道** | `wecom`、`slack`、`email`、`console`、`none` | `notification.type` | 改 `type` + 对应 `webhook` | +| **工作流状态** | 17 种内置状态,可任意拼顺序 | `workflow:` 列表 | 想删步骤直接从列表里删 | + +--- + +## 三、5 分钟接入 + +### 3.1 环境准备 + +- **Python 3.8+** +- **VCS 客户端**(选一个):`svn` CLI / `git` CLI / `p4` CLI +- (可选)**openpyxl**(走 xlsx 格式时自动用) +- (可选)**requests**(走企业微信/Slack/HTTP LLM 时自动用) + +### 3.2 安装 + +```bash +# 克隆、建虚拟环境、安装 +git clone && cd TiMi_HOK_Game_Translator +python -m venv .venv && .\.venv\Scripts\activate # Windows +pip install -r requirements.txt +``` + +### 3.3 配置 3 个文件 + +| 文件 | 做什么 | +|---|---| +| `conf/config.yaml` | 全局:VCS、默认平台、workspace 位置、日志 | +| `conf/llm.yaml` | 把你的 LLM 模型注册到名字(供 profile 引用) | +| `conf/languages/.yaml` | 单个语种的接入——这是日常**最常改的文件** | + +### 3.4 跑一下 + +```bash +python main.py run --language vi +``` + +--- + +## 四、新接入一个语种,一张清单 + +假设你要新接 **"韩语(ko)"**: + +```yaml +# conf/languages/ko.yaml +id: ko +display_name: 韩语(联调样本) +source_locale: zh-CN +target_locale: ko + +locale_names: + cn: 韩语 + en: Korean + +# 1. 源文件在 VCS 工作副本里的路径(相对于 vcs.local_path) +source: + format: xlsx # 文件格式 + path: trunk/tests/fixtures/ko/99.incr.xlsx + +# 2. 用哪个 LLM profile(必须在 conf/llm.yaml 里存在) +llm_profile: hunyuan_mt2_plus + +# 3. 翻译策略(可选) +strategy_config: + class: TwoStepTranslationStrategy # 中→英→韩两步策略;省略则一步直译 + pivot_locale: en + +# 4. 一审 / 二审配置 +reviews: + first: + platform: phrase + project_id: "xxxxx" + project_name: KO First Review (Phrase) + target_language_id: ko + stop_time: "21:00" + extra: + region: eu + second: + platform: crowdin + project_id: "123456" + project_name: KO Second Review (Crowdin) + target_language_id: ko + +# 5. 通知配置 +notification: + type: wecom + webhook: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx" + mentioned: + - "currylong" + +# 6. 工作流编排(按顺序执行) +workflow: + - last_first_review + - last_second_review + - pull_vcs + - translate + - last_merge_data + - update_tm # 🆕 回灌 TM 到一审平台 + - first_review + - update_grn_tm # 🆕 回灌 TM 到二审平台 + - second_review + - validate_data + - merge_data + - push_vcs +``` + +**跑一下**: + +```bash +python main.py run --language ko +``` + +--- + +## 五、关键配置字段速查 + +### 5.1 `conf/config.yaml`(全局) + +| 字段 | 类型 | 说明 | +|---|---|---| +| `project_code` | str | 产品 slug,出现在日志前缀、通知标题、状态文件 | +| `stage` | enum | `exp_week` / `trunk_week` / `pub_week` / `hot_week` | +| `source_locale` | str | 源语种 BCP-47(通常 `zh-CN`) | +| `vcs.type` | enum | `svn` / `git` / `perforce` / `mock` | +| `vcs.url` | str | 仓库地址 | +| `vcs.local_path` | str | 本地工作副本目录(相对 workspace) | +| `vcs.username` / `vcs.password` | str | 凭据,**建议走环境变量** | +| `platform.type` | enum | 全局默认审校平台 | +| `platform.api_token` | str | 平台 token,**敏感字段** | +| `llm_profile` | str | 全局默认 LLM,指向 `conf/llm.yaml` 的 key | +| `languages_dir` | str | 语种 profile 目录(默认 `conf/languages`) | +| `workspace.root` | str | workspace 绝对路径;为空则 `$CWD/workspace` | +| `logging.level` | enum | `DEBUG` / `INFO` / `WARNING` / `ERROR` | + +### 5.2 `conf/llm.yaml`(LLM 注册表) + +每个 profile 的字段: + +| 字段 | 说明 | +|---|---| +| `provider` | `openai` / `openai_compatible` / `anthropic` / `venus` / `hunyuan_translation` / `mock` | +| `model` | 模型名 | +| `api_base` | API 根地址 | +| `api_key` | 鉴权,**敏感字段** | +| `temperature` / `max_tokens` / `batch_size` | 调用参数 | +| `timeout_seconds` / `retries` / `retry_interval_seconds` | 重试策略 | +| `extra` | provider 专属字段(如 `wsid`、`server_id`、`app_group_id`) | + +### 5.3 `conf/languages/.yaml`(语种 profile) + +| 字段 | 说明 | +|---|---| +| `id` | 语种短 ID(与文件名一致) | +| `display_name` | 日志/通知里显示的中文名 | +| `source_locale` / `target_locale` | BCP-47 代码 | +| `locale_names.cn` / `locale_names.en` | 提示词中语种名的中英文显示覆盖 | +| `source.format` | 源文件格式,见能力矩阵 | +| `source.path` | 文件路径(相对 `vcs.local_path`) | +| `vcs` | 可选,覆盖全局 VCS 配置 | +| `llm_profile` | 用哪个 LLM profile | +| `strategy_config.class` | 翻译策略类名或完整 import 路径(见 README) | +| `strategy_config.pivot_locale` | 两步策略的中转语种,默认 `en` | +| `strategy_config.display_name` | 翻译器日志标签 | +| `strategy_config.use_concurrent_by_default` | 是否并发 | +| `strategy_config.default_max_workers` | 并发线程数 | +| `reviews..platform` | `phrase` / `crowdin` / `none` | +| `reviews..project_id` | 平台项目 ID | +| `reviews..target_language_id` | 平台的语种 ID(与 BCP-47 可能不同) | +| `reviews..stop_time` | 审校轮询截止 `HH:MM` 或 `+5m` 相对时间 | +| `reviews..poll_interval_seconds` | 轮询间隔 | +| `reviews..extra` | 平台专属字段(如 Phrase 的 `region`) | +| `notification.type` | `wecom` / `slack` / `email` / `console` / `none` | +| `notification.webhook` | 群机器人地址,**敏感字段** | +| `notification.mentioned` | 需要 @ 的用户 ID 列表 | +| `workflow` | 工作流状态有序列表 | +| `merge_start_time` | 合并窗口起始 `HH:MM`;为空立即执行 | + +### 5.4 Workflow 可用状态清单 + +``` +pending → pull_vcs → translate → update_tm → first_review + → update_grn_tm → second_review → validate_data → merge_data + → push_vcs / push_multi_vcs → finished + +辅助状态: + last_first_review / last_second_review / last_merge_data + (处理昨日续审任务) + light_review(轻量审校)、increment_match(增量匹配) +``` + +--- + +## 六、常见扩展 + +| 需求 | 操作 | +|---|---| +| **加一个新语种** | 复制 `vi.yaml` 改 `id` / `target_locale` / `reviews..project_id` 即可 | +| **切 LLM** | 改 `llm_profile` 字段指向 `conf/llm.yaml` 的另一个 key | +| **一步 ↔ 两步策略** | 加/去 `strategy_config.class: TwoStepTranslationStrategy` | +| **换审校平台** | 改 `reviews.first.platform` / `project_id` | +| **一审 Phrase + 二审 Crowdin** | 两个 `reviews.*` 块各写各的 | +| **跳过某阶段** | 从 `workflow:` 列表里删掉该状态 | +| **不发通知** | `notification.type: none` | +| **只跑翻译,不审校** | `workflow` 保留 `pull_vcs/translate/merge_data/push_vcs` 即可(参见 `conf/languages/de.yaml`) | +| **临时换 token** | 环境变量 `GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN=xxx`(配置键用 `__` 分层) | + +--- + +## 七、敏感字段 & 环境变量 + +**所有标注"敏感字段"的配置项**(`password` / `api_key` / `api_token` / `webhook` 等): + +- `conf/*.yaml` 里**可以写明文**(联调方便),但**上线前必须清空** +- 用环境变量注入覆盖,变量名规则:`GAME_TRANS_TOOLCHAIN__
__` + - 例:`GAME_TRANS_TOOLCHAIN__VCS__PASSWORD=xxx` + - 例:`GAME_TRANS_TOOLCHAIN__LLM__API_KEY=xxx` + - 例:`GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK=xxx` +- 导出当前配置时(`config dump`),敏感字段会自动脱敏为 `****` + +--- + +## 八、常见问题 + +| 问题 | 原因 / 处理 | +|---|---| +| `Unknown source format 'xxx'` | `source.format` 不在支持列表里,查第二节能力矩阵 | +| svn `wc locked` / E155004 | 跑 `svn cleanup ` 清锁;不要用 `svn status` 判断 | +| LLM 响应超时 | 增大 `conf/llm.yaml` 对应 profile 的 `timeout_seconds` / `retries` | +| Phrase 没找到项目 | 检查 `reviews.first.extra.region`(eu 账户用 `eu.phrase.com`) | +| 任务已创建但没发通知 | 检查 `notification.type` 是否 `none`;企业微信看 `webhook` 是否配好 | +| 想看 Step 1 英文中间结果 | 看最终 xlsx 的 `EnglishSide` 列(第 8 列) | + +--- + +## 九、相关文档 + +- 项目总览与特性清单:[`../README.md`](../README.md) +- 配置详解(字段逐项 + 源文件格式参考):[`./configuration.md`](./configuration.md) +- 架构详解:[`./architecture.md`](./architecture.md) +- VCS 扩展指南:[`./extending_vcs.md`](./extending_vcs.md) +- 文件格式扩展:[`./extending_sources.md`](./extending_sources.md) +- LLM 扩展:[`./extending_llm.md`](./extending_llm.md) +- 平台扩展:[`./extending_platforms.md`](./extending_platforms.md) +- Phrase 平台专项:[`./platforms/phrase.md`](./platforms/phrase.md) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/platforms/phrase.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/platforms/phrase.md new file mode 100644 index 0000000000000000000000000000000000000000..e47d0034ae2d494923e5cee6b3a1f5bf4de5cb8d --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/platforms/phrase.md @@ -0,0 +1,177 @@ +# Phrase TMS 平台适配指南 + +`PhrasePlatform` 是 [Phrase TMS](https://developers.phrase.com/en/api/tms/latest/introduction)(原 Memsource)的官方适配器,支持一审 / 二审 / 轻校对三个 `review_stage`。 + +## 一句话上手(推荐:Subject Token Exchange) + +```json +{ + "id": "vi", + "target_locale": "vi", + "reviews": { + "first": { + "platform": "phrase", + "project_id": "abcdef1234", + "target_language_id": "vi", + "stop_time": "19:00", + "extra": { + "subject_token": "PASTE_YOUR_TOKEN_HERE_OR_USE_ENV", + "region": "eu", + "workflow_step_uid": "" + } + } + } +} +``` + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN=xxx +python main.py run --language vi --languages-dir configs/languages/ +``` + +## 三种认证模式 + +| # | 模式 | 何时使用 | 请求头 | +|---|---|---|---| +| 1 | **Subject Token Exchange** ⭐ | 官方 2024+ 推荐;从 Phrase UI *Settings → API tokens → Generate token* 复制的令牌 | `Authorization: Bearer ` | +| 2 | **Legacy ApiToken** | 早期 Memsource 部署里 UI 生成的长期 token | `Authorization: ApiToken ` | +| 3 | **Username + Password** | SSO 关闭且未开放 API token 的场景 | 内部先 `/auth/login` 换 24h ApiToken,然后同模式 2 | + +### 模式 1 · Subject Token Exchange(RFC 8693) + +参考文档: + +**流程**: +1. 从 Phrase UI *Settings → API tokens → Generate token* 复制得到形如 `a2todDBjNXBEVjZM...` 的字符串(内部是 base64 的 `client_id:client_secret`); +2. 适配器把它作为 `subject_token`,向 IDM 端点交换出 Bearer 短期 access token: + ``` + POST https://eu.phrase.com/idm/oauth/token + Content-Type: application/x-www-form-urlencoded + + grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token= + ``` +3. 服务器返回 `{"access_token":"eyJ...", "expires_in":14399, "token_type":"Bearer"}`;适配器缓存 Bearer 直到过期前 60s,自动无感刷新; +4. 后续调用 TMS API 均使用 `Authorization: Bearer `。 + +**区域切换**:EU 账户走 `https://eu.phrase.com`,US 账户走 `https://us.phrase.com`。通过 `extra.region: "eu" | "us"` 指定,默认 EU。 + +**注入方式**(三选一): + +```bash +# A. 环境变量(推荐用于 CI / 服务端) +export GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN=xxx + +# B. 语种配置 JSON 的 reviews..extra.subject_token +``` + +```yaml +# C. 全局 config.yaml +platform: + type: phrase + extra: + subject_token: xxx + region: eu +``` + +### 模式 2 · Legacy ApiToken + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN=phrase_xxx +python main.py run --language vi --languages-dir configs/languages/ +``` + +请求头 `Authorization: ApiToken `。适用于早期 Memsource 后台仍能查到「长期 API Token」的账号。 + +### 模式 3 · Username + Password + +首次调用时适配器会 `POST /web/api2/v3/auth/login`(若 tenant 未升级则回退到 `/v1/auth/login`)换取 **24 小时**有效 token。多公司账号需在 `extra.user_uid` 里指定登录到哪家。 + +401 自动重登:在**模式 1** 与**模式 3** 下,一旦服务器返回 401(token 过期),适配器会强制重新认证一次再重试。 + +## API 基址 + +- **TMS API**:`https://cloud.memsource.com/web/api2`(EU / US 均使用同一域名,区域信息由 Bearer 的 `aud` claim 决定); +- **IDM(仅模式 1)**:`https://eu.phrase.com` 或 `https://us.phrase.com`; +- 私有部署:覆盖 `api_base` 与 `idm_base`。 + +## 端点覆盖 + +| 用途 | HTTP 方法 & 路径 | +|---|---| +| IDM 交换 Bearer(模式 1) | `POST /idm/oauth/token` | +| 登录换 token(模式 3,首选) | `POST /web/api2/v3/auth/login` | +| 登录换 token(模式 3,回退) | `POST /web/api2/v1/auth/login` | +| 当前身份 whoAmI | `GET /web/api2/v1/auth/whoAmI` | +| 上传 job(源文件) | `POST /web/api2/v1/projects/{projectUid}/jobs` (multipart) | +| 查 job | `GET /web/api2/v1/projects/{projectUid}/jobs/{jobUid}` | +| 下载译文 | `GET /web/api2/v1/projects/{projectUid}/jobs/{jobUid}/targetFile` | +| 删除 job | `DELETE /web/api2/v1/projects/{projectUid}/jobs` | +| 查项目 | `GET /web/api2/v1/projects/{projectUid}` | + +## file_id 编码 + +`upload_source` 返回的 `file_id` 是不透明字符串 `"phrase::::"`。这样即便适配器在崩溃后重启,只要从 `AutoSaveDict` 里读回 `file_id` 也能立即定位到原任务,无需保留额外本地映射。 + +## 状态映射 + +| Phrase 状态 | 框架 `TaskStatus` | +|---|---| +| `NEW` / `EMAILED` | `PENDING` | +| `ASSIGNED` / `ACCEPTED_BY_LINGUIST` / `COMPLETED_BY_LINGUIST` | `IN_PROGRESS` | +| `COMPLETED` / `DELIVERED` | `APPROVED` | +| `DECLINED_BY_LINGUIST` / `CANCELLED` / `REJECTED` | `REJECTED` | + +未识别状态映射为 `UNKNOWN` —— 由调用方决定重试策略。 + +## 常用 extra 键 + +| 键 | 类型 | 说明 | +|---|---|---| +| `subject_token` | str | ⭐ 模式 1:Phrase UI 生成的令牌,会被换成 4 小时 Bearer | +| `region` | str | ⭐ 模式 1:`"eu"`(默认)/ `"us"` | +| `idm_base` | str | 模式 1:覆盖 IDM 域名(私有部署或代理时使用) | +| `username` / `password` | str | 模式 3:降级换 token 凭据 | +| `user_uid` | str | 模式 3:多公司账号时指定登录哪家;`/auth/login` 请求体的 `userUid` | +| `workflow_step_uid` | str | 把新建 job 绑定到指定 workflow step | +| `timeout_seconds` | float | HTTP 超时(默认 30s) | +| `retries` | int | 网络失败重试次数(默认 3) | +| `retry_interval_seconds` | float | 重试间隔(默认 30s) | +| `session_factory` | callable | 测试专用:返回自定义 `requests.Session` | +| `clock` | callable | 测试专用:注入自定义 UNIX 时间戳源,用于测试 Bearer 过期刷新 | + +## 快速验证令牌是否可用(`--whoami`) + +拿到 subject_token 后无需真正上传文件,用探针脚本一键验证账号连通: + +```bash +export GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN=xxx +python scripts/probe_platform.py --platform phrase --region eu --whoami +``` + +期望输出: + +``` +[INFO] PhrasePlatform: exchanged subject token for Bearer via https://eu.phrase.com/idm/oauth/token (expires in 14399s) +[OK] whoAmI -> user=your-username role=ADMIN org=your-org (uid=xxx) +``` + +一旦看到这行 `[OK] whoAmI`,说明**整套认证链路完全打通**:`subject_token → IDM 交换 → Bearer 缓存 → TMS API 调用 → 用户身份返回`。 + +## 已知限制 + +- Phrase 原生不区分「approved / pending」段,本适配器通过 `get_task_status` 的整体 `status` 近似:`COMPLETED` 视为全部通过,其余视为 pending。真正需要按段落粒度分裂的项目应覆盖 `split_approved_data`。 +- `export_review_report` 仅生成一个基于 job 元数据的简短 txt 报告,不调用 Phrase 的 Analytics 高级模块。 + +## 常见问题 + +**Q:`AuthInvalidCredentials` / 401 `auth: not logged`。** +A:优先检查是否使用了 subject_token 模式(模式 1)。传统 `ApiToken` 头对新发的 Phrase Platform 令牌无效 —— 那种令牌**必须**先走 IDM Token Exchange 换成 Bearer。 + +**Q:IDM 返回 `invalid_grant`。** +A:99% 是区域错了。EU 账户去 `https://eu.phrase.com/idm/oauth/token`,US 账户去 `https://us.phrase.com/idm/oauth/token`。设置 `extra.region` 或 `--region eu|us`。 + +**Q:出现 `PhrasePlatform: project_id is empty`。** +A:`reviews.first.project_id` 或全局 `platform.project_id` 至少要有一个非空。 + +**Q:想测适配器却不想联网。** +A:注入 `extra["session_factory"] = lambda: FakeSession(...)`,详见 [`tests/unit/test_platform_phrase.py`](../../tests/unit/test_platform_phrase.py)。 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/quickstart.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/quickstart.md new file mode 100644 index 0000000000000000000000000000000000000000..01d3914ad599260c12a607e6af92b651ebba8311 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/quickstart.md @@ -0,0 +1,96 @@ +# 快速开始 —— 5 分钟端到端跑通(JSON demo) + +本教程演示**默认端到端流水线**,全程无需任何外部服务:所有后端都使用 +内置 mock,不需要凭据、网络或构建工具。 + +## 0. 前置要求 + +- Python **3.8 或更高版本** +- Windows / macOS / Linux 均可 + +## 1. 安装 + +```bash +git clone https://github.com//TiMi_HOK_Game_Translator.git +cd TiMi_HOK_Game_Translator + +python -m venv .venv +# Linux / macOS +source .venv/bin/activate +# Windows PowerShell +.venv\Scripts\Activate.ps1 + +pip install -r requirements.txt +``` + +## 2. 查看最终生效的配置 + +本仓库在 [`docs/examples/`](./examples/) 下自带了一个开箱即用的 demo 配置 +与 5 种格式的样例数据: + +``` +docs/examples/ +├── demo.yaml # 全 mock 的 demo 配置 +└── data/ + ├── example_game.en.json + ├── example_game.en.yaml + ├── example_game.en.xml + ├── example_game.en.csv + └── example_game.en.dtxml +``` + +先看一眼最终生效的配置: + +```bash +python main.py config dump --config docs/examples/demo.yaml +``` + +输出的是一份解析后的 YAML 配置,每个敏感字段都会脱敏成 `***`。 +后续排查问题时,这是快速自检的首选命令。 + +## 3. 运行流水线 + +```bash +python main.py run --config docs/examples/demo.yaml +``` + +> 💡 跑过一次之后想从头再来:加 `--fresh`: +> `python main.py run --config docs/examples/demo.yaml --fresh`。 + +预期输出(节选): + +``` +[INFO] TiMi_HOK_Game_Translator: Starting TiMi_HOK_Game_Translator v0.1.0 for project=example_game target=zh-CN +[INFO] TiMi_HOK_Game_Translator.workflow.manager: Entering state 'ingest' +[INFO] TiMi_HOK_Game_Translator.workflow.ingest.pull_vcs_state: Loading source entries from docs/examples/data/example_game.en.json +[INFO] TiMi_HOK_Game_Translator.workflow.manager: Entering state 'translate' +[INFO] TiMi_HOK_Game_Translator.workflow.translate.translate_state: Translating 10 entries into zh-CN via LocalMockLLM +[INFO] TiMi_HOK_Game_Translator.workflow.manager: Entering state 'review' +[INFO] TiMi_HOK_Game_Translator.workflow.manager: Entering state 'merge' +[INFO] TiMi_HOK_Game_Translator.workflow.manager: Entering state 'publish' +[INFO] TiMi_HOK_Game_Translator: Workflow finished with state=finished +``` + +## 4. 检查结果 + +运行完成后,查看 workspace 下的产物: + +- **`workspace/workflow_state.json`** —— 记录最终工作流状态,CLI 崩溃后据此断点续跑; +- **翻译结果** —— demo 中 mock LLM 会在每条 `target_text` 前加 `[zh-CN]` 前缀,便于一眼 + 确认翻译链路通了。 + +## 5. 下一步 + +- **切换源文件格式**:把 `demo.yaml` 里 `source.format` 换成 `yaml`、`xml`、`csv` + 或 `dtxml`,`source.path` 指向 `docs/examples/data/` 下对应的样例文件即可。 +- **接入真实 VCS**:把 `vcs.type` 改成 `svn` / `git` / `perforce`,凭据通过环境 + 变量注入——**永远不要**把它们提交到仓库!详见 [扩展 VCS](./extending_vcs.md)。 +- **接入 LLM**: + ```bash + pip install openai + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=openai + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=sk-... + python main.py run --config docs/examples/demo.yaml + ``` +- **完整字段参考**:[配置详解](./configuration.md) +- **接入审校平台 / 自定义策略**:[getting_started.md](./getting_started.md) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/server.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/server.md new file mode 100644 index 0000000000000000000000000000000000000000..2394bc93586caf90c58e68d5441f8454aaa52ba8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/server.md @@ -0,0 +1,144 @@ +# TiMiHOKGameTranslator Web Console + +一个基于 **FastAPI + Vue3 + Element Plus** 的可视化控制台,用于: + +- 🚀 **首次初始化**:Web 向导生成 `conf/config.yaml` 与 `conf/llm.yaml` +- 🌐 **语种配置**:在页面编辑 `conf/languages/.yaml`(支持新建 / 克隆 / 删除 / 立即运行) +- ⏰ **定时任务**:类似流水线调度(cron 表达式),自动触发工作流 +- 📋 **实时日志**:WebSocket 推送子进程 stdout,终端风格展示 +- 📜 **运行历史**:持久化到 `workspace/server_meta/runs.json` + +> ✨ **零侵入现有 CLI**:Web Console 只是在幕后调用 `python main.py run --language ...` 子进程, +> 和 `main.py` 原有的所有命令完全解耦,CLI 用户不受影响。 + +--- + +## 1. 安装 + +```bash +pip install -r requirements.txt +``` + +关键新增依赖:`fastapi` / `uvicorn[standard]` / `apscheduler`(已写入 `requirements.txt`)。 + +## 2. 启动 + +```bash +python main.py server # 默认 0.0.0.0:8787(同网段任意机器可访问) +python main.py server --host 127.0.0.1 # 仅本机访问 +python main.py server --port 9000 # 自定义端口 +python main.py server --reload # 开发模式(热重载) +``` + +启动后: +- **本机访问**:浏览器打开 `http://127.0.0.1:8787/` +- **局域网访问**:同一网段的其他机器打开 `http://<本机IP>:8787/`(例如 `http://30.23.60.41:8787/`) + - 启动日志会自动列出本机所有可用 IPv4 地址 + - 若无法访问,请在本机防火墙放通 TCP 8787 端口 + (Windows PowerShell 示例,管理员权限执行): + ```powershell + New-NetFirewallRule -DisplayName "TiMiHOKGameTranslator-8787" -Direction Inbound -LocalPort 8787 -Protocol TCP -Action Allow + ``` + +> ⚠️ 当前实现未内置鉴权,仅适用于**可信内网**。暴露到公网时请在前面挂反向代理(Nginx / Caddy)并追加 BasicAuth / SSO。 + +## 3. 使用流程 + +``` + ┌─────────────────┐ + │ 首次访问 │ + └────────┬────────┘ + ▼ + ┌─────────────────────┐ + │ 初始化向导(4 步) │ ← 填 project_code / VCS / LLM,一键落盘 + └────────┬────────────┘ + ▼ + ┌─────────────────────┐ + │ 语种配置页面 │ ← + 新建语种 / 克隆既有 / 立即运行 + └────────┬────────────┘ + ▼ + ┌─────────────────────┐ + │ 定时任务(可选) │ ← cron 调度器 + └────────┬────────────┘ + ▼ + ┌─────────────────────┐ + │ 运行详情(实时日志)│ ← WebSocket 流 + └─────────────────────┘ +``` + +## 4. 目录结构 + +``` +src/TiMi_HOK_Game_Translator/server/ +├── __init__.py +├── __main__.py # python -m TiMi_HOK_Game_Translator.server +├── app.py # FastAPI 应用工厂 +├── backend/ +│ ├── api/ # REST / WebSocket 路由 +│ │ ├── setup.py # 初始化配置 +│ │ ├── languages.py # 语种 CRUD +│ │ ├── runs.py # 启停 / 查询运行 +│ │ ├── schedules.py # 定时任务 CRUD +│ │ ├── logs.py # 日志尾读 + WS +│ │ └── meta.py # 枚举元数据 +│ ├── services/ +│ │ ├── config_service.py # conf/*.yaml 读写(含备份) +│ │ ├── log_bus.py # 日志环形缓冲 + 广播 +│ │ ├── runner_service.py # 子进程启停 + 持久化 +│ │ └── scheduler_service.py# APScheduler cron 封装 +│ └── models/schemas.py # Pydantic 请求/响应模型 +└── frontend/ + ├── index.html # SPA 入口(CDN,无 npm 构建) + └── static/ + ├── app.js # Vue3 应用,所有页面组件 + └── app.css +``` + +## 5. 关键 API + +| 方法 | 路径 | 作用 | +|---|---|---| +| GET | `/api/setup/status` | 查询初始化状态 | +| POST | `/api/setup/init` | 一键写入 config.yaml + llm.yaml | +| GET/PUT | `/api/setup/global-config` | config.yaml 读写 | +| GET/PUT | `/api/setup/llm` | llm.yaml 读写 | +| GET | `/api/languages` | 列出语种 | +| GET/PUT/DELETE | `/api/languages/{id}` | 单语种 CRUD | +| POST | `/api/languages/{id}/duplicate` | 克隆 | +| POST | `/api/runs` | 启动一次运行 | +| GET | `/api/runs` | 运行历史 | +| POST | `/api/runs/{run_id}/stop` | 停止运行 | +| GET | `/api/schedules` | 定时任务列表 | +| PUT | `/api/schedules/{id}` | 新建/更新 | +| GET | `/api/logs/{run_id}?limit=500`| 读取日志 | +| WS | `/api/logs/ws?run_id=xxx` | 实时日志推送 | +| GET | `/api/meta` | 所有枚举(vcs/llm/workflow 等) | + +打开 `http://127.0.0.1:8787/docs` 可查看 FastAPI 自带的 Swagger 页面。 + +## 6. 持久化文件 + +| 文件 | 作用 | +|---|---| +| `conf/config.yaml` / `conf/llm.yaml` / `conf/languages/*.yaml` | 和 CLI 共享 | +| `conf/.backup/*.bak` | 每次写入前的自动备份 | +| `workspace/server_meta/runs.json` | Web 面板的运行历史 | +| `workspace/server_meta/schedules.json` | 定时任务定义 | +| `workspace/server_logs/.log` | 每次运行的 stdout 落盘 | + +## 7. 常见问题 + +**Q: Web 面板和 CLI 冲突吗?** +> 不冲突。Web 面板只是在前端 UI 层操作同一份 `conf/*.yaml`;运行工作流时也是通过 `subprocess` 调起同一个 `main.py run` 命令。两边可以并存使用。 + +**Q: 修改 YAML 时想保留原注释?** +> PyYAML 的 `safe_dump` 不保留注释。如果您对注释敏感,建议:首次由 CLI 创建带注释的 YAML(如 `conf/languages/vi.yaml`),后续在 Web 侧只调整字段值,注释丢失即不可逆。 + +**Q: 怎么安全传递敏感字段(api_key / password / webhook)?** +> 优先走环境变量:`GAME_TRANS_TOOLCHAIN__VCS__PASSWORD` / `GAME_TRANS_TOOLCHAIN__LLM__API_KEY` / `GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN` 等。Web 面板里保留这些字段为空即可。 + +**Q: 定时任务 cron 格式?** +> 标准 5 字段:`分 时 日 月 周`。示例: +> - `0 2 * * *` — 每天 02:00 +> - `*/15 * * * *` — 每 15 分钟 +> - `30 9 * * 1-5` — 工作日 09:30 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/state_registry.md b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/state_registry.md new file mode 100644 index 0000000000000000000000000000000000000000..8cd2728bceee8b11f6ed6ce7cdb8e6750204d978 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/docs/state_registry.md @@ -0,0 +1,96 @@ +# 17 个通用状态族 + +`TiMi_HOK_Game_Translator` 内置 17 个通用状态,覆盖游戏本地化管线的绝大多数环节。每个状态都是**通用的**——不假设具体产品/游戏、不硬编码 Excel 列名、不绑死某个翻译平台。你可以只挑选自己需要的状态,通过 `configs/languages/.json` 的 `workflow` 字段自由编排。 + +## 状态一览 + +| 状态名(配置里用) | 类 | 职责摘要 | +|---|---|---| +| `pull_vcs` | `PullVcsState` | 从 VCS 拉/更新工作副本;调用 `source.load()` 载入 entries | +| `last_first_review` | `LastFirstReviewState` | 处理上一轮遗留的一审 pending 数据 | +| `last_second_review` | `LastSecondReviewState` | 处理上一轮遗留的二审 pending 数据 | +| `last_merge_data` | `LastMergeDataState` | 合并上一轮已通过的数据 | +| `translate` | `TranslateState` | 调用注册到语种的 `BaseTranslationStrategy` 翻译所有 entries | +| `light_review` | `LightReviewState` | 轻量校对—— 未配置时自动跳过 | +| `update_tm` | `UpdateTmState` | 更新本地 TM —— 默认 no-op,用户替换实现 | +| `update_grn_tm` | `UpdateGrnTmState` | 更新伙伴/远端 TM —— 默认 no-op | +| `increment_match` | `IncrementMatchState` | 当日增量字符超阈值时触发的 TM 匹配 sweep | +| `first_review` | `FirstReviewState` | 第一轮正式审校(`review_stage="first"`)| +| `second_review` | `SecondReviewState` | 第二轮正式审校(`review_stage="second"`)—— 未配置平台时跳过 | +| `merge_data` | `MergeDataState` | 汇总两轮审校的 approved 数据 | +| `validate_data` | `ValidateDataState` | 基础质量校验:非空 key、非空 target_text、去重 | +| `push_vcs` | `PushVcsState` | 把 entries dump 回源文件并 commit 到 VCS | +| `push_multi_vcs` | `PushMultiVcsState` | 遍历 `profile.multi_publish_targets` 多路径发布 | +| `finished` | `FinishedState` | 终态:flush AutoSaveDict + StatesManager,触发 `vcs.cleanup()` + notify | +| `pending` / `failed` | (无对应类) | 生命周期枚举保留字,不作为可编排状态 | + +## 配置样例:完整双轮审校 + +```json +{ + "id": "example_vi", + "workflow": [ + "pull_vcs", + "last_first_review", + "last_second_review", + "last_merge_data", + "translate", + "light_review", + "first_review", + "second_review", + "validate_data", + "push_vcs", + "push_multi_vcs" + ] +} +``` + +## 配置样例:轻量单轮 + +```json +{ + "id": "example_ja", + "workflow": [ + "pull_vcs", + "translate", + "first_review", + "validate_data", + "push_vcs" + ] +} +``` + +## 断点续跑约定 + +每个状态在 `execute()` 首行都会调用 `self._already_completed(ctx)`:如果 `StatesManager` 已把它标记为完成,就直接 `return None` 跳过。这意味着: + +- 崩溃后 `python main.py run`(不带 `--fresh`)会自动从上次未完成状态继续; +- Task id / approved_path 等业务字段由 `AutoSaveDict` 存进 `project_run_data.json`,`FirstReviewState` 检测到 `first_review.task_id` 已存在时会**复用**该任务而不是新建。 + +## 自定义状态 + +通过 `register_state`(支持 `replace=True`)替换任一内置状态: + +```python +from TiMi_HOK_Game_Translator.workflow import register_state, WorkflowStateBase +from TiMi_HOK_Game_Translator.commons import WorkflowState + + +class MyMergeData(WorkflowStateBase): + name = WorkflowState.MERGE_DATA.value + + def execute(self, ctx): + # 用 pandas 做业务专属的 DataFrame 合并 + ... + self._mark_completed(ctx) + + +register_state(WorkflowState.MERGE_DATA.value, MyMergeData, replace=True) +``` + +新增自定义状态: + +```python +register_state("my_glossary_check", GlossaryCheckState) +# 然后在 .json 的 workflow 里插入 "my_glossary_check" +``` diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/main.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/main.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd43d6f69a082ad176d8681da9ea1628e45050f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/main.py @@ -0,0 +1,61 @@ +"""项目根一键启动入口。 + +使用方式(无需 ``pip install -e .``): + + python main.py run --language vi --fresh + python main.py config dump --language vi + +本脚本做两件事: + 1. 把 ``src/`` 加入 ``sys.path`` 的最前面,让 ``import TiMi_HOK_Game_Translator`` 生效; + 2. 把项目根加入 ``sys.path``,让 ``import conf._bootstrap`` 生效(CLI 的 + 配置粘合逻辑需要)。 + +同时把 cwd 锚定到本脚本所在目录,保证相对路径(``conf/config.yaml``、 +``conf/languages/*.json``)无论从哪里启动都能被正确解析。 +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + + +def _bootstrap_paths() -> Path: + """把 src/ 与项目根注入 sys.path,并把 cwd 切到项目根。""" + project_root = Path(__file__).resolve().parent + src_dir = project_root / "src" + + # 让 `import TiMi_HOK_Game_Translator` 可用 + if str(src_dir) not in sys.path: + sys.path.insert(0, str(src_dir)) + + # 让 `from conf._bootstrap import ...` 可用 + if str(project_root) not in sys.path: + sys.path.insert(0, str(project_root)) + + # 锚定 cwd —— 配置文件相对路径以项目根为基准 + os.chdir(project_root) + return project_root + + +def main() -> int: + _bootstrap_paths() + + # ``server`` 子命令走独立分支(不侵入 TiMi_HOK_Game_Translator.cli 的 argparser): + # python main.py server # 默认 0.0.0.0:8787,同网段可访问 + # python main.py server --host 127.0.0.1 # 仅本机访问 + # python main.py server --port 9000 # 自定义端口 + # python main.py server --reload # 开发时自动重载 + if len(sys.argv) >= 2 and sys.argv[1] == "server": + from TiMi_HOK_Game_Translator.server.__main__ import main as server_main + # 把 "server" 从 argv 中去掉,让下游 argparse 看到的是正常的 flags + sys.argv = [sys.argv[0]] + sys.argv[2:] + return server_main() + + from TiMi_HOK_Game_Translator.cli import main as cli_main + return cli_main() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/requirements.txt b/timi_hok_game_translator/TiMi_HOK_Game_Translator/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..af908644cea2cf19dac24518eb4329dd2520a62f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/requirements.txt @@ -0,0 +1,65 @@ +# +# TiMi_HOK_Game_Translator - runtime dependencies (one-shot install) +# +# Usage (run inside project root, preferably in a venv): +# +# # 1) Create and activate a Python >= 3.8 virtual env +# py -3.12 -m venv .venv +# . .venv\Scripts\Activate.ps1 # Windows PowerShell +# # source .venv/bin/activate # macOS / Linux +# +# # 2) Upgrade pip and install runtime deps +# python -m pip install --upgrade pip +# pip install -r requirements.txt +# +# # 3) (Optional, intranet) Install Venus SDK from Tencent mirror +# pip install -U venus-api-base -i https://mirrors.cloud.tencent.com/pypi/simple/ +# +# This file mirrors [project.dependencies] in pyproject.toml plus the most +# useful optional extras, so that `pip install -r requirements.txt` sets up +# everything a developer needs in one go. +# + +# ----------- Core runtime (required) ----------- +PyYAML>=6.0 +# ruamel.yaml is used by the Web Console to **preserve YAML comments** when +# saving conf/*.yaml from the browser. Falls back to PyYAML (comments lost) +# if ruamel is unavailable. +ruamel.yaml>=0.17 +requests>=2.31 +lxml>=4.9 +tqdm>=4.66 +python-dotenv>=1.0 + +# ----------- LLM / platform integrations (optional but recommended) ----------- +# openai SDK is shared by every OpenAI-compatible vendor (DeepSeek / Kimi / +# GLM / Qwen compat mode / Hunyuan Hy4 ...). Hunyuan Hy-MT2 / Anthropic / +# Venus go through plain `requests` and need no extra SDK. +openai>=1.0 + +# ----------- Excel / table support (optional) ----------- +# Not needed by the built-in dtxml / xml / csv / json / xliff sources, but +# useful if you later enable XlsxSource or data-export scripts. +pandas>=2.0 +openpyxl>=3.1 + +# ----------- Scheduling (optional) ----------- +# Legacy timer_tool.py used `schedule`. The new framework does not use it +# yet but it is listed here for future cron-style jobs. +schedule>=1.2 + +# ----------- Web Console / Server (optional, required for Web UI) ----------- +# Enable the FastAPI-based Web console (``python main.py server``): +# * fastapi + uvicorn — HTTP / WebSocket server +# * apscheduler — cron-style scheduled runs +# Omit these if you only use the CLI. +fastapi>=0.110 +uvicorn[standard]>=0.27 +apscheduler>=3.10 + +# ----------- Dev / test tools (optional, developers only) ----------- +# These are NOT required to run TiMi_HOK_Game_Translator in production. Only install if you +# plan to hack on the codebase and run the (optional) test suite under tests/. +pytest>=7.4 +pytest-cov>=4.1 +ruff>=0.5 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..561e1ee0f3d18f3fec2a685215c049dd55082f13 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__init__.py @@ -0,0 +1,9 @@ +# pylint: disable=invalid-name +"""TiMi_HOK_Game_Translator:可插拔的游戏本地化自动化框架。 + +提供版本控制(SVN/Git/Perforce)、本地化源文件格式(JSON/YAML/XML/CSV/DTXML/XLIFF)、 +LLM 提供商、审校平台以及基于状态机的工作流等抽象层。 +""" + +__version__ = "0.1.0" +__all__ = ["__version__"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__main__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8245fb6f81f480b9af9fac5e34cc88f5b39c14 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__main__.py @@ -0,0 +1,10 @@ +"""支持 ``python -m TiMi_HOK_Game_Translator`` 直接调用 CLI。""" + +from __future__ import annotations + +import sys + +from .cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6de61cb913755b76e6b7bf4d21dc596df5327cf2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/cli.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/cli.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2fcfe78332146e7cb247514b747058c6d0a511d Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/__pycache__/cli.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/cli.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..e3262f8f522a192e1250a33217ca9aafb48fb7d9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/cli.py @@ -0,0 +1,289 @@ +"""``TiMi_HOK_Game_Translator`` 命令行入口。 + +本模块通过 ``pyproject.toml`` 注册为 console-script ``TiMi_HOK_Game_Translator``, +同时作为 ``python -m TiMi_HOK_Game_Translator`` 的执行目标。 + +支持的子命令: + +* ``TiMi_HOK_Game_Translator run`` — 执行完整工作流。 +* ``TiMi_HOK_Game_Translator config dump`` — 打印当前生效配置。 +""" + +from __future__ import annotations + +import json +import logging +import sys +from typing import Sequence + +from .commons import APP_NAME +from .config import Config, build_argparser, load, require_valid +from .llm import create_llm_client +from .notify import create_notifier +from .platforms import create_platform +from .sources import create_source +from .vcs import create_vcs_client +from .workflow import WorkflowRunner + + +def _configure_logging(config: Config) -> None: + """按配置初始化根 logger。""" + level = getattr(logging, config.logging.level.upper(), logging.INFO) + handlers: list = [] + if config.logging.console: + handlers.append(logging.StreamHandler()) + logging.basicConfig( + level=level, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + handlers=handlers or None, + force=True, + ) + # 给根 logger 挂一个过滤器: + # 1. 把第三方 SDK(如 venus_api_base)用 logger.info 打印 bytes 对象产生的 + # 形如 b'...\xe6\x88\x90\xe5\x8a\x9f...' 的转义字符串还原为 UTF-8 中文; + # 2. 对 "response data:" 这类巨长的原始响应 payload 做压缩/截断,避免噪音。 + root_logger = logging.getLogger() + _bytes_filter = _BytesEscapeDecoder() + # 防止重复挂载(force=True 会清掉 handlers 但不动 filters,这里显式去重) + for existing in list(root_logger.filters): + if isinstance(existing, _BytesEscapeDecoder): + root_logger.removeFilter(existing) + root_logger.addFilter(_bytes_filter) + + +class _BytesEscapeDecoder(logging.Filter): + """把 ``logger.info(bytes_obj)`` 打出来的 bytes-repr 字符串还原为可读 UTF-8。 + + 典型场景:venus_api_base SDK 内部 ``logger.info("response data:%s", resp.content)`` + 直接把 ``bytes`` 作为 msg 参数传入,Python logging 会 ``str(bytes)``——结果 + 控制台看到的中文会变成 ``\\xe6\\x88\\x90\\xe5\\x8a\\x9f`` 这种转义字面量。 + + 过滤器思路: + * 识别 record.getMessage() 中的 ``b'...'`` / ``b"..."`` 字节字面量; + * 用 ``codecs.escape_decode`` 还原为真实 bytes 后再 ``decode("utf-8")``; + * 对超长的 ``response data:`` 做字段级压缩(只保留 message / usage / response)。 + """ + + import re as _re + _BYTES_LITERAL = _re.compile(r"""b(['"])(.*?)\1""", _re.DOTALL) + _MAX_LEN = 1500 # 单条日志最多保留的字符数 + + def filter(self, record: logging.LogRecord) -> bool: # noqa: D401 + try: + msg = record.getMessage() + except Exception: # pylint: disable=broad-except # pragma: no cover + return True + if "\\x" not in msg and "b'" not in msg and 'b"' not in msg: + return True + new_msg = self._BYTES_LITERAL.sub(self._decode_match, msg) + # 过长时做截断,保留头尾用于定位 + if len(new_msg) > self._MAX_LEN: + keep = self._MAX_LEN // 2 - 20 + new_msg = ( + new_msg[:keep] + + f" ... [truncated {len(new_msg) - 2 * keep} chars] ... " + + new_msg[-keep:] + ) + # 清除 args,避免 logging 再做一次 %-formatting + record.msg = new_msg + record.args = None + return True + + @staticmethod + def _decode_match(m) -> str: + raw = m.group(2) + try: + import codecs + decoded_bytes, _ = codecs.escape_decode(raw.encode("utf-8", errors="replace")) + return decoded_bytes.decode("utf-8", errors="replace") + except Exception: # pylint: disable=broad-except # pragma: no cover + return m.group(0) + + +def _dump_config(args, config: Config) -> int: + """``config dump`` 子命令:以 yaml/json 格式打印当前配置。""" + mask = not getattr(args, "no_mask", False) + data = config.to_dict(mask_sensitive=mask) + fmt = getattr(args, "format", "yaml") + if fmt == "json": + print(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)) + else: + try: + import yaml + print( + yaml.safe_dump( + data, default_flow_style=False, allow_unicode=True, sort_keys=True, + ) + ) + except ImportError: # pragma: no cover + print(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)) + return 0 + + +def _merge_notification(profile_notify, global_notify): + """字段级合并语种与全局 ``NotificationConfig``。 + + 合并策略(**字段级继承**,而非整段替换): + * ``type`` —— 语种填了用语种,否则用全局; + * ``webhook`` —— 语种填了用语种,否则继承全局(**解决"语种填了 type + 但 webhook 占位空字符串" → 消息被丢弃**的痛点); + * ``mentioned`` —— 语种填了(非空列表)用语种,否则继承全局; + * ``extra`` —— 语种填了(非空字典)用语种,否则继承全局。 + + 这样业务侧新建语种只需关心"要 @ 谁",webhook 自动走全局即可,避免每个 + 语种 YAML 都复制粘贴相同的 webhook URL(也不容易泄露敏感字段)。 + """ + from dataclasses import replace + if profile_notify is None: + return global_notify + if global_notify is None: + return profile_notify + return replace( + profile_notify, + type=profile_notify.type or global_notify.type, + webhook=profile_notify.webhook or global_notify.webhook, + mentioned=list(profile_notify.mentioned) if profile_notify.mentioned else list(global_notify.mentioned or []), + extra=dict(profile_notify.extra) if profile_notify.extra else dict(global_notify.extra or {}), + ) + + +def _resolve_profile(args, config: Config): + """选择本次要执行的语种配置(LanguageProfile)。 + + 解析顺序: + 1. 命令行显式指定的 ``--language ``; + 2. 与已加载 profile 匹配的 ``config.target_locale``; + 3. ``Config.languages`` 中的第一个 profile(多个时会告警); + 4. 未加载任何 profile 时,通过 :meth:`Config.language_profile` 合成一个。 + """ + language = getattr(args, "language", None) or "" + if not language: + language = config.target_locale + if language and language in config.languages: + return config.languages[language] + if not config.languages: + return config.language_profile(language or "target") + # 兜底:使用第一个 profile,并给出告警 + logger = logging.getLogger(APP_NAME) + first_id = next(iter(config.languages)) + if language: + logger.warning( + "cli: language %r not found in profiles %s — falling back to %r", + language, sorted(config.languages), first_id, + ) + else: + logger.warning( + "cli: no --language given; using first profile %r out of %d", + first_id, len(config.languages), + ) + return config.languages[first_id] + + +def _run(args, config: Config, *, fresh: bool = False, batch: str | None = None) -> int: + """``run`` 子命令:按 profile 组装各后端并驱动 WorkflowRunner。 + + 参数: + args: 已解析的命令行参数。 + config: 加载完成的全局配置。 + fresh: True 时清空断点重跑,否则遵循 ``batch`` 语义。 + batch: 显式续跑指定批次(如 ``vi_20261008204338``);为 ``None`` 时 + 采用"新开批次"的宽松默认(M 语义):不加载历史 state,但保留 + ``last_tasks.json`` 的跨批次状态。 + 返回: + 进程退出码(0 表示成功)。 + """ + # 先解析语种 profile,把 profile 的 target_locale / source 等关键字段 + # 下沉到顶层 config,再做 require_valid 校验。否则在只用 profile 承载 + # target_locale 的常规配置下,会先炸 "target_locale is empty"。 + profile = _resolve_profile(args, config) + if profile.target_locale and not config.target_locale: + config.target_locale = profile.target_locale + if profile.source and profile.source.path and (not config.source or not config.source.path): + config.source = profile.source + + require_valid(config) + _configure_logging(config) + logger = logging.getLogger(APP_NAME) + + workspace = config.workspace_path() + workspace.mkdir(parents=True, exist_ok=True) + + logger.info( + "Starting %s for project=%s language=%s target=%s", + APP_NAME, config.project_code, profile.id, profile.target_locale or config.target_locale, + ) + + # 优先取 profile 上的覆盖配置,否则回退到全局配置 + source_cfg = profile.source if profile.source and profile.source.path else config.source + vcs_cfg = profile.vcs if profile.vcs and profile.vcs.type else config.vcs + llm_cfg = profile.llm if profile.llm and profile.llm.provider else config.llm + notify_cfg = _merge_notification(profile.notification, config.notification) + + runner = WorkflowRunner( + config=config, + profile=profile, + vcs=create_vcs_client(vcs_cfg, workspace=str(workspace)), + source=create_source(source_cfg), + llm=create_llm_client(llm_cfg), + platform=create_platform(config.platform), + notifier=create_notifier(notify_cfg), + workspace=workspace, + ) + + final_state = runner.run(fresh=fresh, batch=batch) + logger.info("Workflow finished with state=%s", final_state) + return 0 + + +def _load_config(args) -> Config: + """加载 config。 + + 优先调用 ``conf._bootstrap.load_config_with_llm_profiles`` 展开 ``llm_profile``、 + 合并 vcs/source 字段级字段、透传 ``locale_names`` 等粘合逻辑;当仓库中 + 没有 ``conf/`` 粘合包(或 import 失败)时,回落到框架自带的 ``load()``, + 保持 ``src/TiMi_HOK_Game_Translator`` 对 ``conf/`` 的零硬依赖。 + + 关于 ``-c/--config``: + * 显式传入时,直接使用该路径; + * 省略时,由 bootstrap 自身按 ``GAME_TRANS_TOOLCHAIN_CONFIG`` 环境变量 + 与 ``conf/config.yaml`` 兜底顺序解析,无需额外指定。 + """ + config_path = getattr(args, "config", None) or None + try: + from conf._bootstrap import load_config_with_llm_profiles # type: ignore + + return load_config_with_llm_profiles(config_path, cli_args=args) + except ImportError: + return load(cli_args=args) + + +def main(argv: Sequence[str] | None = None) -> int: + """``TiMi_HOK_Game_Translator`` 命令行入口。 + + 参数: + argv: 命令行参数序列,None 时从 sys.argv 读取。 + 返回: + 进程退出码。 + """ + parser = build_argparser() + args = parser.parse_args(argv) + + command = getattr(args, "command", None) + if command == "config" and getattr(args, "config_command", None) == "dump": + config = _load_config(args) + return _dump_config(args, config) + + if command == "run": + fresh = bool(getattr(args, "fresh", False)) + batch = getattr(args, "batch", None) or None + if fresh and batch: + parser.error("--fresh and --batch are mutually exclusive.") + config = _load_config(args) + return _run(args, config, fresh=fresh, batch=batch) + + parser.print_help() + return 2 + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbf0cb55d533dad60da76eafc6f5d1e80f682e6 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__init__.py @@ -0,0 +1,105 @@ +"""TiMi_HOK_Game_Translator.commons 子包。 + +集中导出各模块最常用的少量符号,调用方可以直接:: + + from TiMi_HOK_Game_Translator.commons import Stage, ConfigError, APP_NAME +""" + +from .constants import ( + APP_NAME, + CLI_COMMAND, + DEFAULT_CONFIG_FILENAME, + DEFAULT_ENV_FILENAME, + DEFAULT_HTTP_RETRIES, + DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + DEFAULT_HTTP_TIMEOUT_SECONDS, + DEFAULT_LLM_BATCH_SIZE, + DEFAULT_LLM_MAX_TOKENS, + DEFAULT_LLM_TEMPERATURE, + DEFAULT_LOG_DIRNAME, + DEFAULT_REVIEW_POLL_INTERVAL_SECONDS, + DEFAULT_STATE_FILENAME, + DEFAULT_STATE_POLL_INTERVAL_SECONDS, + DEFAULT_VCS_CLI_TIMEOUT_SECONDS, + DEFAULT_VCS_COMMIT_MESSAGE, + DEFAULT_WORKSPACE_DIRNAME, + ENV_NESTED_DELIMITER, + ENV_PREFIX, + SENSITIVE_FIELD_MARKERS, + SENSITIVE_MASK, +) +from .enums import ( + LLMProvider, + LogLevel, + NotifierType, + PlatformType, + ReviewRound, + ReviewStage, + SourceFormat, + Stage, + VcsType, + WorkflowState, +) +from .exceptions import ( + ConfigError, + ConfigFileError, + LLMError, + LLMProviderMissingError, + MissingRequiredConfigError, + OpenLocalizerError, + PlatformError, + SourceError, + UnknownSourceFormatError, + VcsCliMissingError, + VcsCommandError, + VcsError, +) + +__all__ = [ + # constants + "APP_NAME", + "CLI_COMMAND", + "DEFAULT_CONFIG_FILENAME", + "DEFAULT_ENV_FILENAME", + "DEFAULT_HTTP_RETRIES", + "DEFAULT_HTTP_RETRY_INTERVAL_SECONDS", + "DEFAULT_HTTP_TIMEOUT_SECONDS", + "DEFAULT_LLM_BATCH_SIZE", + "DEFAULT_LLM_MAX_TOKENS", + "DEFAULT_LLM_TEMPERATURE", + "DEFAULT_LOG_DIRNAME", + "DEFAULT_REVIEW_POLL_INTERVAL_SECONDS", + "DEFAULT_STATE_FILENAME", + "DEFAULT_STATE_POLL_INTERVAL_SECONDS", + "DEFAULT_VCS_CLI_TIMEOUT_SECONDS", + "DEFAULT_VCS_COMMIT_MESSAGE", + "DEFAULT_WORKSPACE_DIRNAME", + "ENV_NESTED_DELIMITER", + "ENV_PREFIX", + "SENSITIVE_FIELD_MARKERS", + "SENSITIVE_MASK", + # enums + "LLMProvider", + "LogLevel", + "NotifierType", + "PlatformType", + "ReviewRound", + "ReviewStage", + "SourceFormat", + "Stage", + "VcsType", + "WorkflowState", + # exceptions + "ConfigError", + "ConfigFileError", + "LLMError", + "LLMProviderMissingError", + "MissingRequiredConfigError", + "OpenLocalizerError", + "PlatformError", + "SourceError", + "UnknownSourceFormatError", + "VcsCliMissingError", + "VcsCommandError", + "VcsError", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b171c523e1b705138450a8e5f54388568bb64203 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/constants.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/constants.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01fb2e7be0c1e7fefe25def4290e3037cdb5af2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/constants.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/enums.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/enums.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b238a5e51cb01fc1f4426750e462639a2217b81 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/enums.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/exceptions.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/exceptions.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ea4025ffed41a5c720be1c5e566058fd0134af2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/__pycache__/exceptions.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/constants.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..5972f94a84f5e5a3d310eb3954eb31c98dc41baf --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/constants.py @@ -0,0 +1,81 @@ +"""项目级常量。 + +**判断准则**:如果一个字面量被多个模块引用,或者它代表一个"离开上下文 +也能理解含义"的可调项,就应放在本文件(或 :mod:`TiMi_HOK_Game_Translator.commons.enums`)。 + +**不要**把面向用户的可配置项放在这里 —— 那些应写入 ``config.example.yaml``。 +本模块只承载真正不变的常量(默认重试次数、约定 key 等)。 +""" + +from __future__ import annotations + +# --------------------------------------------------------------------------- +# 包身份标识 +# --------------------------------------------------------------------------- +APP_NAME: str = "TiMi_HOK_Game_Translator" +CLI_COMMAND: str = "TiMi_HOK_Game_Translator" + +# 环境变量前缀,用于自动映射到 Config 对象。 +# 例如 GAME_TRANS_TOOLCHAIN__VCS__TYPE 会覆盖 ``config.vcs.type``。 +ENV_PREFIX: str = "GAME_TRANS_TOOLCHAIN" +ENV_NESTED_DELIMITER: str = "__" + +# --------------------------------------------------------------------------- +# 文件系统默认值 +# --------------------------------------------------------------------------- +DEFAULT_CONFIG_FILENAME: str = "config.yaml" +DEFAULT_ENV_FILENAME: str = ".env" +DEFAULT_WORKSPACE_DIRNAME: str = "workspace" +DEFAULT_STATE_FILENAME: str = "workflow_state.json" +DEFAULT_LOG_DIRNAME: str = "logs" + +# --------------------------------------------------------------------------- +# 网络重试默认值(供基于 HTTP 的平台 / 通知客户端使用) +# --------------------------------------------------------------------------- +DEFAULT_HTTP_TIMEOUT_SECONDS: int = 30 +DEFAULT_HTTP_RETRIES: int = 3 +DEFAULT_HTTP_RETRY_INTERVAL_SECONDS: int = 30 + +# --------------------------------------------------------------------------- +# VCS 默认值 +# --------------------------------------------------------------------------- +DEFAULT_VCS_COMMIT_MESSAGE: str = "[TiMi_HOK_Game_Translator] commit translation data" +DEFAULT_VCS_CLI_TIMEOUT_SECONDS: int = 600 + +# --------------------------------------------------------------------------- +# 密钥扫描 / 脱敏 +# --------------------------------------------------------------------------- +# 需要在 ``dump`` / 日志中脱敏的字段名,每一项都是**完整**字段名(大小写不敏感)。 +# 出现新的携带凭据的字段时,请追加到此列表。 +SENSITIVE_FIELD_MARKERS: tuple[str, ...] = ( + "password", + "passwd", + "secret", + "token", + "api_key", + "apikey", + "access_key", + "private_key", + "webhook", + "api_token", +) +SENSITIVE_MASK: str = "***" + +# --------------------------------------------------------------------------- +# LLM 默认值 +# --------------------------------------------------------------------------- +DEFAULT_LLM_TEMPERATURE: float = 0.2 +DEFAULT_LLM_MAX_TOKENS: int = 1024 +DEFAULT_LLM_BATCH_SIZE: int = 32 + +# --------------------------------------------------------------------------- +# 工作流默认值 +# --------------------------------------------------------------------------- +DEFAULT_STATE_POLL_INTERVAL_SECONDS: int = 5 + +# --------------------------------------------------------------------------- +# 审校轮询默认值 +# --------------------------------------------------------------------------- +#: ``first_review`` / ``second_review`` 轮询 Crowdin 任务状态的默认间隔秒数。 +#: 可通过 ``ReviewConfig.poll_interval_seconds`` 在 ``conf/languages/*.json`` 覆盖。 +DEFAULT_REVIEW_POLL_INTERVAL_SECONDS: int = 1800 diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/enums.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac9befb473ddd5d000a765e4338a8dc6c6d2826 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/enums.py @@ -0,0 +1,207 @@ +"""框架内使用的枚举定义。 + +集中在一个模块,可以让状态机流转、VCS 选型、源文件格式选型、 +CLI 参数取值保持一致。所有枚举都继承 ``str``,方便 YAML/JSON 序列化以及 +argparse ``choices`` 使用。 +""" + +from __future__ import annotations + +from enum import Enum + + +class VcsType(str, Enum): + """支持的版本控制后端。 + + :cvar LOCAL: **本地文件系统后端** —— 不走任何 VCS,直接在 ``local_path`` + 目录读写翻译数据;用于本地开发 / demo / 单测。老字段值 ``"mock"`` + 仍被加载器识别为同一枚举(见 :mod:`TiMi_HOK_Game_Translator.vcs.factory`)。 + """ + + SVN = "svn" + GIT = "git" + PERFORCE = "perforce" + LOCAL = "local" + #: 向后兼容别名;老配置里的 ``vcs.type: mock`` 等价于 ``local``。 + MOCK = "local" + + @classmethod + def values(cls) -> list[str]: + """返回全部枚举的字符串值,便于用作 ``argparse(choices=...)``。""" + return [member.value for member in cls] + + +class SourceFormat(str, Enum): + """支持的本地化源文件格式。""" + + JSON = "json" + YAML = "yaml" + XML = "xml" + CSV = "csv" + DTXML = "dtxml" + XLIFF = "xliff" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class LLMProvider(str, Enum): + """支持的 LLM 后端。 + + :cvar ECHO: **回显式占位 provider** —— 把输入文本按 ``[target_locale] 原文`` + 格式回显出来,不联网、确定性输出,用于本地 demo / 单测 / 配置试跑。 + 老字段值 ``"mock"`` 仍被加载器识别为同一枚举(见 + :mod:`TiMi_HOK_Game_Translator.llm.factory`)。 + """ + + ECHO = "echo" + #: 向后兼容别名;老配置里的 ``llm.provider: mock`` 等价于 ``echo``。 + MOCK = "echo" + OPENAI = "openai" + OPENAI_COMPATIBLE = "openai_compatible" + ANTHROPIC = "anthropic" + GEMINI = "gemini" + HUNYUAN_TRANSLATION = "hunyuan_translation" + VENUS = "venus" + CUSTOM = "custom" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class PlatformType(str, Enum): + """支持的审校平台适配器。""" + + NONE = "none" + CROWDIN = "crowdin" + PHRASE = "phrase" + CUSTOM = "custom" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class ReviewStage(str, Enum): + """标识一个 :class:`TranslationPlatform` 实例服务于哪一轮审校。 + + 同一个 :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile` 允许为不同轮次配置 + 不同平台(例如一审用 Phrase、二审用 Crowdin)。工作流状态会依据本枚举 + 从 profile 中挑选对应的 :class:`ReviewConfig`。 + """ + + LIGHT = "light" + FIRST = "first" + SECOND = "second" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class NotifierType(str, Enum): + """支持的通知渠道。""" + + NONE = "none" + WECOM = "wecom" + SLACK = "slack" + EMAIL = "email" + CONSOLE = "console" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class Stage(str, Enum): + """整体流水线阶段 / 发版周期分类。""" + + EXP_WEEK = "exp_week" + TRUNK_WEEK = "trunk_week" + PUB_WEEK = "pub_week" + HOT_WEEK = "hot_week" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class ReviewRound(str, Enum): + """当前工作流处于哪一轮审校。""" + + FIRST = "first" + SECOND = "second" + + +class WorkflowState(str, Enum): + """框架内建工作流状态的标准名称。 + + :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile.workflow` 字段以这些名称 + 组成一个子集(并指定顺序)来编排该语种的流水线。第三方状态可通过 + :func:`TiMi_HOK_Game_Translator.workflow.state_registry.register_state` 用自定义名称注册。 + """ + + # 生命周期首尾 + PENDING = "pending" + FINISHED = "finished" + FAILED = "failed" + + # VCS 相关 + PULL_VCS = "pull_vcs" + PUSH_VCS = "push_vcs" + PUSH_MULTI_VCS = "push_multi_vcs" + + # 上一轮遗留数据处理 + LAST_FIRST_REVIEW = "last_first_review" + LAST_SECOND_REVIEW = "last_second_review" + LAST_MERGE_DATA = "last_merge_data" + + # 翻译与翻译记忆 + TRANSLATE = "translate" + UPDATE_TM = "update_tm" + UPDATE_GRN_TM = "update_grn_tm" + INCREMENT_MATCH = "increment_match" + + # 审校 + LIGHT_REVIEW = "light_review" + FIRST_REVIEW = "first_review" + SECOND_REVIEW = "second_review" + + # 数据装配 + MERGE_DATA = "merge_data" + VALIDATE_DATA = "validate_data" + + # ------------------------------------------------------------------ + # 向后兼容别名。 + # + # 框架早期使用 5 状态流水线(INGEST → TRANSLATE → REVIEW → MERGE → + # PUBLISH)。上方 17 状态模型已是新标准,保留这些别名,让老状态类和 + # 单元测试在渐进迁移期间继续可用。 + # + # ``str`` Enum 的语义使别名会解析到与其规范名相同的成员(别名不占 + # 独立槽位),因此 ``WorkflowState.INGEST is WorkflowState.PULL_VCS`` 恒真。 + # ------------------------------------------------------------------ + INGEST = "pull_vcs" + REVIEW = "first_review" + MERGE = "merge_data" + PUBLISH = "push_vcs" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] + + +class LogLevel(str, Enum): + """标准日志级别,与 ``logging`` 模块名称一致。""" + + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + CRITICAL = "CRITICAL" + + @classmethod + def values(cls) -> list[str]: + return [member.value for member in cls] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/exceptions.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..172c9d89821808dbc42ea4eda1a4223bb0582482 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/commons/exceptions.py @@ -0,0 +1,70 @@ +"""项目级异常层次。 + +用一组小而语义明确的异常,方便调用方(以及 CI)区分用户错误(配置错)、 +基础设施错误(VCS CLI 缺失、上游 500)和程序缺陷(bug)。 +""" + +from __future__ import annotations + + +class OpenLocalizerError(Exception): + """:mod:`TiMi_HOK_Game_Translator` 所有异常的基类。""" + + +# --------------------------------------------------------------------------- +# 配置 +# --------------------------------------------------------------------------- +class ConfigError(OpenLocalizerError): + """配置类问题的基类。""" + + +class ConfigFileError(ConfigError): + """配置文件缺失、格式错误或不可读。""" + + +class MissingRequiredConfigError(ConfigError): + """所有配置层合并后,某个必填字段仍为空。 + + 错误信息应包含出错字段名,以及可以提供该字段的环境变量。 + """ + + +# --------------------------------------------------------------------------- +# VCS +# --------------------------------------------------------------------------- +class VcsError(OpenLocalizerError): + """版本控制类失败的基类。""" + + +class VcsCliMissingError(VcsError): + """所需的 VCS CLI(``svn`` / ``git`` / ``p4``)未安装或未在 PATH 中。""" + + +class VcsCommandError(VcsError): + """VCS 命令在完成所有重试后仍以非零状态退出。""" + + +# --------------------------------------------------------------------------- +# 源文件 +# --------------------------------------------------------------------------- +class SourceError(OpenLocalizerError): + """本地化源文件解析/写入失败的基类。""" + + +class UnknownSourceFormatError(SourceError): + """请求的 ``source.format`` 没有已注册的实现。""" + + +# --------------------------------------------------------------------------- +# LLM 与平台 +# --------------------------------------------------------------------------- +class LLMError(OpenLocalizerError): + """LLM 提供商相关失败的基类。""" + + +class LLMProviderMissingError(LLMError): + """请求的 LLM 提供商未知,或其可选依赖未安装。""" + + +class PlatformError(OpenLocalizerError): + """翻译平台适配器失败的基类。""" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d64e67f7856054279d68071de959e274d78636 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__init__.py @@ -0,0 +1,47 @@ +"""配置包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.config import Config, load, validate, require_valid +""" + +from .language_loader import ( + attach_language_profiles, + load_language_profile, + load_language_profiles, +) +from .loader import build_argparser, load, require_valid, validate +from .schema import ( + Config, + LanguageProfile, + LLMConfig, + LoggingConfig, + NotificationConfig, + PlatformConfig, + PublishTarget, + ReviewConfig, + SourceConfig, + VcsConfig, + WorkspaceConfig, +) + +__all__ = [ + "Config", + "LLMConfig", + "LanguageProfile", + "LoggingConfig", + "NotificationConfig", + "PlatformConfig", + "PublishTarget", + "ReviewConfig", + "SourceConfig", + "VcsConfig", + "WorkspaceConfig", + "attach_language_profiles", + "build_argparser", + "load", + "load_language_profile", + "load_language_profiles", + "require_valid", + "validate", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__main__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..607a3620264101fa3272eecfd63a98b84bf4ac0d --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__main__.py @@ -0,0 +1,60 @@ +"""``python -m TiMi_HOK_Game_Translator.config`` 命令行入口。 + +用法:: + + python -m TiMi_HOK_Game_Translator.config dump [--format yaml|json] [--no-mask] [-c PATH] + +``dump`` 子命令加载当前生效配置并输出到 stdout,默认对敏感字段做脱敏。 +""" + +from __future__ import annotations + +import json +import sys +from typing import Sequence + +from .loader import build_argparser, load + + +def main(argv: Sequence[str] | None = None) -> int: + """``config`` 子命令入口。 + + 参数: + argv: 命令行参数序列,None 时取 sys.argv。 + 返回: + 进程退出码。 + """ + parser = build_argparser(prog="python -m TiMi_HOK_Game_Translator.config") + args = parser.parse_args(argv) + + # 本入口只处理 ``config dump``,其余交给 :mod:`TiMi_HOK_Game_Translator.cli`。 + if ( + getattr(args, "command", None) != "config" + or getattr(args, "config_command", None) != "dump" + ): + parser.print_help() + return 2 + + config = load(cli_args=args) + mask = not getattr(args, "no_mask", False) + data = config.to_dict(mask_sensitive=mask) + + fmt = getattr(args, "format", "yaml") + if fmt == "json": + print(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)) + else: + try: + import yaml + + print( + yaml.safe_dump( + data, default_flow_style=False, allow_unicode=True, sort_keys=True, + ) + ) + except ImportError: # pragma: no cover - PyYAML 是硬依赖 + print(json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)) + return 0 + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..409c017d599a6db81663b357e7b29bcae0b5605b Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/language_loader.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/language_loader.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6bc84d788fc568e62465ce9a95a7ad429150483 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/language_loader.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/loader.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/loader.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..869f134bf8c48dfc62a15590a26943efd9ea5d07 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/loader.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/schema.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/schema.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06eab87dfd5e0ceab147522b75d51b537d79ae3e Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/__pycache__/schema.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/language_loader.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/language_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..2dfcbf249006e2679bb07d2fcd163adebdf542d0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/language_loader.py @@ -0,0 +1,416 @@ +"""单语种配置文件加载器。 + +扫描一个目录下的配置文件(一个语种一份),将其实例化为 +:class:`~TiMi_HOK_Game_Translator.config.schema.LanguageProfile`。 + +**支持的文件格式**: + +* ``.yaml`` / ``.yml``(项目新规范首选,PyYAML 已是硬依赖) +* ``.json``(向后兼容;若同一 id 同时存在 YAML 和 JSON,后扫到的覆盖前者 + 并记告警——建议迁移完成后删掉 JSON 旧文件) + +YAML 结构示例:: + + id: vi + display_name: Vietnamese + source_locale: en + target_locale: vi + source: + format: json + path: strings/vi/en.json + vcs: + type: git + url: "https://..." + llm: + provider: openai + model: gpt-4o-mini + reviews: + light: { platform: none } + first: { platform: phrase, project_id: phrase-uid, + target_language_id: vi } + second: { platform: crowdin, project_id: "12345", + target_language_id: vi } + workflow: + - pull_vcs + - last_first_review + - last_second_review + - last_merge_data + - translate + - light_review + - first_review + - second_review + - validate_data + - push_vcs + - push_multi_vcs + multi_publish_targets: + - name: vi-exp mirror + source_path: exp/strings/vi.json + use_trunk_vcs: true + strategy_config: + display_name: Vietnamese + max_workers: 5 + returns_english_data: false + +加载器故意采用**宽容**策略: + +* 配置中缺失的字段使用 dataclass 默认值; +* 未识别的顶层 key 会被收集到 ``extra`` 而不报错; +* 字符串字段中的 ``{workspace}`` / ``{project_root}`` 占位符会在加载时展开; +* 标记 ``disabled: true`` 的文件会被跳过。 +""" + +from __future__ import annotations + +import json +import logging +import os +from dataclasses import fields, is_dataclass +from pathlib import Path +from typing import Any, Dict, Optional + +from ..commons import ConfigFileError, ReviewStage +from .schema import ( + LanguageProfile, + LLMConfig, + NotificationConfig, + PublishTarget, + ReviewConfig, + SourceConfig, + VcsConfig, +) + +logger = logging.getLogger(__name__) + +#: 本模块支持的 profile 文件后缀,按**扫描/优先匹配**顺序。 +#: YAML 优先于 JSON——项目新规范首选 YAML,若同一 id 同时存在两份, +#: ``load_language_profiles`` 会告警并以**后扫描到的**为准(与旧实现一致)。 +PROFILE_SUFFIXES: tuple[str, ...] = (".yaml", ".yml", ".json") + + +def _read_profile_data(file_path: Path) -> Dict[str, Any]: + """按文件后缀读取 profile,返回原始 dict。 + + * ``.yaml`` / ``.yml`` → ``yaml.safe_load`` (PyYAML 已是硬依赖) + * ``.json`` → ``json.loads`` + * 其他后缀 → 退回 JSON 解析(保持最小惊讶,向后兼容) + + 任何解析失败都抛 :class:`ConfigFileError`,调用方据此决定是中断还是跳过。 + """ + suffix = file_path.suffix.lower() + raw_text = file_path.read_text(encoding="utf-8") + + if suffix in (".yaml", ".yml"): + try: + import yaml # 局部导入,避免拉高模块导入时间 + except ImportError as exc: # pragma: no cover - 安装时已硬依赖 + raise ConfigFileError( + "PyYAML is required to load YAML language profiles. " + "Install with 'pip install PyYAML'." + ) from exc + try: + data = yaml.safe_load(raw_text) or {} + except yaml.YAMLError as exc: + raise ConfigFileError(f"Malformed YAML in {file_path}: {exc}") from exc + else: + try: + data = json.loads(raw_text) + except json.JSONDecodeError as exc: + raise ConfigFileError(f"Malformed JSON in {file_path}: {exc}") from exc + + if not isinstance(data, dict): + raise ConfigFileError( + f"Top-level value in {file_path} must be a mapping, got " + f"{type(data).__name__}." + ) + return data + + +# --------------------------------------------------------------------------- +# 路径变量展开 +# --------------------------------------------------------------------------- +def _project_root() -> Path: + """返回用作 ``{project_root}`` 的进程当前工作目录。 + + 故意使用 *cwd* 而非探测安装位置,因为 profile 预期是用户提供的产物, + 它们与用户的 ``config.yaml`` 一同存放。 + """ + return Path.cwd() + + +def _expand_placeholders(value: Any, workspace: Path) -> Any: + """递归展开字符串中的 ``{workspace}`` / ``{project_root}``。""" + if isinstance(value, str): + return ( + value.replace("{workspace}", str(workspace)) + .replace("{project_root}", str(_project_root())) + ) + if isinstance(value, list): + return [_expand_placeholders(item, workspace) for item in value] + if isinstance(value, dict): + return {k: _expand_placeholders(v, workspace) for k, v in value.items()} + return value + + +# --------------------------------------------------------------------------- +# 子配置区域转换 +# --------------------------------------------------------------------------- +def _apply_section(section_cls: type, raw: Any) -> Any: + """实例化一个 dataclass 区域,容忍未知键与 ``None``。 + + 参数: + section_cls: 目标 dataclass(如 :class:`SourceConfig`)。 + raw: 原始 JSON 值(通常为 dict;None 表示使用默认值)。 + + 返回: + 一个新的 ``section_cls`` 实例。 + """ + if raw is None: + return section_cls() + if not isinstance(raw, dict): + raise ConfigFileError( + f"Language profile section for {section_cls.__name__} must be an " + f"object, got {type(raw).__name__}." + ) + field_names = {f.name for f in fields(section_cls)} + known = {k: v for k, v in raw.items() if k in field_names} + unknown = {k: v for k, v in raw.items() if k not in field_names} + instance = section_cls(**known) + # 当 dataclass 存在 ``extra`` 字段时,将未知 key 收入其中。 + extra_bucket = getattr(instance, "extra", None) + if isinstance(extra_bucket, dict) and unknown: + extra_bucket.update(unknown) + return instance + + +def _apply_reviews(raw: Any) -> Dict[str, ReviewConfig]: + """将 ``reviews`` JSON 块转成 ``stage -> ReviewConfig`` 的 dict。""" + if raw is None: + return {} + if not isinstance(raw, dict): + raise ConfigFileError( + f"'reviews' must be an object of stage → config, got {type(raw).__name__}." + ) + valid_stages = set(ReviewStage.values()) + result: Dict[str, ReviewConfig] = {} + for stage_name, cfg in raw.items(): + if stage_name not in valid_stages: + logger.warning( + "language profile: ignoring unknown review stage %r " + "(expected one of %s)", + stage_name, + sorted(valid_stages), + ) + continue + review = _apply_section(ReviewConfig, cfg or {}) + review.stage = stage_name # 以 key 为准覆盖 stage 字段 + result[stage_name] = review + return result + + +def _apply_publish_targets(raw: Any) -> tuple: + """将 ``multi_publish_targets`` JSON 列表转成 tuple。""" + if not raw: + return () + if not isinstance(raw, list): + raise ConfigFileError( + f"'multi_publish_targets' must be a list, got {type(raw).__name__}." + ) + items = [] + for entry in raw: + if not isinstance(entry, dict): + raise ConfigFileError( + "Each 'multi_publish_targets' entry must be an object." + ) + # 不可达,仅为了让 mypy 满意 + target = _apply_section(PublishTarget, entry) + # 即使 JSON 传入 list,PublishTarget.stages 也需要是 tuple。 + raw_stages = entry.get("stages") + if raw_stages: + target.stages = tuple(str(s) for s in raw_stages) + items.append(target) + return tuple(items) + + +# --------------------------------------------------------------------------- +# 对外 API +# --------------------------------------------------------------------------- +def load_language_profile( + path: str | os.PathLike[str], + *, + workspace: Optional[Path] = None, +) -> Optional[LanguageProfile]: + """加载单个语种配置文件(YAML 或 JSON)。 + + 按文件后缀自动选路: + + * ``.yaml`` / ``.yml`` → PyYAML 解析(项目新规范首选); + * ``.json`` → 标准库 ``json`` 解析(向后兼容旧 profile)。 + + 参数: + path: ``.yaml`` / ``.yml`` / ``.json`` 文件路径。 + workspace: 用于展开 ``{workspace}`` 占位符的目录, + 默认为 :func:`Path.cwd`。 + + 返回: + 一个 :class:`LanguageProfile` 实例;当文件标记 ``disabled: true`` 时返回 ``None``。 + + 异常: + ConfigFileError: 文件缺失或解析失败。 + """ + file_path = Path(path) + if not file_path.exists(): + raise ConfigFileError(f"Language profile file not found: {file_path}") + + raw = _read_profile_data(file_path) + + if raw.get("disabled") is True: + logger.info("Skipping disabled language profile: %s", file_path) + return None + + ws = workspace or Path.cwd() + raw = _expand_placeholders(raw, ws) + + profile_id = raw.get("id") or file_path.stem + display_name = raw.get("display_name") or profile_id + + # 规范化 locale_names:JSON 允许写 {"cn": "...", "en": "..."}; + # 其他类型(list / 非字符串 value)直接报错,避免渲染提示词时发现问题。 + raw_names = raw.get("locale_names") or {} + if not isinstance(raw_names, dict): + raise ConfigFileError( + f"'locale_names' in {file_path} must be an object of " + f"str → str (got {type(raw_names).__name__})." + ) + locale_names: Dict[str, str] = {} + for k, v in raw_names.items(): + if not isinstance(k, str) or not isinstance(v, str): + raise ConfigFileError( + f"'locale_names' entries in {file_path} must map str to str; " + f"got {k!r} → {v!r}." + ) + locale_names[k.strip().lower()] = v + + profile = LanguageProfile( + id=profile_id, + display_name=display_name, + source_locale=raw.get("source_locale", ""), + target_locale=raw.get("target_locale", profile_id), + locale_names=locale_names, + source=_apply_section(SourceConfig, raw.get("source")), + vcs=_apply_section(VcsConfig, raw.get("vcs")), + llm=_apply_section(LLMConfig, raw.get("llm")), + notification=_apply_section(NotificationConfig, raw.get("notification")), + reviews=_apply_reviews(raw.get("reviews")), + workflow=tuple(raw.get("workflow") or ()), + multi_publish_targets=_apply_publish_targets(raw.get("multi_publish_targets")), + strategy_config=dict(raw.get("strategy_config") or {}), + merge_start_time=str(raw.get("merge_start_time", "") or ""), + ) + + # 未识别的顶层 key 全部收集到 profile.extra。 + consumed = { + "id", "display_name", "source_locale", "target_locale", "locale_names", + "source", "vcs", "llm", "notification", + "reviews", "workflow", "multi_publish_targets", "strategy_config", + "merge_start_time", + "disabled", + } + for key, value in raw.items(): + if key not in consumed: + profile.extra[key] = value + + return profile + + +def load_language_profiles( + languages_dir: str | os.PathLike[str], + *, + workspace: Optional[Path] = None, +) -> Dict[str, LanguageProfile]: + """加载 ``languages_dir`` 下所有 YAML / JSON 文件,返回以 id 为键的 dict。 + + 文件掂描顺序:先 YAML(``.yaml`` → ``.yml``)再 JSON(``.json``), + 同后缀下按文件名字典序掂描。若两个文件声明相同 id,则后掂描 + 到的覆盖前者并记告警(向后兼容旧行为)。建议迁移到 YAML 后 + **删掉同 id 的旧 JSON 文件**,避免走覆盖路径。 + + 参数: + languages_dir: 存放各语种 profile 的目录。不存在时视为“无 profile”, + 返回空 dict(并记 debug 日志)。 + workspace: 透传给 :func:`load_language_profile`。 + + 返回: + 以 :attr:`LanguageProfile.id` 为键的 dict。 + """ + dir_path = Path(languages_dir) + if not dir_path.exists() or not dir_path.is_dir(): + logger.debug("Language profile directory does not exist: %s", dir_path) + return {} + + # 按 PROFILE_SUFFIXES 顺序展开文件列表,同后缀内按文件名字典序排序。 + profile_files: list[Path] = [] + for suffix in PROFILE_SUFFIXES: + profile_files.extend(sorted(dir_path.glob(f"*{suffix}"))) + + result: Dict[str, LanguageProfile] = {} + for profile_file in profile_files: + try: + profile = load_language_profile(profile_file, workspace=workspace) + except ConfigFileError: + logger.exception("Failed to load language profile: %s", profile_file) + raise + if profile is None: + continue + if profile.id in result: + logger.warning( + "Duplicate language id %r — %s overrides earlier definition", + profile.id, profile_file, + ) + result[profile.id] = profile + + logger.info( + "Loaded %d language profile(s) from %s: %s", + len(result), dir_path, sorted(result.keys()), + ) + return result + + +def attach_language_profiles(config: Any) -> None: + """从 :attr:`Config.languages_dir` 填充 :attr:`Config.languages`。 + + 路径解析顺序: + + 1. ``Config.languages_dir`` 非空——使用该路径(相对路径以当前 cwd 为基准)。 + 本仓库日常用法:在 ``conf/config.yaml`` 中显式写 + ``languages_dir: conf/languages``。 + 2. 否则回落到约定默认目录 ``/configs/languages``, + 以保证未配置任何 YAML 的 demo 场景也能开箱即用。 + """ + if not is_dataclass(config): + return + + dir_hint = getattr(config, "languages_dir", "") or "" + workspace = config.workspace_path() if hasattr(config, "workspace_path") else None + + if dir_hint: + candidate = Path(dir_hint).expanduser() + if not candidate.is_absolute(): + candidate = Path.cwd() / candidate + else: + candidate = Path.cwd() / "configs" / "languages" + + if not candidate.exists(): + return + + profiles = load_language_profiles(candidate, workspace=workspace) + if profiles: + config.languages = profiles + # 记录实际使用的目录,供 `config dump` 以及辅助工具展示。 + config.languages_dir = str(candidate) + + +__all__ = [ + "load_language_profile", + "load_language_profiles", + "attach_language_profiles", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/loader.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e862201a4b1f5fa767075a0026f585454b86094b --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/loader.py @@ -0,0 +1,411 @@ +"""分层配置加载器。 + +优先级(后面的覆盖前面的): + +1. :mod:`TiMi_HOK_Game_Translator.config.schema` 中声明的内置默认值; +2. ``config.yaml``(路径受 ``--config`` 命令行参数或 + ``GAME_TRANS_TOOLCHAIN_CONFIG`` 环境变量控制); +3. 以 ``GAME_TRANS_TOOLCHAIN__`` 为前缀的环境变量,嵌套 key 以 ``__`` 分隔 + (例如 ``GAME_TRANS_TOOLCHAIN__VCS__PASSWORD``); +4. 由 :func:`build_argparser` 解析的命令行参数——argparse 参数名与 + schema 字段对应(如 ``--vcs.type``)。 + +必填字段在加载时**不会**直接报错;调用方可调用 :func:`validate` +一次性拿到所有问题。这样可以让 ``TiMi_HOK_Game_Translator config dump`` 在配置不完整时仍然导出便于调试。 +""" + +from __future__ import annotations + +import argparse +import json +import os +from dataclasses import fields, is_dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, TypeVar + +from ..commons import ( + APP_NAME, + CLI_COMMAND, + DEFAULT_CONFIG_FILENAME, + ENV_NESTED_DELIMITER, + ENV_PREFIX, + ConfigFileError, + MissingRequiredConfigError, +) +from .schema import Config + +T = TypeVar("T") # pylint: disable=invalid-name + +_ENV_CONFIG_PATH_KEY = f"{ENV_PREFIX}_CONFIG" + + +# --------------------------------------------------------------------------- +# Layer 1 — 默认值 +# --------------------------------------------------------------------------- +def _default_config() -> Config: + """返回一个使用 schema 默认值初始化的 :class:`Config`。""" + return Config() + + +# --------------------------------------------------------------------------- +# Layer 2 — YAML 文件 +# --------------------------------------------------------------------------- +def _load_yaml_file(path: Path) -> Dict[str, Any]: + """解析 ``path`` 处的 YAML 文件。 + + 异常: + ConfigFileError: 文件不存在或格式错误时抛出。 + """ + if not path.exists(): + raise ConfigFileError(f"Config file not found: {path}") + + try: + import yaml # 局部导入,避免拉高模块导入时间 + except ImportError as exc: # pragma: no cover - 安装时已硬依赖 + raise ConfigFileError( + "PyYAML is required to load YAML config files. " + "Install with 'pip install PyYAML'." + ) from exc + + try: + with path.open("r", encoding="utf-8") as fh: + data = yaml.safe_load(fh) or {} + except yaml.YAMLError as exc: + raise ConfigFileError(f"Malformed YAML at {path}: {exc}") from exc + + if not isinstance(data, dict): + raise ConfigFileError( + f"Top-level YAML value in {path} must be a mapping, got {type(data).__name__}." + ) + return data + + +# --------------------------------------------------------------------------- +# Layer 3 — 环境变量 +# --------------------------------------------------------------------------- +def _env_overrides(environ: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """收集环境变量覆盖项为与 schema 具同构型的嵌套 dict。 + + 示例:: + + GAME_TRANS_TOOLCHAIN__VCS__PASSWORD=hunter2 + → {"vcs": {"password": "hunter2"}} + """ + src = environ if environ is not None else os.environ + prefix = f"{ENV_PREFIX}{ENV_NESTED_DELIMITER}" + result: Dict[str, Any] = {} + for key, value in src.items(): + if not key.startswith(prefix): + continue + path = key[len(prefix):].split(ENV_NESTED_DELIMITER) + _set_nested(result, [p.lower() for p in path], value) + return result + + +def _set_nested(target: Dict[str, Any], path: Sequence[str], value: Any) -> None: + """将 ``value`` 写入 ``target`` 中的 ``path`` 位置,途中需要的 dict 会自动创建。""" + cursor: Dict[str, Any] = target + for key in path[:-1]: + nxt = cursor.get(key) + if not isinstance(nxt, dict): + nxt = {} + cursor[key] = nxt + cursor = nxt + cursor[path[-1]] = value + + +# --------------------------------------------------------------------------- +# Layer 4 — CLI +# --------------------------------------------------------------------------- +def build_argparser(prog: str = CLI_COMMAND) -> argparse.ArgumentParser: + """返回 ``run`` / ``config dump`` 子命令的命令行解析器。 + + 只暴露最常用的 schema 字段;其余字段仍可通过环境变量/YAML 提供。 + """ + parser = argparse.ArgumentParser(prog=prog, description=f"{APP_NAME} command-line interface.") + subparsers = parser.add_subparsers(dest="command") + + run_parser = subparsers.add_parser("run", help="Run the localization pipeline.") + _add_common_arguments(run_parser) + run_parser.add_argument( + "--fresh", + action="store_true", + help="Delete any previously persisted workflow state before running " + "(mutually exclusive with --batch).", + ) + run_parser.add_argument( + "--batch", + dest="batch", + default=None, + metavar="BATCH_NAME", + help="Resume a previous batch by name (e.g. 'vi_20261008204338'). " + "The runner will load archived state from " + "workspace/batches//_archive/ and continue from the " + "first incomplete state. Mutually exclusive with --fresh.", + ) + + dump_parser = subparsers.add_parser( + "config", + help="Configuration utilities (dump the effective configuration).", + ) + dump_sub = dump_parser.add_subparsers(dest="config_command") + dump_cmd = dump_sub.add_parser("dump", help="Print the effective configuration.") + _add_common_arguments(dump_cmd) + dump_cmd.add_argument( + "--format", choices=["yaml", "json"], default="yaml", + help="Output format for 'config dump' (default: yaml).", + ) + dump_cmd.add_argument( + "--no-mask", action="store_true", + help="Do not mask sensitive fields (DANGEROUS — only for local debugging).", + ) + return parser + + +def _add_common_arguments(parser: argparse.ArgumentParser) -> None: + parser.add_argument("--config", "-c", default=None, help="Path to config.yaml.") + parser.add_argument("--project-code", default=None) + parser.add_argument("--stage", default=None) + parser.add_argument("--source-locale", default=None) + parser.add_argument("--target-locale", default=None) + parser.add_argument( + "--language", + dest="language", + default=None, + help="Language id to run (matches a LanguageProfile.id).", + ) + parser.add_argument( + "--languages-dir", + dest="languages_dir", + default=None, + help="Directory to scan for per-language profile JSON files.", + ) + parser.add_argument("--vcs-type", dest="vcs__type", default=None) + parser.add_argument("--vcs-url", dest="vcs__url", default=None) + parser.add_argument("--vcs-revision", dest="vcs__revision", default=None) + parser.add_argument("--source-format", dest="source__format", default=None) + parser.add_argument("--source-path", dest="source__path", default=None) + parser.add_argument("--llm-provider", dest="llm__provider", default=None) + parser.add_argument("--log-level", dest="logging__level", default=None) + + +def _cli_overrides(args: argparse.Namespace) -> Dict[str, Any]: + """将 argparse namespace 转为嵌套的覆盖 dict。""" + result: Dict[str, Any] = {} + for key, value in vars(args).items(): + if value is None: + continue + if key in {"command", "config_command", "format", "no_mask", "config", "fresh", "batch"}: + continue + # 将平铺的 ``vcs__type`` 转为嵌套 {"vcs": {"type": ...}}。 + path = [p.replace("-", "_") for p in key.split(ENV_NESTED_DELIMITER.lower())] + # 同时保留顶层扁平参数(如 ``project_code``)。 + if len(path) == 1: + path = [path[0]] + _set_nested(result, path, value) + return result + + +# --------------------------------------------------------------------------- +# 合并 +# --------------------------------------------------------------------------- +def _merge_into_dataclass(instance: Any, overrides: Dict[str, Any]) -> None: + """就地将 ``overrides`` 合并到 dataclass ``instance``。 + + 字段类型会尽量自动转换:环境/CLI 传入的值都是字符串, + 会根据字段声明的 ``bool`` / ``int`` / ``float`` / ``list`` 进行转换。 + """ + if not is_dataclass(instance) or not isinstance(overrides, dict): + return + + field_map = {f.name: f for f in fields(instance)} + for key, value in overrides.items(): + target_field = field_map.get(key) + if target_field is None: + # 未知 key——当 dataclass 存在 ``extra`` 字段时收入其中。 + extra = getattr(instance, "extra", None) + if isinstance(extra, dict): + extra[key] = value + continue + + current = getattr(instance, key) + if is_dataclass(current) and isinstance(value, dict): + _merge_into_dataclass(current, value) + continue + + coerced = _coerce(value, target_field.type, current) + setattr(instance, key, coerced) + + +_BOOL_TRUTHY = {"1", "true", "yes", "on"} +_BOOL_FALSY = {"0", "false", "no", "off", ""} + + +def _coerce(value: Any, declared_type: Any, current: Any) -> Any: + """尽力将 ``value`` 转换为字段声明的类型。""" + if value is None: + return current + + # 仅字符串需要转换,其他类型直接透传。 + if not isinstance(value, str): + return value + + type_name = str(declared_type).lower() + if "bool" in type_name: + low = value.strip().lower() + if low in _BOOL_TRUTHY: + return True + if low in _BOOL_FALSY: + return False + return current + if "int" in type_name: + try: + return int(value) + except ValueError: + return current + if "float" in type_name: + try: + return float(value) + except ValueError: + return current + if "list" in type_name: + return [item.strip() for item in value.split(",") if item.strip()] + if "dict" in type_name: + try: + return json.loads(value) + except ValueError: + return current + return value + + +# --------------------------------------------------------------------------- +# 对外 API +# --------------------------------------------------------------------------- +def load( + *, + config_path: Optional[str] = None, + cli_args: Optional[argparse.Namespace] = None, + environ: Optional[Dict[str, str]] = None, +) -> Config: + """从全部配置层加载并返回 :class:`Config`。 + + 参数: + config_path: 显式指定的 YAML 路径;为 ``None`` 时,依次取 ``cli_args.config`` 、 + ``GAME_TRANS_TOOLCHAIN_CONFIG`` 环境变量,都未提供时默认尝试 + ``./config.yaml``(存在时)。 + cli_args: :func:`build_argparser` 解析后的 argparse namespace。 + environ: 自定义环境变量字典(主要供测试使用)。 + + 返回: + 完整合并后的 :class:`Config` 实例。 + + 异常: + ConfigFileError: 显式指定的 YAML 路径无法读取时。 + """ + config = _default_config() + + # 确定待加载的 YAML 路径。 + yaml_path = _resolve_yaml_path(config_path, cli_args, environ) + if yaml_path is not None: + yaml_data = _load_yaml_file(yaml_path) + _merge_into_dataclass(config, yaml_data) + + env_data = _env_overrides(environ) + _merge_into_dataclass(config, env_data) + + if cli_args is not None: + cli_data = _cli_overrides(cli_args) + _merge_into_dataclass(config, cli_data) + + # 所有层合并完成后,扫描各语种的 profile JSON。 + # 延迟导入,避免包导入时循环依赖。 + from .language_loader import attach_language_profiles + attach_language_profiles(config) + + return config + + +def _resolve_yaml_path( + explicit: Optional[str], + cli_args: Optional[argparse.Namespace], + environ: Optional[Dict[str, str]], +) -> Optional[Path]: + """返回实际要加载的 YAML 路径;均无时返回 ``None``。""" + if explicit: + return Path(explicit).expanduser().resolve() + + if cli_args is not None: + cli_path = getattr(cli_args, "config", None) + if cli_path: + return Path(cli_path).expanduser().resolve() + + src = environ if environ is not None else os.environ + env_path = src.get(_ENV_CONFIG_PATH_KEY) + if env_path: + return Path(env_path).expanduser().resolve() + + default_path = Path.cwd() / DEFAULT_CONFIG_FILENAME + if default_path.exists(): + return default_path.resolve() + return None + + +# --------------------------------------------------------------------------- +# 校验 +# --------------------------------------------------------------------------- +_REQUIRED_FIELDS_BY_VCS: Dict[str, List[str]] = { + "svn": ["vcs.url"], + "git": ["vcs.url"], + "perforce": ["vcs.url"], + # ``local`` 是框架内置的"无 VCS、直接读写本地目录"后端;``mock`` 为 + # 向后兼容的老别名(见 :class:`VcsType`),两者都不需要远端 URL。 + "local": [], + "mock": [], +} + + +def validate(config: Config) -> List[str]: + """返回人可读的问题列表;空列表代表“配置合法”。""" + problems: List[str] = [] + + if not config.project_code: + problems.append("project_code is empty.") + if not config.source_locale: + problems.append("source_locale is empty.") + if not config.target_locale: + problems.append("target_locale is empty (use --target-locale or set it in config.yaml).") + + vcs_required = _REQUIRED_FIELDS_BY_VCS.get(config.vcs.type, []) + for dotted in vcs_required: + section, name = dotted.split(".", 1) + value = getattr(getattr(config, section), name, None) + if not value: + problems.append( + f"{dotted} is empty but required for vcs.type = '{config.vcs.type}'." + ) + + if not config.source.path: + problems.append("source.path is empty.") + + return problems + + +def require_valid(config: Config) -> None: + """当 :func:`validate` 发现问题时抛出 :class:`MissingRequiredConfigError`。""" + problems = validate(config) + if problems: + joined = "\n - ".join(problems) + raise MissingRequiredConfigError( + "Configuration is incomplete. Fix the following issues then retry:\n" + f" - {joined}\n" + "Hint: fields can be supplied via config.yaml, env variables " + f"(prefix '{ENV_PREFIX}{ENV_NESTED_DELIMITER}') or CLI flags." + ) + + +__all__ = [ + "build_argparser", + "load", + "require_valid", + "validate", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/schema.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..43ef4b4a09cbf7d35b55f2a9f687196f2cfc6bdd --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/config/schema.py @@ -0,0 +1,457 @@ +"""带类型注解的配置 schema。 + +整个框架由一棵 dataclass 树驱动,目的在于: + +* 每个字段都有**默认值**(确保一份空白 ``config.yaml`` 也能启动); +* 每个字段都有**类型注解**,供 :func:`config.loader.load` + 在 YAML/env/CLI 层之间自动转换类型; +* 导出当前生效配置时行为确定且安全(敏感字段自动脱敏)。 + +用户一般不需手工构造这些 dataclass——直接调用 +:func:`TiMi_HOK_Game_Translator.config.load` 即可。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, fields, is_dataclass +from pathlib import Path +from typing import Any, Dict, List, Tuple + +from ..commons import ( + DEFAULT_HTTP_RETRIES, + DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + DEFAULT_HTTP_TIMEOUT_SECONDS, + DEFAULT_LLM_BATCH_SIZE, + DEFAULT_LLM_MAX_TOKENS, + DEFAULT_LLM_TEMPERATURE, + DEFAULT_LOG_DIRNAME, + DEFAULT_STATE_FILENAME, + DEFAULT_VCS_CLI_TIMEOUT_SECONDS, + DEFAULT_VCS_COMMIT_MESSAGE, + DEFAULT_WORKSPACE_DIRNAME, + SENSITIVE_FIELD_MARKERS, + SENSITIVE_MASK, + LLMProvider, + LogLevel, + NotifierType, + PlatformType, + ReviewStage, + SourceFormat, + Stage, + VcsType, +) + + +# --------------------------------------------------------------------------- +# 子区域 +# --------------------------------------------------------------------------- +@dataclass +class VcsConfig: + """版本控制配置。""" + + type: str = VcsType.MOCK.value + """后端类型,取值参见 :class:`VcsType`。""" + + url: str = "" + """仓库地址(``svn://…`` / ``https://…`` / ``ssh://…``)。""" + + revision: str = "HEAD" + """目标版本 / commit / changelist。""" + + local_path: str = "" + """本地工作副本目录;为空时使用 ``{workspace}/vcs``。""" + + username: str = "" + """登录用户名;建议从环境变量注入。""" + + password: str = "" + """登录密码/密钥;建议从环境变量注入。""" + + cli_timeout_seconds: int = DEFAULT_VCS_CLI_TIMEOUT_SECONDS + default_commit_message: str = DEFAULT_VCS_COMMIT_MESSAGE + + extra: Dict[str, Any] = field(default_factory=dict) + """后端自定义参数(如 Perforce 的 ``p4port`` 、 Git 的 ``ssh_key``)。""" + + +@dataclass +class SourceConfig: + """本地化源文件配置。""" + + format: str = SourceFormat.JSON.value + """格式标识,取值参见 :class:`SourceFormat`。""" + + path: str = "" + """待加载/写入的文件路径(相对于 workspace)。""" + + encoding: str = "utf-8" + + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class LLMConfig: + """LLM 提供商配置。""" + + provider: str = LLMProvider.MOCK.value + model: str = "" + temperature: float = DEFAULT_LLM_TEMPERATURE + max_tokens: int = DEFAULT_LLM_MAX_TOKENS + batch_size: int = DEFAULT_LLM_BATCH_SIZE + timeout_seconds: int = DEFAULT_HTTP_TIMEOUT_SECONDS + retries: int = DEFAULT_HTTP_RETRIES + retry_interval_seconds: int = DEFAULT_HTTP_RETRY_INTERVAL_SECONDS + + # 敏感字段:``dump`` 会自动脱敏。 + api_key: str = "" + api_base: str = "" + + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class PlatformConfig: + """翻译/审校平台适配器配置。""" + + type: str = PlatformType.NONE.value + api_base: str = "" + + # 敏感字段:``dump`` 会自动脱敏。 + api_token: str = "" + project_id: str = "" + + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class NotificationConfig: + """通知渠道配置。""" + + type: str = NotifierType.CONSOLE.value + + # 敏感字段:``dump`` 会自动脱敏。 + webhook: str = "" + mentioned: List[str] = field(default_factory=list) + + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class WorkspaceConfig: + """运行时的文件布局配置。""" + + root: str = "" + """workspace 的绝对路径;为空时默认为 ``$PWD/workspace``。""" + + subdir: str = DEFAULT_WORKSPACE_DIRNAME + state_filename: str = DEFAULT_STATE_FILENAME + + +@dataclass +class LoggingConfig: + """日志配置(级别 + 文件路径)。""" + level: str = LogLevel.INFO.value + directory: str = DEFAULT_LOG_DIRNAME + filename: str = "TiMi_HOK_Game_Translator.log" + console: bool = True + + +# --------------------------------------------------------------------------- +# 单语种配置 profile(通过 ``conf/languages/.yaml``/``*.json`` +# 加载的产品无关形式)。取配置文件并转为 +# :class:`LanguageProfile` 的加载器见 +# :mod:`TiMi_HOK_Game_Translator.config.language_loader`。 +# --------------------------------------------------------------------------- +@dataclass +class ReviewConfig: + """单个审校阶段在翻译平台上的配置。 + + 字段: + stage: 本记录服务于哪一轮审校(LIGHT / FIRST / SECOND), + 取值参见 :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage`。 + platform: 平台类型标识(如 ``"phrase"`` / ``"crowdin"`` / ``"none"``), + 由 :func:`TiMi_HOK_Game_Translator.platforms.factory.build_review_tool` 解析为具体类。 + project_id: 平台侧的项目/工作区 ID。 + project_name: 人可读的项目名,用于通知。 + api_base / api_token: 可选的阶段级凭据覆盖;为空时使用 + 全局 :class:`PlatformConfig`。**敏感字段**, + ``config dump`` 会脱敏。 + target_language_id: 平台侧的语种代码(各平台可能与 BCP-47 不同)。 + webhook_url / mentioned: 阶段级通知覆盖。 + stop_time: 本地时区下的审校轮询截止时间(``"HH:MM"`` 格式,空串代表禁用)。 + extra: 保留给平台自定义参数(如 Phrase 的 ``workflowStep`` UID、 + Crowdin 的 ``directoryId``)。 + """ + + stage: str = ReviewStage.FIRST.value + platform: str = PlatformType.NONE.value + project_id: str = "" + project_name: str = "" + api_base: str = "" + api_token: str = "" + target_language_id: str = "" + webhook_url: str = "" + mentioned: List[str] = field(default_factory=list) + stop_time: str = "" + #: 单次 ``get_task_status`` 轮询之间的间隔秒数;``0`` 代表使用框架默认 + #: (:const:`DEFAULT_REVIEW_POLL_INTERVAL_SECONDS`)。 + poll_interval_seconds: int = 0 + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class PublishTarget: + """``multi_publish_targets`` 列表中的单条目标。 + + 对应旧项目中的 ``trunk_tdr_configs`` / ``pub_tdr_configs`` 概念: + 同一份翻译结果合并后,可能需要推送到多个目标路径/分支。 + + 字段: + name: 日志/通知中使用的人可读名称。 + source_path: 额外写入翻译结果的路径(相对于 workspace 或绝对)。 + vcs_url_override: 当前目标单独使用的 VCS URL(空则复用 profile / 全局)。 + use_trunk_vcs: True → 推送到 profile 上配置的 "trunk" 分支/URL; + False → 推送到当前选中的 VCS URL。 + stages: 当前目标适用的流水线阶段(``Stage`` 值); + 空元组代表“任何阶段都适用”。 + bundles: 自由形式的标签,描述当前目标发布的资源包 + (由上层业务自定义,框架本身不解释)。 + extra: 平台自定义参数。 + """ + + name: str = "" + source_path: str = "" + vcs_url_override: str = "" + use_trunk_vcs: bool = False + stages: Tuple[str, ...] = () + bundles: str = "" + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class LanguageProfile: + """单语种流水线配置 profile。 + + profile 是描述“单个目标语种如何被处理”的**唯一实例**: + 运行哪些工作流状态、每一轮审校由哪个平台处理、选择哪种翻译策略, + 以及最终数据发布到哪些目标位置。 + + profile 通常从 ``/.json`` 经 + :func:`TiMi_HOK_Game_Translator.config.language_loader.load_language_profiles` + 加载——``languages_dir`` 由 :attr:`Config.languages_dir` 指定 + (本仓库惯用 ``conf/languages``,demo 默认 ``configs/languages``), + 也可以以编程方式构造。 + + 字段: + id: 语种短标识,在状态文件、日志前缀、流水线查找中均使用。 + 惯例采用 BCP-47 或产品自定义 slug(如 ``"vi"`` / ``"vi_exp"``)。 + display_name: 人可读名称,用于日志和通知(如 ``"Vietnamese (Production)"``)。 + source_locale / target_locale: BCP-47 标签;为空时运行时 + 继承全局 :class:`Config` 的值。 + source: 可选的 :class:`SourceConfig` 覆盖(各语种的源文件往往位于不同路径)。 + vcs: 可选的 :class:`VcsConfig` 覆盖(各语种可能属于不同分支/工作副本)。 + llm: 可选的 :class:`LLMConfig` 覆盖(部分语种需要不同模型或提示词)。 + reviews: ``ReviewStage.value → ReviewConfig`` 的映射; + ``workflow`` 里出现的每个审校阶段都应在此有对应项。 + notification: 可选的 :class:`NotificationConfig` 覆盖。 + workflow: 工作流状态名称的有序列表(必须与 + :data:`TiMi_HOK_Game_Translator.workflow.state_registry.STATE_REGISTRY` 一致)。 + multi_publish_targets: 额外发布目标(参见 :class:`PublishTarget`)。 + strategy_config: 供当前语种的 + :class:`~TiMi_HOK_Game_Translator.translation.BaseTranslationStrategy` 使用的 + 自由字典(展示名、提示词模板、最大并发、过滤开关…)。 + 默认解释参见 :mod:`TiMi_HOK_Game_Translator.translation.generic_strategy`。 + locale_names: 可选的 ``{"cn": "...", "en": "..."}`` 字典,供提示词 + 渲染时覆盖内置的中/英文语种名(例如把 ``vi`` 显示为 + "越南文(游戏术语版)")。未填写时自动回落到 + :data:`TiMi_HOK_Game_Translator.llm.prompts.LOCALE_CN_NAME` / + :data:`~TiMi_HOK_Game_Translator.llm.prompts.LOCALE_EN_NAME`,再兜底使用 + locale code 字面量。 + extra: 插件用户可以额外携带的任意内容。 + """ + + id: str = "" + display_name: str = "" + source_locale: str = "" + target_locale: str = "" + locale_names: Dict[str, str] = field(default_factory=dict) + + source: SourceConfig = field(default_factory=SourceConfig) + vcs: VcsConfig = field(default_factory=VcsConfig) + llm: LLMConfig = field(default_factory=LLMConfig) + notification: NotificationConfig = field(default_factory=NotificationConfig) + + reviews: Dict[str, ReviewConfig] = field(default_factory=dict) + workflow: Tuple[str, ...] = () + multi_publish_targets: Tuple[PublishTarget, ...] = () + strategy_config: Dict[str, Any] = field(default_factory=dict) + + #: 导表(``dtxml_merge`` + ``push_vcs``)的目标启动时间,格式 ``"HH:MM"``。 + #: 为空(默认)表示"立即执行";非空时 ``dtxml_merge`` state 会阻塞等待 + #: 到达该本地时刻再开跑,常用于把合表 + commit 压到夜间低峰窗口。 + merge_start_time: str = "" + + extra: Dict[str, Any] = field(default_factory=dict) + + # ----------------------------------------------------------------- + # 便捷方法 + # ----------------------------------------------------------------- + def review(self, stage: str) -> ReviewConfig: + """返回 ``stage`` 对应的 :class:`ReviewConfig`。 + + 当 stage 未配置时返回空壳的 ``ReviewConfig``(``platform="none"``), + 方便工作流状态判定“跳过当前阶段”而无需抛异常。 + """ + return self.reviews.get(stage, ReviewConfig(stage=stage)) + + def has_workflow_state(self, state_name: str) -> bool: + """当 ``state_name`` 属于本 profile 的工作流时返回 True。""" + return state_name in self.workflow + + +# --------------------------------------------------------------------------- +# 根配置 +# --------------------------------------------------------------------------- +@dataclass +class Config: + """唯一的根配置对象。 + + 字段 + ---- + project_code: + 当前游戏/产品的短 slug(取代旧代码中硬编码的 ``AOV_*`` 前缀), + 作为文件名、通知标题、状态文件的命名空间。 + stage: + 当前发版阶段,取值参见 :class:`Stage`。 + source_locale: + 源语言的 BCP-47 标签。 + target_locale: + 本次运行目标语言的 BCP-47 标签。 + """ + + project_code: str = "example_game" + stage: str = Stage.TRUNK_WEEK.value + source_locale: str = "en" + target_locale: str = "" + + vcs: VcsConfig = field(default_factory=VcsConfig) + source: SourceConfig = field(default_factory=SourceConfig) + llm: LLMConfig = field(default_factory=LLMConfig) + platform: PlatformConfig = field(default_factory=PlatformConfig) + notification: NotificationConfig = field(default_factory=NotificationConfig) + workspace: WorkspaceConfig = field(default_factory=WorkspaceConfig) + logging: LoggingConfig = field(default_factory=LoggingConfig) + + #: 单语种流水线 profile,以 :attr:`LanguageProfile.id` 为键。 + #: 由 :func:`TiMi_HOK_Game_Translator.config.language_loader.load_language_profiles` + #: 从 :attr:`languages_dir` 扫描填充(未配置时回落到 ``/configs/languages``; + #: 本仓库日常使用 ``conf/languages``,由 ``conf/config.yaml`` 显式指定)。 + languages: Dict[str, LanguageProfile] = field(default_factory=dict) + + #: 供扫描语种 profile JSON 的目录。为空则代表“未加载任何 profile”, + #: 流水线会回退到顶层的 VCS/source/LLM 区域。 + languages_dir: str = "" + + # 供插件额外使用的自由字段。 + extra: Dict[str, Any] = field(default_factory=dict) + + # ----------------------------------------------------------------- + # 便捷方法 + # ----------------------------------------------------------------- + def workspace_path(self) -> Path: + """返回当前 workspace 的绝对路径。""" + if self.workspace.root: + return Path(self.workspace.root).expanduser().resolve() + return (Path.cwd() / self.workspace.subdir).resolve() + + def language_profile(self, language_id: str) -> LanguageProfile: + """按 id 查找 :class:`LanguageProfile`。 + + 当未找到时,返回一份继承全局 :class:`Config` 子区域的**合成 profile**。 + 这使得即使调用方未创建任何语种 profile 目录也能安全调用。 + """ + cached = self.languages.get(language_id) + if cached is not None: + return cached + return LanguageProfile( + id=language_id, + display_name=language_id, + source_locale=self.source_locale, + target_locale=self.target_locale or language_id, + source=self.source, + vcs=self.vcs, + llm=self.llm, + notification=self.notification, + ) + + def to_dict(self, *, mask_sensitive: bool = True) -> Dict[str, Any]: + """返回配置的 dict 视图。 + + 参数: + mask_sensitive: 为 ``True`` 时(默认),字段名(大小写不敏感) + 与 :data:`SENSITIVE_FIELD_MARKERS` 完全匹配时会被替换为 + :data:`SENSITIVE_MASK`。 + """ + return _dataclass_to_dict(self, mask_sensitive=mask_sensitive) + + +# --------------------------------------------------------------------------- +# 辅助函数 +# --------------------------------------------------------------------------- +def _is_sensitive(field_name: str) -> bool: + """判断字段名是否算敏感字段。 + + 采用大小写不敏感的**全名匹配**与 :data:`SENSITIVE_FIELD_MARKERS`, + 这能避免 ``max_tokens`` 被误判(包含 ``token``), + 也能避免 ``api_key`` 被遗漏(按词拆分会未命中)。 + """ + normalized = field_name.replace("-", "_").lower() + return normalized in {marker.lower() for marker in SENSITIVE_FIELD_MARKERS} + + +def _mask_if_sensitive(field_name: str, value: Any) -> Any: + """若字段敏感则返回脱敏后的占位,否则原样返回。""" + if value in (None, "", [], {}): + return value + if _is_sensitive(field_name): + return SENSITIVE_MASK + return value + + +def _dataclass_to_dict(obj: Any, *, mask_sensitive: bool) -> Any: + """递归地将 dataclass 树转为普通 dict。 + + 不使用 :func:`dataclasses.asdict` 是因为需要在字段名级别 + 做敏感字段脱敏,asdict 未提供这个能力。 + """ + if is_dataclass(obj): + out: Dict[str, Any] = {} + for f in fields(obj): + raw = getattr(obj, f.name) + processed = _dataclass_to_dict(raw, mask_sensitive=mask_sensitive) + if mask_sensitive and not is_dataclass(raw): + processed = _mask_if_sensitive(f.name, processed) + out[f.name] = processed + return out + if isinstance(obj, dict): + return {k: _dataclass_to_dict(v, mask_sensitive=mask_sensitive) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [_dataclass_to_dict(v, mask_sensitive=mask_sensitive) for v in obj] + return obj + + +__all__ = [ + "Config", + "LLMConfig", + "LanguageProfile", + "LoggingConfig", + "NotificationConfig", + "PlatformConfig", + "PublishTarget", + "ReviewConfig", + "SourceConfig", + "VcsConfig", + "WorkspaceConfig", + # helpers (主要供测试导出) + "_is_sensitive", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f243d8952a4c36315eb8cf99494fb116a9cf56f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__init__.py @@ -0,0 +1,40 @@ +"""TiMi_HOK_Game_Translator.llm 子包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.llm import ( + LLMClient, LLMResponse, + LocalMockLLM, OpenAILLM, OpenAICompatibleLLM, + AnthropicLLM, HunyuanTranslationLLM, + build_translation_prompt, + create_llm_client, register_llm_provider, registered_llm_providers, + ) +""" + +from .anthropic_llm import AnthropicLLM +from .base import LLMClient, LLMResponse +from .factory import create_llm_client, register_llm_provider, registered_llm_providers +from .gemini_llm import GeminiLLM +from .hunyuan_translation_llm import HunyuanTranslationLLM +from .mock_llm import LocalMockLLM +from .openai_llm import OpenAICompatibleLLM, OpenAILLM +from .prompts import build_translation_prompt, locale_cn, locale_en +from .venus_llm import VenusLLM + +__all__ = [ + "LLMClient", + "LLMResponse", + "LocalMockLLM", + "OpenAILLM", + "OpenAICompatibleLLM", + "AnthropicLLM", + "GeminiLLM", + "HunyuanTranslationLLM", + "VenusLLM", + "build_translation_prompt", + "locale_cn", + "locale_en", + "create_llm_client", + "register_llm_provider", + "registered_llm_providers", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..633e115f27bdadc1db15ca8472bf99a883a0dbe2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/_http.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/_http.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e45ae53aedd32ecba9e468a1c6d0a2dea364768b Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/_http.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/anthropic_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/anthropic_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c9d0cd39a80ecaf30caa3b0c15b8147f9cc1553 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/anthropic_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81793ae8152fb4d522be6eba2c1ee3a59778b632 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26d6d6199b0f06feb8254cab4ca42300ec500db Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/gemini_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/gemini_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b373376e65d61d58ee833d2fd9d6c043db79a3f1 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/gemini_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/hunyuan_translation_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/hunyuan_translation_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ba280cecbcf53db1c51255d3d024ffb12e67bb Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/hunyuan_translation_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/mock_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/mock_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b95a7573192e4eb7cfb63d684263b7031ff190c2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/mock_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/openai_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/openai_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91b035fcde7aec37f5ae1bf21d66822410768c9c Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/openai_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/prompts.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/prompts.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f26bf6787ab7532ab47d7b6157562a2a078a18cb Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/prompts.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/venus_llm.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/venus_llm.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1444cd00d4b9c72d9d504f96ceda70b3ea38e191 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/__pycache__/venus_llm.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/_http.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/_http.py new file mode 100644 index 0000000000000000000000000000000000000000..a9bf529651ed7f65497e308f555f4bb461d41671 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/_http.py @@ -0,0 +1,102 @@ +"""LLM provider 共享的 HTTP 工具。 + +目的: + - 使用 ``requests.Session`` 复用 TCP/TLS 连接,大幅降低每次调用的开销 + (尤其对 HTTPS 翻译 API,减少 ~100ms 的 TLS 握手时间); + - 统一的 JSON POST 封装,所有 provider 共享超时/重试友好的行为; + - 不新增外部依赖——``requests`` 已是框架硬依赖。 +""" + +from __future__ import annotations + +import json +import threading +from typing import Any, Dict, Optional # pylint: disable=unused-import + +import requests +from requests.adapters import HTTPAdapter + +_SESSION_LOCK = threading.Lock() +_SESSIONS: Dict[str, requests.Session] = {} + + +def get_session(pool_key: str, *, pool_maxsize: int = 32) -> requests.Session: + """按 ``pool_key`` 获取一个共享 ``requests.Session``。 + + 同一个 key 全局复用一个连接池;每个 provider 实例应传入稳定的 key + (例如 ``f"{provider_name}:{api_base}"``)以共享连接。 + + 参数: + pool_key: 连接池命名空间。 + pool_maxsize: HTTPAdapter 的 ``pool_maxsize``;并发线程多时适当调大。 + 返回: + 懒加载的 ``requests.Session``;线程安全。 + """ + sess = _SESSIONS.get(pool_key) + if sess is not None: + return sess + with _SESSION_LOCK: + sess = _SESSIONS.get(pool_key) + if sess is None: + sess = requests.Session() + adapter = HTTPAdapter( + pool_connections=pool_maxsize, + pool_maxsize=pool_maxsize, + # 内置重试交给上层,这里只给网络层连接复用 + max_retries=0, + ) + sess.mount("http://", adapter) + sess.mount("https://", adapter) + _SESSIONS[pool_key] = sess + return sess + + +def post_json( + *, + session: requests.Session, + url: str, + payload: Dict[str, Any], + headers: Dict[str, str], + timeout: int, +) -> Any: + """POST JSON 并解析响应。 + + 参数: + session: ``get_session`` 返回的共享 session。 + url: 完整 URL。 + payload: 请求体,会被 ``json.dumps(ensure_ascii=False)`` 序列化。 + headers: 请求头(会自动补 ``Content-Type``)。 + timeout: 请求总超时秒数。 + 返回: + 解析后的 JSON(dict / list / 原始字符串,视服务端响应而定)。 + 异常: + ``requests.HTTPError``——HTTP 状态码非 2xx 时抛出,附带响应文本。 + """ + merged_headers = dict(headers) + merged_headers.setdefault("Content-Type", "application/json") + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + resp = session.post(url, data=body, headers=merged_headers, timeout=timeout) + if resp.status_code >= 400: + # 把响应内容带进异常,方便上层 debug + raise requests.HTTPError( + f"HTTP {resp.status_code} from {url}: {resp.text[:500]}", + response=resp, + ) + try: + return resp.json() + except ValueError: + return resp.text + + +def reset_sessions() -> None: + """关闭并清理全部缓存 session;主要供测试使用。""" + with _SESSION_LOCK: + for sess in _SESSIONS.values(): + try: + sess.close() + except Exception: # pylint: disable=broad-except # noqa: BLE001 + pass + _SESSIONS.clear() + + +__all__ = ["get_session", "post_json", "reset_sessions"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/anthropic_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/anthropic_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..444178a265a0150a6d548cfa89368ecbd53fd4a8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/anthropic_llm.py @@ -0,0 +1,136 @@ +"""Anthropic Messages 协议 LLM 提供商实现。 + +启用方式:: + + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=anthropic + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=sk-ant-... + +默认走 Anthropic 官方 endpoint ``https://api.anthropic.com``。 +参考:``docs/模型调用/Anthropic Message 协议字段说明.md``。 + +性能优化:使用共享 ``requests.Session`` 复用 TCP/TLS 连接, +不强依赖 ``anthropic`` SDK,内网环境可直接使用。 +""" + +from __future__ import annotations + +import logging +import time +from typing import Any, Optional, Sequence, Tuple + +from ..commons import LLMProviderMissingError +from ._http import get_session, post_json +from .base import LLMClient, LLMResponse +from .prompts import build_translation_prompt + +logger = logging.getLogger(__name__) + +_DEFAULT_MODEL = "claude-3-5-sonnet-20241022" +_DEFAULT_BASE = "https://api.anthropic.com" +_ANTHROPIC_VERSION = "2023-06-01" + + +class AnthropicLLM(LLMClient): + """Claude 系列模型(Anthropic Messages 协议)实现。""" + + provider_name = "anthropic" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._pool_key = f"{self.provider_name}:{(self.api_base or _DEFAULT_BASE).rstrip('/')}" + self._session = get_session(self._pool_key, pool_maxsize=max(32, self.batch_size)) + + # ------------------------------------------------------------------ + def _resolve_endpoint(self) -> str: + base = (self.api_base or _DEFAULT_BASE).rstrip("/") + return f"{base}/v1/messages" + + def _headers(self) -> dict: + if not self.api_key: + raise LLMProviderMissingError( + "Anthropic API key is missing. Set GAME_TRANS_TOOLCHAIN__LLM__API_KEY " + "or the ANTHROPIC_API_KEY environment variable." + ) + return { + "anthropic-version": _ANTHROPIC_VERSION, + "x-api-key": self.api_key, + # 聚合入口(如 TokenHub)兼容 Bearer,顺带带上不冲突 + "Authorization": f"Bearer {self.api_key}", + } + + # ------------------------------------------------------------------ + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + model = self.model or _DEFAULT_MODEL + system_prompt, user_prompt = build_translation_prompt( + provider=self.provider_name, + source_locale=source_locale, + target_locale=target_locale, + source_text=text, + context=context, + format_type=str(self.extra.get("format_type", "plain")), + override_template=str(self.extra.get("prompt_template", "")), + locale_names=self.extra.get("locale_names") or None, + terms=terms, + ) + + payload: dict = { + "model": model, + "max_tokens": self.max_tokens, + "temperature": self.temperature, + "messages": [{"role": "user", "content": user_prompt}], + } + if system_prompt: + payload["system"] = system_prompt + + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._do_request(payload, model) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover - 网络路径 + last_error = exc + logger.warning( + "AnthropicLLM: attempt %d/%d failed: %s", + attempt, self.retries, exc, + ) + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + # ------------------------------------------------------------------ + def _do_request(self, payload: dict, model: str) -> LLMResponse: + data = post_json( + session=self._session, + url=self._resolve_endpoint(), + payload=payload, + headers=self._headers(), + timeout=self.timeout_seconds, + ) + if not isinstance(data, dict): + raise RuntimeError(f"Unexpected response type: {type(data).__name__}") + + # Anthropic 响应:{"content":[{"type":"text","text":"..."}], "usage":{...}} + text_parts: list = [] + for block in data.get("content", []) or []: + if isinstance(block, dict) and block.get("type") == "text": + text_parts.append(block.get("text", "")) + translated = "".join(text_parts).strip() + + return LLMResponse( + text=translated, + provider=self.provider_name, + model=model, + usage=data.get("usage", {}) or {}, + raw=data, + ) + + +__all__ = ["AnthropicLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d21585740e6175fb185cc8b2df1736430259f293 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/base.py @@ -0,0 +1,133 @@ +"""LLM 抽象层。 + +具体提供商实现 :class:`LLMClient`,并在运行时由 +:func:`~.factory.create_llm_client` 选择。内置实现包括: + +* :class:`~.mock_llm.LocalMockLLM`——零依赖、确定性输出的模拟后端, + 作为默认项保证开箱即用的 demo。 +* :class:`~.openai_llm.OpenAILLM` / :class:`~.openai_llm.OpenAICompatibleLLM` + ——OpenAI 及其兼容厂商(DeepSeek / Kimi / GLM / 混元 Hy4 等)。 +* :class:`~.anthropic_llm.AnthropicLLM`——Claude 系列。 +* :class:`~.hunyuan_translation_llm.HunyuanTranslationLLM`——混元 Hy-MT2 翻译模型。 +* :class:`~.venus_llm.VenusLLM`——腾讯内网 Venus。 + +更多私有/厂商专用提供商可放在 ``TiMi_HOK_Game_Translator.strategies/`` 子包下, +自行调用 :func:`register_llm_provider` 注册即可。 +""" + +from __future__ import annotations + +import abc +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence, Tuple + + +# --------------------------------------------------------------------------- +# 数据对象 +# --------------------------------------------------------------------------- +@dataclass +class LLMResponse: + """单次翻译请求的结构化响应。""" + + text: str + provider: str = "" + model: str = "" + usage: Dict[str, Any] = field(default_factory=dict) + raw: Any = None + + +# --------------------------------------------------------------------------- +# 基类 +# --------------------------------------------------------------------------- +class LLMClient(abc.ABC): + """所有 LLM 提供商需实现的接口。""" + + #: 本提供商在工厂中注册的名称。 + provider_name: str = "" + + def __init__( + self, + *, + model: str = "", + temperature: float = 0.2, + max_tokens: int = 1024, + batch_size: int = 32, + api_key: str = "", + api_base: str = "", + timeout_seconds: int = 30, + retries: int = 3, + retry_interval_seconds: int = 30, + extra: Optional[Dict[str, Any]] = None, + ) -> None: + self.model = model + self.temperature = float(temperature) + self.max_tokens = int(max_tokens) + self.batch_size = max(1, int(batch_size)) + self.api_key = api_key + self.api_base = api_base + self.timeout_seconds = int(timeout_seconds) + self.retries = max(1, int(retries)) + self.retry_interval_seconds = max(0, int(retry_interval_seconds)) + self.extra: Dict[str, Any] = dict(extra or {}) + + # ------------------------------------------------------------------ + # 抽象 API + # ------------------------------------------------------------------ + @abc.abstractmethod + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + """翻译单条 ``text`` 并返回结果。 + + 参数: + text: 待翻译文本。 + source_locale: 源语言代码(BCP-47)。 + target_locale: 目标语言代码。 + context: 可选上下文(比如术语、岛语境描述)。 + terms: 术语对列表 ``[(源文, 译文), ...]``;非空时各 provider + 会把术语注入到提示词,详见 + :func:`~.prompts.build_translation_prompt`。 + 返回: + :class:`LLMResponse`。 + """ + + # ------------------------------------------------------------------ + # 默认的批量实现 + # ------------------------------------------------------------------ + def batch_translate( + self, + texts: Sequence[str], + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> List[LLMResponse]: + """按 :attr:`batch_size` 分段批量翻译。 + + 默认实现逆向调用 :meth:`translate`;支持原生批量接口的提供商应覆盖以提高效率。 + 所有条目共用相同的 ``terms`` 列表;如需按条目独立术语,请走单条 translate。 + """ + results: List[LLMResponse] = [] + for chunk_start in range(0, len(texts), self.batch_size): + chunk = texts[chunk_start : chunk_start + self.batch_size] + for text in chunk: + results.append( + self.translate( + text, + source_locale=source_locale, + target_locale=target_locale, + context=context, + terms=terms, + ) + ) + return results + + +__all__ = ["LLMClient", "LLMResponse"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9da669ce35fd8c8d4560730a880b999d863b7b --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/factory.py @@ -0,0 +1,67 @@ +"""LLM 提供商的工厂与注册表。""" + +from __future__ import annotations + +from typing import Any, Dict, Type + +from ..commons import LLMProvider, LLMProviderMissingError +from ..config.schema import LLMConfig +from .anthropic_llm import AnthropicLLM +from .base import LLMClient +from .gemini_llm import GeminiLLM +from .hunyuan_translation_llm import HunyuanTranslationLLM +from .mock_llm import LocalMockLLM +from .openai_llm import OpenAICompatibleLLM, OpenAILLM +from .venus_llm import VenusLLM + +_REGISTRY: Dict[str, Type[LLMClient]] = { + LLMProvider.ECHO.value: LocalMockLLM, + LLMProvider.OPENAI.value: OpenAILLM, + LLMProvider.OPENAI_COMPATIBLE.value: OpenAICompatibleLLM, + LLMProvider.ANTHROPIC.value: AnthropicLLM, + LLMProvider.GEMINI.value: GeminiLLM, + LLMProvider.HUNYUAN_TRANSLATION.value: HunyuanTranslationLLM, + LLMProvider.VENUS.value: VenusLLM, +} + +#: 老配置向后兼容:早期版本把"回显式占位 LLM"命名为 ``mock``; +#: 重命名为 ``echo`` 之后,这里把老值翻译回新值,保证既有 ``llm.yaml`` +#: 不升级就能继续加载。 +_LLM_PROVIDER_ALIASES: Dict[str, str] = { + "mock": LLMProvider.ECHO.value, +} + + +def register_llm_provider(name: str, client_cls: Type[LLMClient]) -> None: + """以 ``name`` 为名注册自定义 :class:`LLMClient` 实现。""" + _REGISTRY[name.lower()] = client_cls + +def registered_llm_providers() -> list: # noqa: E302 + """返回当前已注册的提供商名称列表(排序后)。""" + return sorted(_REGISTRY) + +def create_llm_client(llm_config: LLMConfig) -> LLMClient: # noqa: E302 + """根据 ``llm_config`` 构造 :class:`LLMClient` 实例。""" + key = (llm_config.provider or "").lower() + key = _LLM_PROVIDER_ALIASES.get(key, key) # 兼容老的 "mock" → "echo" + if key not in _REGISTRY: + raise LLMProviderMissingError( + f"Unknown llm.provider '{llm_config.provider}'. " + f"Registered providers: {registered_llm_providers()}" + ) + cls = _REGISTRY[key] + extra: Dict[str, Any] = dict(llm_config.extra or {}) + return cls( + model=llm_config.model, + temperature=llm_config.temperature, + max_tokens=llm_config.max_tokens, + batch_size=llm_config.batch_size, + api_key=llm_config.api_key, + api_base=llm_config.api_base, + timeout_seconds=llm_config.timeout_seconds, + retries=llm_config.retries, + retry_interval_seconds=llm_config.retry_interval_seconds, + extra=extra, + ) + +__all__ = ["create_llm_client", "register_llm_provider", "registered_llm_providers"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/gemini_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/gemini_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..2df1edea947384ba4f6aa0aa4c84df36891310d1 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/gemini_llm.py @@ -0,0 +1,190 @@ +"""Google Gemini LLM 提供商实现。 + +启用方式:: + + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=gemini + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY= + # 或: + export GOOGLE_API_KEY= + +默认走 Google AI Studio 公网端点:: + + https://generativelanguage.googleapis.com/v1beta/models/:generateContent + +参考: + https://ai.google.dev/api/generate-content + +Gemini 的 REST 请求体结构与 OpenAI 不同(``contents`` + ``parts``, +system 走 ``systemInstruction``),因此单独实现一个 provider。 + +性能优化:使用共享 ``requests.Session`` 复用 TCP/TLS 连接; +不强依赖 ``google-generativeai`` SDK,避免 pip 依赖冲突。 +""" + +from __future__ import annotations + +import logging +import os +import time +from typing import Any, Optional, Sequence, Tuple + +from ..commons import LLMProviderMissingError +from ._http import get_session, post_json +from .base import LLMClient, LLMResponse +from .prompts import build_translation_prompt + +logger = logging.getLogger(__name__) + +_DEFAULT_MODEL = "gemini-2.5-flash" +_DEFAULT_BASE = "https://generativelanguage.googleapis.com" + + +class GeminiLLM(LLMClient): + """Google Gemini(generateContent 协议)实现。 + + 支持从以下 3 处获取 API Key(按优先级): + + 1. ``llm.yaml`` 的 ``api_key`` 字段(build_bootstrap 后写入 LLMConfig.api_key); + 2. 环境变量 ``GAME_TRANS_TOOLCHAIN__LLM__API_KEY``; + 3. 环境变量 ``GOOGLE_API_KEY``(Google 官方约定)。 + + ``api_base`` 允许覆盖,支持企业内部的 Gemini 代理网关(如 Vertex AI 托管的 + OpenAI 兼容入口不属于本 provider,走 ``openai_compatible`` 即可)。 + """ + + provider_name = "gemini" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._pool_key = f"{self.provider_name}:{(self.api_base or _DEFAULT_BASE).rstrip('/')}" + self._session = get_session(self._pool_key, pool_maxsize=max(32, self.batch_size)) + + # ------------------------------------------------------------------ + def _resolve_key(self) -> str: + return ( + self.api_key + or os.getenv("GAME_TRANS_TOOLCHAIN__LLM__API_KEY", "") + or os.getenv("GOOGLE_API_KEY", "") + ) + + def _resolve_endpoint(self, model: str) -> str: + base = (self.api_base or _DEFAULT_BASE).rstrip("/") + # 兼容两种风格: + # 1) 用户给 "https://.../v1beta" → 本函数自动补 /models/:generateContent + # 2) 用户给 "https://.../v1beta/models" → 本函数自动补 /:generateContent + # 3) 用户给完整 "https://.../:generateContent" → 原样使用 + if ":generatecontent" in base.lower(): + return base + if base.endswith("/models"): + return f"{base}/{model}:generateContent" + if "/v1" not in base and "/v2" not in base: + base = f"{base}/v1beta" + return f"{base}/models/{model}:generateContent" + + def _headers(self) -> dict: + key = self._resolve_key() + if not key: + raise LLMProviderMissingError( + "Gemini API key is missing. Set GAME_TRANS_TOOLCHAIN__LLM__API_KEY " + "or GOOGLE_API_KEY, or fill `api_key` in conf/llm.yaml." + ) + return { + # Google 的两种鉴权方式都支持:优先 x-goog-api-key; + # 走代理网关时部分服务只认 Bearer,一并带上不冲突。 + "x-goog-api-key": key, + "Authorization": f"Bearer {key}", + } + + # ------------------------------------------------------------------ + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + model = self.model or _DEFAULT_MODEL + system_prompt, user_prompt = build_translation_prompt( + provider=self.provider_name, + source_locale=source_locale, + target_locale=target_locale, + source_text=text, + context=context, + format_type=str(self.extra.get("format_type", "plain")), + override_template=str(self.extra.get("prompt_template", "")), + locale_names=self.extra.get("locale_names") or None, + terms=terms, + ) + + # Gemini generateContent 协议: + # contents: [{"role": "user", "parts": [{"text": "..."}]}] + # systemInstruction: {"parts": [{"text": "..."}]} # 可选 + payload: dict = { + "contents": [ + {"role": "user", "parts": [{"text": user_prompt}]}, + ], + "generationConfig": { + "temperature": self.temperature, + "maxOutputTokens": self.max_tokens, + }, + } + if system_prompt: + payload["systemInstruction"] = {"parts": [{"text": system_prompt}]} + # 透传用户在 extra.generation_config 里的自定义覆盖(topP / topK / stopSequences 等) + extra_gen = self.extra.get("generation_config") + if isinstance(extra_gen, dict): + payload["generationConfig"].update(extra_gen) + + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._do_request(payload, model) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover - 网络路径 + last_error = exc + logger.warning( + "GeminiLLM: attempt %d/%d failed: %s", + attempt, self.retries, exc, + ) + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + # ------------------------------------------------------------------ + def _do_request(self, payload: dict, model: str) -> LLMResponse: + data = post_json( + session=self._session, + url=self._resolve_endpoint(model), + payload=payload, + headers=self._headers(), + timeout=self.timeout_seconds, + ) + if not isinstance(data, dict): + raise RuntimeError(f"Unexpected Gemini response type: {type(data).__name__}") + + # Gemini 响应: + # {"candidates": [{"content": {"parts": [{"text": "..."}], "role": "model"}}], + # "usageMetadata": {"promptTokenCount": N, "candidatesTokenCount": M, ...}} + text_parts: list = [] + for cand in data.get("candidates", []) or []: + if not isinstance(cand, dict): + continue + content = cand.get("content") or {} + for part in content.get("parts", []) or []: + if isinstance(part, dict) and "text" in part: + text_parts.append(part.get("text", "")) + translated = "".join(text_parts).strip() + + usage = data.get("usageMetadata") or {} + return LLMResponse( + text=translated, + provider=self.provider_name, + model=model, + usage=usage if isinstance(usage, dict) else {}, + raw=data, + ) + + +__all__ = ["GeminiLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/hunyuan_translation_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/hunyuan_translation_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..b6be302b8e49a09378ec765fe1890a38197e49e3 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/hunyuan_translation_llm.py @@ -0,0 +1,312 @@ +"""混元 HY-MT 内部直连翻译模型 provider。 + +本模块对接腾讯内网的 **HY-MT 直连 OpenAPI**(非 TokenHub 公有云), +协议是 OpenAI chat.completions 的变体,差异点: + +* URL 走 HTTP: + - 开发/直连机型:``http://:/v1/chat/completions`` + - 在线集群:``http://stream-server-online-openapi.turbotke.production.polaris:1081/openapi/chat/completions`` +* 必须额外带 ``Wsid`` 请求头; +* payload 必须包含 ``query_id``(UUID 字符串),以及 + ``top_p`` / ``top_k`` / ``repetition_penalty`` / ``max_tokens`` / + ``system_prompt`` / ``stream`` / ``chat_template_kwargs`` 等字段; +* 返回体仍是 OpenAI 风格:``choices[0].message.content``。 + +启用方式:: + + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=hunyuan_translation + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY= + # 在 conf/llm.yaml 对应 profile 的 extra 中设置: + # wsid: "" + # top_p: 1.0 + # top_k: -1 + # repetition_penalty: 1.0 + # reasoning_effort: "no_think" + # system_prompt: "" + +关键 ``extra`` 字段(均可选,均有默认): + +* ``wsid``【**强烈建议显式配置**】HY-MT 的 Workspace ID,缺省时为 ``""``; +* ``top_p`` / ``top_k`` / ``repetition_penalty``:解码控制参数; +* ``system_prompt``:顶层 ``system_prompt`` 字段(不走 messages 的 system role); +* ``reasoning_effort``:注入 ``chat_template_kwargs.reasoning_effort``, + 默认 ``"no_think"`` 走快思考; +* ``chat_template_kwargs``:如需覆盖整个对象,可整体传入; +* ``batch_concurrency``:>=1 时启用内部线程池(默认 0,交给上层 strategy 并发); +* ``format_type`` / ``prompt_template`` / ``locale_names``:复用通用提示词。 +""" + +from __future__ import annotations + +import concurrent.futures as _futures +import logging +import time +import uuid +from typing import Any, List, Optional, Sequence, Tuple + +from ..commons import LLMProviderMissingError +from ..utils.think_leak_detector import detect as _detect_think_leak +from ._http import get_session, post_json +from .base import LLMClient, LLMResponse +from .prompts import build_translation_prompt + +logger = logging.getLogger(__name__) + +# HY-MT 直连默认接入点(空字符串 → 强制要求在 conf/llm.yaml 显式配置 api_base) +_DEFAULT_BASE = "" +# 默认模型名(HY-MT 内部命名,可在 llm.yaml / 环境变量中覆盖) +_DEFAULT_MODEL = "A3B_MoE_RL_8K_261007_s630_game_wzaa" + +# 「思考过程外露」固定允许重试 1 次(命中后额外再请求一次), +# 独立于 self.retries 的网络重试计数,避免相互吞配额。 +_THINK_LEAK_MAX_RETRIES = 1 + + +def _normalize_src_lang(source_locale: str) -> str: + """把 BCP-47 源语种归一化为检测器识别的轴:'zh' 或 'en'。 + + 检测器只区分「中文源」与「英文源」两条规则轴(见 + ``think_leak_detector._RATIO_LIMIT_EN_PIVOT``)。非 zh 一律按 en 处理, + 这与业务侧「中→多语」「英→多语」双轴的实际使用场景一致。 + """ + code = (source_locale or "").strip().lower() + if not code: + return "zh" + # 兼容 'zh', 'zh-CN', 'zh-Hans', 'zh_cn' 等写法 + if code.startswith("zh"): + return "zh" + return "en" + + +class HunyuanTranslationLLM(LLMClient): + """HY-MT 内部直连翻译模型实现。 + + HTTP 层复用 ``requests.Session`` 连接池;鉴权为 ``Bearer`` + ``Wsid`` 双头。 + """ + + provider_name = "hunyuan_translation" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + # 内部批量并发数:默认 0 表示串行(由外层 translation.executors.concurrent 并发) + self._batch_concurrency = int(self.extra.get("batch_concurrency", 0) or 0) + # 共享连接池 key——同 api_base 的 provider 实例共用连接池 + self._pool_key = f"{self.provider_name}:{(self.api_base or _DEFAULT_BASE).rstrip('/')}" + self._session = get_session(self._pool_key, pool_maxsize=max(32, self.batch_size)) + + # HY-MT 必备头:Workspace ID + self._wsid = str(self.extra.get("wsid", "") or "") + + # 解码控制参数(HY-MT 直连 payload 必填/推荐字段) + self._top_p = float(self.extra.get("top_p", 1.0)) + self._top_k = int(self.extra.get("top_k", -1)) + self._repetition_penalty = float(self.extra.get("repetition_penalty", 1.0)) + self._system_prompt = str(self.extra.get("system_prompt", "") or "") + self._stream = bool(self.extra.get("stream", False)) + + # chat_template_kwargs 可整体覆盖,也可只配 reasoning_effort + raw_tpl_kwargs = self.extra.get("chat_template_kwargs") + if isinstance(raw_tpl_kwargs, dict) and raw_tpl_kwargs: + self._chat_template_kwargs: dict = dict(raw_tpl_kwargs) + else: + self._chat_template_kwargs = { + "reasoning_effort": str( + self.extra.get("reasoning_effort", "no_think") or "no_think" + ), + } + + # ------------------------------------------------------------------ + def _endpoint(self) -> str: + """构造 chat/completions 完整 URL。 + + 兼容两种 api_base 写法: + * ``http://host:port`` —— 自动补 ``/v1/chat/completions``; + * ``http://host:port/v1`` —— 补 ``/chat/completions``; + * ``http://host.../openapi`` —— 补 ``/chat/completions``; + * 已带 ``/chat/completions`` 的完整 URL —— 原样使用。 + """ + base = (self.api_base or _DEFAULT_BASE).strip().rstrip("/") + if base.endswith("/chat/completions"): + return base + if base.endswith("/v1") or base.endswith("/openapi"): + return f"{base}/chat/completions" + return f"{base}/v1/chat/completions" + + def _headers(self) -> dict: + if not self.api_key: + raise LLMProviderMissingError( + "HY-MT API key is missing. Set GAME_TRANS_TOOLCHAIN__LLM__API_KEY " + "to your HY-MT Bearer token." + ) + headers: dict = { + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", + } + if self._wsid: + headers["Wsid"] = self._wsid + return headers + + # ------------------------------------------------------------------ + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + model = self.model or _DEFAULT_MODEL + _, user_prompt = build_translation_prompt( + provider=self.provider_name, + source_locale=source_locale, + target_locale=target_locale, + source_text=text, + context=context, + format_type=str(self.extra.get("format_type", "plain")), + override_template=str(self.extra.get("prompt_template", "")), + locale_names=self.extra.get("locale_names") or None, + terms=terms, + ) + + # HY-MT 直连 payload:严格按参考脚本字段构造 + payload: dict = { + "model": model, + "query_id": f"TiMi_HOK_Game_Translator_{uuid.uuid4()}", + "messages": [{"role": "user", "content": user_prompt}], + "temperature": self.temperature, + "top_p": self._top_p, + "top_k": self._top_k, + "repetition_penalty": self._repetition_penalty, + "max_tokens": self.max_tokens, + "system_prompt": self._system_prompt, + "stream": self._stream, + "chat_template_kwargs": dict(self._chat_template_kwargs), + } + + last_error: Optional[Exception] = None + # 「思考过程外露」允许的额外请求次数(独立计数,用完即接受当前译文)。 + # 外露重试与网络失败重试共享 self.retries 的循环额度(默认 3 轮), + # 对 ~0.02% 的实测触发率来说完全够用。 + leak_retries_left = _THINK_LEAK_MAX_RETRIES + for attempt in range(1, self.retries + 1): + try: + response = self._do_request(payload, model) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover - 网络路径 + last_error = exc + logger.warning( + "HunyuanTranslationLLM(HY-MT): attempt %d/%d failed: %s", + attempt, self.retries, exc, + ) + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + continue + + # 成功拿到响应——做「思考过程外露」自检。 + # 命中:丢弃本次结果并再请求一次(最多 _THINK_LEAK_MAX_RETRIES 次), + # 并刷新 query_id 避免被服务端缓存同样答案。 + leak = _detect_think_leak( + response.text, + source_text=text, + target_lang=target_locale or None, + src_lang=_normalize_src_lang(source_locale), + ) + if leak.leaked: + logger.warning( + "HunyuanTranslationLLM(HY-MT): think-leak detected, " + "retries_left=%d, %s", + leak_retries_left, leak.describe(), + ) + if leak_retries_left > 0: + leak_retries_left -= 1 + # 刷新 query_id,让下游不要命中可能的缓存 + payload["query_id"] = f"TiMi_HOK_Game_Translator_{uuid.uuid4()}" + if attempt < self.retries: + continue + # 外露重试额度耗尽或循环本身已到最后一轮: + # 退而求其次接受当前译文,交由后续人工兜底 + logger.warning( + "HunyuanTranslationLLM(HY-MT): think-leak retry budget " + "exhausted, accepting latest translation (len=%d).", + len(response.text), + ) + return response + + return response + assert last_error is not None + raise last_error + + # ------------------------------------------------------------------ + def batch_translate( + self, + texts: Sequence[str], + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> List[LLMResponse]: + """批量翻译。 + + * ``extra.batch_concurrency = 0``(默认)——保持串行,交由外层 + ``translation.executors.concurrent`` 做条目级并发; + * ``extra.batch_concurrency >= 1``——在本类内启用线程池并发, + 适合不走 strategy 层的脚本/独立调用场景。 + """ + workers = self._batch_concurrency + if workers < 1 or len(texts) <= 1: + return super().batch_translate( + texts, + source_locale=source_locale, + target_locale=target_locale, + context=context, + terms=terms, + ) + + workers = min(workers, len(texts)) + results: List[Optional[LLMResponse]] = [None] * len(texts) + + def _one(idx: int, text: str) -> None: + results[idx] = self.translate( + text, + source_locale=source_locale, + target_locale=target_locale, + context=context, + terms=terms, + ) + + with _futures.ThreadPoolExecutor(max_workers=workers) as pool: + futures = [pool.submit(_one, i, t) for i, t in enumerate(texts)] + for fut in _futures.as_completed(futures): + fut.result() # 让异常冒泡 + + return [r for r in results if r is not None] + + # ------------------------------------------------------------------ + def _do_request(self, payload: dict, model: str) -> LLMResponse: + data = post_json( + session=self._session, + url=self._endpoint(), + payload=payload, + headers=self._headers(), + timeout=self.timeout_seconds, + ) + if not isinstance(data, dict): + raise RuntimeError(f"Unexpected response type: {type(data).__name__}") + + choices = data.get("choices") or [] + translated = "" + if choices and isinstance(choices[0], dict): + message = choices[0].get("message") or {} + translated = (message.get("content") or "").strip() + + return LLMResponse( + text=translated, + provider=self.provider_name, + model=model, + usage=data.get("usage", {}) or {}, + raw=data, + ) + + +__all__ = ["HunyuanTranslationLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/mock_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/mock_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..c871ef7d2d901f0bcd531184d0460c9739cb54b2 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/mock_llm.py @@ -0,0 +1,70 @@ +"""供 demo 与单测使用的确定性回显 LLM(provider: ``echo``)。 + +不会访问任何外部服务,直接将源文本包上目标语种标记,足以驱动完整工作流。 +老配置里的 ``provider: mock`` 由 :mod:`TiMi_HOK_Game_Translator.llm.factory` 自动翻译到 +``echo``,向后兼容。 +""" + +from __future__ import annotations + +from typing import List, Optional, Sequence, Tuple + +from .base import LLMClient, LLMResponse + + +class LocalMockLLM(LLMClient): + """:class:`LLMClient` 的无网络实现,供本地 demo/测试使用。 + + .. note:: + 类名保留 ``LocalMockLLM`` 以保持向后兼容;``provider_name`` 已更新为 + ``echo`` 以更准确地反映该后端的"回显原文"行为。 + """ + + provider_name = "echo" + + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + tag = f"[{target_locale}]" if target_locale else "[echo]" + translated = f"{tag} {text}" if text else "" + usage: dict = {"input_chars": len(text), "output_chars": len(translated)} + if terms: + # 便于单测断言术语是否被传递到 LLM 层 + usage["terms_count"] = len(terms) + return LLMResponse( + text=translated, + provider=self.provider_name, + model=self.model or "echo-1", + usage=usage, + ) + + def batch_translate( + self, + texts: Sequence[str], + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> List[LLMResponse]: + # 依然使用默认的逆向批量实现,但将 ``batch_size`` + # 注入到首个响应的 ``usage`` 字典,方便单测取用。 + results = super().batch_translate( + texts, + source_locale=source_locale, + target_locale=target_locale, + context=context, + terms=terms, + ) + if results: + results[0].usage["batch_size"] = self.batch_size + return results + + +__all__ = ["LocalMockLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/openai_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/openai_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f2e7e74387305241eac91b3e46f121b5f7ca86 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/openai_llm.py @@ -0,0 +1,140 @@ +"""OpenAI 及其兼容厂商的 LLM 提供商实现。 + +启用方式:: + + pip install "TiMi_HOK_Game_Translator[openai]" + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=openai + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=sk-... + +该实现同时适配所有 **OpenAI chat.completions 兼容** 的厂商(混元 Hy4 系列、 +DeepSeek、Kimi、GLM、通义千问 OpenAI 兼容模式、Xiaomi MiMo、MiniMax 兼容版 +等)。只需在 ``conf/llm.yaml`` 的 profile 中覆盖 ``api_base`` 与 ``model``: + +* OpenAI 官方:``https://api.openai.com/v1`` +* DeepSeek:``https://api.deepseek.com/v1`` +* Kimi/Moonshot:``https://api.moonshot.cn/v1`` +* GLM:``https://open.bigmodel.cn/api/paas/v4`` +* 通义千问兼容模式:``https://dashscope.aliyuncs.com/compatible-mode/v1`` +* 混元 Hy4:``https://api.hunyuan.cloud.tencent.com/v1`` + +提示词由 :mod:`.prompts` 统一生成,不在本模块硬编码。 +""" + +from __future__ import annotations + +import os +import time +from typing import Any, Optional, Sequence, Tuple + +from ..commons import LLMProviderMissingError +from .base import LLMClient, LLMResponse +from .prompts import build_translation_prompt + +_DEFAULT_MODEL = "gpt-4o-mini" + + +class OpenAILLM(LLMClient): + """OpenAI 及其兼容厂商的 chat.completions 实现。 + + 通过 ``extra.prompt_template`` 可按语种覆盖提示词; + 通过 ``extra.format_type`` 可声明原文格式(如 ``dtxml``)以启用结构化模板。 + """ + + provider_name = "openai" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._client: Optional[Any] = None + + # ------------------------------------------------------------------ + def _get_client(self) -> Any: + if self._client is not None: + return self._client + try: + from openai import OpenAI # type: ignore + except ImportError as exc: # pragma: no cover — 可选依赖 + raise LLMProviderMissingError( + "The 'openai' provider requires the 'openai' package. " + "Install with: pip install 'TiMi_HOK_Game_Translator[openai]'." + ) from exc + + api_key = self.api_key or os.getenv("OPENAI_API_KEY", "") + if not api_key: + raise LLMProviderMissingError( + "OpenAI API key is missing. Set GAME_TRANS_TOOLCHAIN__LLM__API_KEY " + "or the OPENAI_API_KEY environment variable." + ) + kwargs: dict = {"api_key": api_key, "timeout": self.timeout_seconds} + if self.api_base: + kwargs["base_url"] = self.api_base + self._client = OpenAI(**kwargs) + return self._client + + # ------------------------------------------------------------------ + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + client = self._get_client() + model = self.model or _DEFAULT_MODEL + + system_prompt, user_prompt = build_translation_prompt( + provider=self.provider_name, + source_locale=source_locale, + target_locale=target_locale, + source_text=text, + context=context, + format_type=str(self.extra.get("format_type", "plain")), + override_template=str(self.extra.get("prompt_template", "")), + locale_names=self.extra.get("locale_names") or None, + terms=terms, + ) + + messages = [] + if system_prompt: + messages.append({"role": "system", "content": system_prompt}) + messages.append({"role": "user", "content": user_prompt}) + + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + response = client.chat.completions.create( + model=model, + messages=messages, + temperature=self.temperature, + max_tokens=self.max_tokens, + ) + choice = response.choices[0] + translated = (choice.message.content or "").strip() + return LLMResponse( + text=translated, + provider=self.provider_name, + model=model, + usage=getattr(response, "usage", None).__dict__ + if getattr(response, "usage", None) + else {}, + raw=response, + ) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover - 网络路径 + last_error = exc + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + +class OpenAICompatibleLLM(OpenAILLM): + """OpenAI 兼容厂商的别名类(DeepSeek/Kimi/GLM/Qwen 兼容模式/Hy4 等)。 + + 与 :class:`OpenAILLM` 行为完全一致,仅通过 ``provider_name`` 区分日志。 + """ + + provider_name = "openai_compatible" + + +__all__ = ["OpenAILLM", "OpenAICompatibleLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/prompts.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..21bb96300ac77bf6bda6ab4f528df1db2011cd64 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/prompts.py @@ -0,0 +1,393 @@ +"""翻译提示词模板中心。 + +按**模型 provider**维度选择提示词模板,而不是按单个语种硬编码。 +语种只负责"把 BCP-47 locale 代码映射为可读的语种名"(如 ``vi`` → ``越南语`` +/ ``Vietnamese``),模板则按 provider 的调优偏好选择: + +* **混元 HY-MT2**:使用官方推荐的中文提示词(含术语模式 / 结构化模式); +* **其它 provider(OpenAI / Claude / Gemini / Venus / openai_compatible)**: + - **源语=中文** → 使用中文 user 提示词 ``"将{src_cn}翻译成{tgt_cn}:{text}"``; + - **源语≠中文** → 使用英文 system+user 提示词(对多数国际模型更友好)。 + +调用方:: + + system, user = build_translation_prompt( + provider="hunyuan_translation", + source_locale="zh-CN", + target_locale="vi", + source_text="你好", + format_type="plain", + ) +""" + +from __future__ import annotations + +from typing import Dict, Optional, Sequence, Tuple + +# --------------------------------------------------------------------------- +# BCP-47 → 中文语种名映射(混元翻译模型需要完整中文名) +# --------------------------------------------------------------------------- +LOCALE_CN_NAME: Dict[str, str] = { + "zh": "中文", + "zh-cn": "简体中文", + "zh-tw": "台湾地区的繁体中文", + "zh-hk": "香港地区的繁体中文", + "en": "英语", + "ja": "日语", + "ko": "韩语", + "vi": "越南语", + "th": "泰语", + "id": "印度尼西亚语", + "ms": "马来语", + "fr": "法语", + "de": "德语", + "ru": "俄语", + "pt": "葡萄牙语", + "pt-br": "巴西葡萄牙语", + "es": "西班牙语", + "it": "意大利语", + "tr": "土耳其语", + "ar": "阿拉伯语", + "nl": "荷兰语", + "pl": "波兰语", +} + +# BCP-47 → 英文语种名(OpenAI/Claude 等英文提示词场景使用) +LOCALE_EN_NAME: Dict[str, str] = { + "zh": "Chinese", + "zh-cn": "Simplified Chinese", + "zh-tw": "Traditional Chinese", + "en": "English", + "ja": "Japanese", + "ko": "Korean", + "vi": "Vietnamese", + "th": "Thai", + "id": "Indonesian", + "ms": "Malay", + "fr": "French", + "de": "German", + "ru": "Russian", + "pt": "Portuguese", + "pt-br": "Brazilian Portuguese", + "es": "Spanish", + "it": "Italian", + "tr": "Turkish", + "ar": "Arabic", +} + +# 中文系源语的判定集合(lower-case) +_CHINESE_SOURCE_LOCALES = {"zh", "zh-cn", "zh-hans", "zh-tw", "zh-hk", "zh-hant"} + + +def locale_cn( + locale: str, + overrides: Optional[Dict[str, str]] = None, +) -> str: + """BCP-47 代码转中文语种名。 + + 参数: + locale: BCP-47 代码(``"vi"`` / ``"zh-tw"`` 等)。 + overrides: 可选的语种 JSON 覆盖字典(见 LanguageProfile.locale_names); + 键使用 ``"cn"`` 时优先于内置字典。 + 返回: + 用于提示词渲染的中文语种名;全部未命中时回落到 ``locale`` 本身。 + """ + if overrides: + v = overrides.get("cn") + if v: + return v + if not locale: + return "目标语种" + key = locale.strip().lower() + return LOCALE_CN_NAME.get(key, LOCALE_CN_NAME.get(key.split("-")[0], locale)) + + +def locale_en( + locale: str, + overrides: Optional[Dict[str, str]] = None, +) -> str: + """BCP-47 代码转英文语种名。 + + 参数: + locale: BCP-47 代码。 + overrides: 可选的语种 JSON 覆盖字典;键 ``"en"`` 优先于内置字典。 + 返回: + 英文语种名;全部未命中时回落到 ``locale`` 本身。 + """ + if overrides: + v = overrides.get("en") + if v: + return v + if not locale: + return "target language" + key = locale.strip().lower() + return LOCALE_EN_NAME.get(key, LOCALE_EN_NAME.get(key.split("-")[0], locale)) + + +def _is_chinese_source(source_locale: str) -> bool: + """判断源语种是否为中文系(含简体/繁体/港澳)。""" + if not source_locale: + return False + return source_locale.strip().lower() in _CHINESE_SOURCE_LOCALES + + +# --------------------------------------------------------------------------- +# 混元 Hy-MT2 官方推荐提示词(docs/模型调用/混元调用指南.md 1830/2028 行) +# --------------------------------------------------------------------------- +_HUNYUAN_PLAIN = ( + "将以下文本翻译为 {target_lang},注意只需要输出翻译后的结果,不要额外解释:\n" + "{text}" +) + +_HUNYUAN_STRUCTURED = ( + "# 任务目标\n" + "将下方 source_text 中的 {format_type} 格式数据翻译为 {target_lang}。\n\n" + "# 严格约束\n" + "1. 结构锁定:绝对保持原有的 {format_type} 数据结构、缩进和层级完全不变。\n" + "2. 选择性翻译:仅翻译面向用户展示的可见文本内容。\n" + "3. 禁止修改:严禁翻译或更改任何代码标签、键名 (Key)、变量占位符(如 " + "{{var}}、${{var}}、%s、%d 等)或代码属性。\n\n" + "# 数据输入\n" + "{text}" +) + +# 术语模式提示词模板。``{term_pairs}`` 由代码按每条一行拼成 +# ``<源文> 翻译成 <译文>``;``term_pairs`` 末尾不含换行。 +_HUNYUAN_TERMINOLOGY = ( + "参考下面的翻译:\n" + "{term_pairs}\n" + "将以下文本翻译为 {target_lang},注意只需要输出翻译后的结果,不要额外解释:\n" + "\n" + "{text}" +) + +# 结构化格式判定(format_type → 混元接受的格式名) +_STRUCTURED_FORMATS = { + "json": "JSON", + "xml": "XML", + "dtxml": "XML", + "html": "HTML", + "markdown": "Markdown", + "md": "Markdown", + "yaml": "YAML", + "xliff": "XML", +} + +# --------------------------------------------------------------------------- +# 通用英文 system/user 提示词(OpenAI / Claude 等) +# --------------------------------------------------------------------------- +_GENERIC_SYSTEM = ( + "You are a professional game localization translator. " + "Preserve placeholders like {value}, {0}, %s, %d and inline tags verbatim. " + "Return only the translation without any additional commentary." +) + + +def _build_hunyuan_prompt( + target_locale: str, + source_text: str, + format_type: str, + locale_names: Optional[Dict[str, str]] = None, + terms: Optional[Sequence[Tuple[str, str]]] = None, +) -> Tuple[str, str]: + """构造混元 Hy-MT2 的提示词。混元翻译模型不使用 system role。 + + * ``terms`` 非空 → 走术语模式(:data:`_HUNYUAN_TERMINOLOGY`); + * ``format_type`` 为结构化格式 → 走结构化模板(:data:`_HUNYUAN_STRUCTURED`); + * 其它 → 走默认模板(:data:`_HUNYUAN_PLAIN`)。 + + 术语模式与结构化模式互斥;本框架业务约定术语优先(术语是对翻译结果的 + 硬约束,结构化只是数据格式提示)。 + """ + target_lang = locale_cn(target_locale, locale_names) + + # 术语模式优先:有术语对就走术语模板 + if terms: + term_pairs = "\n".join( + f"{src} 翻译成 {dst}" for src, dst in terms if src and dst + ) + if term_pairs: + user = _HUNYUAN_TERMINOLOGY.format( + term_pairs=term_pairs, + target_lang=target_lang, + text=source_text, + ) + return "", user + + fmt_key = (format_type or "plain").lower() + if fmt_key in _STRUCTURED_FORMATS: + user = _HUNYUAN_STRUCTURED.format( + format_type=_STRUCTURED_FORMATS[fmt_key], + target_lang=target_lang, + text=source_text, + ) + else: + user = _HUNYUAN_PLAIN.format(target_lang=target_lang, text=source_text) + return "", user + + +def _build_chinese_source_prompt( + source_locale: str, + target_locale: str, + source_text: str, + locale_names: Optional[Dict[str, str]] = None, +) -> Tuple[str, str]: + """源语=中文时的通用提示词:``将{src_cn}翻译成{tgt_cn}:{text}``。 + + 对所有非混元 provider(OpenAI / Claude / Gemini / Venus / + openai_compatible 等)都适用——这些厂商的中文翻译模型对该模板 + 理解度很高,且比英文 prompt 短 1/3 token。 + + 不使用 system role——该简短模板已经包含足够指令,加 system 反而 + 会让部分模型在译文前输出"好的"等客套话。 + """ + src_cn = locale_cn(source_locale, locale_names) + tgt_cn = locale_cn(target_locale, locale_names) + user = f"将{src_cn}翻译成{tgt_cn}:{source_text}" + return "", user + + +def _build_generic_prompt( + source_locale: str, + target_locale: str, + source_text: str, + context: str, + locale_names: Optional[Dict[str, str]] = None, +) -> Tuple[str, str]: + """通用英文 system + user 提示词(OpenAI / Claude 公共版本)。 + + 仅在**源语不是中文**时使用;源语是中文的场景走 + :func:`_build_chinese_source_prompt` 以获得更紧凑的中文提示。 + """ + src_name = locale_en(source_locale, locale_names) if source_locale else "auto" + tgt_name = ( + locale_en(target_locale, locale_names) if target_locale else "unspecified" + ) + parts = [ + f"Source language: {src_name}", + f"Target language: {tgt_name}", + ] + if context: + parts.append(f"Context: {context}") + parts.append(f"Text: {source_text}") + return _GENERIC_SYSTEM, "\n".join(parts) + + +def build_translation_prompt( + *, + provider: str, + source_locale: str = "", + target_locale: str = "", + source_text: str = "", + context: str = "", + format_type: str = "plain", + override_template: str = "", + locale_names: Optional[Dict[str, str]] = None, + terms: Optional[Sequence[Tuple[str, str]]] = None, +) -> Tuple[str, str]: + """根据 provider / 源语种 选择提示词。 + + 返回 ``(system_prompt, user_prompt)``。``system_prompt`` 为空字符串时 + 表示该 provider 的习惯不使用 system role。 + + 选择策略(按优先级从高到低): + + 1. ``override_template`` 非空 → 直接用模板,占位符 ``{text}`` / + ``{target_lang}`` / ``{source_lang}``; + 2. provider 为 ``hunyuan_translation`` → 混元官方推荐提示词 + (含术语模式 + 结构化模式); + 3. 源语是**中文系**(zh / zh-CN / zh-TW ...)→ 中文紧凑提示词 + ``"将{src_cn}翻译成{tgt_cn}:{text}"``; + 4. 兜底 → 通用英文 system+user 提示词。 + + 参数: + provider: LLM provider 名称。 + source_locale / target_locale: BCP-47 代码。 + source_text / context: 原文与可选上下文。 + format_type: 结构化翻译格式(混元专用)。 + override_template: 语种 JSON ``strategy_config.prompt_template`` + 传入的自定义模板。 + locale_names: ``LanguageProfile.locale_names`` 覆盖字典 + (``{"cn": "...", "en": "..."}``)。 + terms: 术语对列表 ``[(源文, 译文), ...]``; + 混元:切换到术语模式;其它 provider:以 ``Reference terms:`` + 形式追加到 user 消息末尾。 + """ + # 1) 显式覆盖模板优先级最高 + if override_template: + user = override_template.format( + text=source_text, + target_lang=locale_cn(target_locale, locale_names), + source_lang=locale_cn(source_locale, locale_names), + ) + if terms: + user = _append_terms_hint(user, terms) + return "", user + + key = (provider or "").strip().lower() + + # 2) 混元翻译模型使用官方推荐提示词(原生支持术语模式) + if key in {"hunyuan_translation", "hunyuan-mt", "hy-mt"}: + return _build_hunyuan_prompt( + target_locale, source_text, format_type, locale_names, terms=terms, + ) + + # 3) 源语是中文系 → 中文紧凑提示词 + if _is_chinese_source(source_locale): + system, user = _build_chinese_source_prompt( + source_locale, target_locale, source_text, locale_names, + ) + if terms: + user = _append_terms_hint(user, terms, chinese=True) + return system, user + + # 4) 兜底:通用英文 system+user 模板(源语非中文:如 Step 2 的 en→vi) + system, user = _build_generic_prompt( + source_locale, target_locale, source_text, context, locale_names, + ) + if terms: + user = _append_terms_hint(user, terms) + return system, user + + +def _append_terms_hint( + user_prompt: str, + terms: Sequence[Tuple[str, str]], + *, + chinese: bool = False, +) -> str: + """给非混元 provider 的 user 消息追加术语对参考(通用兜底)。 + + 参数: + chinese: 为 True 时使用中文表述(配合 + :func:`_build_chinese_source_prompt`);默认英文。 + + 输出形如(英文版本):: + + <原 user_prompt> + + Reference terms (keep these translations consistent): + - 艾薇塔 → Evita + - 护盾 → shield + """ + pairs = [(src, dst) for src, dst in terms if src and dst] + if not pairs: + return user_prompt + if chinese: + joined = "\n".join(f"- {src} → {dst}" for src, dst in pairs) + return f"{user_prompt}\n\n参考术语(请保持译文一致):\n{joined}" + joined = "\n".join(f"- {src} → {dst}" for src, dst in pairs) + return ( + f"{user_prompt}\n\n" + "Reference terms (keep these translations consistent):\n" + f"{joined}" + ) + + +__all__ = [ + "LOCALE_CN_NAME", + "LOCALE_EN_NAME", + "locale_cn", + "locale_en", + "build_translation_prompt", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/venus_llm.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/venus_llm.py new file mode 100644 index 0000000000000000000000000000000000000000..a4b4953e53164228c4fbaf5489c610004769ec68 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/llm/venus_llm.py @@ -0,0 +1,220 @@ +"""Venus 内网 LLM 提供商实现。 + +Venus 是腾讯内部的大模型服务平台,承载 llama3-70B / llama3.1-70B / +Qwen 等翻译模型。本模块基于 ``venus_api_base.http_client.HttpClient`` +按 :class:`LLMClient` 协议封装到框架内。 + +关键配置(放在 ``conf/llm.yaml`` 对应 profile 的 ``extra`` 下): + +* ``server_id`` 【必填】Venus 服务 ID(旧 ``MODEL_SERVER_IDS``); +* ``app_group_id``【必填】Venus 应用组 ID; +* ``secret_id`` / ``secret_key`` 两种填法(任选其一即可): + 1. profile 的 ``api_key`` 以 ``:`` 格式填写; + 2. 分别放在 ``extra.secret_id`` / ``extra.secret_key``; +* ``model_params`` 可选,直接透传到请求体(如 + ``{"temperature": 0.1, "top_p": 0.1, "repetition_penalty": 1.1, + "do_sample": false, ...}``)。 + +启用方式:: + + export GAME_TRANS_TOOLCHAIN__LLM__PROVIDER=venus + export GAME_TRANS_TOOLCHAIN__LLM__API_KEY=: +""" + +from __future__ import annotations + +import logging +import time +from typing import Any, Optional, Sequence, Tuple + +from ..commons import LLMProviderMissingError +from .base import LLMClient, LLMResponse +from .prompts import build_translation_prompt + +logger = logging.getLogger(__name__) + +_DEFAULT_API_BASE = "http://v2.open.venus.oa.com/chat/single" + + +class VenusLLM(LLMClient): + """Venus 内网大模型 provider。 + + 依赖 ``venus_api_base`` 包(内网安装);缺省时在首次调用时抛出清晰错误。 + """ + + provider_name = "venus" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self._client: Optional[Any] = None + + # 解析鉴权凭据:优先 extra.secret_id/secret_key,然后 api_key 冒号分隔 + self._secret_id = str(self.extra.get("secret_id", "") or "") + self._secret_key = str(self.extra.get("secret_key", "") or "") + if (not self._secret_id or not self._secret_key) and self.api_key: + parts = self.api_key.split(":", 1) + if len(parts) == 2: + self._secret_id = self._secret_id or parts[0].strip() + self._secret_key = self._secret_key or parts[1].strip() + else: + # 旧 model_service 中 secret 直接硬编码两段,这里兼容"只传 secret_key"场景 + self._secret_key = self._secret_key or self.api_key + + # 必填:server_id / app_group_id + self._server_id = int(self.extra.get("server_id") or 0) + self._app_group_id = int( + self.extra.get("app_group_id") + or self.extra.get("venus_app_group_id") + or 0 + ) + # 可选的请求体扩展参数(透传到 Venus,复用旧 model_service 的 model_params) + self._model_params = dict(self.extra.get("model_params") or {}) + + # ------------------------------------------------------------------ + def _get_http_client(self) -> Any: + if self._client is not None: + return self._client + try: + from venus_api_base.config import Config # type: ignore + from venus_api_base.http_client import HttpClient # type: ignore + except ImportError as exc: # pragma: no cover — 内网可选依赖 + raise LLMProviderMissingError( + "The 'venus' provider requires 'venus_api_base'. " + "Install the internal package from your corporate mirror." + ) from exc + + if not self._secret_id or not self._secret_key: + raise LLMProviderMissingError( + "Venus credentials missing. Provide extra.secret_id + " + "extra.secret_key, or set api_key=':'." + ) + + self._client = HttpClient( + config=Config(read_timeout=self.timeout_seconds), + secret_id=self._secret_id, + secret_key=self._secret_key, + ) + return self._client + + # ------------------------------------------------------------------ + def translate( + self, + text: str, + *, + source_locale: str = "", + target_locale: str = "", + context: str = "", + terms: Optional[Sequence[Tuple[str, str]]] = None, + ) -> LLMResponse: + if not self._server_id or not self._app_group_id: + raise LLMProviderMissingError( + "Venus profile missing extra.server_id / extra.app_group_id." + ) + + system_prompt, user_prompt = build_translation_prompt( + provider=self.provider_name, + source_locale=source_locale, + target_locale=target_locale, + source_text=text, + context=context, + format_type=str(self.extra.get("format_type", "plain")), + override_template=str(self.extra.get("prompt_template", "")), + locale_names=self.extra.get("locale_names") or None, + terms=terms, + ) + + body = self._build_payload(system_prompt, user_prompt) + endpoint = (self.api_base or _DEFAULT_API_BASE).strip() + + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._do_request(endpoint, body) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover — 网络路径 + last_error = exc + logger.warning( + "VenusLLM: attempt %d/%d failed: %s", + attempt, self.retries, exc, + ) + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + # ------------------------------------------------------------------ + def _build_payload(self, system_prompt: str, user_prompt: str) -> dict: + """构造 Venus 请求体,参数命名与旧 model_service 保持一致。""" + messages: list = [] + if system_prompt: + messages.append({"role": "system", "content": system_prompt}) + messages.append({"role": "user", "content": user_prompt}) + + payload: dict = { + "appGroupId": self._app_group_id, + "serverId": self._server_id, + "messages": messages, + "temperature": self.temperature, + } + # 透传可选的调优参数(do_sample / top_p / top_k / repetition_penalty 等) + for k, v in self._model_params.items(): + # 不覆盖已显式传入的核心字段 + payload.setdefault(k, v) + return payload + + def _do_request(self, endpoint: str, body: dict) -> LLMResponse: + import json as _json + + client = self._get_http_client() + header = {"Content-Type": "application/json"} + resp = client.post(endpoint, header=header, body=_json.dumps(body)) + + content, usage = _extract_venus_content(resp) + if not content: + logger.warning("VenusLLM: empty content in response: %r", resp) + + return LLMResponse( + text=content.strip(), + provider=self.provider_name, + model=self.model or f"venus-{self._server_id}", + usage=usage, + raw=resp, + ) + + +def _extract_venus_content(resp: Any) -> Tuple[str, dict]: + """从 Venus 响应中提取翻译文本与 usage。 + + Venus 返回结构常见三种,按优先级依次尝试: + + 1) 当前内网主路径:``{"data": {"response": "..."}}``—— + ``v2.open.venus.oa.com/chat/single`` 实测返回此字段; + 2) OpenAI 风格:``{"data": {"choices": [{"message": {"content": ...}}]}}``; + 3) 旧封装:``{"data": {"generated_text": "..."}}`` / + ``{"data": {"output": "..."}}`` 等。 + """ + if not isinstance(resp, dict): + return "", {} + data = resp.get("data") if "data" in resp else resp + if not isinstance(data, dict): + return "", {} + + # 优先 OpenAI 风格 + choices = data.get("choices") or [] + if choices and isinstance(choices[0], dict): + message = choices[0].get("message") or {} + if isinstance(message, dict): + text = message.get("content") or "" + if text: + return str(text), dict(data.get("usage") or {}) + + # 兼容多种返回字段(新/旧封装);"response" 是 Venus 当前 + # /chat/single 接口的实际字段名——放首位,命中率最高。 + for key in ("response", "generated_text", "output", "content", "result"): + value = data.get(key) + if isinstance(value, str) and value: + return value, dict(data.get("usage") or {}) + + return "", dict(data.get("usage") or {}) + + +__all__ = ["VenusLLM"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..970ddbda2510a759e0c89e4f5dc69b27469a286f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__init__.py @@ -0,0 +1,26 @@ +"""TiMi_HOK_Game_Translator.notify 子包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.notify import ( + Notifier, NotificationMessage, + ConsoleNotifier, WeComNotifier, SlackNotifier, EmailNotifier, + create_notifier, register_notifier, registered_notifiers, + ) +""" + +from .base import NotificationMessage, Notifier +from .factory import create_notifier, register_notifier, registered_notifiers +from .notifiers import ConsoleNotifier, EmailNotifier, SlackNotifier, WeComNotifier + +__all__ = [ + "ConsoleNotifier", + "EmailNotifier", + "NotificationMessage", + "Notifier", + "SlackNotifier", + "WeComNotifier", + "create_notifier", + "register_notifier", + "registered_notifiers", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b80976231d1b80515211ae37137c463414fb3b2 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52843f691143223fe4a0e2bb5d0b46d466ccf9de Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80d8a8397f0530fe4dcaa995a3dee672b8b3020f Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/notifiers.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/notifiers.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cb84c09518072abd054bdc14a81975c228014e8 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/__pycache__/notifiers.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/base.py new file mode 100644 index 0000000000000000000000000000000000000000..03f13bca98b69049e962a66f5de59d089779c03a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/base.py @@ -0,0 +1,41 @@ +"""通知抽象层。 + +通知器是可插拔的消息推送渠道(WeCom / Slack / Email / Console)。 +由于只是辅助能力,调用站都用 ``try/except`` 包裹,任一渠道失败不会阻断流水线。 +""" + +from __future__ import annotations + +import abc +from dataclasses import dataclass +from typing import Any, Dict, Optional + + +@dataclass +class NotificationMessage: + """传递给 :class:`Notifier` 的结构化消息。""" + + text: str + title: str = "" + mentioned: tuple = () + extra: Dict[str, Any] = None # type: ignore[assignment] + + def __post_init__(self) -> None: + if self.extra is None: + self.extra = {} + + +class Notifier(abc.ABC): + """所有通知渠道的基类。""" + + notifier_name: str = "" + + def __init__(self, *, extra: Optional[Dict[str, Any]] = None) -> None: + self.extra: Dict[str, Any] = dict(extra or {}) + + @abc.abstractmethod + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: + """发送一条通知;实现时建议不因瞬时错误抛异常。""" + + +__all__ = ["NotificationMessage", "Notifier"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..85455e5e0601c376d291d93ec583d58776429983 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/factory.py @@ -0,0 +1,61 @@ +"""通知器的工厂与注册表。""" + +from __future__ import annotations + +from typing import Any, Dict, Type + +from ..commons import NotifierType +from ..config.schema import NotificationConfig +from .base import Notifier +from .notifiers import ConsoleNotifier, EmailNotifier, SlackNotifier, WeComNotifier + + +class _NullNotifier(Notifier): + """静默丢弃全部消息的 :class:`Notifier`。""" + + notifier_name = "none" + + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: # noqa: D401 + return None + + +_REGISTRY: Dict[str, Type[Notifier]] = { + NotifierType.NONE.value: _NullNotifier, + NotifierType.CONSOLE.value: ConsoleNotifier, + NotifierType.WECOM.value: WeComNotifier, + NotifierType.SLACK.value: SlackNotifier, + NotifierType.EMAIL.value: EmailNotifier, +} + + +def register_notifier(name: str, notifier_cls: Type[Notifier]) -> None: + """以 ``name`` 为名注册自定义 :class:`Notifier`。""" + _REGISTRY[name.lower()] = notifier_cls + + +def registered_notifiers() -> list: + """返回当前已注册的通知器名称列表(排序后)。""" + return sorted(_REGISTRY) + + +def create_notifier(notification_config: NotificationConfig) -> Notifier: + """根据 ``notification_config`` 构造具体 :class:`Notifier` 实例。""" + key = (notification_config.type or "").lower() + if key not in _REGISTRY: + raise ValueError( + f"Unknown notification.type '{notification_config.type}'. " + f"Registered notifiers: {registered_notifiers()}" + ) + cls = _REGISTRY[key] + extra: Dict[str, Any] = dict(notification_config.extra or {}) + + # 将顶层 webhook 字段合入 ``extra``,使需要 webhook 的渠道(WeCom / Slack) + # 能一致地拿到它。 + kwargs: Dict[str, Any] = {"extra": extra} + if key in {NotifierType.WECOM.value, NotifierType.SLACK.value}: + kwargs["webhook"] = notification_config.webhook + + return cls(**kwargs) + + +__all__ = ["create_notifier", "register_notifier", "registered_notifiers"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/notifiers.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/notifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..09fed7c23bee1dd64b45f5c98358aa539604a976 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/notify/notifiers.py @@ -0,0 +1,152 @@ +"""内置通知器实现。 + +* :class:`ConsoleNotifier`——通过日志输出。 +* :class:`WeComNotifier`——发送到企业微信群机器人 webhook。 +* :class:`SlackNotifier`——发送到 Slack incoming webhook。 +* :class:`EmailNotifier`——通过 SMTP 发送邮件。 + +所有网络 IO 都经由 :mod:`requests`(WeCom / Slack)或 :mod:`smtplib`(Email)。 +每个通知器自行吸收异常并记告警,不会因为通知失败而中断流水线。 +""" + +from __future__ import annotations + +import logging +import smtplib +from email.message import EmailMessage +from typing import Any, Dict + +from .base import Notifier + +logger = logging.getLogger(__name__) + + +class ConsoleNotifier(Notifier): + """通过标准 logger 输出通知的实现。""" + + notifier_name = "console" + + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: + prefix = f"[{title}] " if title else "" + mention_str = f" (@{', @'.join(mentioned)})" if mentioned else "" + logger.info("%s%s%s", prefix, text, mention_str) + + +class WeComNotifier(Notifier): + """企业微信群机器人通知器。 + + webhook 地址通过 + :class:`~TiMi_HOK_Game_Translator.config.schema.NotificationConfig` 的 ``webhook`` 字段传入; + 该字段被视为敏感内容,在 ``config dump`` 输出时会脱敏。 + """ + + notifier_name = "wecom" + + def __init__(self, *, webhook: str = "", **kwargs: Any) -> None: + super().__init__(**kwargs) + self.webhook = webhook + + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: + if not self.webhook: + logger.warning("WeComNotifier has no webhook configured; message dropped.") + return + payload: Dict[str, Any] = { + "msgtype": "text", + "text": { + "content": (f"[{title}] " if title else "") + text, + "mentioned_list": list(mentioned), + }, + } + _post(self.webhook, payload, self.notifier_name) + + +class SlackNotifier(Notifier): + """发送到 Slack incoming webhook 的通知器。""" + + notifier_name = "slack" + + def __init__(self, *, webhook: str = "", **kwargs: Any) -> None: + super().__init__(**kwargs) + self.webhook = webhook + + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: + if not self.webhook: + logger.warning("SlackNotifier has no webhook configured; message dropped.") + return + payload: Dict[str, Any] = { + "text": (f"*{title}*\n" if title else "") + text, + } + if mentioned: + payload["text"] = " ".join(f"<@{m}>" for m in mentioned) + " " + payload["text"] + _post(self.webhook, payload, self.notifier_name) + + +class EmailNotifier(Notifier): + """SMTP 邮件通知器。 + + 需要的 ``extra`` 字段: + + * ``host``——SMTP 主机名(如 ``smtp.example.com``)。 + * ``port``——SMTP 端口号(整数)。 + * ``username`` / ``password``——SMTP 鉴权(开放中继可选)。 + * ``sender``——RFC 5322 发件人地址。 + * ``recipients``——逗号分隔的收件人列表。 + * ``tls``——bool,默认 True。 + """ + + notifier_name = "email" + + def notify(self, text: str, *, title: str = "", mentioned: tuple = ()) -> None: + host = str(self.extra.get("host", "")) + port = int(self.extra.get("port", 25)) + sender = str(self.extra.get("sender", "")) + recipients = self.extra.get("recipients", []) + if isinstance(recipients, str): + recipients = [r.strip() for r in recipients.split(",") if r.strip()] + if not host or not sender or not recipients: + logger.warning("EmailNotifier missing host/sender/recipients; message dropped.") + return + + message = EmailMessage() + message["Subject"] = title or "TiMi_HOK_Game_Translator notification" + message["From"] = sender + message["To"] = ", ".join(recipients) + body = text + if mentioned: + body = body + "\n\nMentions: " + ", ".join(mentioned) + message.set_content(body) + + try: + with smtplib.SMTP(host, port, timeout=30) as smtp: + if bool(self.extra.get("tls", True)): + smtp.starttls() + username = self.extra.get("username") + password = self.extra.get("password") + if username and password: + smtp.login(str(username), str(password)) + smtp.send_message(message) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("EmailNotifier failed to send: %s", exc) + + +def _post(webhook: str, payload: Dict[str, Any], notifier_name: str) -> None: + """将 ``payload`` 以 JSON 形式 POST 到 ``webhook``,异常仅记日志不抛出。""" + try: + import requests # 局部导入——测试环境可能未安装 + except ImportError: # pragma: no cover + logger.warning("%s notifier requires the 'requests' package.", notifier_name) + return + try: + response = requests.post(webhook, json=payload, timeout=15) + if response.status_code >= 400: + logger.warning( + "%s notifier got HTTP %s: %s", + notifier_name, + response.status_code, + response.text[:200], + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 非致命 + logger.warning("%s notifier failed: %s", notifier_name, exc) + + +__all__ = ["ConsoleNotifier", "EmailNotifier", "SlackNotifier", "WeComNotifier"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d580886aab7a5c08e8f30a561b68c319da225af8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__init__.py @@ -0,0 +1,45 @@ +"""TiMi_HOK_Game_Translator.platforms 子包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.platforms import ( + TranslationPlatform, TaskInfo, TaskStatus, UploadResult, SplitResult, + NoopPlatform, PhrasePlatform, CrowdinPlatform, + create_platform, build_review_tool, + register_platform, registered_platforms, + ) +""" + +from .base import ( + SplitResult, + TaskInfo, + TaskStatus, + TranslationPlatform, + UploadResult, +) + +# 导入以下模块的副作用是把对应平台适配器注册到工厂。 +from .crowdin_platform import CrowdinPlatform +from .factory import ( + build_review_tool, + create_platform, + register_platform, + registered_platforms, +) +from .noop import NoopPlatform +from .phrase_platform import PhrasePlatform + +__all__ = [ + "CrowdinPlatform", + "NoopPlatform", + "PhrasePlatform", + "SplitResult", + "TaskInfo", + "TaskStatus", + "TranslationPlatform", + "UploadResult", + "build_review_tool", + "create_platform", + "register_platform", + "registered_platforms", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e4fdf4d6d705f1adcb2550ab1ed01bb46597dac Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/_batch.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/_batch.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd11e7bd6cbb32df764a0a7a4713b93c9bb4345f Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/_batch.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b374497712c38bb0ea5545f03858fca0a597c322 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/crowdin_platform.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/crowdin_platform.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..800845ac9e1e4be9c6ce095d4182f78740e3fd3c Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/crowdin_platform.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0198e24ac7e6089f6212671b78a1833d8eef4386 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/noop.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/noop.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0e901f50ea3eb6fde3e912c7b145c7a31de0722 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/noop.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/phrase_platform.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/phrase_platform.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e33f494be3adf387e839fcba2b8dd02cb551b5e Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/__pycache__/phrase_platform.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/_batch.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..496c5b892bfc0da51bd715501bd32a874a4b7ad4 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/_batch.py @@ -0,0 +1,101 @@ +"""审校批次(batch)辅助。 + +一个"批次"指:某一次 ``TiMi_HOK_Game_Translator run`` 的 ``first_review`` 或 +``second_review`` 向审校平台(Crowdin / Phrase)提交的一组产物。 +批次统一落在 ``workspace/batches///`` 下,便于 +留痕、重跑定位、以及人工排错。 + +命名约定:: + + 批次名:_ + 例如:vi_20261008200000 + + 产物文件:_<中文审校阶段>.xlsx / .xliff + 例如:vi_20261008200000_第一轮审核.xlsx + vi_20261008200000_第二轮审核.xlsx + +目录布局:: + + workspace/batches// + ├── first_review/ + │ ├── _第一轮审核.xlsx ← 上传到平台 + │ ├── _第一轮审核.xliff ← 从平台导出 + │ └── first_review.meta.json + └── second_review/ + ├── _第二轮审核.xlsx + ├── _第二轮审核.xliff + └── second_review.meta.json +""" + +from __future__ import annotations + +import re +import time +from pathlib import Path +from typing import Final + +#: 批次下按阶段细分的子目录名;与 :class:`ReviewStage` 对齐。 +_STAGE_SUBDIR: Final = { + "first": "first_review", + "second": "second_review", + "light": "light_review", +} + +#: 产物文件后缀——使用中文,便于审校员一眼识别审校阶段。 +_STAGE_FILE_SUFFIX: Final = { + "first": "第一轮审核", + "second": "第二轮审核", + "light": "轻度审核", +} + +#: ``target_locale`` 允许的字符白名单;其它字符替换成 ``_``。 +_SAFE_RE = re.compile(r"[^A-Za-z0-9]+") + + +def build_batch_name( + *, + project_code: str = "", + target_locale: str, + timestamp: str = "", +) -> str: + """按 ``_`` 规则生成批次名。 + + 参数: + project_code: 保留参数,当前实现忽略——批次名已去除 project_code + 前缀以保持简洁;保留签名便于未来扩展/避免调用方破坏。 + target_locale: 目标语种,如 ``vi``。 + timestamp: ``yyyyMMddHHmmss`` 格式时间戳;为空时用当前时间。 + 返回: + 形如 ``vi_20261008200000`` 的批次名。 + """ + _ = project_code # 当前不参与命名,仅保留签名 + safe_locale = _SAFE_RE.sub("_", target_locale.strip()) or "target" + ts = timestamp or time.strftime("%Y%m%d%H%M%S", time.localtime()) + return f"{safe_locale}_{ts}" + + +def batch_root(workspace: Path, batch_name: str) -> Path: + """返回批次根目录;不自动创建。""" + return Path(workspace) / "batches" / batch_name + + +def stage_dir(workspace: Path, batch_name: str, review_stage: str) -> Path: + """返回批次下指定阶段的目录;自动 ``mkdir``。""" + subdir = _STAGE_SUBDIR.get(review_stage, review_stage) + path = batch_root(workspace, batch_name) / subdir + path.mkdir(parents=True, exist_ok=True) + return path + + +def stage_file_stem(batch_name: str, review_stage: str) -> str: + """生成形如 ``_第一轮审核`` 的文件 stem。""" + suffix = _STAGE_FILE_SUFFIX.get(review_stage, review_stage) + return f"{batch_name}_{suffix}" + + +__all__ = [ + "build_batch_name", + "batch_root", + "stage_dir", + "stage_file_stem", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f20c066b3261c09d7c725730bd6459b3caf1c43e --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/base.py @@ -0,0 +1,277 @@ +"""翻译/审校平台抽象层。 + +“平台”指 Crowdin、Phrase(Memsource)等第三方服务,它们在外部管理项目、任务与 +翻译者工作流。本框架仅通过 :class:`TranslationPlatform` 接口与它们交互, +将厂商 SDK 隔离在主包外。 + +参考发行包提供 :class:`NoopPlatform`,供 ``platform.type = "none"`` 使用; +真实集成位于本子包(``phrase_platform.py`` 、 ``crowdin_platform.py`` …), +通过 ``@register_platform("")`` 启用。 + +同一份 :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile` 可为不同审校阶段配置 +不同平台(参见 :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage`)。因此所有需区分 +阶段的方法都接受命名参数 ``review_stage``,使工作流无歧义地指定“轮询一审任务”。 +""" + +from __future__ import annotations + +import abc +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, Optional, Sequence, Tuple + +from ..commons import ReviewStage + + +class TaskStatus(str, Enum): + """远端平台上一个翻译任务的粗粒度状态。""" + + PENDING = "pending" + IN_PROGRESS = "in_progress" + APPROVED = "approved" + REJECTED = "rejected" + UNKNOWN = "unknown" + + +@dataclass +class TaskInfo: + """平台返回的单个任务信息。 + + 字段: + task_id: 平台侧的任务 ID。 + status: 粗粒度审校状态;平台自定义状态可放入 :attr:`extra`。 + source_locale / target_locale: BCP-47 标签。 + project_id: 平台侧项目 ID。 + review_stage: 本任务归属的审校阶段(对应 + :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage.value`)。 + percent_completed: 0..100 的进度(平台不提供时为 0)。 + extra: 平台自定义字段(``jobUid`` / ``workflow_step`` / ``translator`` …)。 + """ + + task_id: str + status: TaskStatus = TaskStatus.UNKNOWN + source_locale: str = "" + target_locale: str = "" + project_id: str = "" + review_stage: str = ReviewStage.FIRST.value + percent_completed: float = 0.0 + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class UploadResult: + """将源文件上传到平台后的返回信息。""" + + file_id: str + revision: str = "" + extra: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class SplitResult: + """:meth:`TranslationPlatform.split_approved_data` 的返回结果。 + + 字段: + approved_path: 已写入已批准译文的本地文件。 + pending_path: 已写入仍然待审校条目的本地文件,空串代表“全部批准”。 + should_continue: 便捷标志,存在已批准译文时为 True;下游状态据此 + 判断是否跳过 merge / publish。 + is_complete: 当前审校轮是否已完全完成(无残留条目); + 与 ``complete`` 字段的语义对齐。 + extra: 平台自定义字段。 + """ + + approved_path: str = "" + pending_path: str = "" + should_continue: bool = False + is_complete: bool = False + extra: Dict[str, Any] = field(default_factory=dict) + + +class TranslationPlatform(abc.ABC): + """所有平台适配器需实现的接口。 + + 适配器作者通常需重写: + + * :meth:`upload_source` / :meth:`create_task`——上传文件并创建审校任务; + * :meth:`get_task_status` / :meth:`get_task_percent`——轮询任务状态; + * :meth:`download_translations` / :meth:`import_approved`——拉取已批准译文; + * :meth:`split_approved_data`——拆分已批准与待审校译文; + * :meth:`delete_task` / :meth:`get_project_name`——后处理辅助。 + """ + + #: 人可读名称(与配置中的 ``platform.type`` 以及 ``@register_platform`` 的 key 一致)。 + platform_name: str = "" + + #: 本适配器可服务的 :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage` 集合; + #: 空元组代表“支持任意阶段”。 + supports_stages: Tuple[str, ...] = () + + def __init__( + self, + *, + api_base: str = "", + api_token: str = "", + project_id: str = "", + extra: Optional[Dict[str, Any]] = None, + ) -> None: + self.api_base = api_base + self.api_token = api_token + self.project_id = project_id + self.extra: Dict[str, Any] = dict(extra or {}) + + # ------------------------------------------------------------------ + # 自省辅助 + # ------------------------------------------------------------------ + def supports(self, review_stage: str) -> bool: + """当本适配器能服务 ``review_stage`` 时返回 True。 + + 默认实现::attr:`supports_stages` 为空时总是 True,否则判断是否包含。 + 子类可重写以实现更细粒度的判定。 + """ + if not self.supports_stages: + return True + return review_stage in self.supports_stages + + # ------------------------------------------------------------------ + # 抽象 API + # ------------------------------------------------------------------ + @abc.abstractmethod + def upload_source(self, file_path: str, *, remote_path: str = "") -> UploadResult: + """上传 ``file_path``,返回平台上的文件记录。""" + + @abc.abstractmethod + def download_translations( + self, + file_id: str, + target_locale: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + """下载 ``file_id`` 对应 ``target_locale`` 的译文到 ``dest_path``,返回写入的本地路径。""" + + @abc.abstractmethod + def create_task( + self, + file_ids: Sequence[str], + target_locale: str, + *, + review_stage: str = ReviewStage.FIRST.value, + title: str = "", + description: str = "", + ) -> TaskInfo: + """创建一个覆盖指定文件集与语种的审校任务。""" + + @abc.abstractmethod + def get_task_status( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> TaskInfo: + """返回 ``task_id`` 当前状态。""" + + @abc.abstractmethod + def import_approved( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + """将 ``task_id`` 的已批准译文写入 ``dest_path``,返回写入的本地路径。""" + + @abc.abstractmethod + def export_review_report( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + """导出 ``task_id`` 的人可读审校报告。""" + + # ------------------------------------------------------------------ + # 扩展 API(已提供默认实现,简单适配器不必重写) + # ------------------------------------------------------------------ + def get_task_percent( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> float: + """返回 ``task_id`` 的 0..100 完成度。 + + 默认实现多调一次 :meth:`get_task_status`;如果平台提供更便宜的接口, + 子类可重写。 + """ + info = self.get_task_status(task_id, review_stage=review_stage) + return info.percent_completed + + def split_approved_data( + self, + task_id: str, + *, + save_approved_path: str, + save_pending_path: str = "", + review_stage: str = ReviewStage.FIRST.value, + ) -> SplitResult: + """拉取 ``task_id`` 并拆分为已批准/待审校两份本地文件。 + + 默认实现:仅调用 :meth:`import_approved` 拿到已批准部分,pending_path 为空。 + 当平台能提供更细粒度的数据(Crowdin 的 ``ApprovalStatus`` 列、 + Phrase 的 ``segmentStatus`` 字段)时,子类应重写。 + """ + approved = self.import_approved( + task_id, save_approved_path, review_stage=review_stage, + ) + return SplitResult( + approved_path=approved, + pending_path="", + should_continue=bool(approved), + is_complete=True, + ) + + def delete_task( # noqa: B027 — 默认空实现即为预期行为 + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + """删除 ``task_id`` 及其关联的远端文件。 + + 默认为空实现;当平台提供清理接口且你需要在工作流末尾调用时重写。 + """ + + def delete_file( # noqa: B027 — 默认空实现即为预期行为 + self, + file_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + """删除平台侧 ``file_id`` 对应的文件(上传过的 xlsx / xml 等)。 + + 与 :meth:`delete_task` 配对使用,用于防止平台项目目录被已完成/ + 已拆分的历史文件无限堆积。默认空实现——仅在平台提供 DELETE + ``/projects/{pid}/files/{file_id}`` 之类接口时重写。 + + 调用方应**在删除 task 之后**再删 file,顺序颠倒可能触发平台 + "文件被 task 引用无法删除"的 409 响应。 + """ + + def get_project_name(self, project_id: str = "") -> str: + """返回 ``project_id`` 对应的人可读名称。 + + 默认直接返回 ``project_id``。适配器如需调用 REST 回填名称,可重写。 + """ + return project_id or self.project_id + + +__all__ = [ + "SplitResult", + "TaskInfo", + "TaskStatus", + "TranslationPlatform", + "UploadResult", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/crowdin_platform.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/crowdin_platform.py new file mode 100644 index 0000000000000000000000000000000000000000..f5ddfaa5f89024803d68b5448cfae6c7addb5bc9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/crowdin_platform.py @@ -0,0 +1,1178 @@ +"""Crowdin(Crowdin API v2)翻译平台适配器。 + +基于 **Crowdin REST API v2** 实现 +:class:`~TiMi_HOK_Game_Translator.platforms.TranslationPlatform` 契约。 + +参考文档: + +* API 概览 — https://developer.crowdin.com/api/v2/ +* 文件相关 — https://developer.crowdin.com/api/v2/#tag/Source-Files +* 任务相关 — https://developer.crowdin.com/api/v2/#tag/Tasks +* 译文相关 — https://developer.crowdin.com/api/v2/#tag/Translations +* 存储相关 — https://developer.crowdin.com/api/v2/#tag/Storage + +鉴权方式 +-------- +Crowdin Cloud 使用**个人访问令牌**(Bearer)。企业版采用同一令牌模型但 + API base 不同:``https://.api.crowdin.com/api/v2``。调整 ``api_base`` 即可兼容两者。 + +使用的接口 +------------ +==================================== =============================================================== +用途 接口(相对于 ``api_base``) +==================================== =============================================================== +添加 storage(上传文件体) ``POST /storages``(原始文件体) +将源文件挂到项目 ``POST /projects/{projectId}/files`` +创建任务 ``POST /projects/{projectId}/tasks`` +获取任务 ``GET /projects/{projectId}/tasks/{taskId}`` +删除任务 ``DELETE /projects/{projectId}/tasks/{taskId}`` +导出任务译文 ``POST /projects/{projectId}/translations/exports`` +下载导出后文件 ``GET `` +获取项目 ``GET /projects/{projectId}` +==================================== =============================================================== + +本适配器故意保持**短小**,只覆盖框架实际需要的接口。如需术语、机器翻译、 +截图等能力,可继承本类自行扩展。 +""" + +from __future__ import annotations + +import logging +import os +import threading +from typing import Any, Callable, Dict, List, Optional, Sequence + +from ..commons import ( + DEFAULT_HTTP_RETRIES, + DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + DEFAULT_HTTP_TIMEOUT_SECONDS, + PlatformError, + ReviewStage, +) +from .base import ( + SplitResult, + TaskInfo, + TaskStatus, + TranslationPlatform, + UploadResult, +) +from .factory import register_platform + +logger = logging.getLogger(__name__) + +_DEFAULT_API_BASE = "https://api.crowdin.com/api/v2" + + +# Crowdin 任务状态 → 框架状态。 +_STATUS_MAP: Dict[str, TaskStatus] = { + "todo": TaskStatus.PENDING, + "in_progress": TaskStatus.IN_PROGRESS, + "done": TaskStatus.APPROVED, + "closed": TaskStatus.APPROVED, + "cancelled": TaskStatus.REJECTED, + "canceled": TaskStatus.REJECTED, +} + + +def _map_status(remote: str) -> TaskStatus: + if not remote: + return TaskStatus.UNKNOWN + return _STATUS_MAP.get(remote.lower(), TaskStatus.UNKNOWN) + + +# --------------------------------------------------------------------------- +# 适配器主体 +# --------------------------------------------------------------------------- +class CrowdinPlatform(TranslationPlatform): + """Crowdin API v2 适配器。 + + 支持的 ``extra`` key: + + * ``directory_id``——将上传文件挂在指定目录下; + * ``workflow_step_id``——将任务固定到某个工作流步; + * ``timeout_seconds`` / ``retries`` / ``retry_interval_seconds``——HTTP 可调参数; + * ``session_factory``——高级选项,可传入自定义的 ``requests.Session`` 工厂。 + """ + + platform_name = "crowdin" + supports_stages = ( + ReviewStage.FIRST.value, + ReviewStage.SECOND.value, + ReviewStage.LIGHT.value, + ) + + def __init__( + self, + *, + api_base: str = "", + api_token: str = "", + project_id: str = "", + extra: Optional[Dict[str, Any]] = None, + ) -> None: + super().__init__( + api_base=api_base or _DEFAULT_API_BASE, + api_token=api_token, + project_id=project_id, + extra=extra, + ) + self.api_base = self.api_base.rstrip("/") + + self._directory_id: str = str(self.extra.get("directory_id", "") or "") + self._workflow_step_id: str = str(self.extra.get("workflow_step_id", "") or "") + + self._timeout: float = float( + self.extra.get("timeout_seconds", DEFAULT_HTTP_TIMEOUT_SECONDS) + ) + self._retries: int = int(self.extra.get("retries", DEFAULT_HTTP_RETRIES)) + self._retry_interval: float = float( + self.extra.get("retry_interval_seconds", DEFAULT_HTTP_RETRY_INTERVAL_SECONDS) + ) + + session_factory: Optional[Callable[[], Any]] = self.extra.get("session_factory") + self._session_factory: Optional[Callable[[], Any]] = ( + session_factory if callable(session_factory) else None + ) + + self._lock = threading.RLock() + # file_id → { "file_id": str, "storage_id": str, "filename": str } + self._files: Dict[str, Dict[str, Any]] = {} + # task_id → 上次得到的 TaskInfo,供后续快速查找 + self._tasks: Dict[str, TaskInfo] = {} + + # ------------------------------------------------------------------ + # HTTP 工作基础 + # ------------------------------------------------------------------ + def _session(self): + if self._session_factory is not None: + return self._session_factory() + try: + import requests # noqa: WPS433 — 局部导入 + except ImportError as exc: # pragma: no cover + raise PlatformError( + "CrowdinPlatform requires 'requests'. Install with " + "`pip install requests`." + ) from exc + return requests.Session() + + def _headers( + self, + *, + content_type: str = "application/json", + extra: Optional[Dict[str, str]] = None, + ) -> Dict[str, str]: + if not self.api_token: + raise PlatformError( + "CrowdinPlatform: api_token is empty. Set GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN " + "or the ReviewConfig.api_token field." + ) + headers = { + "Authorization": f"Bearer {self.api_token}", + "Accept": "application/json", + } + if content_type: + headers["Content-Type"] = content_type + if extra: + headers.update(extra) + return headers + + def _request( + self, + method: str, + path: str, + *, + params: Optional[Dict[str, Any]] = None, + json_body: Optional[Any] = None, + raw_body: Optional[bytes] = None, + stream: bool = False, + extra_headers: Optional[Dict[str, str]] = None, + full_url: Optional[str] = None, + ): + """发送带鉴权的 HTTP 请求,按需重试。""" + session = self._session() + url = full_url or f"{self.api_base}{path}" + content_type = ( + "application/octet-stream" if raw_body is not None else "application/json" + ) + headers = self._headers(content_type=content_type, extra=extra_headers) + + last_exc: Optional[BaseException] = None + for attempt in range(1, self._retries + 1): + try: + response = session.request( + method.upper(), + url, + params=params, + json=json_body if raw_body is None else None, + data=raw_body, + headers=headers, + timeout=self._timeout, + stream=stream, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 任何传输错误都需重试 + last_exc = exc + logger.warning( + "CrowdinPlatform: %s %s failed on attempt %d/%d: %s", + method, path, attempt, self._retries, exc, + ) + if attempt >= self._retries: + break + _sleep(self._retry_interval) + continue + + if response.status_code >= 500 or response.status_code == 429: + logger.warning( + "CrowdinPlatform: %s %s got HTTP %d (attempt %d/%d)", + method, path, response.status_code, attempt, self._retries, + ) + if attempt >= self._retries: + self._raise_for_status(response, path) + _sleep(self._retry_interval) + continue + + self._raise_for_status(response, path) + return response + + if last_exc is not None: + raise PlatformError( + f"CrowdinPlatform: exhausted {self._retries} retries for {method} {path}: {last_exc}" + ) from last_exc + raise PlatformError( + f"CrowdinPlatform: exhausted {self._retries} retries for {method} {path}" + ) + + @staticmethod + def _raise_for_status(response, path: str) -> None: + if 200 <= response.status_code < 300: + return + body: Any = "" + try: + body = response.json() + except Exception: # pylint: disable=broad-except # noqa: BLE001 + body = getattr(response, "text", "") + raise PlatformError( + f"CrowdinPlatform: {path} → HTTP {response.status_code}: {body!r}" + ) + + def _project_id(self) -> str: + if not self.project_id: + raise PlatformError("CrowdinPlatform: project_id is empty.") + return str(self.project_id) + + # ------------------------------------------------------------------ + # 适配器 API + # ------------------------------------------------------------------ + def upload_source(self, file_path: str, *, remote_path: str = "") -> UploadResult: + """两步上传:先写入 storage,再挂到项目文件。 + + 关键细节: + * 对 ``.xlsx`` 文件,Crowdin 需要显式传 ``type: "xlsx"`` **和** + ``importOptions.scheme`` 才能把表格解析成一组可翻译的 strings; + 否则 Crowdin 虽然会收下文件,但解析不出任何 string,后续 + :meth:`create_task` 会因 "fileIds not found" 返回 HTTP 400。 + * 本方法默认按仓库约定的 5 列表头(Key / Source / Target / + Context / Comment)生成 scheme;若上传的是其它格式/其它列顺序, + 可通过构造器 ``extra['file_type']`` 与 ``extra['import_options']`` + 整体覆盖。 + """ + filename = os.path.basename(remote_path) or os.path.basename(file_path) + # requests 库对 HTTP header 默认用 latin-1 编码。Crowdin 的 + # ``Crowdin-API-FileName`` 不接受非 ASCII 字符(中文文件名会直接报 + # ``'latin-1' codec can't encode``),这里专门为 header 构造一个 + # ASCII-safe 版本;而 body 的 ``name`` 字段依然用原始中文名—— + # Crowdin 侧界面显示仍然是用户熟悉的中文。 + header_safe_filename = _to_ascii_filename(filename) + + with open(file_path, "rb") as handle: + data = handle.read() + + storage_response = self._request( + "POST", + "/storages", + raw_body=data, + extra_headers={ + "Crowdin-API-FileName": header_safe_filename, + }, + ) + storage_payload = storage_response.json().get("data", {}) + storage_id = str(storage_payload.get("id", "")) + if not storage_id: + raise PlatformError( + "CrowdinPlatform: /storages response missing data.id" + ) + + body: Dict[str, Any] = { + "storageId": int(storage_id), + "name": filename, + } + if self._directory_id: + body["directoryId"] = int(self._directory_id) + + # 根据扩展名(或 extra 覆盖)自动补上 type + importOptions。 + file_type, import_options = self._infer_file_type_and_options(filename) + if file_type: + body["type"] = file_type + if import_options: + body["importOptions"] = import_options + + file_response = self._request( + "POST", + f"/projects/{self._project_id()}/files", + json_body=body, + ) + file_payload = file_response.json().get("data", {}) + file_id = str(file_payload.get("id", "")) + if not file_id: + raise PlatformError( + "CrowdinPlatform: files response missing data.id" + ) + + record = { + "file_id": file_id, + "storage_id": storage_id, + "filename": filename, + } + with self._lock: + self._files[file_id] = record + + logger.info( + "CrowdinPlatform: uploaded %s (fileId=%s, storageId=%s)", + filename, file_id, storage_id, + ) + return UploadResult( + file_id=file_id, + revision=str(file_payload.get("revisionId", "")), + extra=record, + ) + + def upload_translations( + self, + file_id: str, + target_locale: str, + local_xlsx_path: str, + *, + auto_approve: bool = False, + import_eq_suggestions: bool = True, + ) -> None: + """把 ``local_xlsx_path`` 中 **Target 列** 的译文作为 "已有翻译" 上传到 + Crowdin,关联到 ``file_id`` 和 ``target_locale``。 + + **为什么单独一个接口?** + + Crowdin 的 ``POST /projects/{id}/files``(挂文件)只识别**源串字段** + (``identifier``/``sourcePhrase``/``context`` …),不会把 Target 列 + 作为译文导入——哪怕 scheme 里写了 ``translation``。要让 Crowdin 侧 + 同时看到 LLM 预译结果,必须额外调一次 + ``POST /projects/{id}/translations/{languageId}`` 接口,走的也是先 + ``/storages`` 上传文件体、再提交 ``storageId + fileId`` 的两步法。 + + 调用 Crowdin ``POST /projects/{id}/translations/{languageId}`` 接口 + 上传已有译文。默认参数: + + * ``importEqSuggestions=True``——完全相同的源串若已有 TM 命中, + 依然把本次译文作为候选加入; + * ``autoApproveImported=False``——导入的译文**不自动审核通过**, + 仍需审校员手动点 approve(符合"LLM 预译作为初稿"的工作流语义); + * ``translateHidden=False``:不翻译隐藏串; + * ``addToTm=False``:不入 Crowdin 项目 TM(避免 LLM 结果污染术语库)。 + + 参数: + file_id: Crowdin 侧已挂载的源文件 ID(即 :meth:`upload_source` 返回的 ``file_id``); + target_locale: Crowdin 语种代码(如 ``"vi"`` / ``"zh-CN"``); + local_xlsx_path: 本地 xlsx 路径,必须和挂文件时同一份 xlsx + (Crowdin 侧按 Key 列对齐,Target 列作为译文); + auto_approve: 覆盖默认的 ``autoApproveImported=False``; + import_eq_suggestions: 覆盖默认的 ``importEqSuggestions=True``。 + """ + filename = os.path.basename(local_xlsx_path) + header_safe_filename = _to_ascii_filename(filename) + + with open(local_xlsx_path, "rb") as handle: + data = handle.read() + + storage_response = self._request( + "POST", + "/storages", + raw_body=data, + extra_headers={"Crowdin-API-FileName": header_safe_filename}, + ) + storage_id = str(storage_response.json().get("data", {}).get("id", "")) + if not storage_id: + raise PlatformError( + "CrowdinPlatform.upload_translations: /storages response missing data.id" + ) + + body: Dict[str, Any] = { + "storageId": int(storage_id), + "fileId": int(file_id) if str(file_id).isdigit() else file_id, + "importEqSuggestions": bool(import_eq_suggestions), + "autoApproveImported": bool(auto_approve), + "translateHidden": False, + "addToTm": False, + } + + self._request( + "POST", + f"/projects/{self._project_id()}/translations/{target_locale}", + json_body=body, + ) + logger.info( + "CrowdinPlatform: uploaded translations for fileId=%s locale=%s " + "(storageId=%s, auto_approve=%s)", + file_id, target_locale, storage_id, auto_approve, + ) + + def create_task( + self, + file_ids: Sequence[str], + target_locale: str, + *, + review_stage: str = ReviewStage.FIRST.value, + title: str = "", + description: str = "", + ) -> TaskInfo: + if not file_ids: + raise PlatformError("CrowdinPlatform.create_task: file_ids is empty.") + + body: Dict[str, Any] = { + "title": title or f"Review {target_locale}", + "languageId": target_locale, + # type=0 → 翻译任务(要求至少 1 条 untranslated 字串); + # type=1 → 校对任务(要求目标语言已有译文)。 + # + # 本项目的审校流程为"LLM 已预译 → 人工校对":先用 + # upload_translations 把 Target 列全量导入 Crowdin,所以目标 + # 语言下 untranslated=0,若用 type=0 会被 Crowdin 以 + # HTTP 409 "Language has no untranslated words" 拒绝。 + # 因此默认选 1(校对);若调用方确有必要可通过 extra["task_type"] + # 覆盖。 + "type": 1, + "fileIds": [int(f) for f in file_ids], + } + if description: + body["description"] = description + if self._workflow_step_id: + body["workflowStepId"] = int(self._workflow_step_id) + # 允许调用方以 extra 中的 ``task_*`` 字段覆盖任务字段。 + for key, value in self.extra.items(): + if key.startswith("task_"): + body[key[len("task_"):]] = value + + response = self._request( + "POST", + f"/projects/{self._project_id()}/tasks", + json_body=body, + ) + data = response.json().get("data", {}) + task_id = str(data.get("id", "")) + remote_status = str(data.get("status", "")) + info = TaskInfo( + task_id=task_id, + status=_map_status(remote_status), + target_locale=target_locale, + project_id=self._project_id(), + review_stage=review_stage, + percent_completed=float(data.get("progress", {}).get("percent", 0.0)), + extra={ + "raw_status": remote_status, + "title": title, + "description": description, + "type": data.get("type"), + }, + ) + with self._lock: + self._tasks[task_id] = info + return info + + def get_task_status( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> TaskInfo: + response = self._request( + "GET", + f"/projects/{self._project_id()}/tasks/{task_id}", + ) + data = response.json().get("data", {}) + remote_status = str(data.get("status", "")) + percent = float(data.get("progress", {}).get("percent", 0.0)) + # Crowdin GET /tasks/{id} 响应里**语言字段叫 ``targetLanguageId``** + # (见老项目 crowdin_service.py 第 698/714 行与 + # docs/crowdin_dual_platform_sync.md 第 260 行)。为兼容未来可能 + # 的字段名变更或其它 Crowdin 兼容实现,这里按 + # ``targetLanguageId → languageId`` 的顺序兜底读取;若还为空, + # 回退到内存里**上次创建**该 task 时持有的 target_locale——而不是 + # 直接设成空串污染后续 translations/exports 调用。 + resolved_locale = ( + str(data.get("targetLanguageId", "") or "") + or str(data.get("languageId", "") or "") + ) + if not resolved_locale: + with self._lock: + cached = self._tasks.get(task_id) + if cached is not None and cached.target_locale: + resolved_locale = cached.target_locale + info = TaskInfo( + task_id=task_id, + status=_map_status(remote_status), + target_locale=resolved_locale, + project_id=self._project_id(), + review_stage=review_stage, + percent_completed=percent, + extra={ + "raw_status": remote_status, + "title": data.get("title", ""), + # 保留 fileIds,避免 import_approved() 重复拉取。 + "fileIds": list(data.get("fileIds") or []), + }, + ) + with self._lock: + self._tasks[task_id] = info + return info + + def download_translations( + self, + file_id: str, + target_locale: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + # Crowdin:先创建 exports 、再从返回的预签名 URL 下载。 + # 本处采用一步 exports 并直接下载。 + if not target_locale: + raise PlatformError( + "CrowdinPlatform.download_translations: target_locale is empty. " + "This usually means get_task_status() returned a TaskInfo with " + "empty target_locale (Crowdin task detail missing both " + "'targetLanguageId' and 'languageId' fields). " + f"review_stage={review_stage}, file_id={file_id}." + ) + if not file_id: + raise PlatformError( + "CrowdinPlatform.download_translations: file_id is empty." + ) + # 关键:显式传 ``format="xliff"``。 + # 若不传 format,Crowdin 会按源文件扩展名返回;源文件若为 xlsx, + # 下游会收到一个 xlsx 包(内含 theme1.xml 等组件),错误挑成员 + # 后被 XliffSource 解析为 0 条 entries,导致 ``split_approved_data`` + # 返回 approved=0/pending=0,内存里的 ``ctx.entries`` 被错误清空。 + # + # ``skipUntranslatedStrings=False``:pending 条目也要出现在导出 + # 里,不然 ``split_approved_data`` 无法分组。 + response = self._request( + "POST", + f"/projects/{self._project_id()}/translations/exports", + json_body={ + "targetLanguageId": target_locale, + "fileIds": [int(file_id)] if file_id.isdigit() else [file_id], + "format": "xliff", + "skipUntranslatedStrings": False, + }, + ) + data = response.json().get("data", {}) + url = data.get("url") or "" + if not url: + raise PlatformError( + "CrowdinPlatform: translations/exports response missing data.url" + ) + + # 返回的 URL 为 S3 预签名链接,下载时**不能**带 Authorization 头。 + payload = self._download_binary(url) + + # Crowdin 的 translations/exports 即使只导出一个文件也会把它包进 + # zip 返回(魔数 ``PK\x03\x04``)。此处识别并解压出真实的翻译文件, + # 否则调用方按 UTF-8 解析 zip 字节流会立刻挂在 ``codec can't decode``。 + os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) + if payload[:4] == b"PK\x03\x04": + extracted = _unzip_single_translation(payload) + if extracted is None: + raise PlatformError( + "CrowdinPlatform: downloaded zip contains no translation file" + ) + with open(dest_path, "wb") as fh: + fh.write(extracted) + else: + with open(dest_path, "wb") as fh: + fh.write(payload) + return dest_path + + def _download_binary(self, url: str) -> bytes: + session = self._session() + try: + response = session.request( + "GET", url, timeout=self._timeout, stream=True, + ) + except Exception as exc: # noqa: BLE001 + raise PlatformError(f"CrowdinPlatform: download failed: {exc}") from exc + if response.status_code >= 400: + raise PlatformError( + f"CrowdinPlatform: download HTTP {response.status_code}" + ) + if hasattr(response, "iter_content"): + chunks: List[bytes] = [] + for chunk in response.iter_content(chunk_size=8192): + if chunk: + chunks.append(chunk) + return b"".join(chunks) + return getattr(response, "content", b"") + + def import_approved( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + # 先拿任务元信息拿到 fileIds 与 languageId,再复用 download_translations。 + info = self.get_task_status(task_id, review_stage=review_stage) + file_ids = info.extra.get("fileIds") or info.extra.get("file_ids") or [] + target_locale = info.target_locale + # 当汇总信息不足时回退重新拉取原始作为兵。 + if not file_ids: + response = self._request( + "GET", + f"/projects/{self._project_id()}/tasks/{task_id}", + ) + data = response.json().get("data", {}) + file_ids = data.get("fileIds") or [] + # Crowdin 响应用 targetLanguageId(见 crowdin_dual_platform_sync.md + # 第 260 行);languageId 作为降级兼容。 + target_locale = ( + target_locale + or str(data.get("targetLanguageId", "") or "") + or str(data.get("languageId", "") or "") + ) + if not file_ids: + raise PlatformError( + f"CrowdinPlatform: cannot resolve fileIds for task {task_id}" + ) + if not target_locale: + raise PlatformError( + f"CrowdinPlatform: cannot resolve target_locale for task {task_id} " + f"(response missing both 'targetLanguageId' and 'languageId')" + ) + return self.download_translations( + str(file_ids[0]), target_locale, dest_path, review_stage=review_stage, + ) + + def export_review_report( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + info = self.get_task_status(task_id, review_stage=review_stage) + os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) + with open(dest_path, "w", encoding="utf-8") as fh: + fh.write(f"# Crowdin review report — taskId={task_id}\n") + fh.write(f"stage={review_stage}\n") + fh.write(f"status={info.extra.get('raw_status', '')}\n") + fh.write(f"percent_completed={info.percent_completed}\n") + fh.write(f"target_locale={info.target_locale}\n") + fh.write(f"title={info.extra.get('title', '')}\n") + return dest_path + + def split_approved_data( + self, + task_id: str, + *, + save_approved_path: str, + save_pending_path: str = "", + review_stage: str = ReviewStage.FIRST.value, + ) -> SplitResult: + """按条目维度把 ``task_id`` 的译文拆成 **approved** 与 **pending** 两份本地文件。 + + 按条目维度把 ``task_id`` 的译文拆分成两份本地文件: + + 1. 调 :meth:`download_translations` 拿到 Crowdin 导出的 **xliff**; + 2. 解析每个 ```` 的 ``approved`` 属性——有值表示已审通过; + 3. 把 approved 对应 key 的条目物化成 ``save_approved_path`` 下的 xlsx; + 4. 其余 key 的条目物化成 ``save_pending_path`` 下的 xlsx(当该参数为空时跳过)。 + + 返回的 :class:`SplitResult`: + + * ``approved_path`` / ``pending_path``——两份 xlsx 的本地绝对路径(无内容时也会落空表); + * ``is_complete``——pending 为 0 时为 ``True``(整单审完); + * ``should_continue``——approved 有内容时为 ``True``(下游 merge 有数据可做); + * ``extra['approved_keys'] / extra['pending_keys']``——两组 key 列表, + 供工作流 state 直接按 key 拆分 ``ctx.entries``,免二次 I/O。 + """ + # 延迟导入避免 platforms 子包反向依赖 sources/workflow。 + from ..sources import XliffSource, XlsxSource # noqa: WPS433 + + # 1) 下载 xliff(import_approved 已经把 task → fileIds → export URL + # 这条链封装好;它写入的就是 xliff 二进制)。 + xliff_path = save_approved_path.rsplit(".", 1)[0] + ".source.xliff" + self.import_approved(task_id, xliff_path, review_stage=review_stage) + + # 2) 解析 xliff → entries(XliffSource 会把 trans-unit 上的 + # ``approved`` 属性填入 entry.metadata["approved"])。 + xliff_entries = XliffSource(encoding="utf-8").load(xliff_path) + + # 2.1 空数据保护:如果 xliff 解析出 0 条,一定是下载/格式出了问题 + # (正常情况下任务里有多少条字串、xliff 里就应有多少 trans-unit)。 + # 此时**不能**悄悄返回 approved=0/pending=0 让上游走"整单审完" + # 分支——那会把内存里的 ``ctx.entries`` 全部清空,造成"审核结果 + # 凭空消失"。显式抛错,runner 会保留 state_data(含 task_id), + # 下次运行时(不加 ``--fresh``)会复用同一个 task_id 续跑。 + if not xliff_entries: + raise PlatformError( + f"CrowdinPlatform.split_approved_data: parsed 0 entries from " + f"xliff {xliff_path!r} — the file is probably not a valid " + f"XLIFF (e.g. Crowdin returned the source xlsx package " + f"instead). Check the request body to /translations/exports " + f"includes format='xliff'. task_id={task_id}, " + f"xliff_size={os.path.getsize(xliff_path) if os.path.exists(xliff_path) else 'missing'}." + ) + + approved_entries = [] + pending_entries = [] + for entry in xliff_entries: + if entry.metadata.get("approved"): + approved_entries.append(entry) + else: + pending_entries.append(entry) + + is_complete = len(pending_entries) == 0 + + # 3) 落两份 xlsx(即使 pending 为 0 或 approved 为 0 也落空表, + # 保证下游"文件存在"的前置假设稳定)。 + os.makedirs(os.path.dirname(save_approved_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump(approved_entries, save_approved_path) + + pending_path_out = "" + if save_pending_path: + os.makedirs(os.path.dirname(save_pending_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump(pending_entries, save_pending_path) + pending_path_out = save_pending_path + + info = self.get_task_status(task_id, review_stage=review_stage) + logger.info( + "CrowdinPlatform: split task=%s approved=%d pending=%d " + "(is_complete=%s, raw_status=%s)", + task_id, len(approved_entries), len(pending_entries), + is_complete, info.extra.get("raw_status", ""), + ) + return SplitResult( + approved_path=save_approved_path, + pending_path=pending_path_out, + should_continue=len(approved_entries) > 0, + is_complete=is_complete, + extra={ + "raw_status": info.extra.get("raw_status", ""), + "approved_keys": [e.key for e in approved_entries], + "pending_keys": [e.key for e in pending_entries], + }, + ) + + def delete_task( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + self._request( + "DELETE", + f"/projects/{self._project_id()}/tasks/{task_id}", + ) + with self._lock: + self._tasks.pop(task_id, None) + + def delete_file( + self, + file_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + """``DELETE /projects/{pid}/files/{file_id}``。 + + Crowdin 返回 204 表示删除成功,404 代表远端文件已不存在(上一轮 + 已清理 / 用户手工删过),这两种情况都视为幂等成功。其他错误原样 + 往上抛,让调用方决定重试策略。 + """ + if not file_id: + return + try: + self._request( + "DELETE", + f"/projects/{self._project_id()}/files/{file_id}", + ) + except PlatformError as exc: + # 404 直接当作 "已删除"——保证流程幂等(例如上一轮已清、或 + # 测试环境下用户手工在 Crowdin UI 删过)。 + if "HTTP 404" in str(exc): + logger.info( + "CrowdinPlatform: file %s already absent on remote " + "(treating 404 as success).", + file_id, + ) + else: + raise + with self._lock: + self._files.pop(file_id, None) + logger.info("CrowdinPlatform: deleted file %s", file_id) + + def get_project_name(self, project_id: str = "") -> str: + pid = project_id or self.project_id + if not pid: + return "" + response = self._request("GET", f"/projects/{pid}") + data = response.json().get("data", {}) + return data.get("name") or str(pid) + + # ------------------------------------------------------------------ + # 文件类型推断 + # ------------------------------------------------------------------ + def _infer_file_type_and_options( + self, filename: str, + ) -> tuple[str, Optional[Dict[str, Any]]]: + """按扩展名推断 Crowdin ``file.type`` 和 ``importOptions``。 + + xlsx 场景下必须显式告诉 Crowdin 哪一列是 identifier / source / + translation / context,否则 Crowdin 收下文件但不解析出任何 + string,后续 create_task 会 400。 + + 用户可通过构造器 ``extra`` 覆盖本方法推断值: + + * ``extra['file_type']``——完全覆盖 ``file.type``; + * ``extra['import_options']``——完全覆盖 ``importOptions``; + * ``extra['xlsx_scheme']``——仅在 xlsx 场景下覆盖默认 scheme; + 常用场景:如果你的 xlsx 列顺序和框架不同,可传入 + ``{"identifier": 0, "sourcePhrase": 1, "translation": 2}`` 之类。 + """ + # 用户覆盖具有最高优先级。 + overridden_type = str(self.extra.get("file_type", "") or "") + overridden_opts = self.extra.get("import_options") + + ext = os.path.splitext(filename)[1].lower() + if ext == ".xlsx": + file_type = overridden_type or "xlsx" + if isinstance(overridden_opts, dict): + return file_type, dict(overridden_opts) + # 与 XlsxSource 的 5 列表头一一对应: + # 列 0 Key | 列 1 Source | 列 2 Target | 列 3 Context | 列 4 Comment + # + # Crowdin ``/projects/{id}/files`` 接口要求 + # ``importOptions.scheme`` **同时**声明 ``sourcePhrase`` 和 + # ``translation`` 两列——缺任何一个都会返回: + # HTTP 400 schemeInvalid: The file schema must include the + # "Source String" and "Translation" elements + # scheme 里声明 ``translation`` 并**不会**自动把该列作为"已有译文" + # 导入(那是 ``/projects/{id}/translations/{languageId}`` 接口的 + # 职责——见 :meth:`upload_translations`),scheme 只是 Crowdin + # 用来识别 xlsx 列结构的元信息。 + default_scheme = { + "identifier": 0, + "sourcePhrase": 1, + "translation": 2, + "context": 3, + } + scheme = self.extra.get("xlsx_scheme") + if not isinstance(scheme, dict): + scheme = default_scheme + import_options: Dict[str, Any] = { + "firstLineContainsHeader": True, + "scheme": dict(scheme), + } + return file_type, import_options + + if ext == ".csv": + file_type = overridden_type or "csv" + if isinstance(overridden_opts, dict): + return file_type, dict(overridden_opts) + return file_type, None + + # 对 json / xml / xliff 等,由 Crowdin 自动按扩展名识别。 + return overridden_type, (dict(overridden_opts) if isinstance(overridden_opts, dict) else None) + + # ------------------------------------------------------------------ + # 翻译记忆(TM)回灌 + # ------------------------------------------------------------------ + # 以下 4 个方法为**可选扩展**,不属于 :class:`TranslationPlatform` 基类的 + # 抽象 API——不同平台的 TM 支持能力不一致,state 代码通过 + # ``hasattr(platform, "upload_tm")`` 探测,有则走 TM 回灌,无则告警跳过。 + # 相关端点: + # * 拿项目默认 TM:GET /projects/{id} → data.defaultTmId + # * 清空 TM 片段 :DELETE /tms/{tm_id}/segments + # * 添加 storage :POST /storages (与 upload_source 共用) + # * 导入 TM 文件 :POST /tms/{tm_id}/imports + def get_project_default_tm_id(self) -> str: + """返回当前项目的默认 TM 库 ID。查不到返回空串,不抛异常。""" + try: + res = self._request( + "GET", f"/projects/{self._project_id()}", + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — TM 操作失败不致命 + logger.warning( + "CrowdinPlatform.get_project_default_tm_id: GET /projects/%s " + "failed: %s", self._project_id(), exc, + ) + return "" + data = res.json().get("data", {}) if res is not None else {} + tm_id = data.get("defaultTmId") or data.get("tmId") or "" + if not tm_id: + logger.warning( + "CrowdinPlatform.get_project_default_tm_id: project %s has no " + "defaultTmId configured", self._project_id(), + ) + return str(tm_id) + + def clear_tm_segments(self, tm_id: str) -> bool: + """清空指定 TM 库下的所有片段。成功返回 True,失败返回 False(不抛)。 + + 调 ``DELETE /tms/{tm_id}/segments``;预期 204。 + """ + if not tm_id: + return False + try: + self._request("DELETE", f"/tms/{tm_id}/segments") + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "CrowdinPlatform.clear_tm_segments: DELETE /tms/%s/segments " + "failed: %s", tm_id, exc, + ) + return False + logger.info("CrowdinPlatform: cleared TM segments for tm_id=%s", tm_id) + return True + + def _resolve_tm_source_locale(self, tm_id: str) -> str: + """从 TM 库本身的配置里拿**源语 locale**。 + + **为何不从项目取**:Crowdin TM 库和项目是**独立实体**,TM 库自己有 + ``languageId`` + ``languageIds`` 字段登记"这个库里存了哪些语种的 + 翻译",TM import 的 ``scheme`` 字段必须用 **TM 库登记的 locale 码** + (见 ``GET /tms/{id}`` 返回的 ``languageIds``),而不是项目的 + ``targetLanguages[].locale``——两者可能不一致(例如项目配置的 + ``vi-VN``,TM 库里登记的是 ``vi``)。 + + 实现方式: + + 1. ``GET /tms/{tm_id}`` 返回 ``data.languageId``(主源语); + 2. 取不到就回退到 ``"zh-CN"``(当前新项目的默认源语)。 + + 参数: + tm_id: TM 库 ID。 + + 返回: + 源语 locale 字符串(如 ``"zh-CN"``)。 + """ + default_source = "zh-CN" + if not tm_id: + return default_source + try: + res = self._request("GET", f"/tms/{tm_id}") + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "CrowdinPlatform._resolve_tm_source_locale: GET /tms/%s " + "failed: %s — fallback to %r", tm_id, exc, default_source, + ) + return default_source + data = res.json().get("data", {}) if res is not None else {} + src = str(data.get("languageId") or "").strip() + if not src: + logger.warning( + "CrowdinPlatform._resolve_tm_source_locale: TM %s has no " + "languageId — fallback to %r", tm_id, default_source, + ) + return default_source + logger.info( + "CrowdinPlatform._resolve_tm_source_locale: tm_id=%s source=%r", + tm_id, src, + ) + return src + + def upload_tm(self, tm_file_path: str, *, target_locale: str, tm_id: str = "") -> bool: + """把本地 TM xlsx 上传到 Crowdin 项目默认 TM 库(**先传后清**)。 + + 流程: + 1. 若 ``tm_id`` 为空,自动调用 :meth:`get_project_default_tm_id` 获取; + 2. 调用 :meth:`_resolve_tm_source_locale` 从 TM 库的 ``languageId`` + 字段取源语 locale(如 ``"zh-CN"``); + 3. ``POST /storages`` 上传 xlsx 文件体; + 4. ``POST /tms/{tm_id}/imports`` 触发 TM 导入; + 5. **import 成功**后再调 :meth:`clear_tm_segments` 清空旧片段。 + + **"先传后清"的意义**: + 若 import 失败(例如 scheme 校验失败),TM 会保持原样,而不是 + 留下清空后的空壳。Crowdin TM import 对同源同译对会 upsert, + 不会无限膨胀。 + + **scheme 字段约定**: + scheme 的 **key 必须严格使用 TM 库 ``languageIds`` 里登记的 + locale 码**(例如 ``{"zh-CN": 0, "vi": 1}``),不能用: + + - 字面占位符(``"sourcePhrase"``)→ 400 scheme not valid + - 项目的 ``targetLanguages[].locale``(``"vi-VN"``)→ 400 scheme not valid + - 任何 TM 库 ``languageIds`` 之外的 locale 码 → 400 + + value 是文件里的列号,列顺序对齐 :mod:`utils.tm_file_builder` + 实际写入格式:列 0 = 源语文本、列 1 = 目标语文本。 + + 参数: + tm_file_path: 由 :mod:`utils.tm_file_builder` 产出的两列 xlsx + (列 0 = 源语文本,列 1 = 目标语文本)。 + target_locale: Crowdin TM 库 ``languageIds`` 里登记的目标语 locale + 码(如 ``"vi"``)。调用方传入的就是项目 ``targetLanguageId``, + 和 TM 库登记码天然一致,这里**不做任何转换**。 + tm_id: 可选,直接指定 TM 库 ID;为空则取项目默认 TM。 + + 返回: + 全链路成功返回 True;任一步失败均返回 False 并记日志,不抛异常。 + """ + import os as _os + + if not _os.path.exists(tm_file_path): + logger.warning( + "CrowdinPlatform.upload_tm: file not found: %s", tm_file_path, + ) + return False + + tm_id = tm_id or self.get_project_default_tm_id() + if not tm_id: + return False + + # 从 TM 库自己的 languageId 取源语 locale(如 "zh-CN") + source_locale = self._resolve_tm_source_locale(tm_id) + + filename = _os.path.basename(tm_file_path) + header_safe_filename = _to_ascii_filename(filename) + + try: + with open(tm_file_path, "rb") as fh: + data = fh.read() + storage_response = self._request( + "POST", + "/storages", + raw_body=data, + extra_headers={"Crowdin-API-FileName": header_safe_filename}, + ) + storage_id = str(storage_response.json().get("data", {}).get("id", "")) + if not storage_id: + logger.warning( + "CrowdinPlatform.upload_tm: /storages response missing data.id", + ) + return False + + # scheme 字段:key 必须是 TM 库 languageIds 里登记的 locale 码。 + # - 源语 key = TM 库的 data.languageId(已由 _resolve_tm_source_locale 取好) + # - 目标语 key = 调用方传入的 target_locale(天然对齐 TM 库) + # 列号对齐 tm_file_builder 实际写入:列 0 = 源语、列 1 = 目标语。 + body: Dict[str, Any] = { + "storageId": int(storage_id), + "firstLineContainsHeader": True, + "scheme": { + source_locale: 0, + target_locale: 1, + }, + } + self._request( + "POST", + f"/tms/{tm_id}/imports", + json_body=body, + ) + # import 成功后才清空旧 segments(先传后清): + # 若 import 失败走到下面 except,这里不会执行——TM 保持原样。 + self.clear_tm_segments(tm_id) + logger.info( + "CrowdinPlatform.upload_tm: imported TM into tm_id=%s " + "(file=%s, scheme=%s→%s)", + tm_id, filename, source_locale, target_locale, + ) + return True + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — TM 回灌失败不阻塞主流程 + logger.warning( + "CrowdinPlatform.upload_tm: failed to import TM to tm_id=%s " + "(file=%s): %s", tm_id, filename, exc, + ) + return False + + +def _sleep(seconds: float) -> None: + import time as _time + _time.sleep(max(0.0, seconds)) + + +def _unzip_single_translation(payload: bytes) -> Optional[bytes]: + """从 Crowdin 导出的 zip payload 里抽出真实的翻译文件内容。 + + Crowdin 的 ``/translations/exports`` 下载是一个 zip 包;即使只有一个 + 文件也会被 zip 封装。本函数: + + * 只取 ``.xliff`` / ``.xlf`` 结尾的成员(我们在 + :meth:`CrowdinPlatform.download_translations` 显式传了 + ``format="xliff"``,所以 zip 里必然有且仅有 xliff 成员); + * 若 zip 里**没有**任何 ``.xliff`` 成员——通常意味着 Crowdin 把源文件 + 格式(xlsx 等)直接整包返回了(xlsx 本身就是 zip,内含 + ``theme1.xml`` / ``sharedStrings.xml`` 等组件)——**不要**回退到 + "挑第一个成员",那样会把 xlsx 的 Office Theme XML 当成 xliff, + 导致 :class:`XliffSource` 解析 0 条、下游 ``split_approved_data`` + 误判为"空审核"从而擦掉内存里的 ``ctx.entries``。直接返回 ``None`` + 让上游显式报错; + * 空压缩包同样返回 ``None``。 + """ + import io + import zipfile + + try: + zf = zipfile.ZipFile(io.BytesIO(payload)) + except zipfile.BadZipFile: + return None + + try: + members = [m for m in zf.namelist() if not m.endswith("/")] + if not members: + return None + xliff = next( + (m for m in members if m.lower().endswith((".xliff", ".xlf"))), + None, + ) + if xliff is None: + # 关键兜底:zip 里没有 xliff 成员——不再 fallback 到 members[0], + # 避免把 xlsx 内部组件(theme1.xml 等)错当翻译结果。 + logger.warning( + "CrowdinPlatform: downloaded zip contains no .xliff/.xlf " + "member (found %d members: %s). This usually means " + "/translations/exports did not include format='xliff' in the " + "request body — refusing to pick a random member.", + len(members), + members[:5], + ) + return None + return zf.read(xliff) + finally: + zf.close() + + +def _to_ascii_filename(filename: str) -> str: + """把一个可能含中文的文件名转为 ASCII-only 版本,保留扩展名。 + + 用途:Crowdin 的 ``Crowdin-API-FileName`` HTTP header 不接受非 ASCII + 字符(``requests`` 库默认用 latin-1 编码 header)。本函数策略: + + * 完整文件名已是 ASCII → 原样返回; + * 否则 stem/扩展名分别做 URL 百分号编码(``%E7%AC%AC...``); + Crowdin 服务器端会按百分号解码得到原始中文。 + """ + try: + filename.encode("latin-1") + return filename + except UnicodeEncodeError: + pass + + from urllib.parse import quote + + stem, dot, ext = filename.rpartition(".") + if not dot: + return quote(filename, safe="") + return f"{quote(stem, safe='')}.{quote(ext, safe='')}" + + +# --------------------------------------------------------------------------- +# 注册 +# --------------------------------------------------------------------------- +register_platform("crowdin", CrowdinPlatform) + + +__all__ = ["CrowdinPlatform"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..6785eda44779f313508840c6bca6de19f1b7ca54 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/factory.py @@ -0,0 +1,189 @@ +"""平台适配器的工厂与注册表。 + +提供两个入口: + +* :func:`create_platform`——从**全局** :class:`~TiMi_HOK_Game_Translator.config.PlatformConfig` + 构造平台,适合整个流水线使用单一平台的情形。 +* :func:`build_review_tool`——为 + :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile` 上的**某个审校阶段**构造平台; + ``FirstReviewState`` / ``SecondReviewState`` 之类工作流状态应调用它。 + +两个函数共享同一份由 :func:`register_platform` 填充的注册表。 +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, Optional, Type + +from ..commons import PlatformError, PlatformType, ReviewStage +from ..config.schema import LanguageProfile, PlatformConfig, ReviewConfig +from .base import TranslationPlatform +from .noop import NoopPlatform + +logger = logging.getLogger(__name__) + +_REGISTRY: Dict[str, Type[TranslationPlatform]] = { + PlatformType.NONE.value: NoopPlatform, +} + + +def register_platform(name: str, platform_cls: Type[TranslationPlatform]) -> None: + """以 ``name`` 为名注册自定义 :class:`TranslationPlatform` 实现。 + + 名称大小写不敏感(``"Phrase"`` 与 ``"phrase"`` 合并为同一个)。 + 允许重复注册,插件需要掩盖内置实现时很常见。 + """ + _REGISTRY[name.lower()] = platform_cls + + +def registered_platforms() -> list: + """返回当前已注册的平台名称列表(排序后)。""" + return sorted(_REGISTRY) + + +def create_platform(platform_config: PlatformConfig) -> TranslationPlatform: + """根据 ``platform_config`` 构造 :class:`TranslationPlatform`。 + + 异常: + PlatformError: ``type`` 未注册。 + """ + key = (platform_config.type or "").lower() + if key not in _REGISTRY: + raise PlatformError( + f"Unknown platform.type '{platform_config.type}'. " + f"Registered platforms: {registered_platforms()}. " + "Install the matching plugin (e.g. 'TiMi_HOK_Game_Translator[phrase]') " + "or set platform.type to 'none' to disable the integration." + ) + cls = _REGISTRY[key] + return cls( + api_base=platform_config.api_base, + api_token=platform_config.api_token, + project_id=platform_config.project_id, + extra=dict(platform_config.extra or {}), + ) + + +def build_review_tool( + profile: LanguageProfile, + review_stage: str = ReviewStage.FIRST.value, + *, + fallback: Optional[str] = None, + global_platform: Optional[PlatformConfig] = None, +) -> TranslationPlatform: + """为 ``profile`` 在 ``review_stage`` 上选择平台。 + + 解析顺序: + + 1. ``profile.reviews[review_stage]`` ——阶段级最具体的配置; + 2. 当其 ``platform`` 为空或 ``"none"`` 时,尝试 ``fallback`` 名称; + 3. 仍为空时回退到 ``global_platform``(顶层 :class:`PlatformConfig`); + 4. 均无时返回 :class:`NoopPlatform`,便于工作流状态判定“无需处理”而不报错。 + + 参数: + profile: 当前运行使用的语种 profile。 + review_stage: :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage` 之一( + ``"light"`` / ``"first"`` / ``"second"``)。 + fallback: 当阶段平台为 ``"none"`` 时的回退平台名,可选。 + global_platform: :attr:`Config.platform`,仅在 profile 级无配置时使用。 + + 返回: + 已初始化的 :class:`TranslationPlatform`。 + + 异常: + PlatformError: 解析出的平台名未注册。 + """ + review_cfg = profile.review(review_stage) if profile else ReviewConfig(stage=review_stage) + chosen: Optional[str] = None + source_of_config: Optional[ReviewConfig] = None + + if review_cfg.platform and review_cfg.platform != PlatformType.NONE.value: + chosen = review_cfg.platform + source_of_config = review_cfg + elif fallback: + chosen = fallback + source_of_config = review_cfg + elif global_platform and global_platform.type and global_platform.type != PlatformType.NONE.value: + chosen = global_platform.type + + if chosen is None: + chosen = PlatformType.NONE.value + + key = chosen.lower() + if key not in _REGISTRY: + raise PlatformError( + f"Unknown review platform '{chosen}' for stage {review_stage!r} " + f"on language {profile.id!r}. Registered: {registered_platforms()}." + ) + + cls = _REGISTRY[key] + + # 优先使用阶段级凭据;为空时回退到全局配置。 + api_base = "" + api_token = "" + project_id = "" + extra: Dict[str, Any] = {} + + if source_of_config is not None: + api_base = source_of_config.api_base + api_token = source_of_config.api_token + project_id = source_of_config.project_id + extra = dict(source_of_config.extra or {}) + # 透传 ReviewConfig.target_language_id —— 平台适配器(如 PhrasePlatform + # 需要在 Memsource 头的 ``targetLangs`` 字段里带目标语种)通过 + # ``extra["target_language_id"]`` 读到它。其他未读此键的平台不受影响。 + if source_of_config.target_language_id: + extra.setdefault("target_language_id", source_of_config.target_language_id) + + if global_platform is not None: + # ⚠️ 跨平台类型保护(针对**强绑定**字段): + # ``api_base`` / ``api_token`` / ``project_id`` 强绑定具体平台 —— 若 + # 全局 ``platform.type`` 与当前阶段选中平台不一致,就不能回退,否则 + # 会出现"Phrase 用了 Crowdin 的 api_base"这种污染(请求打到对方 + # nginx,直接 ``404 {"error":{"message":"Not Found","code":404}}``)。 + if (global_platform.type or "").lower() == key: + api_base = api_base or global_platform.api_base + api_token = api_token or global_platform.api_token + project_id = project_id or global_platform.project_id + else: + logger.debug( + "[REVIEW_TOOL_FACTORY] skipping global api_base/api_token/" + "project_id fallback: global.type=%r != stage.platform=%r " + "(would cross-contaminate endpoint).", + global_platform.type, chosen, + ) + # ``extra`` 字典按原方式 setdefault 透传,不做类型隔离 —— 因为 extra + # 里的键都是**平台特定**的(Phrase 读 ``subject_token``/``region``; + # Crowdin 读 ``base_url``/``organization`` 等),各平台只读自己认识 + # 的键,互不干扰;而且用户经常把令牌通过环境变量注入**全局** + # ``platform.extra`` 块(如 ``GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN`` + # → ``platform.extra.subject_token``),不透传反而破坏这个约定。 + for k, v in (global_platform.extra or {}).items(): + extra.setdefault(k, v) + + instance = cls( + api_base=api_base, + api_token=api_token, + project_id=project_id, + extra=extra, + ) + if not instance.supports(review_stage): + raise PlatformError( + f"Platform {chosen!r} does not support review_stage={review_stage!r}. " + f"Supported stages: {instance.supports_stages}." + ) + + logger.info( + "[REVIEW_TOOL_FACTORY] language=%s stage=%s platform=%s project=%s", + profile.id, review_stage, chosen, project_id, + ) + return instance + + +__all__ = [ + "build_review_tool", + "create_platform", + "register_platform", + "registered_platforms", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/noop.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/noop.py new file mode 100644 index 0000000000000000000000000000000000000000..c2590d3806f2292654d8d4e1e092542c7b4b7b46 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/noop.py @@ -0,0 +1,161 @@ +"""空实现的平台适配器。 + +当 :data:`config.platform.type` 为 ``"none"`` 时默认选用。所有操作要么返回循环内存记录, +要么将源文件拷贝到本地,保证工作流无网络依赖即可运行。 +""" + +from __future__ import annotations + +import itertools +import shutil +from pathlib import Path +from typing import Sequence + +from ..commons import ReviewStage +from .base import ( + SplitResult, + TaskInfo, + TaskStatus, + TranslationPlatform, + UploadResult, +) + + +class NoopPlatform(TranslationPlatform): + """:class:`TranslationPlatform` 的空实现。 + + 支持全部审校阶段(``supports_stages`` 保持为空)。所有操作均即时 + 返回确定性的内存记录,便于在完全无外部服务的情形下运行工作流。 + """ + + platform_name = "none" + + def __init__(self, **kwargs: object) -> None: + super().__init__(**kwargs) # type: ignore[arg-type] + self._counter = itertools.count(start=1) + self._files: dict = {} + self._tasks: dict = {} + + # ------------------------------------------------------------------ + def upload_source(self, file_path: str, *, remote_path: str = "") -> UploadResult: + file_id = f"noop-{next(self._counter)}" + self._files[file_id] = file_path + return UploadResult(file_id=file_id, revision="1", extra={"remote_path": remote_path}) + + def download_translations( + self, + file_id: str, + target_locale: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + source = self._files.get(file_id) + if not source: + raise KeyError(f"Unknown file_id in NoopPlatform: {file_id}") + dest = Path(dest_path) + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, dest) + return str(dest) + + def create_task( + self, + file_ids: Sequence[str], + target_locale: str, + *, + review_stage: str = ReviewStage.FIRST.value, + title: str = "", + description: str = "", + ) -> TaskInfo: + task_id = f"noop-task-{next(self._counter)}" + info = TaskInfo( + task_id=task_id, + status=TaskStatus.APPROVED, # 无需审校——总是直接“完成”。 + target_locale=target_locale, + project_id=self.project_id, + review_stage=review_stage, + percent_completed=100.0, + extra={ + "file_ids": list(file_ids), + "title": title, + "description": description, + }, + ) + self._tasks[task_id] = info + return info + + def get_task_status( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> TaskInfo: + info = self._tasks.get(task_id) + if info is None: + return TaskInfo( + task_id=task_id, + status=TaskStatus.UNKNOWN, + review_stage=review_stage, + ) + return info + + def import_approved( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + # 无实际内容导入,仅创建一个空占位文件。 + dest = Path(dest_path) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text("", encoding="utf-8") + return str(dest) + + def export_review_report( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + dest = Path(dest_path) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text( + f"NoopPlatform review report for {task_id} (stage={review_stage})\n", + encoding="utf-8", + ) + return str(dest) + + # ------------------------------------------------------------------ + # 扩展 API——重写以保证已批准/待处理拆分一致。 + # ------------------------------------------------------------------ + def split_approved_data( + self, + task_id: str, + *, + save_approved_path: str, + save_pending_path: str = "", + review_stage: str = ReviewStage.FIRST.value, + ) -> SplitResult: + self.import_approved(task_id, save_approved_path, review_stage=review_stage) + if save_pending_path: + Path(save_pending_path).parent.mkdir(parents=True, exist_ok=True) + Path(save_pending_path).write_text("", encoding="utf-8") + return SplitResult( + approved_path=save_approved_path, + pending_path=save_pending_path, + should_continue=True, + is_complete=True, + ) + + def delete_task( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + self._tasks.pop(task_id, None) + + +__all__ = ["NoopPlatform"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/phrase_platform.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/phrase_platform.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf4d740a88601df57d9006ff8ff2065435e4230 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/platforms/phrase_platform.py @@ -0,0 +1,1938 @@ +"""Phrase TMS(旧名 Memsource)翻译平台适配器。 + +基于 **Phrase TMS REST API**(旧称 "Memsource API v1/v2")实现 +:class:`~TiMi_HOK_Game_Translator.platforms.TranslationPlatform` 契约。 + +参考文档: + +* Overview — https://developers.phrase.com/en/api/overview +* TMS 参考 — https://developers.phrase.com/en/api/tms/latest/introduction +* Platform IDM 令牌交换 — + https://developers.phrase.com/en/api/platform/authentication + +鉴权方式 +-------- +支持三种方式,优先级从高到低: + +1. **Subject Token Exchange**(⭐ 推荐,官方 2024+ 新流程)—— + 在 ``extra["subject_token"]`` 传入从 Phrase UI *Settings → API tokens → Generate token* + 屏复制的 token。适配器会通过 + ``POST https://.phrase.com/idm/oauth/token``(grant type + ``urn:ietf:params:oauth:grant-type:token-exchange``)将它交换为短时 Bearer, + 缓存在内存中,并在过期前约 60 秒自动刷新。后续请求会携带 + ``Authorization: Bearer ``。 +2. **旧式 ApiToken**——直接传入 ``api_token``。适配器发送 + ``Authorization: ApiToken ``,用于兼容早期 Phrase / Memsource 部署。 +3. **用户名 + 密码**——在 ``extra["username"]`` / ``extra["password"]`` 传入, + 首次需鉴权时适配器自动调用 + ``POST /web/api2/v3/auth/login``(旧租户回退 ``/v1/auth/login``)获取 + 24 小时 ApiToken。适用于禁用 SSO / 不能新建 API token 的情景。 + +使用的接口 +------------ +============================================== ================================================================== +用途 接口(相对于 ``api_base``) +============================================== ================================================================== +IDM 令牌交换(方式 1) ``POST /idm/oauth/token`` +登录(方式 3,首选) ``POST /web/api2/v3/auth/login`` +登录(方式 3,回退) ``POST /web/api2/v1/auth/login`` +当前身份 ``GET /web/api2/v1/auth/whoAmI`` +获取项目 ``GET /web/api2/v1/projects/{projectUid}`` +上传 Job(源文件) ``POST /web/api2/v1/projects/{projectUid}/jobs`` +获取 Job ``GET /web/api2/v1/projects/{projectUid}/jobs/{jobUid}`` +下载双语/目标文件 ``GET /web/api2/v1/projects/{projectUid}/jobs/{jobUid}/targetFile`` +修改 Job 状态 ``POST /web/api2/v1/projects/{projectUid}/jobs/setStatus`` +============================================== ================================================================== + +敏感字段 +-------- +适配器不会将 ``api_token`` / ``password`` 写入日志。当外层 +:class:`~TiMi_HOK_Game_Translator.config.Config` 通过 +:meth:`~TiMi_HOK_Game_Translator.config.Config.to_dict` 导出时,这些字段会被 +通用敏感字段逻辑脱敏(参见 +:data:`TiMi_HOK_Game_Translator.commons.SENSITIVE_FIELD_MARKERS`)。 +""" + +from __future__ import annotations + +import json +import logging +import os +import re +import threading +from typing import Any, Callable, Dict, Optional, Sequence + +from ..commons import ( + DEFAULT_HTTP_RETRIES, + DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + DEFAULT_HTTP_TIMEOUT_SECONDS, + PlatformError, + ReviewStage, +) +from .base import ( + SplitResult, + TaskInfo, + TaskStatus, + TranslationPlatform, + UploadResult, +) +from .factory import register_platform + +logger = logging.getLogger(__name__) + +_DEFAULT_API_BASE = "https://cloud.memsource.com/web/api2" + +# --- Phrase Platform IDM(Token Exchange) ------------------------------------- +# 参考:https://developers.phrase.com/en/api/platform/authentication +_TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" +# 在 ``exp`` 前提前多少秒刷新——小预量,避免请求到达服务器时令牌刚好过期。 +_TOKEN_EXPIRY_SKEW_SECONDS = 60.0 + +# Region → (IDM base, TMS API base):IDM 位于 ``.phrase.com``,而 TMS REST API +# 仍使用 ``cloud.memsource.com``(EU/US 共用,区域由 Bearer 的 ``aud`` / tenant claim 控制)。 +_REGION_BASES: Dict[str, Dict[str, str]] = { + "eu": { + "idm": "https://eu.phrase.com", + "api": "https://cloud.memsource.com/web/api2", + }, + "us": { + "idm": "https://us.phrase.com", + "api": "https://cloud.memsource.com/web/api2", + }, +} + +# --------------------------------------------------------------------------- +# Phrase ↔ 框架的映射辅助 +# --------------------------------------------------------------------------- +# Phrase Job 工作流级别状态(参考 TMS OpenAPI 中的 JobPartStatusDto)。 +_STATUS_MAP: Dict[str, TaskStatus] = { + "NEW": TaskStatus.PENDING, + "EMAILED": TaskStatus.PENDING, + "ASSIGNED": TaskStatus.IN_PROGRESS, + "DECLINED_BY_LINGUIST": TaskStatus.REJECTED, + "COMPLETED_BY_LINGUIST": TaskStatus.IN_PROGRESS, + "COMPLETED": TaskStatus.APPROVED, + "ACCEPTED_BY_LINGUIST": TaskStatus.IN_PROGRESS, + "CANCELLED": TaskStatus.REJECTED, + "REJECTED": TaskStatus.REJECTED, + "DELIVERED": TaskStatus.APPROVED, +} + + +def _map_status(remote: str) -> TaskStatus: + """将 Phrase 状态字符串映射为 :class:`TaskStatus`。""" + if not remote: + return TaskStatus.UNKNOWN + return _STATUS_MAP.get(remote.upper(), TaskStatus.UNKNOWN) + +def _extract_percent(data: Dict[str, Any]) -> float: # noqa: E302 + """从 Phrase job 响应里提取"完成百分比",兼容多种响应形态。 + + 已知形态: + * **新版 TMS**:顶层 ``workflowLevel`` 直接是 int(如 ``1``), + ``providers`` / ``status`` 另行表达进度;百分比字段不存在。 + * **旧版 TMS / 某些 workflow 项目**:``workflowLevel`` 为 dict, + 内含 ``percentageCompleted`` 浮点字段。 + * **若干 fallback 顶层字段**:``percentageCompleted`` / + ``progressPercentage``——存在时直接读。 + + 任何解析失败都返回 ``0.0``,让轮询器据此继续等。 + """ + # 顶层直接给百分比的 fallback + for key in ("percentageCompleted", "progressPercentage"): + val = data.get(key) + if isinstance(val, (int, float)): + return float(val) + if isinstance(val, str): + try: + return float(val) + except (TypeError, ValueError): + pass + # workflowLevel 旧结构 { "percentageCompleted": X } + workflow_level = data.get("workflowLevel") + if isinstance(workflow_level, dict): + val = workflow_level.get("percentageCompleted") + if isinstance(val, (int, float)): + return float(val) + if isinstance(val, str): + try: + return float(val) + except (TypeError, ValueError): + return 0.0 + return 0.0 + + +# --------------------------------------------------------------------------- +# 适配器主体 +# --------------------------------------------------------------------------- +class PhrasePlatform(TranslationPlatform): + """Phrase TMS 适配器——支持 一审/二审/轻度审校 三个阶段。 + + 构造参数(均为关键字参数): + + * ``api_base``——Phrase TMS API 基地址。默认为 + ``https://cloud.memsource.com/web/api2``(EU / US 两个租户共用, + 区域由令牌本身控制,而非 DNS);区域化/私部部署需改写。 + * ``api_token``——旧式长效 API token,提供时直接发送 + ``Authorization: ApiToken ``。 + * ``project_id``——Phrase 项目 UID。 + * ``extra``——自由字段,已识别的 key: + + * ``subject_token``——从 Phrase UI 复制的 API token(*Settings → + API tokens → Generate token*)。提供后适配器会自动向 + ``/idm/oauth/token`` 交换为短时 Bearer,并在 + 过期前自动刷新。 + * ``region``——``"eu"``(默认)或 ``"us"``;当仅提供 + ``subject_token`` 时,用于选择 IDM 主机。显式传入 ``idm_base`` 时忽略。 + * ``idm_base``——覆盖 IDM 主机(如 ``"https://eu.phrase.com"``), + 仅令牌交换时需要。 + * ``username`` / ``password``——旧式流程回退凭据;上述两者均未提供时, + 将通过 ``/auth/login`` 获取 24 小时 ApiToken。 + * ``user_uid``——同一用户名属于多个 TMS company 时必填, + 它会作为 ``userUid`` 发到登录接口。 + * ``workflow_step_uid``——将新建 Job 固定到某个工作流步。 + * ``timeout_seconds`` / ``retries`` / ``retry_interval_seconds``—— + HTTP 可调参数(默认值见 :mod:`TiMi_HOK_Game_Translator.commons.constants`)。 + * ``session_factory``——高级选项,可传入一个返回预配好的 + ``requests.Session`` 的工厂,供测试避免全局 patch ``requests``。 + * ``clock``——高级选项,可传入无参返回 UNIX 时间戳的可调用对象, + 供测试确定性地推进时间。 + + 本适配器线程安全::attr:`_token_lock` 将令牌刷新串行化,但在令牌已缓存后 + 允许并发发起 HTTP 请求。 + """ + + platform_name = "phrase" + supports_stages = ( + ReviewStage.FIRST.value, + ReviewStage.SECOND.value, + ReviewStage.LIGHT.value, + ) + + def __init__( + self, + *, + api_base: str = "", + api_token: str = "", + project_id: str = "", + extra: Optional[Dict[str, Any]] = None, + ) -> None: + merged_extra = dict(extra or {}) + + # --- 区域与基地址选择 ------------------------------------- + # 区域默认 ``eu``(Phrase 官方入口现在默认新建于 EU);US 租户需显式传入 + # ``extra["region"] = "us"``。 + region = str(merged_extra.get("region", "eu") or "eu").lower() + if region not in _REGION_BASES: + raise PlatformError( + f"PhrasePlatform: unknown region {region!r} — expected 'eu' or 'us'." + ) + region_bases = _REGION_BASES[region] + + super().__init__( + api_base=api_base or region_bases["api"], + api_token=api_token, + project_id=project_id, + extra=merged_extra, + ) + self.api_base = self.api_base.rstrip("/") + + self._region: str = region + self._idm_base: str = str( + merged_extra.get("idm_base") or region_bases["idm"] + ).rstrip("/") + + # 令牌交换模式(模块 docstring 中的方式 1)。 + self._subject_token: str = str(merged_extra.get("subject_token", "") or "") + # 当前 Bearer 失效的 UNIX 时间戳;0.0 代表“尚未缓存”。 + self._bearer_expires_at: float = 0.0 + + # 旧式用户名密码模式(模式 3)。 + self._username: str = str(merged_extra.get("username", "")) + self._password: str = str(merged_extra.get("password", "")) + self._workflow_step_uid: str = str(merged_extra.get("workflow_step_uid", "")) + + # 目标语种 locale——Phrase 上传 job 时 Memsource 头的 ``targetLangs`` + # 必须非空,否则服务器直接 404(Spring 兜底,连 Phrase 应用层都进不去)。 + # 工厂 ``build_review_tool`` 当前未把 ``ReviewConfig.target_language_id`` + # 透传成实例属性,因此在构造时从 extra 兜底读取,优先级: + # 1. extra["target_language_id"](ReviewConfig 的字段名;见 schema.py) + # 2. extra["target_locale"](通用别名) + # 3. 空串——留给调用方后续通过 ``instance.target_locale = ...`` 覆盖 + self._target_locale: str = str( + merged_extra.get("target_language_id") + or merged_extra.get("target_locale") + or "" + ) + + # 【方案 🅒】Phrase 的默认 XLSX import 解析器不认识本项目固定的 5 列 + # 格式(Key/Source/Target/Context/Comment),导致 wordsCount=0, segments=[],UI 显示 + # “The job has no segments”。解决方案:**首次 upload 前延迟创建**一个 + # multilingual_xls 类型的 ImportSettings,并在 upload 的 Memsource 头里通过 + # ``importSettings.uid`` 引用它。 + # * 缓存到实例字段 → 单次 PhrasePlatform 实例生命周期内只建一次,后续 + # upload 按 uid 复用;不做跨 run 持久化(ImportSettings 对象在 Phrase 侧 + # 是全组织级别的,没理由污染它,每次 run 重建最干净)。 + # * 设为 ``None`` 表示未尝试创建;设为空串 ``""`` 表示尝试过但失败 + # (此时 upload 降级为不带 importSettings,走 Phrase 默认解析——虽然解析不 + # 出 segments,但至少不让整个流水线崩)。 + self._import_settings_uid: Optional[str] = None + + # —— 诊断日志(排障用,默认 DEBUG 级别;流水线稳定后仅在 ``logging.level=DEBUG`` + # 时打印):构造时拿到的凭据/配置状态。 + logger.debug( + "[PhraseDBG-INIT] project_id=%r api_base=%r api_token_len=%d " + "subject_token_len=%d region=%r target_locale=%r " + "extra_keys=%s", + project_id, self.api_base, len(self.api_token or ""), + len(self._subject_token or ""), self._region, + self._target_locale, sorted(list(merged_extra.keys())), + ) + + self._timeout: float = float( + merged_extra.get("timeout_seconds", DEFAULT_HTTP_TIMEOUT_SECONDS) + ) + self._retries: int = int(merged_extra.get("retries", DEFAULT_HTTP_RETRIES)) + self._retry_interval: float = float( + merged_extra.get( + "retry_interval_seconds", DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + ) + ) + + session_factory: Optional[Callable[[], Any]] = merged_extra.get( + "session_factory" + ) + self._session_factory: Optional[Callable[[], Any]] = ( + session_factory if callable(session_factory) else None + ) + clock: Optional[Callable[[], float]] = merged_extra.get("clock") + self._clock: Callable[[], float] = clock if callable(clock) else _now + + self._token_lock = threading.RLock() + # 本地缓存:创建过的 job 信息,供 :meth:`download_translations` 直接 + # 从 file_id 将 jobUid 解出来,无需额外请求。 + self._jobs: Dict[str, Dict[str, str]] = {} + + # ------------------------------------------------------------------ + # HTTP 工作基础 + # ------------------------------------------------------------------ + def _session(self): + """返回一个全新或用户自定义的 ``requests.Session``。 + + 避免全局导入 ``requests``,保证在无 HTTP 库环境下也能引用本模块。 + """ + if self._session_factory is not None: + return self._session_factory() + try: + import requests # noqa: WPS433 — 故意局部导入 + except ImportError as exc: # pragma: no cover — 安装时已硬依赖 + raise PlatformError( + "PhrasePlatform requires 'requests'. Install with " + "`pip install requests`." + ) from exc + return requests.Session() + + def _authenticate(self, session) -> None: + """保证 :attr:`api_token` 已填充且未过期。 + + 根据提供的凭据选择不同模式: + + 1. **Subject Token Exchange**——存在 ``extra["subject_token"]`` 时, + 通过 ``/idm/oauth/token`` 交换为 Bearer, + 缓存至过期前约 60 秒。 + 2. **静态 ApiToken**——已提供 ``api_token`` 且无子 token 时直接使用。 + 3. **用户名 + 密码**——均未提供时回退到 ``/auth/login`` 拿 24 小时 ApiToken。 + """ + with self._token_lock: + # 模式 1:使用 subject_token 交换令牌,并在过期前自动刷新。 + if self._subject_token: + now = self._clock() + if ( + self.api_token + and self._bearer_expires_at + and now < self._bearer_expires_at - _TOKEN_EXPIRY_SKEW_SECONDS + ): + return + self._exchange_subject_token(session) + return + + # 模式 2:调用方预先提供了静态 ApiToken。 + if self.api_token: + return + + # 模式 3:用户名 + 密码 → 24 小时 ApiToken。 + if not (self._username and self._password): + raise PlatformError( + "PhrasePlatform: no credentials configured. Set one of " + "extra.subject_token / api_token / (extra.username + " + "extra.password)." + ) + self._login_with_password(session) + + def _exchange_subject_token(self, session) -> None: + """将 ``subject_token`` 交换为 Bearer access token。 + + 采用 RFC 8693 OAuth 2.0 Token Exchange,请求 Phrase Platform IDM。 + 必须在 :attr:`_token_lock` 保护下调用。 + """ + url = f"{self._idm_base}/idm/oauth/token" + try: + response = session.post( + url, + data={ + "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE, + "subject_token": self._subject_token, + }, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + timeout=self._timeout, + ) + except Exception as exc: # noqa: BLE001 — 传输层失败 + raise PlatformError( + f"PhrasePlatform: IDM token exchange transport error: {exc}" + ) from exc + self._raise_for_status(response, "idm/oauth/token") + + data = response.json() + access_token = data.get("access_token") or "" + if not access_token: + raise PlatformError( + "PhrasePlatform: IDM response missing 'access_token'." + ) + expires_in = float(data.get("expires_in", 0.0) or 0.0) + # ``expires_in`` 一般总存在,但若服务器未返回则回退 3600,以保证仍会刷新。 + if expires_in <= 0.0: + expires_in = 3600.0 + self.api_token = access_token + self._bearer_expires_at = self._clock() + expires_in + logger.info( + "PhrasePlatform: exchanged subject token for Bearer via %s " + "(expires in %.0fs)", + url, expires_in, + ) + + def _login_with_password(self, session) -> None: + """将用户名 + 密码换取 24 小时 ApiToken。 + + 遵循官方推荐的新接口 ``POST /web/api2/v3/auth/login``, + 未迁移的旧租户回退到 ``/v1/auth/login``。必须在 :attr:`_token_lock` 下调用。 + + 当同一用户名属于多个 TMS company 时需传 ``extra["user_uid"]``, + 它会作为 ``userUid`` 提交。 + """ + payload: Dict[str, Any] = { + "userName": self._username, + "password": self._password, + } + user_uid = str(self.extra.get("user_uid", "") or "") + if user_uid: + payload["userUid"] = user_uid + + last_error: Optional[Exception] = None + for path in ("/v3/auth/login", "/v1/auth/login"): + try: + response = session.post( + f"{self.api_base}{path}", + json=payload, + timeout=self._timeout, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 传输层失败 + last_error = exc + continue + if response.status_code == 404: + # 当前租户未提供该接口,尝试下一个。 + last_error = PlatformError( + f"PhrasePlatform: {path} returned 404 " + "(tenant does not expose it)." + ) + continue + self._raise_for_status(response, path) + data = response.json() + token = data.get("token") or "" + if not token: + raise PlatformError( + f"PhrasePlatform: {path} response missing 'token'." + ) + self.api_token = token + # Phrase 保证本模式下令牌有15天/24小时有效期。 + self._bearer_expires_at = 0.0 + logger.info( + "PhrasePlatform: acquired 24-hour ApiToken via %s", path, + ) + return + + # 两个接口都失败。 + if last_error is not None: + raise PlatformError( + f"PhrasePlatform: auth/login failed on all endpoints: " + f"{last_error}" + ) from last_error + raise PlatformError( + "PhrasePlatform: auth/login failed on all endpoints." + ) + + def _headers(self) -> Dict[str, str]: + """构造当前模式对应的 ``Authorization`` 头。 + + * Subject-Token-Exchange 模式 → ``Bearer `` + * ApiToken / 密码模式 → ``ApiToken `` + """ + scheme = "Bearer" if self._subject_token else "ApiToken" + return { + "Authorization": f"{scheme} {self.api_token}", + "Accept": "application/json", + } + + def _request( + self, + method: str, + path: str, + *, + params: Optional[Dict[str, Any]] = None, + json_body: Optional[Any] = None, + files: Optional[Any] = None, + data: Optional[Any] = None, + stream: bool = False, + extra_headers: Optional[Dict[str, str]] = None, + ): + """发送带鉴权的 HTTP 请求,按需重试。""" + session = self._session() + self._authenticate(session) + + url = f"{self.api_base}{path}" + headers = self._headers() + if extra_headers: + headers.update(extra_headers) + + # requests 会将超时/连接重置抛为异常;重试在本处包裹。 + last_exc: Optional[BaseException] = None + for attempt in range(1, self._retries + 1): + try: + # —— 诊断日志(排障用,默认 DEBUG):请求全貌 —— + _safe_headers = { + k: (v if k not in ("Authorization",) else f"<{v.split(' ', 1)[0]} ...masked>") + for k, v in headers.items() + } + _body_hint = ( + f"data_bytes={len(data) if isinstance(data, (bytes, bytearray)) else type(data).__name__}" + if data is not None else + f"files={list(files.keys()) if isinstance(files, dict) else files}" if files is not None else + f"json_keys={list(json_body.keys()) if isinstance(json_body, dict) else json_body}" + ) + logger.debug( + "[PhraseDBG] %s %s | headers=%s | %s | params=%s", + method.upper(), url, _safe_headers, _body_hint, params, + ) + response = session.request( + method.upper(), + url, + params=params, + json=json_body, + files=files, + data=data, + headers=headers, + timeout=self._timeout, + stream=stream, + ) + # —— 诊断日志(排障用,默认 DEBUG):响应关键头 —— + _rh = response.headers + logger.debug( + "[PhraseDBG] <- HTTP %s | server=%r | content-type=%r | x-request-id=%r | body_preview=%r", + response.status_code, + _rh.get("Server") or _rh.get("server"), + _rh.get("Content-Type") or _rh.get("content-type"), + _rh.get("X-Request-Id") or _rh.get("x-request-id"), + (getattr(response, "text", "") or "")[:300], + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 任何传输错误都需重试 + last_exc = exc + logger.warning( + "PhrasePlatform: %s %s failed on attempt %d/%d: %s", + method, path, attempt, self._retries, exc, + ) + if attempt >= self._retries: + break + _sleep(self._retry_interval) + continue + + # 已持有令牌但回 401——可能已过期。强制重新鉴权一次,但仅当已有 + # 可自动刷新的模式(subject_token 或密码)时才重试。 + can_refresh = bool(self._subject_token or (self._username and self._password)) + if response.status_code == 401 and can_refresh and attempt == 1: + logger.info( + "PhrasePlatform: 401 on %s %s — re-authenticating", method, path, + ) + with self._token_lock: + self.api_token = "" + self._bearer_expires_at = 0.0 + self._authenticate(session) + headers = self._headers() + if extra_headers: + headers.update(extra_headers) + continue + + # 5xx / 429 重试,其他直接返回。 + if response.status_code >= 500 or response.status_code == 429: + logger.warning( + "PhrasePlatform: %s %s got HTTP %d (attempt %d/%d)", + method, path, response.status_code, attempt, self._retries, + ) + if attempt >= self._retries: + self._raise_for_status(response, path) + _sleep(self._retry_interval) + continue + + self._raise_for_status(response, path) + return response + + if last_exc is not None: + raise PlatformError( + f"PhrasePlatform: exhausted {self._retries} retries for {method} {path}: {last_exc}" + ) from last_exc + raise PlatformError( + f"PhrasePlatform: exhausted {self._retries} retries for {method} {path}" + ) + + @staticmethod + def _raise_for_status(response, path: str) -> None: + """当 ``response`` 报错时抛出 :class:`PlatformError`。""" + if 200 <= response.status_code < 300: + return + # 保留错误主体以便排查,但不写入任何令牌。 + body: Any = "" + try: + body = response.json() + except Exception: # pylint: disable=broad-except # noqa: BLE001 — 主体未必是 JSON + body = getattr(response, "text", "") + raise PlatformError( + f"PhrasePlatform: {path} → HTTP {response.status_code}: {body!r}" + ) + + # ------------------------------------------------------------------ + # 适配器 API + # ------------------------------------------------------------------ + def _project_uid(self) -> str: + if not self.project_id: + raise PlatformError( + "PhrasePlatform: project_id is empty; set it on the ReviewConfig " + "or global platform config." + ) + return self.project_id + + def _ensure_import_settings(self, target_locale: str) -> str: + """按需创建一个 multilingual-XLSX 的 ImportSettings 对象,返回 uid。 + + **为什么需要**:Phrase 的默认 XLSX import 解析器不识别本项目固定的 + 5 列格式(``Key | Source | Target | Context | Comment``),直接 upload + 会导致 ``wordsCount=0, segments=[]``,UI 显示 "The job has no segments + and cannot be accessed. Job is empty"。按 Phrase 官方 + ``POST /api2/v1/importSettings`` 的 ``MultilingualXlsSettingsDtoV1`` + schema 构造 ImportSettings,让 Phrase 按本框架 XLSX 的列映射把它正确 + 解析成 segments。 + + **列映射**(和 :class:`XlsxSource` 的 ``_HEADERS`` 对齐):: + + A = Key → contextKeyColumn(上下文 key) + B = Source → sourceColumn + C = Target → targetColumns[target_locale] + D = Context → contextNoteColumn(上下文备注) + E = Comment → 本次不传给 Phrase(Phrase 没对应字段) + + **复用策略**(2025+ 优化):ImportSettings 在 Phrase 侧是**账号级** + 对象(不是项目级),重复 POST 会**无限累积**同名垃圾。本方法改为: + 1. 先 ``GET /v1/importSettings`` 列表按 ``name == settings_name`` + 查找已存在的,有则直接复用其 ``uid``; + 2. 没有再 POST 新建。 + 这样一个账号 × 一个 target_locale 对应至多一个 ImportSettings,流水线 + 重跑不会污染账号。 + + **缓存策略**:PhrasePlatform 实例生命周期内只查/建一次(``self. + _import_settings_uid`` 缓存)。 + + **降级**:若查询/创建失败(权限、网络等),记空串,upload 退回不带 + ``importSettings`` 的模式。 + """ + if self._import_settings_uid is not None: + # 已尝试过(成功 → 非空字符串;失败 → 空串);都不再重试。 + return self._import_settings_uid + + settings_name = f"TiMi_HOK_Game_Translator_xlsx_{target_locale}" + + # Step 1: 先尝试复用现有同名 ImportSettings + try: + resp = self._request( + "GET", + "/v1/importSettings", + params={"pageSize": 50}, + ) + existing = resp.json().get("content", []) if callable(getattr(resp, "json", None)) else [] + for item in existing: + if item.get("name") == settings_name and item.get("uid"): + uid = str(item["uid"]) + self._import_settings_uid = uid + logger.info( + "PhrasePlatform: reused existing ImportSettings uid=%s " + "name=%r (avoid account-level duplication)", + uid, settings_name, + ) + return uid + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 查询失败则走创建分支 + logger.debug( + "PhrasePlatform: list ImportSettings failed (%s); will try to create.", + exc, + ) + + # Step 2: 没有同名 → 创建新的 + body = { + "name": settings_name, + "fileImportSettings": { + "fileFormat": "multiling_xls", + "autodetectMultilingualFiles": True, + "multilingualXls": { + "sourceColumn": "B", + "targetColumns": {target_locale: "C"}, + "contextKeyColumn": "A", + "contextNoteColumn": "D", + "importRows": "2-", # 跳过首行表头 + "segmentation": True, + }, + }, + } + try: + response = self._request( + "POST", + "/v1/importSettings", + json_body=body, + extra_headers={"Content-Type": "application/json"}, + ) + uid = str(response.json().get("uid") or "") + self._import_settings_uid = uid + if uid: + logger.info( + "PhrasePlatform: created ImportSettings uid=%s name=%r " + "(multilingualXls: A=key, B=source, C=target[%s], D=contextNote)", + uid, settings_name, target_locale, + ) + else: + logger.warning( + "PhrasePlatform: ImportSettings creation returned no uid; " + "upload will fall back to default (segments may be empty).", + ) + return uid + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 创建失败不致命,走降级分支 + logger.warning( + "PhrasePlatform: ImportSettings creation failed (%s); upload " + "will fall back to default (segments may be empty). This is " + "non-fatal but reviewers won't see translatable segments in UI.", + exc, + ) + self._import_settings_uid = "" # 标记尝试过且失败,避免反复 POST + return "" + + def upload_source(self, file_path: str, *, remote_path: str = "") -> UploadResult: + """将 ``file_path`` 以新 Phrase Job 的形式上传到项目。 + + Phrase 中 Job 的源语言固定为项目源语言,目标语言则归一个 Job; + 因此调用方通常通过 :meth:`create_task` 为每个目标语种创建一个 Job。 + + **Phrase 契约要点**(2024+): + * 请求体必须是**纯文件二进制**(``application/octet-stream``), + **不能**用 ``multipart/form-data``——后者会被 API 网关识别不出而 + 返回 ``404 Not Found``; + * ``Content-Disposition`` 必须**严格匹配**服务器正则: + ``((inline|attachment); )?(filename\\*=UTF-8''(.+)|filename="?(.+)"?)`` — + 即 ``filename=`` 和 ``filename*=`` **二选一不可同时存在**。 + 含中文时统一用 ``filename*=UTF-8''``; + * ``Memsource`` 头承载 JSON 元信息(``targetLangs``、 + ``importSettings`` 等),必须是 ASCII(``ensure_ascii=True``)。 + """ + from urllib.parse import quote as _url_quote + + project_uid = self._project_uid() + filename = os.path.basename(remote_path) or os.path.basename(file_path) + # Phrase 服务器只允许单一 filename 字段。有非 ASCII 字符时用 + # RFC 5987 的 ``filename*=UTF-8''``;全 ASCII 则直接 + # 用 ``filename="..."``——避免同时提供两者触发 400 Bad Request。 + is_ascii = all(ord(ch) < 128 for ch in filename) + if is_ascii: + content_disposition = f'attachment; filename="{filename}"' + else: + encoded_filename = _url_quote(filename, safe="") + content_disposition = f"attachment; filename*=UTF-8''{encoded_filename}" + + # Memsource 元信息: + # * ``targetLangs``:Phrase 支持一个 upload 产出多个 target-locale Job; + # 本框架每个语种独立上传,所以这里直接把 target_locale 塞进去。 + # 读取优先级:构造时从 ``extra["target_language_id"]`` 兜底的 + # ``self._target_locale`` > 外部动态赋值的 ``self.target_locale`` + # 属性 > 空串。 + # **⚠️ 实测**:此字段**必须非空**,否则 Phrase API 网关会在应用层 + # 之前直接返回 ``404 Not Found``(Spring 兜底 ``{"error":{"message": + # "Not Found","code":404}}`` 格式),和路径找不到完全无法区分。 + # * **不要**传 ``importSettings: {}``:Phrase 会把它解释为"引用一个 + # uid=null 的 Import Settings 对象"而报 ``ResourceNotFound``; + # 省略此字段即走项目模板的默认 import 行为(含 pre-translate 等)。 + target_locale = ( + self._target_locale + or str(getattr(self, "target_locale", "") or "") + ) + metadata: Dict[str, Any] = {} + if target_locale: + metadata["targetLangs"] = [target_locale] + if self._workflow_step_uid: + metadata["workflowSteps"] = [{"uid": self._workflow_step_uid}] + + # 【方案 🅒】引用按需创建的 ImportSettings——让 Phrase 按 ``Key|Source|Target| + # Context|Comment`` 5 列模板解析 XLSX,使 segments > 0。若创建失败则降级 + # 为不带 ``importSettings``(入 Phrase 默认 import,解析出来是 0 条 segment 但 + # job 条目本身能被创建)。 + if target_locale: + settings_uid = self._ensure_import_settings(target_locale) + if settings_uid: + metadata["importSettings"] = {"uid": settings_uid} + + with open(file_path, "rb") as handle: + file_bytes = handle.read() + response = self._request( + "POST", + f"/v1/projects/{project_uid}/jobs", + data=file_bytes, + extra_headers={ + "Content-Type": "application/octet-stream", + "Content-Disposition": content_disposition, + "Memsource": json.dumps(metadata, ensure_ascii=True), + }, + ) + + data = response.json() + # Phrase 返回体形如 { "jobs": [{ "uid": "...", ... }, ...] } + jobs = data.get("jobs") or [] + if not jobs: + raise PlatformError( + "PhrasePlatform: upload response missing 'jobs' payload." + ) + job_uid = jobs[0].get("uid", "") + internal_id = data.get("asyncRequest", {}).get("id") or job_uid or filename + file_id = f"phrase::{project_uid}::{job_uid}" + self._jobs[file_id] = { + "project_uid": project_uid, + "job_uid": job_uid, + # 【fallback 方案 A 用】记原始上传文件绝对路径——当 MXLF 段级拆分 + # (方案 C)失败降级时,直接把原上传 xlsx 复制为 pending.xlsx 让 + # 下游 ``XlsxSource.load`` 能拿到完整 Entry 列表(含 LLM 译文)。 + "source_file_path": os.path.abspath(file_path), + } + logger.info( + "PhrasePlatform: uploaded %s (jobUid=%s, projectUid=%s)", + filename, job_uid, project_uid, + ) + + # ⚠️ import gate:Phrase 的 ``POST /jobs`` 只是 "上传完成 + 创建占位 + # Job",真实的 segment 解析是**异步**跑的(``asyncRequest.action = + # IMPORT_JOB``)。实测 ~5 秒。如果不等 import 完成就返回: + # * 下游调 ``get_task_status``/轮询,看到的始终是 ``status=NEW, + # wordsCount=-1``,根本没进入"审员可操作"状态; + # * 用户 UI 打开 job 看到 "The job has no segments, Job is empty"; + # * ``bilingualFile`` 导出 404 ``ResourceNotFound: 工作未正确导入``。 + # 所以必须阻塞到 ``importStatus.status == OK``;若 ERROR 立刻抛错, + # 让流水线上层通过 ``PlatformError`` 感知;超时也抛错避免悬挂。 + try: + self._wait_for_import(project_uid, job_uid) + except PlatformError: + # 清理失败的本地缓存(Phrase 侧也应清理,但 Phrase 对 import ERROR + # 的 job 已经视为垃圾,调用方可以择机 delete_task) + self._jobs.pop(file_id, None) + raise + + return UploadResult( + file_id=file_id, + revision=str(internal_id), + extra={"job_uid": job_uid, "project_uid": project_uid, "filename": filename}, + ) + + def _wait_for_import( + self, + project_uid: str, + job_uid: str, + *, + timeout_seconds: float = 180.0, + poll_interval_seconds: float = 2.0, + ) -> None: + """阻塞轮询直到 Phrase job 的异步 import 完成。 + + Phrase 对 ``POST /jobs`` 的处理是"同步建占位 Job + 异步真正解析"。 + ``GET /jobs/{jobUid}`` 返回体里的 ``importStatus.status`` 字段才是 + 真正的 import 进度,取值: + + * ``"RUNNING"``:异步 import 还在进行,继续等; + * ``"OK"``:import 完成,``wordsCount`` 变为实际词数,``imported`` + 变 ``true``,``segments`` 可访问; + * ``"ERROR"``:import 失败,``errorMessage`` 字段带错误原因(如列 + 映射错、文件被识别为不支持的格式等)。 + + **超时策略**:默认 180s(30 轮 × 2s)。本框架的典型文件尺寸(<1MB、 + <1000 条段落)实测 2-5s 完成,180s 保守但足够兜底 Phrase 偶发延迟。 + 超时抛 :class:`PlatformError`,上层清理本地缓存。 + + **兼容性兜底**:某些旧版 Phrase 响应里 ``importStatus`` 字段可能为 + ``null``;本方法额外用 ``imported == true`` 或 ``wordsCount > 0`` 作 + 次级判定。 + """ + deadline = _now() + timeout_seconds + attempt = 0 + while True: + attempt += 1 + response = self._request( + "GET", + f"/v1/projects/{project_uid}/jobs/{job_uid}", + ) + data = response.json() if callable(getattr(response, "json", None)) else {} + status_info = data.get("importStatus") or {} + import_status = (status_info or {}).get("status") if isinstance(status_info, dict) else "" + imported = bool(data.get("imported")) + words_count = data.get("wordsCount") + try: + words_count_int = int(words_count) if words_count is not None else -1 + except (TypeError, ValueError): + words_count_int = -1 + + # 终态:OK + if import_status == "OK": + logger.info( + "PhrasePlatform: job %s import OK (attempt=%d, wordsCount=%d)", + job_uid, attempt, words_count_int, + ) + return + + # 终态:ERROR + if import_status == "ERROR": + err_msg = "" + if isinstance(status_info, dict): + err_msg = str(status_info.get("errorMessage") or "") + raise PlatformError( + f"PhrasePlatform: job {job_uid} import ERROR" + + (f": {err_msg}" if err_msg else "") + ) + + # 兜底判定:旧版 Phrase 可能不返回 importStatus;靠 imported 和 + # wordsCount 推断 + if (import_status in ("", None)) and imported and words_count_int > 0: + logger.info( + "PhrasePlatform: job %s import inferred-done (no importStatus " + "field but imported=true, wordsCount=%d)", + job_uid, words_count_int, + ) + return + + logger.debug( + "[PhraseDBG] waiting for import: job=%s attempt=%d importStatus=%r " + "imported=%s wordsCount=%s", + job_uid, attempt, import_status, imported, words_count, + ) + + if _now() >= deadline: + raise PlatformError( + f"PhrasePlatform: job {job_uid} import timed out after " + f"{timeout_seconds:.0f}s (last importStatus={import_status!r}, " + f"imported={imported}, wordsCount={words_count})" + ) + _sleep(poll_interval_seconds) + + def create_task( + self, + file_ids: Sequence[str], + target_locale: str, + *, + review_stage: str = ReviewStage.FIRST.value, + title: str = "", + description: str = "", + ) -> TaskInfo: + """返回描述审校 Job 的 :class:`TaskInfo`。 + + Phrase 在上传时即完成 Job 创建(每份上传文件产生一或多个 Job); + 因此本方法仅拉取 ``file_ids[0]`` 的最新状态,并补充框架需要的本地化元信息。 + """ + if not file_ids: + raise PlatformError("PhrasePlatform.create_task: file_ids is empty.") + file_id = file_ids[0] + record = self._jobs.get(file_id) or _parse_file_id(file_id) + project_uid = record["project_uid"] + job_uid = record["job_uid"] + + response = self._request( + "GET", + f"/v1/projects/{project_uid}/jobs/{job_uid}", + ) + data = response.json() + remote_status = (data.get("status") or "").upper() + info = TaskInfo( + task_id=job_uid, + status=_map_status(remote_status), + target_locale=target_locale or data.get("targetLang", ""), + project_id=project_uid, + review_stage=review_stage, + percent_completed=_extract_percent(data), + extra={ + "raw_status": remote_status, + "filename": data.get("filename", ""), + "title": title, + "description": description, + }, + ) + return info + + def get_task_status( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> TaskInfo: + project_uid = self._project_uid() + response = self._request( + "GET", + f"/v1/projects/{project_uid}/jobs/{task_id}", + ) + data = response.json() + remote_status = (data.get("status") or "").upper() + + # —— 真·段级进度:调 segmentsCount 接口 —— + # Phrase 的 ``job.status`` 轴(NEW/ACCEPTED/COMPLETED)**和已 confirmed + # 段落数完全解耦**——只有审员**手动点 "Complete this job"**,status + # 才会变 COMPLETED。而 ``POST /jobs/segmentsCount`` 给出的 + # ``completedSegmentsCount / segmentsCount`` 才是真实的审员工作量进度。 + # 另外 ``counts.allConfirmed`` 字段用于识别"审员已 confirm 所有段但 + # 未点 Complete this job" 的场景,供上层轮询器提前终止。 + # + # 失败降级:segmentsCount 404/5xx 时沿用老的 ``_extract_percent`` + # (返回 0),不影响流水线继续推进。 + percent, all_confirmed, counts = self._fetch_segments_count( + project_uid, task_id, + ) + if counts is None: + # 退回老的字段解析(workflowLevel.percentageCompleted 等) + percent = _extract_percent(data) + return TaskInfo( + task_id=task_id, + status=_map_status(remote_status), + target_locale=data.get("targetLang", ""), + project_id=project_uid, + review_stage=review_stage, + percent_completed=percent, + extra={ + "raw_status": remote_status, + "filename": data.get("filename", ""), + "all_confirmed": all_confirmed, + "segments_counts": counts or {}, + }, + ) + + def _fetch_segments_count( + self, + project_uid: str, + job_uid: str, + ) -> "tuple[float, bool, Optional[Dict[str, Any]]]": + """调 ``POST /v1/projects/{projectUid}/jobs/segmentsCount`` 获取段级进度。 + + Phrase 2024+ 推荐这个接口替代旧的 ``workflowLevel.percentageCompleted`` + 字段。返回体示例:: + + { + "segmentsCountsResults": [ + {"jobPartUid": "...", + "counts": { + "allConfirmed": false, + "segmentsCount": 20, + "completedSegmentsCount": 11, + "confirmedWordsCount": 180, + "wordsCount": 318, + ... + }} + ] + } + + **进度口径**:``completedSegmentsCount / segmentsCount * 100``。 + 文档明确说明 ``completedSegmentsCount = confirmed + locked - + (confirmed and locked)``——即审员真正"做完的"段落数。 + + **allConfirmed**:当审员**在 UI 把所有段都 confirm** 但没点 + "Complete this job",该字段仍为 ``true``;上层轮询器可据此提前终止。 + + 返回 ``(percent, all_confirmed, counts_dict_or_None)``。失败时返回 + ``(0.0, False, None)``,让调用方自行退路。 + """ + try: + response = self._request( + "POST", + f"/v1/projects/{project_uid}/jobs/segmentsCount", + json_body={"jobs": [{"uid": job_uid}]}, + extra_headers={"Content-Type": "application/json"}, + ) + payload = response.json() if callable(getattr(response, "json", None)) else {} + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 失败降级 + logger.debug( + "[PhraseDBG] segmentsCount fetch failed for job=%s: %s", + job_uid, exc, + ) + return (0.0, False, None) + + results = payload.get("segmentsCountsResults") or [] + if not results: + return (0.0, False, None) + counts = results[0].get("counts") or {} + total = int(counts.get("segmentsCount") or 0) + completed = int(counts.get("completedSegmentsCount") or 0) + all_confirmed = bool(counts.get("allConfirmed") or False) + percent = (completed / total * 100.0) if total > 0 else 0.0 + return (percent, all_confirmed, counts) + + def get_task_percent( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> float: + return self.get_task_status(task_id, review_stage=review_stage).percent_completed + + def download_translations( + self, + file_id: str, + target_locale: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + record = self._jobs.get(file_id) or _parse_file_id(file_id) + project_uid = record["project_uid"] + job_uid = record["job_uid"] + response = self._request( + "GET", + f"/v1/projects/{project_uid}/jobs/{job_uid}/targetFile", + stream=True, + ) + os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) + with open(dest_path, "wb") as fh: + for chunk in _iter_response_content(response): + if chunk: + fh.write(chunk) + logger.info( + "PhrasePlatform: downloaded target file for jobUid=%s → %s", + job_uid, dest_path, + ) + return dest_path + + def import_approved( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + # Phrase 中“已批准的数据”即为完成后的 target file,直接复用下载接口。 + project_uid = self._project_uid() + file_id = f"phrase::{project_uid}::{task_id}" + self._jobs.setdefault(file_id, {"project_uid": project_uid, "job_uid": task_id}) + return self.download_translations( + file_id, "", dest_path, review_stage=review_stage, + ) + + def export_review_report( + self, + task_id: str, + dest_path: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> str: + # Phrase 对单 job 提供“analysis”接口;为避免依赖付费的分析模块, + # 本处仅导出一份纯文本报告,够框架使用。 + project_uid = self._project_uid() + response = self._request( + "GET", + f"/v1/projects/{project_uid}/jobs/{task_id}", + ) + data = response.json() + os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) + with open(dest_path, "w", encoding="utf-8") as fh: + fh.write(f"# Phrase review report — jobUid={task_id}\n") + fh.write(f"stage={review_stage}\n") + for key in ("status", "workflowLevel", "filename", "targetLang"): + fh.write(f"{key}: {data.get(key)}\n") + return dest_path + + def split_approved_data( + self, + task_id: str, + *, + save_approved_path: str, + save_pending_path: str = "", + review_stage: str = ReviewStage.FIRST.value, + ) -> SplitResult: + """按**段级** approved/pending 拆分 Phrase job 的译文产物。 + + **方案 C(真·段级拆分,2025+ 推荐)**: + 1. 调 ``POST /v1/projects/{projectUid}/jobs/bilingualFile?format=MXLF`` + 拉取 Phrase 的 MXLF(XLIFF 1.2 + Phrase ``m:`` 命名空间); + 2. 解析每个 ```` 节点的 ``m:confirmed`` 属性: + - ``"1"`` → **approved**(审员已 confirm 的段落,```` 内是 + 审员的真实译文); + - ``"0"`` → **pending**(未 confirm,```` 内是 LLM 原译文 + 或空); + 3. ``approved.xlsx`` 写含真实译文的 approved 段;``pending.xlsx`` 写 + pending 段(Target 列保留 LLM 原译文,供下轮回流); + 4. ``is_complete`` 的判定变成 "是否全部段落 confirmed=1" 而不是 Job + 整体 ``status == COMPLETED``——因为用户可以 "全部 confirm 但未 + 手动 Complete this job",这种情况之前方案 A 会错判为 pending。 + + **降级**:MXLF 下载失败 / 解析失败 → 自动退回方案 A(见 + :meth:`_split_fallback_whole_job`),按 Job 整体状态做 "全有或全无"。 + + **key 回映射**:MXLF 的 ``//`` 文本就是 upload 时 XLSX 第一列 ``Key`` 的值 + (由 :class:`XlsxSource` 固定列映射 + ImportSettings 的 + ``contextKeyColumn="A"`` 共同保证)。 + """ + from ..sources import XlsxSource, Entry # 局部导入避免顶层循环依赖 + + try: + segs = self._parse_mxlf_segments( + self._download_bilingual_mxlf(task_id, review_stage=review_stage), + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — MXLF 失败则降级 + # 优先识别 "job 已不存在" 这类**不可恢复**错误:Phrase 侧 404 + # ResourceNotFound 意味着这个 tail job 已被人工删除/被其他 run + # 清理,再怎么降级也拿不到数据。直接返回空 SplitResult 让上层 + # ``LastFirstReviewState`` 把 slot 当"已完成"清掉,而不是在 + # ``_split_fallback_whole_job`` 里再 404 一次导致流水线崩溃。 + if _is_job_gone_error(exc): + logger.warning( + "PhrasePlatform.split_approved_data: task=%s is GONE on " + "Phrase side (404 ResourceNotFound). Treating as " + "zero-content complete to let pipeline clear the slot.", + task_id, + ) + return self._empty_split_result( + save_approved_path=save_approved_path, + save_pending_path=save_pending_path, + raw_status="job_gone", + ) + logger.warning( + "PhrasePlatform.split_approved_data: MXLF segment-level split " + "failed (%s); falling back to whole-job split (approach A).", + exc, + ) + return self._split_fallback_whole_job( + task_id, + save_approved_path=save_approved_path, + save_pending_path=save_pending_path, + review_stage=review_stage, + ) + + info = self.get_task_status(task_id, review_stage=review_stage) + raw_status = info.extra.get("raw_status", "") + + # 1) 段级分桶 + approved_entries: list = [] + pending_entries: list = [] + for seg in segs: + key = seg.get("key") or "" + if not key: + continue # 没 context x-key 的段无法回映射,跳过 + entry = Entry( + key=key, + source_text=seg.get("source") or "", + target_text=seg.get("target") or "", + context=seg.get("context_note") or "", + comment="", # MXLF 不携带原 Excel E 列 Comment + ) + if seg.get("confirmed"): + approved_entries.append(entry) + else: + pending_entries.append(entry) + + approved_keys = [e.key for e in approved_entries] + pending_keys = [e.key for e in pending_entries] + is_complete = (len(pending_entries) == 0 and len(approved_entries) > 0) + + logger.info( + "PhrasePlatform.split_approved_data: MXLF segment-level split " + "task=%s → approved=%d pending=%d is_complete=%s (raw_status=%s)", + task_id, len(approved_keys), len(pending_keys), is_complete, raw_status, + ) + + # 2) 写 approved.xlsx(即使 0 条也写合法空 xlsx,便于下游幂等判存在) + approved_path_out = save_approved_path + try: + os.makedirs(os.path.dirname(save_approved_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump(approved_entries, save_approved_path) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform.split_approved_data: cannot write approved xlsx " + "at %s (%s); approved_path will be empty string.", + save_approved_path, exc, + ) + approved_path_out = "" + + # 3) 写 pending.xlsx(仅当 save_pending_path 非空) + pending_path_out = "" + if save_pending_path: + try: + os.makedirs(os.path.dirname(save_pending_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump(pending_entries, save_pending_path) + pending_path_out = save_pending_path + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform.split_approved_data: cannot write pending " + "xlsx at %s (%s); pending_path will be empty.", + save_pending_path, exc, + ) + + return SplitResult( + approved_path=approved_path_out, + pending_path=pending_path_out, + should_continue=True, + is_complete=is_complete, + extra={ + "raw_status": raw_status, + "approved_keys": approved_keys, + "pending_keys": pending_keys, + }, + ) + + def _split_fallback_whole_job( + self, + task_id: str, + *, + save_approved_path: str, + save_pending_path: str = "", + review_stage: str = ReviewStage.FIRST.value, + ) -> SplitResult: + """**方案 A(降级 fallback)**:按 Job 整体 status 做"全有或全无"拆分。 + + 仅在方案 C(MXLF 段级拆分)失败时触发(例如 Phrase 版本不支持 + ``bilingualFile`` 接口、网络抖动、MXLF 格式变更等)。保留此分支以保 + 证流水线在平台异常时仍能完成一轮——即使拆分粒度退回到 job 级。 + + **COMPLETED 分支**: + * ``approved.xlsx`` ← :meth:`import_approved` 下载的双语文件; + * ``pending.xlsx`` 为仅表头的占位; + * ``extra = {approved_keys: [全部], pending_keys: []}``。 + + **非 COMPLETED 分支**(stop_time 到期但 Phrase 尚未审完): + * ``approved.xlsx`` 为仅表头占位; + * ``pending.xlsx`` ← 原始上传 xlsx 的完整副本; + * ``extra = {approved_keys: [], pending_keys: [全部]}``。 + """ + import shutil + from pathlib import Path as _Path + from ..sources import XlsxSource # 局部导入,避免顶层循环依赖 + + try: + info = self.get_task_status(task_id, review_stage=review_stage) + except Exception as exc: # noqa: BLE001 — 二级 404 保护 + if _is_job_gone_error(exc): + logger.warning( + "PhrasePlatform._split_fallback_whole_job: task=%s is GONE " + "(get_task_status 404). Treating as zero-content complete.", + task_id, + ) + return self._empty_split_result( + save_approved_path=save_approved_path, + save_pending_path=save_pending_path, + raw_status="job_gone", + ) + raise + is_approved = info.status == TaskStatus.APPROVED + + if is_approved: + # —— 全部通过分支 —— + approved = self.import_approved( + task_id, save_approved_path, review_stage=review_stage, + ) + approved_keys: list = [] + try: + entries = XlsxSource(encoding="utf-8").load(approved) + approved_keys = [e.key for e in entries if getattr(e, "key", "")] + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 读失败不致命,仅告警 + logger.warning( + "PhrasePlatform._split_fallback_whole_job: approved file %s " + "cannot be parsed as xlsx (%s); approved_keys will be empty.", + approved, exc, + ) + pending = "" + if save_pending_path: + os.makedirs(os.path.dirname(save_pending_path) or ".", exist_ok=True) + try: + XlsxSource(encoding="utf-8").dump([], save_pending_path) + pending = save_pending_path + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._split_fallback_whole_job: cannot write " + "empty pending xlsx at %s (%s); leaving pending_path empty.", + save_pending_path, exc, + ) + return SplitResult( + approved_path=approved, + pending_path=pending, + should_continue=True, + is_complete=True, + extra={ + "raw_status": info.extra.get("raw_status", ""), + "approved_keys": approved_keys, + "pending_keys": [], + }, + ) + + # —— 未完成分支:全部视为 pending —— + pending_source_path = self._lookup_source_file_path(task_id) + + pending_path = "" + pending_keys: list = [] + if save_pending_path: + os.makedirs(os.path.dirname(save_pending_path) or ".", exist_ok=True) + if pending_source_path and _Path(pending_source_path).exists(): + try: + shutil.copyfile(pending_source_path, save_pending_path) + pending_path = save_pending_path + logger.info( + "PhrasePlatform._split_fallback_whole_job: pending.xlsx ← " + "copied from upload source %s", + pending_source_path, + ) + except OSError as exc: + logger.warning( + "PhrasePlatform._split_fallback_whole_job: failed to copy " + "upload source %s → %s (%s); falling back to targetFile download.", + pending_source_path, save_pending_path, exc, + ) + if not pending_path: + try: + pending_path = self.import_approved( + task_id, save_pending_path, review_stage=review_stage, + ) + logger.info( + "PhrasePlatform._split_fallback_whole_job: pending.xlsx ← " + "fallback: downloaded targetFile for job=%s (upload source " + "not available).", + task_id, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._split_fallback_whole_job: fallback targetFile " + "download also failed (%s); pending.xlsx will be empty.", + exc, + ) + if pending_path: + try: + entries = XlsxSource(encoding="utf-8").load(pending_path) + pending_keys = [e.key for e in entries if getattr(e, "key", "")] + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._split_fallback_whole_job: cannot parse " + "pending xlsx %s (%s); pending_keys will be empty.", + pending_path, exc, + ) + + approved_path_out = save_approved_path + try: + os.makedirs(os.path.dirname(save_approved_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump([], save_approved_path) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._split_fallback_whole_job: cannot write empty " + "approved xlsx at %s (%s); approved_path will be empty string.", + save_approved_path, exc, + ) + approved_path_out = "" + + return SplitResult( + approved_path=approved_path_out, + pending_path=pending_path, + should_continue=False, + is_complete=False, + extra={ + "raw_status": info.extra.get("raw_status", ""), + "approved_keys": [], + "pending_keys": pending_keys, + }, + ) + + def _empty_split_result( + self, + *, + save_approved_path: str, + save_pending_path: str = "", + raw_status: str = "", + ) -> SplitResult: + """构造一个"零内容"的 :class:`SplitResult`,用于 Phrase job 已消失等 + 不可恢复场景。 + + **使用场景**: + * tail job 在 Phrase 侧被人工删除 / 已被另一次 run 清理 → 当前 + run 没数据可审,应放流水线继续推进(下一轮会从头建新 job); + * ``split_approved_data`` 的 MXLF 下载 404、``get_task_status`` + 404 都走这里,避免 ``_split_fallback_whole_job`` 二级 404 把流 + 水线崩掉。 + + **产物契约**: + * ``approved.xlsx`` 和 ``pending.xlsx`` 都写**仅表头**的合法空 + xlsx(下游 ``XlsxSource.load`` 能读到 ``entries == []``, + ``_apply_split_to_entries`` 会把 ``ctx.entries`` 筛空); + * ``is_complete=False``:没有真正审完,上层 ``LastFirstReviewState`` + 看到就清掉 ``last_tasks.json`` 的 slot; + * ``should_continue=True``:允许流水线进入下游 state; + * ``extra.raw_status`` 带入传参(典型 ``"job_gone"``)。 + """ + from ..sources import XlsxSource # 局部导入避免顶层循环依赖 + + approved_out = save_approved_path + try: + os.makedirs(os.path.dirname(save_approved_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump([], save_approved_path) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._empty_split_result: cannot write empty " + "approved xlsx at %s (%s); approved_path will be empty.", + save_approved_path, exc, + ) + approved_out = "" + + pending_out = "" + if save_pending_path: + try: + os.makedirs(os.path.dirname(save_pending_path) or ".", exist_ok=True) + XlsxSource(encoding="utf-8").dump([], save_pending_path) + pending_out = save_pending_path + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform._empty_split_result: cannot write empty " + "pending xlsx at %s (%s); pending_path will be empty.", + save_pending_path, exc, + ) + + return SplitResult( + approved_path=approved_out, + pending_path=pending_out, + should_continue=True, + is_complete=False, + extra={ + "raw_status": raw_status, + "approved_keys": [], + "pending_keys": [], + }, + ) + + # ------------------------------------------------------------------ + # MXLF(Phrase 双语 XLIFF)相关辅助——方案 C 的核心 + # ------------------------------------------------------------------ + def _download_bilingual_mxlf( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, # noqa: ARG002 — 暂不区分 stage + ) -> bytes: + """调 ``POST /v1/projects/{projectUid}/jobs/bilingualFile?format=MXLF`` + 下载指定 job 的 Phrase MXLF 双语文件(二进制)。 + + **接口契约**(2025+ 实测): + * 必须用 ``POST``(不是 GET); + * 请求体 ``{"jobs":[{"uid":""}]}``; + * ``Accept`` 不能是 ``application/json`` —— MXLF 走 + ``application/mxliff;charset=utf-8``,这里设为 ``*/*``; + * ``format=MXLF`` 作为 query param。 + """ + project_uid = self._project_uid() + response = self._request( + "POST", + f"/v1/projects/{project_uid}/jobs/bilingualFile", + json_body={"jobs": [{"uid": task_id}]}, + params={"format": "MXLF"}, + extra_headers={ + "Accept": "*/*", + "Content-Type": "application/json", + }, + ) + return response.content + + @staticmethod + def _parse_mxlf_segments(mxlf_bytes: bytes) -> list: + """解析 Phrase MXLF 字节流,返回每段的 ``dict`` 列表。 + + 返回元素字段:: + + { + "key": str, # ... + "source": str, # 文本 + "target": str, # 文本 + "confirmed": bool, # m:confirmed=="1" + "context_note": str, # 其他 文本(如果有) + } + + **XML 命名空间**:MXLF 混用 XLIFF 1.2 (``urn:oasis:names:tc:xliff:document:1.2``) + 和 Phrase (``http://www.memsource.com/mxlf/2.0``)。```` / + ```` / ```` / ```` / ```` / + ```` 都在 XLIFF 默认命名空间下;``m:confirmed`` 属性在 Phrase + 命名空间下。 + + **容错**:解析失败(空字节、XML 格式错误等)抛 :class:`PlatformError`, + 由调用方降级到方案 A。 + """ + import xml.etree.ElementTree as ET + + if not mxlf_bytes: + raise PlatformError("PhrasePlatform: empty MXLF payload") + + try: + root = ET.fromstring(mxlf_bytes) + except ET.ParseError as exc: + raise PlatformError( + f"PhrasePlatform: malformed MXLF ({exc})" + ) from exc + + NS_XLIFF = "urn:oasis:names:tc:xliff:document:1.2" # pylint: disable=invalid-name + NS_PHRASE = "http://www.memsource.com/mxlf/2.0" # pylint: disable=invalid-name + CONFIRMED_ATTR = f"{{{NS_PHRASE}}}confirmed" # pylint: disable=invalid-name + + segments: list = [] + # 遍历所有 (在 group 下,也可能直接在 body 下) + for tu in root.iter(f"{{{NS_XLIFF}}}trans-unit"): + source_elem = tu.find(f"{{{NS_XLIFF}}}source") + target_elem = tu.find(f"{{{NS_XLIFF}}}target") + source_text = _xliff_elem_text(source_elem) + target_text = _xliff_elem_text(target_elem) + confirmed = (tu.get(CONFIRMED_ATTR, "0") == "1") + + # key 来自父 // + # XLIFF 没父指针,向上找需用 iter 的侧扫路线 + segments.append({ + "key": "", # 稍后用 group 层扫描补齐 + "source": source_text, + "target": target_text, + "confirmed": confirmed, + "context_note": "", + "_tu_id": tu.get("id", ""), + }) + + # 再扫一遍 ,用它的 补齐 key / context_note + # —— 一个 group 对应一个 trans-unit(Phrase MXLF 的约定) + tu_id_to_meta: Dict[str, Dict[str, str]] = {} + for group in root.iter(f"{{{NS_XLIFF}}}group"): + key = "" + context_note = "" + for ctx in group.iter(f"{{{NS_XLIFF}}}context"): + ctype = ctx.get("context-type", "") + text = (ctx.text or "").strip() + if ctype == "x-key": + key = text + elif ctype in ("x-context", "x-note", "note"): + # 其他类型的 context 当作 context_note(罕见) + if text and not context_note: + context_note = text + tu_in_group = group.find(f"{{{NS_XLIFF}}}trans-unit") + if tu_in_group is not None: + tu_id_to_meta[tu_in_group.get("id", "")] = { + "key": key, + "context_note": context_note, + } + + for seg in segments: + meta = tu_id_to_meta.get(seg["_tu_id"], {}) + seg["key"] = meta.get("key", "") + seg["context_note"] = meta.get("context_note", "") + seg.pop("_tu_id", None) + + return segments + + def _lookup_source_file_path(self, job_uid: str) -> str: + """在 ``self._jobs`` 内存缓存里按 ``job_uid`` 反查原上传文件路径。 + + * 若调用方传入的 ``task_id`` 就是 ``file_id``(``phrase::proj::job``), + 直接命中; + * 否则遍历 values 匹配 ``job_uid`` 字段——这是本次 run 内刚上传过的 + job 走 split 分支时的典型场景; + * 跨 run 续审(Day-N)时内存缓存是空,返回空串,由调用方处理退路。 + """ + record = self._jobs.get(job_uid) or self._jobs.get(f"phrase::{self._project_uid()}::{job_uid}") + if isinstance(record, dict): + path = str(record.get("source_file_path") or "") + if path: + return path + for cached in self._jobs.values(): + if isinstance(cached, dict) and cached.get("job_uid") == job_uid: + path = str(cached.get("source_file_path") or "") + if path: + return path + return "" + + def delete_task( + self, + task_id: str, + *, + review_stage: str = ReviewStage.FIRST.value, + ) -> None: + """删除指定 Phrase job。 + + **端点选择**:Phrase 新版 TMS 的删除走 + ``DELETE /v1/projects/{projectUid}/jobs/batch`` 而不是 + ``.../jobs``——后者 ``Allow`` 头只有 ``HEAD,POST,GET,OPTIONS``, + 调用会返回 ``405 Method Not Allowed``。通过手工 ``OPTIONS`` 探测 + 得到 ``jobs/batch`` 的 ``Allow: DELETE,OPTIONS,PUT``,实际 DELETE + 返回 ``204 No Content`` 已验证。 + """ + project_uid = self._project_uid() + self._request( + "DELETE", + f"/v1/projects/{project_uid}/jobs/batch", + json_body={"jobs": [{"uid": task_id}]}, + ) + # 同时清理本地缓存。 + for cached_id, record in list(self._jobs.items()): + if record.get("job_uid") == task_id: + self._jobs.pop(cached_id, None) + + def get_project_name(self, project_id: str = "") -> str: + uid = project_id or self.project_id + if not uid: + return "" + response = self._request("GET", f"/v1/projects/{uid}") + data = response.json() + return data.get("name") or uid + + # ------------------------------------------------------------------ + # 翻译记忆(TM)回灌 + # ------------------------------------------------------------------ + # 以下 4 个方法为**可选扩展**,不属于 :class:`TranslationPlatform` 基类的 + # 抽象 API——由 ``update_tm_state`` 通过 ``hasattr`` 探测调用。 + # Phrase TM 相关端点(详见 docs/platforms/report_final.md): + # * 项目 TM 列表:GET /api2/v3/projects/{projectUid}/transMemories + # 响应体 ``transMemories[*]`` 元素含 ``transMemory.uid`` 和 + # ``writeMode``。回灌时取 ``writeMode=true`` 的那一条作为"默认 TM"; + # 若全部 writeMode=false,则取第一条兜底。 + # * 清空 TM 片段:DELETE /api2/v2/transMemories/{uid}/segments → 202 + # * 导入 TMX/xlsx:POST /api2/v2/transMemories/{uid}/import → 202 + # - 请求体直接传二进制文件 + # - 必须带 Content-Disposition: ``attachment; filename*=UTF-8''`` + def get_project_default_tm_id(self) -> str: + """返回当前项目用于 writeMode 的 TM 库 UID;查不到返回空串。""" + uid = self._project_uid() + if not uid: + return "" + try: + response = self._request( + "GET", f"/v3/projects/{uid}/transMemories", + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform.get_project_default_tm_id: GET " + "/v3/projects/%s/transMemories failed: %s", uid, exc, + ) + return "" + data = response.json() if response is not None else {} + tm_list = data.get("transMemories") or [] + if not tm_list: + logger.warning( + "PhrasePlatform.get_project_default_tm_id: project %s has no " + "transMemories assigned", uid, + ) + return "" + # 优先 writeMode=true 的 TM;否则取第一条兜底 + write_tm = next( + (item for item in tm_list if item.get("writeMode")), tm_list[0], + ) + tm_entry = write_tm.get("transMemory") or {} + tm_uid = str(tm_entry.get("uid") or "") + if not tm_uid: + logger.warning( + "PhrasePlatform.get_project_default_tm_id: TM entry missing uid: %r", + write_tm, + ) + return tm_uid + + def clear_tm_segments(self, tm_id: str) -> bool: + """清空指定 TM 库下的所有片段。成功返回 True,失败返回 False(不抛)。 + + 调 ``DELETE /api2/v2/transMemories/{tm_id}/segments``,异步 202。 + """ + if not tm_id: + return False + try: + self._request("DELETE", f"/v2/transMemories/{tm_id}/segments") + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PhrasePlatform.clear_tm_segments: DELETE " + "/v2/transMemories/%s/segments failed: %s", tm_id, exc, + ) + return False + logger.info( + "PhrasePlatform: cleared TM segments for tm_uid=%s (async request)", + tm_id, + ) + return True + + def upload_tm(self, tm_file_path: str, *, target_locale: str, tm_id: str = "") -> bool: + """把本地 TM xlsx/TMX 文件上传到项目默认 TM 库(**先清后传**)。 + + 流程: + 1. 若 ``tm_id`` 为空,自动调用 :meth:`get_project_default_tm_id`; + 2. 调用 :meth:`clear_tm_segments` 清空旧 TM; + 3. ``POST /api2/v2/transMemories/{tm_id}/import`` 二进制上传。 + + 参数: + tm_file_path: 由 :mod:`utils.tm_file_builder` 产出的 xlsx 文件 + (Phrase 自动按扩展名识别为 Excel 格式)。 + target_locale: 保留以保持与 Crowdin 版 ``upload_tm`` 签名一致; + Phrase TMX import 不需要显式传 target_locale,列头已含语种。 + tm_id: 可选,直接指定 TM UID;为空则取项目默认 TM。 + + 返回: + True 全链路成功;False 任一步失败。失败只记日志,不抛异常。 + """ + import os as _os + + _ = target_locale # 保持签名一致;Phrase 不需要这个参数 + + if not _os.path.exists(tm_file_path): + logger.warning( + "PhrasePlatform.upload_tm: file not found: %s", tm_file_path, + ) + return False + + tm_id = tm_id or self.get_project_default_tm_id() + if not tm_id: + return False + + # 先清后传 + self.clear_tm_segments(tm_id) + + filename = _os.path.basename(tm_file_path) + # RFC 5987 扩展:Phrase 要求 Content-Disposition 必须用 UTF-8 编码 + from urllib.parse import quote as _quote + content_disposition = ( + f"attachment; filename*=UTF-8''{_quote(filename, safe='')}" + ) + + try: + with open(tm_file_path, "rb") as fh: + data = fh.read() + self._request( + "POST", + f"/v2/transMemories/{tm_id}/import", + data=data, + extra_headers={ + "Content-Disposition": content_disposition, + "Content-Type": "application/octet-stream", + }, + ) + logger.info( + "PhrasePlatform.upload_tm: imported TM into tm_uid=%s (file=%s)", + tm_id, filename, + ) + return True + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — TM 回灌失败不阻塞主流程 + logger.warning( + "PhrasePlatform.upload_tm: failed to import TM to tm_uid=%s " + "(file=%s): %s", tm_id, filename, exc, + ) + return False + + +# --------------------------------------------------------------------------- +# 辅助函数 +# --------------------------------------------------------------------------- +_FILE_ID_RE = re.compile(r"^phrase::(?P[^:]+)::(?P[^:]+)$") + + +def _parse_file_id(file_id: str) -> Dict[str, str]: + """尽力从不透明的 ``file_id`` 中写回 ``(project_uid, job_uid)``。""" + match = _FILE_ID_RE.match(file_id or "") + if not match: + raise PlatformError( + f"PhrasePlatform: unknown file_id {file_id!r} — expected " + "'phrase::::'." + ) + return {"project_uid": match.group("project"), "job_uid": match.group("job")} + + +def _iter_response_content(response, chunk_size: int = 8192): + """递增迭代 ``response`` 主体,兼容未提供流式接口的 mock 对象。""" + if hasattr(response, "iter_content"): + yield from response.iter_content(chunk_size=chunk_size) + return + payload = getattr(response, "content", b"") or b"" + yield payload + + +def _sleep(seconds: float) -> None: + """封装 ``time.sleep``,便于测试 patch。""" + import time as _time + _time.sleep(max(0.0, seconds)) + + +def _now() -> float: + """返回当前 UNIX 时间戳;单独抽出便于测试 patch。""" + import time as _time + return _time.time() + + +def _is_job_gone_error(exc: BaseException) -> bool: + """判定一个异常是否属于"Phrase job 已不存在"类错误。 + + Phrase TMS 对已删除/未成功导入的 job 返回 HTTP 404,错误体通常是以下 + 两种模式之一(EU 中文返回;英文服务器可能是 ``Not Found``):: + + {"errorCode":"ResourceNotFound", + "errorDescription":"[UidReference(uid:xxx)]工作未正确导入或导入正在进行 ..."} + + {"errorCode":"无效的参数", + "errorDescription":"被"jobUid"字段和"xxx"值所引用的对象找不到。"} + + 由于 :class:`PlatformError` 的 message 里会包含 ``HTTP 404`` 和原始错 + 误 body(见 :meth:`PhrasePlatform._raise_for_status`),本函数通过字 + 符串匹配识别。保守起见只匹配 **404 + 下列任一关键词**: + + * ``ResourceNotFound`` — 删除/没导入成功的通用错误码 + * ``找不到`` / ``已删除`` — 中文返回的两种描述 + * ``Not Found`` — 英文返回 + + **只应用于识别"不可恢复、应优雅跳过"的场景**(如 split 时 tail job + 已被人工删除)。网络超时、鉴权失败、重试类错误**不**走这里。 + """ + msg = str(exc) if exc is not None else "" + if "404" not in msg: + return False + for keyword in ("ResourceNotFound", "找不到", "已删除", "Not Found"): + if keyword in msg: + return True + return False + + +def _xliff_elem_text(elem) -> str: + """提取 XLIFF ```` / ```` 的纯文本内容。 + + XLIFF 允许 inline tag(````、```` 等)嵌入到 ```` / + ```` 中::: + + Hello World! + + 对于 Phrase MXLF 的双语文件,我们只关心最终呈现给审员的**可读文本**, + inline tag 本身是 XLIFF 的格式元信息,不应保留。本函数做深度文本遍历, + 把 ``elem.text`` + 每个子节点的 ``.text`` + ``tail`` 按顺序拼起来。 + + 若 ``elem`` 为 ``None`` 则返回空串。 + """ + if elem is None: + return "" + parts: list = [] + if elem.text: + parts.append(elem.text) + for child in elem: + parts.append(_xliff_elem_text(child)) + if child.tail: + parts.append(child.tail) + return "".join(parts) + + +# --------------------------------------------------------------------------- +# 注册 +# --------------------------------------------------------------------------- +register_platform("phrase", PhrasePlatform) + + +__all__ = ["PhrasePlatform"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4d2ea8fe304225f2cba75d0a64620a2bb26030a7 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__init__.py @@ -0,0 +1,20 @@ +"""TiMi_HOK_Game_Translator Web 服务端(前后端一体)。 + +目录结构: + +* :mod:`TiMi_HOK_Game_Translator.server.backend` —— FastAPI 后端(API + 服务层) +* :mod:`TiMi_HOK_Game_Translator.server.frontend` —— 静态前端资源(HTML/CSS/JS) + +启动方式:: + + python -m TiMi_HOK_Game_Translator.server # 等价于 python main.py server(默认 0.0.0.0:8787) + python main.py server --host 127.0.0.1 --port 8787 # 仅本机访问 + python main.py server --port 9000 # 自定义端口,同网段可用 http://<本机IP>:9000/ 访问 + +前端默认挂载在 ``/`` 根路径,API 挂载在 ``/api/*``,日志实时推送通道 +位于 ``/api/logs/ws``。 +""" + +from .app import create_app, run + +__all__ = ["create_app", "run"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__main__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..1739c7da46e36952a72d799ed5fe30a3708b18b1 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/__main__.py @@ -0,0 +1,31 @@ +"""``python -m TiMi_HOK_Game_Translator.server`` 入口。 + +读取环境变量 ``GAME_TRANS_TOOLCHAIN_SERVER_HOST`` / ``GAME_TRANS_TOOLCHAIN_SERVER_PORT`` +作为默认绑定地址,命令行参数可覆盖之。 + +默认绑定 ``0.0.0.0``:允许同一局域网内的其它机器通过本机 IP 访问 +(例如 ``http://30.23.60.41:8787/``)。若只希望本机访问,可显式传入 +``--host 127.0.0.1``,或设置环境变量 ``GAME_TRANS_TOOLCHAIN_SERVER_HOST=127.0.0.1``。 +""" + +from __future__ import annotations + +import argparse +import os +import sys + + +def main() -> int: + parser = argparse.ArgumentParser(description="TiMiHOKGameTranslator Web Server") + parser.add_argument("--host", default=os.environ.get("GAME_TRANS_TOOLCHAIN_SERVER_HOST", "0.0.0.0")) + parser.add_argument("--port", type=int, default=int(os.environ.get("GAME_TRANS_TOOLCHAIN_SERVER_PORT", "8787"))) + parser.add_argument("--reload", action="store_true", help="启用自动重载(开发用)") + args = parser.parse_args() + + from .app import run + run(host=args.host, port=args.port, reload=args.reload) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/app.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/app.py new file mode 100644 index 0000000000000000000000000000000000000000..4330a5537a279119bd65297b7feb132146b19ac3 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/app.py @@ -0,0 +1,196 @@ +"""FastAPI 应用工厂。 + +本模块只负责: + 1. 装配 FastAPI 应用、CORS、静态文件挂载; + 2. 注册 ``/api/*`` 路由; + 3. 应用生命周期钩子(启动 scheduler / 关闭时优雅停止子进程)。 + +真正的业务代码分散在 ``backend/api/*`` 与 ``backend/services/*``。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any + +try: + from fastapi import FastAPI + from fastapi.middleware.cors import CORSMiddleware + from fastapi.responses import FileResponse + from fastapi.staticfiles import StaticFiles +except ImportError as exc: # pragma: no cover + raise ImportError( + "TiMiHOKGameTranslator Web 服务依赖 fastapi / uvicorn,请先执行:\n" + " pip install fastapi uvicorn[standard]" + ) from exc + +from .backend.api import setup as setup_api +from .backend.api import languages as languages_api +from .backend.api import runs as runs_api +from .backend.api import schedules as schedules_api +from .backend.api import logs as logs_api +from .backend.api import meta as meta_api +from .backend.services.scheduler_service import SchedulerService +from .backend.services.runner_service import RunnerService +from .backend.services.log_bus import LogBus +from .backend.services.config_service import ConfigService + +logger = logging.getLogger(__name__) + +FRONTEND_DIR = Path(__file__).resolve().parent / "frontend" + + +def create_app(project_root: Path | None = None) -> FastAPI: + """创建并返回一个配置好的 ``FastAPI`` 实例。 + + 参数: + project_root: TiMiHOKGameTranslator 项目根目录(含 ``conf/``、``main.py``)。 + 省略时自动按 ``src/TiMi_HOK_Game_Translator/server/app.py`` 向上三级定位到项目根。 + """ + if project_root is None: + # /src/TiMi_HOK_Game_Translator/server/app.py → + project_root = Path(__file__).resolve().parents[3] + + app = FastAPI( + title="TiMiHOKGameTranslator Web Console", + version="0.1.0", + description="游戏本地化流水线可视化配置 / 调度 / 监控面板", + ) + + # CORS:允许开发期任意来源,生产部署可通过反向代理锁定。 + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + # ---------- 服务层(单例,挂到 app.state) ---------- + config_service = ConfigService(project_root) + log_bus = LogBus(max_buffer=5000) + runner_service = RunnerService(project_root=project_root, log_bus=log_bus) + scheduler_service = SchedulerService(runner_service=runner_service) + + app.state.project_root = project_root + app.state.config_service = config_service + app.state.log_bus = log_bus + app.state.runner_service = runner_service + app.state.scheduler_service = scheduler_service + + # ---------- 路由 ---------- + app.include_router(setup_api.router, prefix="/api/setup", tags=["setup"]) + app.include_router(languages_api.router, prefix="/api/languages", tags=["languages"]) + app.include_router(runs_api.router, prefix="/api/runs", tags=["runs"]) + app.include_router(schedules_api.router, prefix="/api/schedules", tags=["schedules"]) + app.include_router(logs_api.router, prefix="/api/logs", tags=["logs"]) + app.include_router(meta_api.router, prefix="/api/meta", tags=["meta"]) + + # ---------- 静态前端 ---------- + # 开发/联调场景下,前端 app.js 频繁改动——给静态资源统一加 no-cache 响应头, + # 让浏览器每次都走条件请求(If-Modified-Since / 304),避免陈旧缓存命中。 + class _NoCacheStaticFiles(StaticFiles): + async def get_response(self, path: str, scope): # type: ignore[override] + response = await super().get_response(path, scope) + response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" + response.headers["Pragma"] = "no-cache" + response.headers["Expires"] = "0" + return response + + static_dir = FRONTEND_DIR / "static" + if static_dir.exists(): + app.mount("/static", _NoCacheStaticFiles(directory=str(static_dir)), name="static") + + @app.get("/", include_in_schema=False) + async def _index() -> Any: + index_html = FRONTEND_DIR / "index.html" + if not index_html.exists(): + return {"message": "Frontend not built. See src/TiMi_HOK_Game_Translator/server/frontend/."} + # index.html 自身也禁缓存,确保用户刷新即可加载最新前端代码 + return FileResponse( + str(index_html), + headers={ + "Cache-Control": "no-cache, no-store, must-revalidate", + "Pragma": "no-cache", + "Expires": "0", + }, + ) + + @app.on_event("startup") + async def _startup() -> None: + scheduler_service.start() + scheduler_service.restore_from_disk(config_service.schedules_file()) + logger.info("TiMiHOKGameTranslator Web Console started.") + + @app.on_event("shutdown") + async def _shutdown() -> None: + scheduler_service.shutdown() + runner_service.shutdown_all() + logger.info("TiMiHOKGameTranslator Web Console stopped.") + + return app + + +def run(*, host: str = "0.0.0.0", port: int = 8787, reload: bool = False) -> None: + """便捷启动器——直接调用 ``uvicorn`` 启动当前 app。 + + 默认绑定 ``0.0.0.0``:允许同一局域网内的其它机器通过本机 IP 访问。 + 若只希望本机访问,可显式传入 ``host="127.0.0.1"``。 + """ + try: + import uvicorn + except ImportError as exc: # pragma: no cover + raise ImportError( + "缺少 uvicorn,请执行:pip install uvicorn[standard]" + ) from exc + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + ) + + _print_access_urls(host, port) + + if reload: + # 开启 reload 时必须以 import string 传入 + uvicorn.run( + "TiMi_HOK_Game_Translator.server.app:create_app", + host=host, port=port, reload=True, factory=True, + ) + else: + uvicorn.run(create_app(), host=host, port=port) + + +def _print_access_urls(host: str, port: int) -> None: + """在启动日志中打印可访问的 URL 列表,方便用户把地址发给同事。""" + import socket + + banner_lines: list[str] = [] + banner_lines.append("") + banner_lines.append("=" * 60) + banner_lines.append(" TiMiHOKGameTranslator Web Console") + banner_lines.append("=" * 60) + + if host in ("0.0.0.0", "::"): + banner_lines.append(f" 本机访问: http://127.0.0.1:{port}/") + # 枚举所有 IPv4 地址,筛掉环回 + try: + hostname = socket.gethostname() + addrs = {info[4][0] for info in socket.getaddrinfo(hostname, None, socket.AF_INET)} + addrs.discard("127.0.0.1") + for addr in sorted(addrs): + banner_lines.append(f" 局域网访问: http://{addr}:{port}/") + except OSError: + pass + banner_lines.append("") + banner_lines.append(" [!] 已监听 0.0.0.0,同网段任意机器均可访问。") + banner_lines.append(f" [!] 若无法访问,请检查本机防火墙是否放通 TCP {port}。") + else: + banner_lines.append(f" 访问地址: http://{host}:{port}/") + + banner_lines.append("=" * 60) + banner_lines.append("") + + for line in banner_lines: + logger.info(line) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a55b6d0acbbc529c2f594a84d5f5c44a0afca0b --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/__init__.py @@ -0,0 +1 @@ +"""后端业务层:API 路由、Pydantic 模型、服务(配置读写/子进程调度/日志总线)。""" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c705d6c3b06bfe661e59246a6ef110937e13c0e9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/__init__.py @@ -0,0 +1 @@ +"""REST / WebSocket 路由集合。""" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/languages.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/languages.py new file mode 100644 index 0000000000000000000000000000000000000000..fdbd7d3abc2e6d864400a636179a64e75a592bad --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/languages.py @@ -0,0 +1,62 @@ +"""``/api/languages`` —— 语种 profile CRUD。""" + +from __future__ import annotations + +from typing import Any, Dict, List + +from fastapi import APIRouter, HTTPException, Request + +router = APIRouter() + + +@router.get("") +async def list_languages(request: Request) -> List[Dict[str, Any]]: + cs = request.app.state.config_service + return cs.list_languages() + + +@router.get("/{lang_id}") +async def get_language(lang_id: str, request: Request) -> Dict[str, Any]: + cs = request.app.state.config_service + path = cs.language_file(lang_id) + if not path.exists(): + raise HTTPException(404, f"language profile {lang_id!r} not found") + return cs.load_language(lang_id) + + +@router.put("/{lang_id}") +async def put_language(lang_id: str, payload: Dict[str, Any], request: Request) -> Dict[str, Any]: + cs = request.app.state.config_service + try: + cs.save_language(lang_id, payload) + except (OSError, ValueError) as exc: + raise HTTPException(400, f"保存失败:{exc}") from exc + return {"ok": True, "id": lang_id} + + +@router.delete("/{lang_id}") +async def delete_language(lang_id: str, request: Request) -> Dict[str, Any]: + cs = request.app.state.config_service + try: + cs.delete_language(lang_id) + except (OSError, ValueError) as exc: + raise HTTPException(400, f"删除失败:{exc}") from exc + return {"ok": True} + + +@router.post("/{lang_id}/duplicate") +async def duplicate_language(lang_id: str, payload: Dict[str, Any], request: Request): + """从一个已存在的 profile 克隆为新语种。``payload = {"target_id": "..."}``。""" + cs = request.app.state.config_service + target_id = (payload or {}).get("target_id") + if not target_id: + raise HTTPException(400, "target_id 必填") + src = cs.load_language(lang_id) + if not src: + raise HTTPException(404, f"source {lang_id!r} not found") + src["id"] = target_id + try: + cs.save_language(target_id, src) + except (OSError, ValueError) as exc: + raise HTTPException(400, f"保存失败:{exc}") from exc + return {"ok": True, "id": target_id} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/logs.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/logs.py new file mode 100644 index 0000000000000000000000000000000000000000..0b30f0ba1e006a8a0a42d38a5dbce4b28c39e6c2 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/logs.py @@ -0,0 +1,64 @@ +"""``/api/logs`` —— 日志尾读 + WebSocket 实时推送。""" + +from __future__ import annotations + +import asyncio +import logging + +from fastapi import APIRouter, Query, Request, WebSocket, WebSocketDisconnect + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +@router.get("/{run_id}") +async def tail(run_id: str, request: Request, limit: int = Query(500, ge=1, le=10000)): + log_bus = request.app.state.log_bus + buf = log_bus.tail(run_id, limit=limit) + if buf: + return {"source": "memory", "entries": buf} + # 内存里没了,再读落盘文件 + runner = request.app.state.runner_service + lines = runner.read_log_file(run_id, tail=limit) + return { + "source": "file", + "entries": [ + {"run_id": run_id, "ts": 0, "stream": "stdout", "line": ln} + for ln in lines + ], + } + + +@router.websocket("/ws") +async def ws(websocket: WebSocket, run_id: str | None = Query(None)): + """订阅实时日志流。 + + 参数: + run_id: 为空时订阅 ALL(全部 run 的广播);指定时只接收该 run。 + """ + await websocket.accept() + log_bus = websocket.app.state.log_bus + log_bus.bind_loop(asyncio.get_running_loop()) + + # 补发历史尾巴 + if run_id: + for entry in log_bus.tail(run_id, limit=200): + try: + import json + await websocket.send_text(json.dumps(entry, ensure_ascii=False)) + except Exception: # pylint: disable=broad-except + await websocket.close() + return + + queue = await log_bus.subscribe(run_id) + try: + while True: + payload = await queue.get() + await websocket.send_text(payload) + except WebSocketDisconnect: + pass + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.warning("ws loop error: %s", exc) + finally: + log_bus.unsubscribe(queue, run_id) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/meta.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/meta.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c9619a33d05e5165d70333168c73c6b3c08169 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/meta.py @@ -0,0 +1,99 @@ +"""``/api/meta`` —— 把枚举(VCS 类型、LLM provider、workflow 状态等) +全部暴露给前端做下拉选项,避免魔法字符串硬编码。 +""" + +from __future__ import annotations + +from fastapi import APIRouter + +router = APIRouter() + + +# ----------------------------------------------------------------------------- +# Workflow 状态的中文描述与推荐分组。前端用它渲染"状态编排"面板。 +# key 必须与 :class:`WorkflowState` 的 value 完全一致。 +# +# ⚠️ 顺序即推荐执行顺序:pull_vcs → ... → push_vcs。 +# ⚠️ 以下状态**不在此列表中**,因为它们**不参与用户编排**: +# - pending / finished / failed —— 运行时生命周期状态,由 StatesManager 自动流转 +# - increment_match / dtxml_merge —— 翻译器内部状态,无独立 state 类定义 +# ----------------------------------------------------------------------------- +_WORKFLOW_STATE_META = [ + # (key, 中文名, 简短说明, 分组, 是否推荐默认启用) + ("pull_vcs", "拉取源文件", "从 VCS/本地读取最新源文件", "版本控制", True), + ("last_first_review", "上轮一审遗留处理", "拉取上一批次仍挂在平台的一审任务结果", "上一轮遗留", True), + ("last_second_review", "上轮二审遗留处理", "拉取上一批次仍挂在平台的二审任务结果", "上一轮遗留", True), + ("last_merge_data", "上轮数据合并", "把上一批次的译文合并回主表", "上一轮遗留", True), + ("translate", "LLM 机器翻译", "调用大模型批量翻译增量条目", "翻译", True), + ("update_tm", "一审 TM 回灌", "历史已审译文灌回一审平台 TM", "翻译记忆", True), + ("update_grn_tm", "二审 TM 回灌", "历史已审译文灌回二审平台 TM", "翻译记忆", True), + ("light_review", "轻校对", "快速人工 QA(可选,无需平台)", "审校", False), + ("first_review", "一审", "推送到一审平台,等待语言质检", "审校", True), + ("second_review", "二审", "推送到二审平台,等待终审出稿", "审校", True), + ("validate_data", "数据校验", "对最终译文做占位符/长度等结构性校验", "数据装配", True), + ("merge_data", "数据合并", "把译文合并回最终导出表", "数据装配", True), + ("push_vcs", "推送到 VCS", "把结果提交到仓库 / 落回本地目录", "版本控制", True), + ("push_multi_vcs", "多仓库推送", "一次性把结果推送到多个 VCS 后端", "版本控制", False), +] + +# 不该暴露给"状态编排"面板的内部 / 生命周期状态 +_WORKFLOW_STATE_HIDDEN = { + "pending", "finished", "failed", + "increment_match", "dtxml_merge", +} + + +@router.get("") +async def meta(): + from ....commons.enums import ( + LLMProvider, + LogLevel, + NotifierType, + PlatformType, + ReviewStage, + SourceFormat, + Stage, + VcsType, + WorkflowState, + ) + from ....workflow.state_registry import registered_state_names + + registered = set(registered_state_names()) + # 按预设顺序输出带中文标签的清单;只保留实际注册的状态 + workflow_states_meta = [] + seen = set() + for key, label, desc, group, recommended in _WORKFLOW_STATE_META: + if key in registered: + workflow_states_meta.append({ + "key": key, + "label": label, + "desc": desc, + "group": group, + "recommended": recommended, + }) + seen.add(key) + # 兜底:第三方 register_state 注册的额外状态也追加到末尾 + # —— 但排除生命周期状态(pending/finished/failed)和内部状态 + # (increment_match/dtxml_merge),它们不应出现在用户的"状态编排"面板。 + for key in sorted(registered - seen - _WORKFLOW_STATE_HIDDEN): + workflow_states_meta.append({ + "key": key, + "label": key, + "desc": "(第三方注册状态)", + "group": "其他", + "recommended": False, + }) + + return { + "vcs_types": VcsType.values(), + "source_formats": SourceFormat.values(), + "llm_providers": LLMProvider.values(), + "platform_types": PlatformType.values(), + "review_stages": ReviewStage.values(), + "notifier_types": NotifierType.values(), + "stages": Stage.values(), + "log_levels": LogLevel.values(), + "workflow_states": sorted(registered_state_names()), + "workflow_states_canonical": WorkflowState.values(), + "workflow_states_meta": workflow_states_meta, + } diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/runs.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/runs.py new file mode 100644 index 0000000000000000000000000000000000000000..a1aad478e668d6111db29699397467b40dfbe414 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/runs.py @@ -0,0 +1,45 @@ +"""``/api/runs`` —— 启动 / 停止 / 查询工作流运行。""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Request + +from ..models import RunStartRequest + +router = APIRouter() + + +@router.post("") +async def start_run(payload: RunStartRequest, request: Request): + runner = request.app.state.runner_service + rec = runner.start( + language=payload.language, + fresh=payload.fresh, + batch=payload.batch, + stage=payload.stage, + ) + return rec.to_public() + + +@router.get("") +async def list_runs(request: Request, limit: int = 50): + runner = request.app.state.runner_service + return runner.list_runs(limit=limit) + + +@router.get("/{run_id}") +async def get_run(run_id: str, request: Request): + runner = request.app.state.runner_service + rec = runner.get(run_id) + if not rec: + raise HTTPException(404, "run not found") + return rec.to_public() + + +@router.post("/{run_id}/stop") +async def stop_run(run_id: str, request: Request): + runner = request.app.state.runner_service + ok = runner.stop(run_id) + if not ok: + raise HTTPException(404, "run not running") + return {"ok": True} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/schedules.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/schedules.py new file mode 100644 index 0000000000000000000000000000000000000000..c802bde4c5e006702f3d7dca56b5a55b282b70f0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/schedules.py @@ -0,0 +1,51 @@ +"""``/api/schedules`` —— 定时任务 CRUD。""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Request + +from ..models import ScheduleModel +from ..services.scheduler_service import ScheduleEntry + +router = APIRouter() + + +@router.get("") +async def list_schedules(request: Request): + return request.app.state.scheduler_service.list() + + +@router.put("/{schedule_id}") +async def upsert_schedule(schedule_id: str, payload: ScheduleModel, request: Request): + if payload.id != schedule_id: + raise HTTPException(400, "path id mismatch body id") + entry = ScheduleEntry( + id=payload.id, + language=payload.language, + cron=payload.cron, + enabled=payload.enabled, + fresh=payload.fresh, + description=payload.description, + ) + try: + request.app.state.scheduler_service.upsert(entry) + except (ValueError, RuntimeError) as exc: + raise HTTPException(400, str(exc)) from exc + return {"ok": True} + + +@router.delete("/{schedule_id}") +async def delete_schedule(schedule_id: str, request: Request): + ok = request.app.state.scheduler_service.delete(schedule_id) + if not ok: + raise HTTPException(404, "schedule not found") + return {"ok": True} + + +@router.post("/{schedule_id}/toggle") +async def toggle_schedule(schedule_id: str, payload: dict, request: Request): + enabled = bool((payload or {}).get("enabled", True)) + entry = request.app.state.scheduler_service.toggle(schedule_id, enabled) + if not entry: + raise HTTPException(404, "schedule not found") + return {"ok": True, "enabled": entry.enabled} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/setup.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dbab97955167282999f5e51959c4f43138149013 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/api/setup.py @@ -0,0 +1,96 @@ +"""``/api/setup`` —— 首次初始化配置 + 字段 schema + 健康检查。 + +前端进入时先查询 ``GET /api/setup/status``;若未初始化则引导用户填写 +全局 config.yaml + llm.yaml,一键 ``POST /api/setup/init`` 落盘。 + +字段 schema 由 ``GET /api/setup/schema/{kind}`` 返回,kind ∈ +{"global", "llm_profile", "language"}。前端据此渲染结构化表单。 +""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Request + +from ..services.field_schema import get_schema + +router = APIRouter() + + +@router.get("/status") +async def get_status(request: Request): + """返回初始化状态 + 分模块健康检查。""" + cs = request.app.state.config_service + return cs.setup_status() + + +@router.post("/init") +async def init(payload: dict, request: Request): + """首次初始化:写入 config.yaml + llm.yaml,并记录用户偏好。""" + cs = request.app.state.config_service + config = payload.get("config") or {} + llm = payload.get("llm") or {} + preferences = payload.get("preferences") or {} + try: + cs.save_global_config(config) + cs.save_llm_registry(llm) + if preferences: + cs.save_preferences(preferences) + except OSError as exc: + raise HTTPException(500, f"写入配置失败:{exc}") from exc + return cs.setup_status() + + +@router.get("/global-config") +async def get_global_config(request: Request): + cs = request.app.state.config_service + return cs.load_global_config() + + +@router.put("/global-config") +async def put_global_config(payload: dict, request: Request): + cs = request.app.state.config_service + try: + cs.save_global_config(payload) + except OSError as exc: + raise HTTPException(500, f"写入 config.yaml 失败:{exc}") from exc + return {"ok": True} + + +@router.get("/llm") +async def get_llm(request: Request): + cs = request.app.state.config_service + return cs.load_llm_registry() + + +@router.put("/llm") +async def put_llm(payload: dict, request: Request): + cs = request.app.state.config_service + try: + cs.save_llm_registry(payload) + except OSError as exc: + raise HTTPException(500, f"写入 llm.yaml 失败:{exc}") from exc + return {"ok": True} + + +@router.get("/schema/{kind}") +async def get_field_schema(kind: str): + """返回面向 UI 的字段清单。kind ∈ {global, llm_profile, language}。""" + try: + return {"kind": kind, "fields": get_schema(kind)} + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + +@router.get("/preferences") +async def get_preferences(request: Request): + return request.app.state.config_service.load_preferences() + + +@router.put("/preferences") +async def put_preferences(payload: dict, request: Request): + cs = request.app.state.config_service + try: + cs.save_preferences(payload) + except OSError as exc: + raise HTTPException(500, f"保存失败:{exc}") from exc + return {"ok": True} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3daefe746b71e4baa3a277bbf5646047f5d7955a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/__init__.py @@ -0,0 +1,25 @@ +"""Pydantic 请求/响应模型集合。""" + +from .schemas import ( + GlobalConfigModel, + LLMProfileModel, + LLMRegistryModel, + LanguageProfileModel, + ScheduleModel, + RunStartRequest, + RunInfoModel, + SetupStatusModel, + InitSetupRequest, +) + +__all__ = [ + "GlobalConfigModel", + "LLMProfileModel", + "LLMRegistryModel", + "LanguageProfileModel", + "ScheduleModel", + "RunStartRequest", + "RunInfoModel", + "SetupStatusModel", + "InitSetupRequest", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/schemas.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb386afe8b4c0e50fcf639b547ec84b2e1301e3 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/models/schemas.py @@ -0,0 +1,112 @@ +"""Pydantic 模型。 + +为了对前端最大限度宽松(允许直接编辑原始 YAML 结构), +大部分配置块使用 ``Dict[str, Any]``,由后端服务层做最小的字段兜底。 +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +try: + from pydantic import BaseModel, Field +except ImportError as exc: # pragma: no cover + raise ImportError( + "缺少 pydantic。请执行 pip install fastapi uvicorn[standard]" + ) from exc + + +# ============================================================================= +# Setup / 初始化 +# ============================================================================= +class SetupStatusModel(BaseModel): + """初始化状态。""" + + initialized: bool = Field(..., description="是否已完成初始化") + config_yaml_exists: bool = False + llm_yaml_exists: bool = False + languages_count: int = 0 + missing_fields: List[str] = Field(default_factory=list, description="全局配置中仍缺失的关键字段") + + +class InitSetupRequest(BaseModel): + """首次初始化请求体。""" + + config: Dict[str, Any] = Field(..., description="conf/config.yaml 的完整内容") + llm: Dict[str, Any] = Field(..., description="conf/llm.yaml 的完整内容") + + +# ============================================================================= +# 全局配置 / LLM +# ============================================================================= +class GlobalConfigModel(BaseModel): + """conf/config.yaml 内容(宽松模型)。""" + + data: Dict[str, Any] = Field(default_factory=dict) + + +class LLMProfileModel(BaseModel): + """单个 LLM profile。""" + + name: str + provider: str + model: str = "" + api_base: str = "" + api_key: str = "" + temperature: float = 0.2 + max_tokens: int = 1024 + batch_size: int = 16 + timeout_seconds: int = 60 + retries: int = 3 + retry_interval_seconds: int = 10 + extra: Dict[str, Any] = Field(default_factory=dict) + + +class LLMRegistryModel(BaseModel): + """conf/llm.yaml 内容。""" + + default: str = "" + profiles: Dict[str, Dict[str, Any]] = Field(default_factory=dict) + + +# ============================================================================= +# 语种 profile +# ============================================================================= +class LanguageProfileModel(BaseModel): + """conf/languages/.yaml 内容。""" + + id: str = Field(..., description="语种短 ID,与文件名一致(例如 vi、ja、ko)") + data: Dict[str, Any] = Field(default_factory=dict, description="完整 YAML 内容") + + +# ============================================================================= +# 运行 / 调度 +# ============================================================================= +class RunStartRequest(BaseModel): + language: str = Field(..., description="要运行的语种 ID") + fresh: bool = False + batch: Optional[str] = None + stage: Optional[str] = None + + +class RunInfoModel(BaseModel): + run_id: str + language: str + status: str # running | finished | failed | killed + started_at: str + finished_at: Optional[str] = None + exit_code: Optional[int] = None + fresh: bool = False + batch: Optional[str] = None + log_file: Optional[str] = None + + +class ScheduleModel(BaseModel): + """一个定时任务。""" + + id: str = Field(..., description="调度 ID,唯一") + language: str + cron: str = Field(..., description="标准 5 字段 cron 表达式:分 时 日 月 周") + enabled: bool = True + fresh: bool = False + description: str = "" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..162edb5260b27bf00aa2410fd678c7c015a854f0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/__init__.py @@ -0,0 +1 @@ +"""服务层:封装文件 IO、子进程、调度器、日志广播。""" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/config_service.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/config_service.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb29be8352633d23bdeb7e5bb7e5337ebf88918 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/config_service.py @@ -0,0 +1,853 @@ +# pylint: disable=line-too-long + +"""配置文件读写服务。 + +统一管理: + * conf/config.yaml —— 全局配置 + * conf/llm.yaml —— LLM profile 注册表 + * conf/languages/*.yaml —— 单语种 profile(文件名即 id) + * workspace/server_meta/preferences.json —— 用户初始化偏好 + * workspace/server_meta/schedules.json —— Web 面板专属元数据 + +所有写操作保留 YAML 可读格式(``default_flow_style=False``、 +``allow_unicode=True``),不打乱注释是做不到的(PyYAML 默认不保留), +但键顺序会按业务常见顺序排列。 +""" + + + +from __future__ import annotations + +import io # pylint: disable=unused-import +import json +import logging +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +import yaml # 仅在 ruamel 不可用时兜底使用 + +# ruamel.yaml 支持 round-trip(保留注释、顺序、空行)。 +# 没装时降级到 PyYAML(会丢注释,但功能可用)。 +try: + from ruamel.yaml import YAML as _RuamelYAML # type: ignore + from ruamel.yaml.comments import CommentedMap # type: ignore + _HAS_RUAMEL = True +except Exception: # pylint: disable=broad-except # pragma: no cover + _RuamelYAML = None # pylint: disable=invalid-name # type: ignore + CommentedMap = dict # type: ignore + _HAS_RUAMEL = False + +logger = logging.getLogger(__name__) + + +def _make_yaml(): + """构造一个 round-trip 的 ruamel.yaml.YAML 实例。""" + y = _RuamelYAML() # 默认 typ='rt' + y.preserve_quotes = True + y.width = 4096 + y.allow_unicode = True + y.indent(mapping=2, sequence=4, offset=2) + return y + + +class ConfigService: + """封装 ``conf/`` 目录下所有读写。""" + + def __init__(self, project_root: Path) -> None: + self.project_root = Path(project_root).resolve() + self.conf_dir = self.project_root / "conf" + self.languages_dir = self.conf_dir / "languages" + self.server_meta_dir = self.project_root / "workspace" / "server_meta" + self.backup_dir = self.conf_dir / ".backup" + + # ------------------------------------------------------------------ + # 路径 + # ------------------------------------------------------------------ + def config_file(self) -> Path: + return self.conf_dir / "config.yaml" + + def llm_file(self) -> Path: + return self.conf_dir / "llm.yaml" + + def language_file(self, lang_id: str) -> Path: + safe = _safe_lang_id(lang_id) + return self.languages_dir / f"{safe}.yaml" + + def schedules_file(self) -> Path: + self.server_meta_dir.mkdir(parents=True, exist_ok=True) + return self.server_meta_dir / "schedules.json" + + def preferences_file(self) -> Path: + self.server_meta_dir.mkdir(parents=True, exist_ok=True) + return self.server_meta_dir / "preferences.json" + + def runs_file(self) -> Path: + self.server_meta_dir.mkdir(parents=True, exist_ok=True) + return self.server_meta_dir / "runs.json" + + def logs_dir(self) -> Path: + d = self.project_root / "workspace" / "server_logs" + d.mkdir(parents=True, exist_ok=True) + return d + + # ------------------------------------------------------------------ + # 偏好(用户初始化时选择要启用的模块) + # ------------------------------------------------------------------ + def load_preferences(self) -> Dict[str, Any]: + p = self.preferences_file() + if not p.exists(): + return { + "enable_platform_first": False, + "enable_platform_second": False, + "enable_notification": False, + "first_platform_type": "none", # phrase | crowdin | none + "second_platform_type": "none", + "notification_type": "none", # wecom | slack | console | email | none + } + try: + with p.open("r", encoding="utf-8") as f: + return json.load(f) or {} + except (OSError, json.JSONDecodeError): + return {} + + def save_preferences(self, data: Dict[str, Any]) -> None: + p = self.preferences_file() + tmp = p.with_suffix(".tmp") + with tmp.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + tmp.replace(p) + + # ------------------------------------------------------------------ + # Setup / 初始化状态检查 + # ------------------------------------------------------------------ + def setup_status(self) -> Dict[str, Any]: + """返回初始化状态与分模块健康检查。 + + 返回结构: + { + initialized: bool, # 核心配置是否已可以跑 workflow + config_yaml_exists: bool, + llm_yaml_exists: bool, + languages_count: int, + missing_fields: [str], # 核心阻塞字段 + checks: [ # 分模块健康检查 + { + module: str, -- project / vcs / llm / platform_first / platform_second / notification / languages + label: str, # 中文名 + status: str, # ok | warn | fail | skip + message: str, # 简短摘要 + details: [str], # 问题清单 + env_hints: [str], # 需要配置的环境变量提示 + }, + ... + ] + } + """ + config_exists = self.config_file().exists() + llm_exists = self.llm_file().exists() + langs = self.list_languages() + prefs = self.load_preferences() + + config_data: Dict[str, Any] = {} + if config_exists: + try: + config_data = self.load_global_config() or {} + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.warning("Failed to parse config.yaml: %s", exc) + + llm_data: Dict[str, Any] = {} + if llm_exists: + try: + llm_data = self.load_llm_registry() or {} + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.warning("Failed to parse llm.yaml: %s", exc) + + checks: List[Dict[str, Any]] = [] + missing: List[str] = [] + + # 1) 文件是否存在 + if not config_exists: + missing.append("conf/config.yaml") + if not llm_exists: + missing.append("conf/llm.yaml") + + # 2) 项目基础 + proj_details: List[str] = [] + if not config_data.get("project_code"): + proj_details.append("project_code 未填") + if not config_data.get("source_locale"): + proj_details.append("source_locale 未填(建议 zh-CN)") + checks.append(_mk_check( + module="project", label="项目基础", + details=proj_details, + ok_msg="项目基础配置完整", + fail_msg="项目基础字段缺失", + )) + + # 3) VCS + vcs = config_data.get("vcs") or {} + vcs_details: List[str] = [] + vcs_env_hints: List[str] = [] + vcs_type = (vcs.get("type") or "").strip() + if not vcs_type: + vcs_details.append("vcs.type 未选择") + # local_path 对所有 vcs 类型(含 local)都必填 —— 它决定流水线在哪里读写 + if not vcs.get("local_path"): + vcs_details.append("vcs.local_path 未填(流水线读写工作副本的根目录;local 推荐填绝对路径)") + # local 和老别名 mock 都不需要 vcs.url + if vcs_type not in {"local", "mock", ""} and not vcs.get("url"): + vcs_details.append("vcs.url 未填(远端仓库地址)") + if vcs_type in {"svn", "perforce"}: + if not vcs.get("username") and not _env_set("GAME_TRANS_TOOLCHAIN__VCS__USERNAME"): + vcs_details.append("vcs.username 未填 且 环境变量未设置") + vcs_env_hints.append("GAME_TRANS_TOOLCHAIN__VCS__USERNAME") + if not vcs.get("password") and not _env_set("GAME_TRANS_TOOLCHAIN__VCS__PASSWORD"): + vcs_details.append("vcs.password 未填 且 环境变量未设置") + vcs_env_hints.append("GAME_TRANS_TOOLCHAIN__VCS__PASSWORD") + checks.append(_mk_check( + module="vcs", label="版本控制 (VCS)", + details=vcs_details, env_hints=vcs_env_hints, + ok_msg=f"VCS 已配置 ({vcs_type or '未选'})", + fail_msg="VCS 配置不完整", + )) + + # 4) LLM + llm_details: List[str] = [] + llm_env_hints: List[str] = [] + profiles = (llm_data.get("profiles") or {}) if isinstance(llm_data, dict) else {} + default_profile = (llm_data.get("default") or "") if isinstance(llm_data, dict) else "" + if not profiles: + llm_details.append("conf/llm.yaml 中没有任何 profile") + else: + if default_profile and default_profile not in profiles: + llm_details.append(f"默认 profile '{default_profile}' 不在 profiles 列表中") + # 结构性检查(所有 profile):provider 必须填 + for name, prof in profiles.items(): + if not isinstance(prof, dict): + llm_details.append(f"profile '{name}' 结构非法") + continue + provider = prof.get("provider") or "" + if not provider: + llm_details.append(f"profile '{name}' 缺 provider") + # **严格 api_key / 必填 extra** 检查只针对**默认 profile**。 + # 其他 profile 允许作为"示例/占位 YAML 存在",api_key 为空也不阻塞 + # 初始化(真正使用时才由 run 流水线报错,更符合用户心智)。 + if default_profile and default_profile in profiles: + prof = profiles[default_profile] + if isinstance(prof, dict): + provider = (prof.get("provider") or "").strip() + # 老配置里的 `mock` 是 `echo` 的别名,两者都不需 api_key / model。 + if provider and provider not in {"echo", "mock"}: + # model 对真实 provider 必填 + if not (prof.get("model") or "").strip(): + llm_details.append( + f"默认 profile '{default_profile}' 的 model 未填(请在 conf/llm.yaml 或 LLM 页面补充)" + ) + # api_base 对部分 provider 必填 + needs_base = {"openai_compatible", "venus", "hunyuan_translation"} + if provider in needs_base and not (prof.get("api_base") or "").strip(): + llm_details.append( + f"默认 profile '{default_profile}' (provider={provider}) 的 api_base 未填" + ) + # 鉴权凭据检查 —— 按 provider 分支: + # * venus —— 走 extra.secret_id / extra.secret_key(不走 api_key) + # * hunyuan —— 走 api_key + extra.wsid + # * gemini —— 走 api_key 或 GOOGLE_API_KEY 环境变量 + # * 其他真实 —— 走 api_key 或 GAME_TRANS_TOOLCHAIN__LLM__API_KEY + if provider == "venus": + ex = prof.get("extra") or {} + if not ex.get("server_id") or not ex.get("app_group_id"): + llm_details.append( + f"默认 profile '{default_profile}' 为 venus 但 extra.server_id / extra.app_group_id 未填" + ) + # venus 的凭据:extra.secret_id + extra.secret_key,或走环境变量 api_key + has_pair = bool(ex.get("secret_id")) and bool(ex.get("secret_key")) + has_env = _env_set("GAME_TRANS_TOOLCHAIN__LLM__API_KEY") + if not has_pair and not has_env: + llm_details.append( + f"默认 profile '{default_profile}' 为 venus 但未配置 extra.secret_id / extra.secret_key," + f"也未设置环境变量 GAME_TRANS_TOOLCHAIN__LLM__API_KEY=:" + ) + llm_env_hints.append("GAME_TRANS_TOOLCHAIN__LLM__API_KEY") + elif provider == "hunyuan_translation": + if not (prof.get("extra") or {}).get("wsid"): + llm_details.append( + f"默认 profile '{default_profile}' 为 hunyuan_translation 但 extra.wsid 未填" + ) + if not prof.get("api_key") and not _env_set("GAME_TRANS_TOOLCHAIN__LLM__API_KEY"): + llm_details.append( + f"默认 profile '{default_profile}' 的 api_key 未填 且 环境变量 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 未设置" + ) + llm_env_hints.append("GAME_TRANS_TOOLCHAIN__LLM__API_KEY") + elif provider == "gemini": + # gemini 支持 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 或 GOOGLE_API_KEY + if not prof.get("api_key") and not _env_set("GAME_TRANS_TOOLCHAIN__LLM__API_KEY") and not _env_set("GOOGLE_API_KEY"): + llm_details.append( + f"默认 profile '{default_profile}' 为 gemini 但 api_key 未填 且 环境变量 " + f"GAME_TRANS_TOOLCHAIN__LLM__API_KEY / GOOGLE_API_KEY 均未设置" + ) + llm_env_hints.append("GOOGLE_API_KEY") + else: + # openai / openai_compatible / anthropic 等走 api_key + if not prof.get("api_key") and not _env_set("GAME_TRANS_TOOLCHAIN__LLM__API_KEY"): + llm_details.append( + f"默认 profile '{default_profile}' 的 api_key 未填 且 环境变量 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 未设置" + ) + llm_env_hints.append("GAME_TRANS_TOOLCHAIN__LLM__API_KEY") + checks.append(_mk_check( + module="llm", label="LLM 大模型", + details=llm_details, env_hints=llm_env_hints, + ok_msg=f"LLM 已配置 (共 {len(profiles)} 个 profile)", + fail_msg="LLM 配置不完整", + )) + + # 5) 全局平台(可选) + plat = config_data.get("platform") or {} + plat_type = (plat.get("type") or "none").strip() + plat_details: List[str] = [] + plat_env_hints: List[str] = [] + if plat_type in {"phrase", "crowdin"}: + # 要么写了 api_token,要么走环境变量 + tokens_ok = bool(plat.get("api_token")) or _env_set("GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN") + # Phrase 可用 subject_token 代替 api_token + if plat_type == "phrase": + tokens_ok = tokens_ok or bool((plat.get("extra") or {}).get("subject_token")) or _env_set("GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN") + if not tokens_ok: + plat_details.append(f"{plat_type} 平台的 api_token / subject_token 未填且环境变量未设置") + plat_env_hints.append("GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN") + if plat_type == "phrase": + plat_env_hints.append("GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN") + if not plat.get("project_id"): + plat_details.append(f"{plat_type} 平台的 project_id 未填(可在语种 profile 的 reviews 中覆盖)") + status_override = None + else: + # 用户选择 none(不启用全局平台) + status_override = "skip" + checks.append(_mk_check( + module="platform", label=f"审校平台(全局兜底,{plat_type})", + details=plat_details, env_hints=plat_env_hints, + ok_msg=f"全局平台已配置 ({plat_type})", + fail_msg="全局平台配置不完整", + status_override=status_override, + skip_msg="未启用全局审校平台(type=none)", + )) + + # 6) 通知 + notif = config_data.get("notification") or {} + notif_type = (notif.get("type") or "none").strip() + notif_details: List[str] = [] + notif_env_hints: List[str] = [] + if notif_type in {"wecom", "slack"}: + if not notif.get("webhook") and not _env_set("GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK"): + notif_details.append(f"{notif_type} 通知的 webhook 未填且环境变量未设置") + notif_env_hints.append("GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK") + notif_override = None + elif notif_type == "email": + notif_details.append("email 通知的详细字段请在语种 profile 中按需覆盖") + notif_override = None + else: + notif_override = "skip" + checks.append(_mk_check( + module="notification", label=f"通知渠道 ({notif_type})", + details=notif_details, env_hints=notif_env_hints, + ok_msg=f"通知已配置 ({notif_type})", + fail_msg="通知配置不完整", + status_override=notif_override, + skip_msg="未启用通知(type=none / console)", + )) + + # 7) 语种 + lang_details: List[str] = [] + if not langs: + lang_details.append("conf/languages/ 下还没有任何语种 profile,无法启动工作流") + checks.append(_mk_check( + module="languages", label=f"语种 profile ({len(langs)} 个)", + details=lang_details, + ok_msg=f"已有 {len(langs)} 个语种 profile", + fail_msg="还没有任何语种 profile", + )) + + # 最终 initialized 判定 + blocking_modules = {"project", "vcs", "llm"} + has_blocker = any( + c["module"] in blocking_modules and c["status"] == "fail" + for c in checks + ) + initialized = config_exists and llm_exists and not has_blocker + # 把阻塞字段也汇总 + for c in checks: + if c["module"] in blocking_modules and c["status"] == "fail": + missing.extend(c["details"]) + + return { + "initialized": initialized, + "config_yaml_exists": config_exists, + "llm_yaml_exists": llm_exists, + "languages_count": len(langs), + "missing_fields": missing, + "preferences": prefs, + "checks": checks, + } + + # ------------------------------------------------------------------ + # 全局 config.yaml + # ------------------------------------------------------------------ + def load_global_config(self) -> Dict[str, Any]: + return _load_yaml(self.config_file()) + + def save_global_config(self, data: Dict[str, Any]) -> None: + """保存全局 config.yaml(合并模式,保留注释)。 + + 行为: + - 读旧文件(含注释) → 把 ``data`` 的键值**合并**进去(已有 key 更新、 + 新 key 追加)→ 写回。注释、键顺序、空行基本保留。 + - 若 ``platform.type`` 发生变化,自动把所有已存在的语种 profile + 的 ``reviews.{first,second,light}.platform`` 同步成新值。 + """ + old_type = "" + existing: Dict[str, Any] = {} + try: + existing = self.load_global_config() or {} + old_type = ((existing.get("platform") or {}).get("type") or "").strip() + except Exception: # pylint: disable=broad-except # pragma: no cover + pass + + self._backup(self.config_file()) + merged = _merge_into(existing if existing else {}, data or {}) + _dump_yaml(self.config_file(), merged) + + new_type = ((merged.get("platform") or {}).get("type") or "none").strip() + if new_type != old_type: + self._sync_language_platforms(new_type) + + def _sync_language_platforms(self, platform_type: str) -> None: + """把所有语种 profile 的 reviews.*.platform 同步到 ``platform_type``。""" + if not self.languages_dir.exists(): + return + for p in self.languages_dir.glob("*.yaml"): + try: + data = _load_yaml(p) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.warning("Skip syncing %s: %s", p, exc) + continue + if not isinstance(data, dict): + continue + reviews = data.setdefault("reviews", {}) if isinstance(data.get("reviews", {}), dict) else {} + changed = False + for stage in ("first", "second", "light"): + stage_cfg = reviews.setdefault(stage, {}) if isinstance(reviews.get(stage, {}), dict) else {} + has_project = bool((stage_cfg.get("project_id") or "").strip()) or \ + bool((stage_cfg.get("project_name") or "").strip()) + new_val = platform_type if (has_project and platform_type and platform_type != "none") else "none" + if stage_cfg.get("platform") != new_val: + stage_cfg["platform"] = new_val + changed = True + reviews[stage] = stage_cfg + if changed: + data["reviews"] = reviews + self._backup(p) + _dump_yaml(p, data) + logger.info("[CONFIG] synced reviews.*.platform in %s → %r", p.name, platform_type) + + # ------------------------------------------------------------------ + # LLM llm.yaml + # ------------------------------------------------------------------ + def load_llm_registry(self) -> Dict[str, Any]: + data = _load_yaml(self.llm_file()) + data.setdefault("profiles", {}) + data.setdefault("default", "") + _normalize_llm_profiles(data.get("profiles") or {}) + return data + + def save_llm_registry(self, data: Dict[str, Any]) -> None: + """保存 llm.yaml(合并模式,保留注释与已有示例 profile)。 + + 行为: + - 校验 profile 名合法; + - 与已有 llm.yaml 做**深合并**: + * ``default`` 若 ``data`` 有值则覆盖;否则保留旧值; + * ``profiles`` 下已有 key → 字段级合并;新 key → 追加。 + 这样向导传入的 payload 不会把 llm.yaml 里已有的示例 profile 丢弃。 + """ + profiles = (data or {}).get("profiles") or {} + if not isinstance(profiles, dict): + raise ValueError("llm.yaml 的 profiles 必须是对象(key -> profile 配置)") + for name in profiles.keys(): + if not isinstance(name, str) or not name.strip(): + raise ValueError("LLM profile 名称不能为空") + if any(ch.isspace() for ch in name) or "/" in name or "\\" in name: + raise ValueError( + f"LLM profile 名称 '{name}' 不能包含空白字符或路径分隔符," + "建议使用 `provider_model` 的小写蛇形命名(如 openai_gpt4o_mini)" + ) + + # 入库前把 extra 下本该是 dict 的字段(model_params / extra 等)从 + # 可能的 JSON 字符串形式归一化回真实 dict,避免老前端的容错 bug + # 把文本污染到持久化配置里。 + _normalize_llm_profiles(profiles) + + existing = self.load_llm_registry() or {} + existing.setdefault("profiles", {}) + existing.setdefault("default", "") + + self._backup(self.llm_file()) + merged = _merge_into(existing, data or {}) + _dump_yaml(self.llm_file(), merged) + + def upsert_llm_profile(self, name: str, profile: Dict[str, Any]) -> None: + reg = self.load_llm_registry() + reg.setdefault("profiles", {})[name] = profile + if not reg.get("default"): + reg["default"] = name + self.save_llm_registry(reg) + + def delete_llm_profile(self, name: str) -> None: + reg = self.load_llm_registry() + profiles = reg.get("profiles") or {} + if name in profiles: + del profiles[name] + if reg.get("default") == name: + reg["default"] = next(iter(profiles), "") + self.save_llm_registry(reg) + + # ------------------------------------------------------------------ + # 语种 profile + # ------------------------------------------------------------------ + def list_languages(self) -> List[Dict[str, Any]]: + if not self.languages_dir.exists(): + return [] + items: List[Dict[str, Any]] = [] + for p in sorted(self.languages_dir.glob("*.yaml")): + try: + data = _load_yaml(p) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.warning("Failed to load %s: %s", p, exc) + data = {} + # id 使用文件名(p.stem)作为稳定索引键,与所有 CRUD API 的路径 + # 参数保持一致。YAML 内的 `id` 字段仅作为"业务别名"展示,便于用户 + # 识别用途(例如 de.yaml 的 id 字段 = "de_example" 表示这是示例)。 + file_id = p.stem + business_alias = (data.get("id") or "").strip() + items.append({ + "id": file_id, + "alias": business_alias if business_alias and business_alias != file_id else "", + "display_name": data.get("display_name", file_id), + "target_locale": data.get("target_locale", ""), + "workflow": data.get("workflow", []), + "updated_at": _ts(p), + }) + return items + + def load_language(self, lang_id: str) -> Dict[str, Any]: + return _load_yaml(self.language_file(lang_id)) + + def save_language(self, lang_id: str, data: Dict[str, Any]) -> None: + """保存语种 profile(合并模式,保留注释)。 + + 自动化行为: + - 与已有 YAML 做**深合并**:保留原有注释、顺序; + - **自动同步** ``reviews.{first, second, light}.platform`` 与全局 + ``config.yaml`` 的 ``platform.type`` 保持一致(审校平台只在全局 + 配置一次,所有阶段都用它)。 + - 若某阶段的 ``project_id`` / ``project_name`` 均为空,则认为该 + 阶段**禁用**,platform 置为 ``"none"`` 以便 workflow 跳过。 + """ + self.languages_dir.mkdir(parents=True, exist_ok=True) + path = self.language_file(lang_id) + self._backup(path) + data["id"] = lang_id + + existing = _load_yaml(path) if path.exists() else {} + merged = _merge_into(existing if existing else {}, data) + + # 读取全局 platform.type,自动写回各阶段 + try: + global_cfg = self.load_global_config() or {} + global_platform_type = ((global_cfg.get("platform") or {}).get("type") or "none").strip() + except Exception: # pylint: disable=broad-except # pragma: no cover + global_platform_type = "none" + + reviews = merged.setdefault("reviews", {}) + for stage in ("first", "second", "light"): + stage_cfg = reviews.setdefault(stage, {}) + # 判定该阶段是否"启用":填了 project_id 或 project_name + has_project = bool((stage_cfg.get("project_id") or "").strip()) or \ + bool((stage_cfg.get("project_name") or "").strip()) + if has_project and global_platform_type and global_platform_type != "none": + stage_cfg["platform"] = global_platform_type + else: + stage_cfg["platform"] = "none" + + _dump_yaml(path, merged) + + def delete_language(self, lang_id: str) -> None: + path = self.language_file(lang_id) + if path.exists(): + self._backup(path) + path.unlink() + + # ------------------------------------------------------------------ + # 备份 + # ------------------------------------------------------------------ + def _backup(self, path: Path) -> None: + if not path.exists(): + return + self.backup_dir.mkdir(parents=True, exist_ok=True) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + dest = self.backup_dir / f"{path.name}.{ts}.bak" + try: + shutil.copy2(path, dest) + except OSError as exc: # pragma: no cover + logger.warning("Backup failed for %s: %s", path, exc) + + +# ----------------------------------------------------------------------------- +# 辅助 +# ----------------------------------------------------------------------------- +def _mk_check( + *, + module: str, + label: str, + details: List[str], + ok_msg: str, + fail_msg: str, + env_hints: Optional[List[str]] = None, + status_override: Optional[str] = None, + skip_msg: str = "", +) -> Dict[str, Any]: + """构造一个 check 条目。""" + if status_override: + return { + "module": module, "label": label, + "status": status_override, + "message": skip_msg or ok_msg, + "details": [], + "env_hints": [], + } + status = "ok" if not details else "fail" + message = ok_msg if status == "ok" else fail_msg + return { + "module": module, "label": label, + "status": status, "message": message, + "details": details, "env_hints": env_hints or [], + } + + +def _env_set(name: str) -> bool: + import os + return bool(os.environ.get(name, "").strip()) + + +def _safe_lang_id(lang_id: str) -> str: + if not lang_id or "/" in lang_id or "\\" in lang_id or lang_id in {".", ".."}: + raise ValueError(f"invalid language id: {lang_id!r}") + return lang_id + + +def _load_yaml(path: Path) -> Dict[str, Any]: + """加载 YAML。使用 ruamel.yaml round-trip 读入,保留注释/顺序/锚点。 + + 返回值既可以当普通 dict 用(Vue 前端/其他服务),也能原地改回写时保留注释。 + """ + if not path.exists(): + return {} + if _HAS_RUAMEL: + yml = _make_yaml() + with path.open("r", encoding="utf-8") as f: + data = yml.load(f) + return data if data is not None else {} + with path.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) + return data or {} + + +def _dump_yaml(path: Path, data: Dict[str, Any]) -> None: + """写回 YAML。使用 ruamel.yaml round-trip 保留注释/顺序。""" + path.parent.mkdir(parents=True, exist_ok=True) + if _HAS_RUAMEL: + yml = _make_yaml() + with path.open("w", encoding="utf-8") as f: + yml.dump(data, f) + return + with path.open("w", encoding="utf-8") as f: + yaml.safe_dump( + data, + f, + default_flow_style=False, + allow_unicode=True, + sort_keys=False, + indent=2, + ) + + +def _plain_merged(target: Any, source: Any) -> Any: + """构造一个**普通 dict** 版本的深合并结果(不带 ruamel 注释容器)。""" + if not isinstance(source, dict): + return source + if not isinstance(target, dict): + return dict(source) + out: Dict[str, Any] = {} + for k, v in target.items(): + out[k] = v + for k, v in source.items(): + if k in out and isinstance(out[k], dict) and isinstance(v, dict): + out[k] = _plain_merged(out[k], v) + else: + out[k] = v + return out + + +def _merge_commented_subdoc(container: Any, patch: Dict[str, Any]) -> None: + """就地把 ``patch`` 合并到 ``container`` (ruamel CommentedMap)。 + + 关键修复:ruamel.yaml 把"**跟在当前 subdoc 之后、属于父级的分区注释**" + (如 ``# ---- next section ----``)错误地挂在了 subdoc 内部**最后一个 + key** 的"after-value"注释槽上(``.ca.items[last_key][2]``)。如果直接 + 往 subdoc 追加新 key,这段分区注释会被挤到新 key 的中间,出现::: + + notification: + type: none + # ---- next section ---- ← 本应在 subdoc 结束之后 + webhook: ... ← 新 key 跑到了注释下方(错位) + + 为此,追加前先把这段 after-注释从旧的"最后一个 key"剥离、暂存,追加 + 完成后把它挂到**新的最后一个 key** 的 after 槽上,让它继续起分区注释 + 作用。 + """ + # 对已存在 key:原地赋值(允许用相同 key 刷新值;ruamel 会保留其注释) + # 对新 key:追加到末尾(追加前要先暂存旧末尾 key 的 after-注释) + existing_keys = list(container.keys()) if hasattr(container, "keys") else [] + new_keys = [k for k in patch.keys() if k not in existing_keys] + + # 暂存"旧末尾 key"的 after-注释(如果有) + cached_after = None + cached_key = None + if _HAS_RUAMEL and new_keys and existing_keys: + tail = existing_keys[-1] + try: + slot = container.ca.items.get(tail) if container.ca else None + if slot and slot[2]: + cached_after = slot[2] + cached_key = tail + slot[2] = None + except Exception: # pylint: disable=broad-except # pragma: no cover + pass + + # 更新已存在的 key + for k in existing_keys: + if k in patch: + v_patch = patch[k] + v_cur = container[k] + if isinstance(v_cur, dict) and isinstance(v_patch, dict) and _HAS_RUAMEL and isinstance(v_cur, CommentedMap): + # 递归合并嵌套 subdoc(同样走"暂存+迁移"策略) + _merge_commented_subdoc(v_cur, v_patch) + else: + container[k] = v_patch + + # 追加新 key + for k in new_keys: + v = patch[k] + if _HAS_RUAMEL and isinstance(v, dict): + inner = CommentedMap() + _merge_commented_subdoc(inner, v) + container[k] = inner + else: + container[k] = v + + # 把暂存的 after-注释挂到新末尾 key 上 + if cached_after is not None and _HAS_RUAMEL: + all_keys = list(container.keys()) + if all_keys: + new_tail = all_keys[-1] + try: + items = container.ca.items + if new_tail not in items: + items[new_tail] = [None, None, None, None] + items[new_tail][2] = cached_after + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.debug("Restore trailing comment failed on key %r: %s", new_tail, exc) + # 回滚到原位置,不丢注释 + try: + container.ca.items[cached_key][2] = cached_after + except Exception: # pylint: disable=broad-except + pass + + +def _merge_into(target: Any, source: Any) -> Any: + """把 ``source`` 的键合并到 ``target``,并返回合并后的 target。 + + 合并策略: + - 若 target 是 ruamel.yaml CommentedMap:使用 ``_merge_commented_subdoc`` + 做"暂存分区注释 + 原地追加 key + 迁移注释"的 round-trip 友好合并; + - 若 target 不是 dict:用 source 替换; + - 若 ruamel 不可用:退化为普通 dict 的深合并(注释天然无保留)。 + + 这个实现解决了 ruamel.yaml 对"**分区注释存在前一个 subdoc 内部最后一 + 个 key 的 after 槽**"的归属偏差 bug —— 追加/修改 key 时主动迁移这段 + 注释,让它继续起到"分区标题"的作用,不会错位到 subdoc 内部。 + """ + if not isinstance(source, dict): + return source + if not isinstance(target, dict): + if _HAS_RUAMEL: + new = CommentedMap() + _merge_commented_subdoc(new, source) + return new + return _plain_merged({}, source) + if _HAS_RUAMEL and isinstance(target, CommentedMap): + _merge_commented_subdoc(target, source) + return target + # 退化路径(没装 ruamel,或已经是普通 dict) + for k, v in source.items(): + if k in target and isinstance(target[k], dict) and isinstance(v, dict): + target[k] = _plain_merged(target[k], v) + else: + target[k] = v + return target + + +# 这些 key 在 LLM profile 的 extra 下,schema 中声明为 type="dict"。 +# 老前端的容错 bug 曾把输入框原文(可能是 JSON 字符串)直接存成 string, +# 导致下次打开"没渲染"。这里在读/写时做兜底归一化。 +_LLM_EXTRA_DICT_KEYS = ("model_params", "generation_config", "extra") + + +def _normalize_llm_profiles(profiles: Dict[str, Any]) -> None: + """就地归一化:把被误存成 JSON 字符串的 extra 子 dict 恢复为真实 dict。 + + 参数: + profiles: ``llm.yaml`` 的 ``profiles`` 节点(key -> profile 配置)。 + 修改是**原地的**,调用方不需要接收返回值。 + """ + if not isinstance(profiles, dict): + return + for _name, prof in profiles.items(): + if not isinstance(prof, dict): + continue + extra = prof.get("extra") + if not isinstance(extra, dict): + continue + for k in _LLM_EXTRA_DICT_KEYS: + v = extra.get(k) + if isinstance(v, str): + t = v.strip() + if not t: + extra[k] = {} + continue + try: + parsed = json.loads(t) + except Exception: # pylint: disable=broad-except + # 实在解析不动就留着原字符串,前端的新 asJson 会尝试 + # 再解一次;保守做法是不冒险扔数据。 + continue + if isinstance(parsed, dict): + extra[k] = parsed + + +def _ts(path: Path) -> str: + try: + return datetime.fromtimestamp(path.stat().st_mtime).isoformat(timespec="seconds") + except OSError: + return "" diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/field_schema.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/field_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..3cfd7d22a97e4c662c0c64017ec5715f2a796986 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/field_schema.py @@ -0,0 +1,436 @@ +# pylint: disable=line-too-long + +"""字段 schema —— 面向 UI 的"配置项清单"。 + +把 YAML 的每个关键字段抽象成一个描述项: + * key: 点分路径(如 ``vcs.url``) + * label: 中文标签 + * type: 表单控件类型(string / password / int / float / bool / select / list / dict / textarea) + * required: 是否必填(在当前"启用场景"下) + * placeholder: 输入框占位符 + * example: 示例值(给用户参考) + * help: 详细说明(显示在输入框下方) + * options: select / radio 的候选项 + * secret: 是否敏感字段(UI 用 password 组件 + 建议走环境变量) + * env_hint: 对应的环境变量名(可选) + * default: 默认值 + * group: 表单分组标题 + +本模块**只是**面向 UI 的描述数据,并不承担数据校验职责——真正校验仍走 +框架内部的 ``validate(config)``。 +""" + + + +from __future__ import annotations + +from typing import Any, Dict, List + + +def _f(**kw: Any) -> Dict[str, Any]: + """构造一个字段描述,key 必填,其他可选。 + + 支持的额外元信息(前端据此做条件渲染/校验): + depends_on: str + 父字段路径(如 ``"provider"`` 或 ``"vcs.type"``)。配合 + ``applies_to`` / ``required_if`` 使用。 + applies_to: list[str] + 仅当父字段的值 ∈ 列表时才显示本字段;未命中则 UI 隐藏。 + required_if: list[str] + 仅当父字段的值 ∈ 列表时才视为必填;否则按选填处理。 + """ + kw.setdefault("required", False) + kw.setdefault("secret", False) + return kw + + +# ============================================================================= +# 全局 config.yaml 的字段清单 +# ============================================================================= +def global_config_schema() -> List[Dict[str, Any]]: + return [ + # ----- 项目基础 ----- + _f(key="project_code", label="项目标识 project_code", + type="string", required=True, group="项目基础", + placeholder="my_game", example="dragon_quest_mobile", + help="产品 slug,出现在日志前缀、通知标题、状态文件名;建议小写字母+下划线。"), + _f(key="stage", label="发版阶段 stage", + type="select", group="项目基础", + options=["exp_week", "trunk_week", "pub_week", "hot_week"], + default="trunk_week", + help="当前流水线阶段,可被命令行 --stage 覆盖。"), + _f(key="source_locale", label="源语种 source_locale", + type="string", required=True, group="项目基础", + default="zh-CN", example="zh-CN", + help="源语种 BCP-47 代码。中国出海项目通常固定为 zh-CN。"), + + # ----- VCS ----- + _f(key="vcs.type", label="VCS 类型", + type="select", required=True, group="版本控制", + options=["local", "git", "svn", "perforce"], + default="local", + help="选 **local** 可零依赖试跑(无需远端 URL / 账号密码,流水线直接在本地工作副本路径读写源文件与译文);真实项目选对应的后端。老配置里的 `mock` 自动视为 `local`。"), + _f(key="vcs.url", label="仓库地址 vcs.url", + type="string", group="版本控制", + depends_on="vcs.type", applies_to=["git", "svn", "perforce"], + required_if=["git", "svn", "perforce"], + placeholder="https://github.com/you/game-i18n.git", + example="https://svn.example.com/game-i18n/trunk", + help="远端仓库地址;选 mock 时不需要。"), + _f(key="vcs.local_path", label="本地工作副本 vcs.local_path", + type="string", required=True, group="版本控制", + placeholder="D:/workspace/game-i18n 或 workspace/repo", + example="C:/data/game-i18n 或 svn/game", + help="**所有 VCS 类型都必填**。可填**绝对路径**(如 `D:/workspace/xxx`,推荐 mock 场景使用,流水线直接读写该目录);也可填**相对路径**(factory 自动拼接 workspace 根,git/svn/perforce 常用);不要加 'workspace/' 前缀。"), + _f(key="vcs.revision", label="修订号 vcs.revision", + type="string", group="版本控制", default="HEAD", + depends_on="vcs.type", applies_to=["git", "svn", "perforce"], + help="默认 HEAD,可指定 commit / changelist / rev。"), + _f(key="vcs.username", label="用户名 vcs.username", + type="string", group="版本控制", secret=True, + depends_on="vcs.type", applies_to=["svn", "perforce"], + env_hint="GAME_TRANS_TOOLCHAIN__VCS__USERNAME", + help="建议走环境变量注入;仅 svn / perforce 场景需要。"), + _f(key="vcs.password", label="密码 vcs.password", + type="password", group="版本控制", secret=True, + depends_on="vcs.type", applies_to=["svn", "perforce"], + env_hint="GAME_TRANS_TOOLCHAIN__VCS__PASSWORD", + help="**严禁明文提交**;优先走环境变量。"), + _f(key="vcs.cli_timeout_seconds", label="CLI 超时(秒)", + type="int", group="版本控制", default=600, + depends_on="vcs.type", applies_to=["git", "svn", "perforce"], + help="单条 svn / git / p4 命令超时时间。"), + _f(key="vcs.default_commit_message", label="默认提交消息", + type="string", group="版本控制", + default="[TiMi_HOK_Game_Translator] commit translation data", + depends_on="vcs.type", applies_to=["git", "svn", "perforce"], + help="push_vcs 阶段的提交消息兜底。"), + + # ----- LLM profile 引用 ----- + _f(key="llm_profile", label="默认 LLM profile", + type="llm_profile_ref", group="LLM 引用", required=True, + placeholder="echo", + help="指向 conf/llm.yaml 的 profiles 下的 key,必须存在;下拉列表来自已配置的 profiles。"), + + # ----- 全局平台(统一审校平台配置) ----- + _f(key="platform.type", label="审校平台 type", + type="select", group="审校平台", + options=["none", "phrase", "crowdin"], default="none", + help="**统一**审校平台 —— 一审 / 二审 / 轻校对**都用这一个平台**,只是在各语种的 reviews.* 下填不同的 project_id 来区分项目。"), + _f(key="platform.api_base", label="api_base", + type="string", group="审校平台", + depends_on="platform.type", applies_to=["phrase", "crowdin"], + placeholder="https://api.crowdin.com/api/v2", + help="Phrase 常见:https://cloud.memsource.com/web/api2 ;EU 账户:https://cloud.memsource.com/web/api2 ;US 账户:https://us.cloud.memsource.com/web/api2"), + _f(key="platform.api_token", label="api_token", + type="password", group="审校平台", secret=True, + depends_on="platform.type", applies_to=["phrase", "crowdin"], + env_hint="GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN", + help="**敏感**;Crowdin 使用;Phrase 推荐改用下方 subject_token。建议走环境变量。"), + _f(key="platform.project_id", label="默认 project_id", + type="string", group="审校平台", + depends_on="platform.type", applies_to=["phrase", "crowdin"], + help="全局默认项目;多项目场景下在语种 profile 的 reviews.* 阶段覆盖。"), + _f(key="platform.extra.region", label="Phrase region", + type="select", group="审校平台", + depends_on="platform.type", applies_to=["phrase"], + options=["", "eu", "us"], + help="仅 Phrase 使用:EU 账户 → eu,US 账户 → us。"), + _f(key="platform.extra.subject_token", label="Phrase subject_token", + type="password", group="审校平台", secret=True, + depends_on="platform.type", applies_to=["phrase"], + env_hint="GAME_TRANS_TOOLCHAIN__PLATFORM__SUBJECT_TOKEN", + help="**敏感**;Phrase 推荐的鉴权方式,走环境变量更安全。"), + + # ----- 通知 ----- + _f(key="notification.type", label="通知渠道 type", + type="select", group="通知", + options=["none", "console", "wecom"], + default="none", + help="none 不通知;console 走日志;wecom 走企业微信群机器人 webhook。"), + _f(key="notification.webhook", label="webhook 地址", + type="password", group="通知", secret=True, + depends_on="notification.type", applies_to=["wecom"], + required_if=["wecom"], + env_hint="GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK", + placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx", + help="企业微信群机器人地址,**敏感**,建议走环境变量注入。"), + + # ----- Workspace / 日志 ----- + _f(key="workspace.root", label="workspace 绝对路径", + type="string", group="工作区", + help="留空则取 ${CWD}/workspace。"), + _f(key="workspace.subdir", label="workspace 子目录", + type="string", group="工作区", default="workspace"), + _f(key="workspace.state_filename", label="状态文件名", + type="string", group="工作区", default="workflow_state.json", + help="断点续跑状态落盘文件名。"), + _f(key="logging.level", label="日志级别", + type="select", group="日志", + options=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], + default="INFO"), + _f(key="logging.directory", label="日志目录", + type="string", group="日志", default="logs"), + _f(key="logging.filename", label="日志文件名", + type="string", group="日志", default="TiMi_HOK_Game_Translator.log"), + _f(key="logging.console", label="同时输出到控制台", + type="bool", group="日志", default=True), + ] + + +# ============================================================================= +# 单个 LLM profile 的字段清单 +# ============================================================================= +def llm_profile_schema() -> List[Dict[str, Any]]: + return [ + # ---------- 基础(所有 provider 通用) ---------- + _f(key="name", label="profile 名称", + type="string", required=True, group="基础", + placeholder="my_openai_gpt4o_mini", + help="**必须全局唯一**。被 config.yaml 的 llm_profile 字段或语种 profile 的 llm_profile 字段按名引用,重名会导致冲突。建议格式:`_`,例如 `openai_gpt4o_mini`、`hunyuan_mt2_plus`、`venus_deepseek_v3`。注意:带 `_example` 后缀的是模板示例,请复制后重命名再使用。"), + _f(key="provider", label="provider 提供商", + type="select", required=True, group="基础", + options=["echo", "openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + default="echo", + help="选 **echo** 零依赖试跑(回显式占位 LLM,把原文打上语种标签输出,无需 api_key / api_base);openai_compatible 可对接 DeepSeek / Kimi / GLM / Qwen 等;gemini 走 Google AI Studio。老配置里的 `mock` 自动视为 `echo`。"), + _f(key="model", label="模型名 model", + type="string", group="基础", + depends_on="provider", applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + required_if=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + placeholder="gpt-4o-mini", example="gemini-2.5-flash / claude-3-5-sonnet", + help="模型 ID;gemini 常用 gemini-2.5-flash / gemini-2.5-pro;venus / hunyuan_translation 走的是服务端模型路由。"), + + # ---------- 接入(根据 provider 条件显示) ---------- + _f(key="api_base", label="api_base", + type="string", group="接入", + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + required_if=["openai_compatible", "venus", "hunyuan_translation"], + placeholder="https://api.openai.com/v1", + help="**OpenAI** 官方可省;**gemini** 默认 `https://generativelanguage.googleapis.com`;**venus** 常用 `http://v2.open.venus.oa.com/chat/single`(内网);**openai_compatible** / **hunyuan_translation** 必填完整 URL。"), + _f(key="api_key", label="api_key", + type="password", group="接入", secret=True, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "hunyuan_translation"], + required_if=["openai", "openai_compatible", "anthropic", "gemini", "hunyuan_translation"], + env_hint="GAME_TRANS_TOOLCHAIN__LLM__API_KEY", + help="**敏感**;建议走环境变量。gemini 也支持 GOOGLE_API_KEY。**venus 的凭据**不在此处填写,请到下方「Venus 专属」分组分别填 secret_id / secret_key。"), + + # ---------- Venus 专属 ---------- + _f(key="extra.server_id", label="server_id", + type="int", group="Venus 专属", + depends_on="provider", applies_to=["venus"], required_if=["venus"], + placeholder="3", example="3 / 42", + help="Venus 平台的服务 ID(整数),**必填**。来自 Venus 控制台 → 服务管理。"), + _f(key="extra.app_group_id", label="app_group_id", + type="int", group="Venus 专属", + depends_on="provider", applies_to=["venus"], required_if=["venus"], + placeholder="4", example="4 / 128", + help="Venus 平台的应用组 ID(整数),**必填**。来自 Venus 控制台 → 应用组。"), + _f(key="extra.secret_id", label="secret_id", + type="password", group="Venus 专属", secret=True, + depends_on="provider", applies_to=["venus"], + env_hint="GAME_TRANS_TOOLCHAIN__LLM__API_KEY", + placeholder="Venus 控制台生成的 secret_id", + help="Venus 鉴权凭据之一,与 secret_key 配对使用。**敏感**,上线前请改走环境变量 `GAME_TRANS_TOOLCHAIN__LLM__API_KEY=:`。"), + _f(key="extra.secret_key", label="secret_key", + type="password", group="Venus 专属", secret=True, + depends_on="provider", applies_to=["venus"], + env_hint="GAME_TRANS_TOOLCHAIN__LLM__API_KEY", + placeholder="Venus 控制台生成的 secret_key", + help="Venus 鉴权凭据之一,与 secret_id 配对使用。**敏感**,上线前请改走环境变量。"), + _f(key="extra.model_params", label="model_params 生成参数", + type="dict", group="Venus 专属", + depends_on="provider", applies_to=["venus"], + placeholder='{"repetition_penalty": 1.1, "do_sample": false}', + example='{"repetition_penalty": 1.1, "do_sample": false, "top_p": 0.9, "top_k": 40}', + help="**JSON 对象**,透传到 Venus 请求体,用于控制解码行为。常用键:`repetition_penalty`(重复惩罚,1.0~2.0)、`do_sample`(是否采样)、`top_p`、`top_k`、`max_new_tokens` 等。留空则不传。"), + + # ---------- 混元翻译专属 ---------- + _f(key="extra.wsid", label="wsid 工作空间 ID", + type="string", group="混元翻译专属", + depends_on="provider", applies_to=["hunyuan_translation"], required_if=["hunyuan_translation"], + help="混元翻译服务的工作空间 ID,**必填**。"), + _f(key="extra.top_p", label="top_p", + type="float", group="混元翻译专属", default=1.0, + depends_on="provider", applies_to=["hunyuan_translation"], + help="解码参数:核采样阈值,取 0.0~1.0。"), + _f(key="extra.top_k", label="top_k", + type="int", group="混元翻译专属", default=-1, + depends_on="provider", applies_to=["hunyuan_translation"], + help="解码参数:候选词数量,-1 表示不限制。"), + _f(key="extra.repetition_penalty", label="repetition_penalty", + type="float", group="混元翻译专属", default=1.0, + depends_on="provider", applies_to=["hunyuan_translation"], + help="重复惩罚系数,大于 1 会抑制重复,范围 1.0~2.0。"), + + # ---------- 调用参数(所有真实 provider 通用) ---------- + _f(key="temperature", label="temperature", + type="float", group="调用参数", default=0.2, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + help="翻译建议 0.1 ~ 0.3,稳定性优先。"), + _f(key="max_tokens", label="max_tokens", + type="int", group="调用参数", default=1024, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + help="单次响应上限;长文本建议 4096。"), + _f(key="batch_size", label="batch_size", + type="int", group="调用参数", default=16, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"], + help="单次打包多少条 Entry;越大越省调用次数但更易超时。"), + + # ---------- 重试与超时 ---------- + _f(key="timeout_seconds", label="timeout_seconds", + type="int", group="重试与超时", default=60, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"]), + _f(key="retries", label="retries", + type="int", group="重试与超时", default=3, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"]), + _f(key="retry_interval_seconds", label="retry_interval_seconds", + type="int", group="重试与超时", default=10, + depends_on="provider", + applies_to=["openai", "openai_compatible", "anthropic", "gemini", "venus", "hunyuan_translation"]), + ] + + +# ============================================================================= +# 语种 profile 的字段清单 +# ============================================================================= +def language_profile_schema() -> List[Dict[str, Any]]: + return [ + # ----- 基础 ----- + _f(key="id", label="语种 ID", + type="string", required=True, group="基础", + placeholder="vi / ja / ko", + help="与文件名一致的短 ID。"), + _f(key="display_name", label="显示名", + type="string", group="基础", + placeholder="越南语", + help="日志 / 通知中使用的中文名。"), + _f(key="source_locale", label="source_locale", + type="string", group="基础", default="zh-CN"), + _f(key="target_locale", label="target_locale", + type="string", required=True, group="基础", + placeholder="vi", + help="BCP-47 代码,如 vi、ja、ko、ar、tr。"), + _f(key="locale_names.cn", label="locale_names.cn", + type="string", group="基础", placeholder="越南语", + help="提示词中语种名的中文显示覆盖。"), + _f(key="locale_names.en", label="locale_names.en", + type="string", group="基础", placeholder="Vietnamese", + help="提示词中语种名的英文显示覆盖。"), + + # ----- source ----- + _f(key="source.format", label="源文件格式", + type="select", required=True, group="源文件", + options=["xlsx", "json", "yaml", "xml", "csv", "dtxml", "xliff"], + default="xlsx", + help="游戏项目强烈推荐 xlsx(支持 EnTerms/Terms 术语列)。💡 切换此项时,下方「源文件路径」若已是常见后缀会**自动同步**后缀。"), + _f(key="source.path", label="源文件路径", + type="string", required=True, group="源文件", + placeholder="trunk/tests/fixtures/vi/99.incr.xlsx", + help="**相对于** vcs.local_path 的路径。后缀建议与上方「源文件格式」一致(切换格式时会自动同步常见后缀)。"), + _f(key="source.encoding", label="encoding", + type="string", group="源文件", default="utf-8"), + + # ----- LLM / 策略 ----- + _f(key="llm_profile", label="llm_profile", + type="llm_profile_ref", required=True, group="翻译策略", + placeholder="echo", + help="必须存在于 conf/llm.yaml 的 profiles 中;下拉列表来自已配置的 profiles。"), + _f(key="strategy_config.class", label="策略类名", + type="select", group="翻译策略", + options=["", "GenericTranslationStrategy", "TwoStepTranslationStrategy"], + help="留空走装饰器或 Generic 一步直译;小语种(de/fr/ru/tr/ar 等)推荐 TwoStepTranslationStrategy。"), + _f(key="strategy_config.pivot_locale", label="pivot_locale(两步策略专属)", + type="string", group="翻译策略", default="en", + help="两步策略的中转语种,默认 en。"), + _f(key="strategy_config.display_name", label="策略显示名", + type="string", group="翻译策略", placeholder="越南语翻译"), + _f(key="strategy_config.use_concurrent_by_default", label="默认并发", + type="bool", group="翻译策略", default=True), + _f(key="strategy_config.default_max_workers", label="并发线程数", + type="int", group="翻译策略", default=32), + _f(key="strategy_config.progress_log_interval", label="进度日志间隔", + type="int", group="翻译策略", default=100), + + # ----- 一审 ----- + # 说明:一审是否启用,取决于 workflow 是否包含 first_review 状态 + + # project_id/project_name 是否填写;平台类型统一走全局 platform.type。 + _f(key="reviews.first.project_id", label="一审 project_id", + type="string", group="一审(first_review)", + help="留空则跳过一审。Phrase 项目 UID / Crowdin 项目数字 ID。"), + _f(key="reviews.first.project_name", label="一审 project_name", + type="string", group="一审(first_review)", + placeholder="VI First Review", + help="仅用于日志 / 通知显示的项目名称。"), + _f(key="reviews.first.target_language_id", label="一审 target_language_id", + type="string", group="一审(first_review)", + placeholder="vi", + help="平台侧的语种 ID(可能与 BCP-47 不同,Phrase 用 vi、Crowdin 用数字 ID)。"), + _f(key="reviews.first.stop_time", label="一审截止 stop_time", + type="string", group="一审(first_review)", placeholder="17:00", + help="HH:MM 绝对时间;或 +5m / +2h 相对时间。到点未完成会强制跳过。"), + _f(key="reviews.first.poll_interval_seconds", label="轮询间隔(秒)", + type="int", group="一审(first_review)", default=60), + + # ----- 二审 ----- + _f(key="reviews.second.project_id", label="二审 project_id", + type="string", group="二审(second_review)", + help="留空则跳过二审。"), + _f(key="reviews.second.project_name", label="二审 project_name", + type="string", group="二审(second_review)", + placeholder="VI Second Review"), + _f(key="reviews.second.target_language_id", label="二审 target_language_id", + type="string", group="二审(second_review)"), + _f(key="reviews.second.stop_time", label="二审截止 stop_time", + type="string", group="二审(second_review)", placeholder="18:00"), + _f(key="reviews.second.poll_interval_seconds", label="轮询间隔(秒)", + type="int", group="二审(second_review)", default=60), + + # ----- 轻校对 ----- + _f(key="reviews.light.project_id", label="轻校对 project_id", + type="string", group="轻校对(light_review)", + help="留空则跳过轻校对。"), + _f(key="reviews.light.project_name", label="轻校对 project_name", + type="string", group="轻校对(light_review)"), + + # ----- 通知 ----- + _f(key="notification.type", label="通知渠道", + type="select", group="通知", + options=["none", "console", "wecom"], + default="console", + help="留空或与全局一致时,运行时会**字段级继承** config.yaml 的 notification 配置。"), + _f(key="notification.webhook", label="webhook", + type="password", group="通知", secret=True, + depends_on="notification.type", applies_to=["wecom"], + env_hint="GAME_TRANS_TOOLCHAIN__NOTIFICATION__WEBHOOK", + help="企业微信群机器人地址。**留空自动继承全局 config.yaml 的 webhook**;填入则覆盖。敏感字段,建议走环境变量。"), + _f(key="notification.mentioned", label="需要 @ 的用户", + type="list", group="通知", + depends_on="notification.type", applies_to=["wecom"], + help="数组形式,如 ['user_a', 'user_b']。**留空自动继承全局 mentioned 列表**。"), + + # ----- 工作流 ----- + _f(key="workflow", label="工作流状态", + type="workflow", required=True, group="工作流编排", + help=""), + _f(key="merge_start_time", label="merge_start_time", + type="string", group="工作流编排", + placeholder="08:30", + help="空=立即执行;HH:MM=等到当日该时刻再合并。"), + ] + + +def get_schema(kind: str) -> List[Dict[str, Any]]: + if kind == "global": + return global_config_schema() + if kind == "llm_profile": + return llm_profile_schema() + if kind == "language": + return language_profile_schema() + raise ValueError(f"unknown schema kind: {kind!r}") diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/log_bus.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/log_bus.py new file mode 100644 index 0000000000000000000000000000000000000000..6372561710928213031da9a6792de5fa1471a54a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/log_bus.py @@ -0,0 +1,128 @@ +"""日志总线:子进程 stdout → 环形缓冲 + WebSocket 实时推送。 + +架构: + [子进程 stdout 行] ──push──▶ [per-run 内存 ring + 落盘文件] + │ + └─broadcast─▶ 所有订阅的 WebSocket + +设计要点: + * 单例实例由 ``app.state.log_bus`` 持有,所有子进程 / 路由共享; + * ``publish`` 必须是**线程安全**(子进程读取线程调用), + 但 WebSocket 回写走 ``asyncio``,故采用"把消息塞到 asyncio.Queue" + 的做法:主事件循环在 ``register_subscriber`` 阶段注入。 +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import threading +import time +from collections import defaultdict, deque +from dataclasses import asdict, dataclass +from typing import Deque, Dict, List, Optional, Set + +logger = logging.getLogger(__name__) + + +@dataclass +class LogLine: + """一行日志。""" + + run_id: str + ts: float + stream: str # "stdout" | "stderr" | "meta" + line: str + + +class LogBus: + """全局日志总线。""" + + def __init__(self, max_buffer: int = 5000) -> None: + self._max_buffer = max_buffer + self._buffers: Dict[str, Deque[LogLine]] = defaultdict(lambda: deque(maxlen=max_buffer)) + self._subscribers: Dict[str, Set[asyncio.Queue]] = defaultdict(set) + self._global_subscribers: Set[asyncio.Queue] = set() + self._lock = threading.Lock() + self._loop: Optional[asyncio.AbstractEventLoop] = None + + def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None: + """由 FastAPI 事件循环启动时注入。""" + self._loop = loop + + # ------------------------------------------------------------------ + # 发布 + # ------------------------------------------------------------------ + def publish(self, run_id: str, line: str, *, stream: str = "stdout") -> None: + """线程安全:子进程读取线程调用。""" + entry = LogLine(run_id=run_id, ts=time.time(), stream=stream, line=line.rstrip("\r\n")) + with self._lock: + self._buffers[run_id].append(entry) + targets: List[asyncio.Queue] = list(self._subscribers.get(run_id, ())) + targets.extend(self._global_subscribers) + loop = self._loop + + if loop is None or not targets: + return + + payload = _to_json(entry) + for queue in targets: + # call_soon_threadsafe 避免跨线程 await + loop.call_soon_threadsafe(_safe_put, queue, payload) + + # ------------------------------------------------------------------ + # 订阅 / 读取 + # ------------------------------------------------------------------ + async def subscribe(self, run_id: Optional[str] = None) -> asyncio.Queue: + """注册订阅者,返回一个 ``asyncio.Queue``,消息已经是 JSON 字符串。""" + if self._loop is None: + self._loop = asyncio.get_running_loop() + queue: asyncio.Queue = asyncio.Queue(maxsize=10000) + with self._lock: + if run_id is None: + self._global_subscribers.add(queue) + else: + self._subscribers[run_id].add(queue) + return queue + + def unsubscribe(self, queue: asyncio.Queue, run_id: Optional[str] = None) -> None: + with self._lock: + if run_id is None: + self._global_subscribers.discard(queue) + else: + self._subscribers.get(run_id, set()).discard(queue) + + def tail(self, run_id: str, limit: int = 500) -> List[Dict[str, object]]: + """抓取最近 ``limit`` 行。""" + with self._lock: + buf = list(self._buffers.get(run_id, ())) + if limit and len(buf) > limit: + buf = buf[-limit:] + return [asdict(x) for x in buf] + + def clear(self, run_id: str) -> None: + with self._lock: + self._buffers.pop(run_id, None) + + +# ----------------------------------------------------------------------------- +# 辅助 +# ----------------------------------------------------------------------------- +def _to_json(entry: LogLine) -> str: + return json.dumps(asdict(entry), ensure_ascii=False) + + +def _safe_put(queue: asyncio.Queue, payload: str) -> None: + """asyncio Queue.put_nowait 的宽容版本——队列满了直接丢最老的。""" + try: + queue.put_nowait(payload) + except asyncio.QueueFull: + try: + queue.get_nowait() + except Exception: # pylint: disable=broad-except + return + try: + queue.put_nowait(payload) + except Exception: # pylint: disable=broad-except + return diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/runner_service.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/runner_service.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ffa834c25070a710d5b5869b0a5a5733339c7b --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/runner_service.py @@ -0,0 +1,344 @@ +"""Runner 服务:以**子进程**方式启动 ``python main.py run ...``。 + +**选用子进程方案**的原因: + * 完全复用现有 CLI(``main.py``),零改动零风险; + * 工作流中可能长时间阻塞(LLM 调用 / 轮询审校),放到子进程里 + Web 事件循环才不会卡住; + * 日志天然隔离,每个 run 一个 stdout 流,便于分流落盘和广播。 + +每个 run: + * 分配唯一 run_id = ``_``; + * stdout/stderr 读取线程推送到 :class:`LogBus`,并落盘到 + ``workspace/server_logs/.log``; + * 元信息写入 ``workspace/server_meta/runs.json``。 +""" + +from __future__ import annotations + +import json +import logging +import os +import subprocess +import sys +import threading +from dataclasses import asdict, dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Dict, List, Optional + +from .log_bus import LogBus + +logger = logging.getLogger(__name__) + + +@dataclass +class RunRecord: + run_id: str + language: str + status: str # running | finished | failed | killed + started_at: str + finished_at: Optional[str] = None + exit_code: Optional[int] = None + fresh: bool = False + batch: Optional[str] = None + log_file: Optional[str] = None + pid: Optional[int] = None + cmd: List[str] = field(default_factory=list) + + def to_public(self) -> Dict[str, object]: + d = asdict(self) + d.pop("pid", None) + return d + + +class RunnerService: + """以子进程方式启动工作流。""" + + def __init__(self, *, project_root: Path, log_bus: LogBus) -> None: + self.project_root = Path(project_root).resolve() + self.log_bus = log_bus + self._procs: Dict[str, subprocess.Popen] = {} + self._records: Dict[str, RunRecord] = {} + self._lock = threading.Lock() + self._records_file = ( + self.project_root / "workspace" / "server_meta" / "runs.json" + ) + self._logs_dir = self.project_root / "workspace" / "server_logs" + self._logs_dir.mkdir(parents=True, exist_ok=True) + # 启动时打印一次解释器信息,方便诊断 "装了但是用不到" 的问题。 + # Web 界面点"运行"派生的子进程 cmd[0] = sys.executable,所以这里打印的 + # 就是子进程将要使用的 Python。 + logger.info( + "RunnerService: subprocess will use python=%s (venv=%s)", + sys.executable, + os.environ.get("VIRTUAL_ENV", ""), + ) + self._load_history() + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + def start( + self, + *, + language: str, + fresh: bool = False, + batch: Optional[str] = None, + stage: Optional[str] = None, + ) -> RunRecord: + """启动一次运行。""" + run_id = f"{language}_{datetime.now().strftime('%Y%m%d%H%M%S')}" + + cmd = [sys.executable, "main.py", "run", "--language", language] + if fresh: + cmd.append("--fresh") + if batch: + cmd.extend(["--batch", batch]) + if stage: + cmd.extend(["--stage", stage]) + + # 兜底:目录可能在服务运行期间被清理/手动删除,这里再次确保存在 + try: + self._logs_dir.mkdir(parents=True, exist_ok=True) + except OSError as exc: # pragma: no cover + logger.warning("Failed to ensure server_logs dir %s: %s", self._logs_dir, exc) + log_file = self._logs_dir / f"{run_id}.log" + + env = os.environ.copy() + env.setdefault("PYTHONUNBUFFERED", "1") + env.setdefault("PYTHONIOENCODING", "utf-8") + + logger.info("Launching run %s: %s", run_id, " ".join(cmd)) + try: + proc = subprocess.Popen( + cmd, + cwd=str(self.project_root), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env, + bufsize=1, + text=True, + encoding="utf-8", + errors="replace", + ) + except OSError as exc: + logger.exception("Failed to start subprocess for run %s", run_id) + record = RunRecord( + run_id=run_id, language=language, status="failed", + started_at=_now(), finished_at=_now(), exit_code=-1, + fresh=fresh, batch=batch, log_file=str(log_file), cmd=cmd, + ) + with self._lock: + self._records[run_id] = record + self._persist() + self.log_bus.publish(run_id, f"failed to spawn: {exc}", stream="meta") + return record + + record = RunRecord( + run_id=run_id, language=language, status="running", + started_at=_now(), fresh=fresh, batch=batch, + log_file=str(log_file), pid=proc.pid, cmd=cmd, + ) + + with self._lock: + self._procs[run_id] = proc + self._records[run_id] = record + self._persist() + + # 开一条后台线程:读取子进程 stdout,推 LogBus + 落盘 + t = threading.Thread( + target=self._pump_output, + args=(run_id, proc, log_file), + name=f"TiMi_HOK_Game_Translator-run-{run_id}", + daemon=True, + ) + t.start() + + self.log_bus.publish(run_id, f"started: {' '.join(cmd)}", stream="meta") + return record + + def stop(self, run_id: str) -> bool: + with self._lock: + proc = self._procs.get(run_id) + if not proc: + return False + try: + proc.terminate() + except ProcessLookupError: + return False + self.log_bus.publish(run_id, "terminate signal sent", stream="meta") + return True + + def shutdown_all(self) -> None: + with self._lock: + procs = list(self._procs.items()) + for run_id, proc in procs: + try: + proc.terminate() + except Exception: # pylint: disable=broad-except # pragma: no cover + pass + self.log_bus.publish(run_id, "server shutdown — terminated", stream="meta") + + def list_runs(self, limit: int = 50) -> List[Dict[str, object]]: + # 列表接口也先做一次全量对账,防止列表页显示陈旧的"运行中" + self._reconcile() + with self._lock: + records = list(self._records.values()) + records.sort(key=lambda r: r.started_at, reverse=True) + return [r.to_public() for r in records[:limit]] + + def get(self, run_id: str) -> Optional[RunRecord]: + # 读取前先做一次"状态对账":若后台 pump 线程异常挂掉, + # 这里兜底修正 running → finished/failed,避免前端一直看到"运行中"。 + self._reconcile(run_id) + with self._lock: + return self._records.get(run_id) + + def _reconcile(self, run_id: Optional[str] = None) -> None: + """对账:检查子进程是否仍存活;对已退出的进程强制回填记录状态。 + + 正常情况下 ``_pump_output`` 会在 ``finally`` 中更新 record。 + 但若 pump 线程被异常/阻塞卡死,record 会永远停在 ``running``。 + 这里提供一道兜底:根据 ``proc.poll()`` 真实状态强制同步。 + """ + with self._lock: + targets = ( + [(run_id, self._procs.get(run_id))] if run_id is not None + else list(self._procs.items()) + ) + for rid, proc in targets: + if proc is None: + # 没有活跃 proc,但记录可能仍是 running(历史遗留 / pump 异常) + with self._lock: + rec = self._records.get(rid) if rid else None + if rec is not None and rec.status == "running": + rec.status = "failed" + rec.finished_at = _now() + if rec.exit_code is None: + rec.exit_code = -1 + self._persist() + continue + code = proc.poll() + if code is None: + continue # 子进程仍在跑,无需处理 + # 子进程已退出但 record 仍是 running —— pump 线程大概率卡死 + with self._lock: + rec = self._records.get(rid) + if rec is not None and rec.status == "running": + rec.exit_code = code + rec.finished_at = _now() + rec.status = ( + "finished" if code == 0 + else ("killed" if code < 0 else "failed") + ) + self._persist() + self._procs.pop(rid, None) + + def read_log_file(self, run_id: str, *, tail: int = 2000) -> List[str]: + rec = self.get(run_id) + if not rec or not rec.log_file: + return [] + p = Path(rec.log_file) + if not p.exists(): + return [] + try: + with p.open("r", encoding="utf-8", errors="replace") as f: + lines = f.readlines() + except OSError: + return [] + if tail and len(lines) > tail: + lines = lines[-tail:] + return [ln.rstrip("\n") for ln in lines] + + # ------------------------------------------------------------------ + # Internal + # ------------------------------------------------------------------ + def _pump_output(self, run_id: str, proc: subprocess.Popen, log_file: Path) -> None: + # 打开日志文件;若打开失败(如父目录被外部清理),不中断 stdout 消费, + # 只是放弃落盘,避免子进程 PIPE 缓冲区满而阻塞。 + f = None + try: + try: + log_file.parent.mkdir(parents=True, exist_ok=True) + f = log_file.open("w", encoding="utf-8", errors="replace") + except OSError as exc: + logger.exception("Failed to open log file %s", log_file) + self.log_bus.publish( + run_id, f"[log file open failed] {exc}; 日志仅通过 WebSocket 推送", + stream="meta", + ) + + assert proc.stdout is not None + for line in proc.stdout: + if f is not None: + try: + f.write(line) + f.flush() + except OSError as exc: # pragma: no cover - defensive + logger.warning("write log failed for %s: %s", run_id, exc) + try: + f.close() + except Exception: # pylint: disable=broad-except + pass + f = None + self.log_bus.publish(run_id, line) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover - defensive + logger.exception("pump output failed for %s", run_id) + self.log_bus.publish(run_id, f"[pump error] {exc}", stream="meta") + finally: + if f is not None: + try: + f.close() + except Exception: # pylint: disable=broad-except + pass + exit_code = proc.wait() + status = "finished" if exit_code == 0 else ( + "killed" if exit_code is not None and exit_code < 0 else "failed" + ) + with self._lock: + rec = self._records.get(run_id) + if rec is not None: + rec.exit_code = exit_code + rec.finished_at = _now() + rec.status = status + self._procs.pop(run_id, None) + self._persist() + self.log_bus.publish( + run_id, f"exited with code={exit_code} status={status}", stream="meta", + ) + + def _persist(self) -> None: + # 必须在 self._lock 上下文内调用 + self._records_file.parent.mkdir(parents=True, exist_ok=True) + payload = [r.to_public() for r in self._records.values()] + tmp = self._records_file.with_suffix(".tmp") + try: + with tmp.open("w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2) + tmp.replace(self._records_file) + except OSError as exc: # pragma: no cover + logger.warning("Failed to persist runs.json: %s", exc) + + def _load_history(self) -> None: + if not self._records_file.exists(): + return + try: + with self._records_file.open("r", encoding="utf-8") as f: + data = json.load(f) + except (OSError, json.JSONDecodeError): + return + for item in data or []: + try: + # 过去的 run 不再 attach 真实进程,仅复原状态 + item.pop("pid", None) + if item.get("status") == "running": + item["status"] = "killed" + item.setdefault("finished_at", _now()) + rec = RunRecord(**item) + except TypeError: + continue + self._records[rec.run_id] = rec + + +def _now() -> str: + return datetime.now().isoformat(timespec="seconds") diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/scheduler_service.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/scheduler_service.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc9914b7ac58f75de2907ba3272296af777feac --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/backend/services/scheduler_service.py @@ -0,0 +1,185 @@ +"""定时调度服务 —— 基于 APScheduler。 + +每条 schedule 对应一个 cron 任务;触发时调用 :class:`RunnerService.start`。 +schedule 列表持久化到 ``workspace/server_meta/schedules.json``。 +""" + +from __future__ import annotations + +import json +import logging +import threading +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Dict, List, Optional + +try: + from apscheduler.schedulers.background import BackgroundScheduler + from apscheduler.triggers.cron import CronTrigger +except ImportError: # pragma: no cover + BackgroundScheduler = None # type: ignore + CronTrigger = None # type: ignore + +from .runner_service import RunnerService + +logger = logging.getLogger(__name__) + + +@dataclass +class ScheduleEntry: + id: str + language: str + cron: str + enabled: bool = True + fresh: bool = False + description: str = "" + + +class SchedulerService: + """封装 APScheduler,提供 CRUD + 持久化。""" + + def __init__(self, *, runner_service: RunnerService) -> None: + self.runner = runner_service + self._schedules: Dict[str, ScheduleEntry] = {} + self._lock = threading.Lock() + self._scheduler = BackgroundScheduler() if BackgroundScheduler else None + self._schedules_file: Optional[Path] = None + + # ------------------------------------------------------------------ + # 生命周期 + # ------------------------------------------------------------------ + def start(self) -> None: + if self._scheduler is not None and not self._scheduler.running: + self._scheduler.start() + + def shutdown(self) -> None: + if self._scheduler is not None and self._scheduler.running: + self._scheduler.shutdown(wait=False) + + def restore_from_disk(self, path: Path) -> None: + self._schedules_file = path + if not path.exists(): + return + try: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + except (OSError, json.JSONDecodeError): + return + for item in data or []: + try: + entry = ScheduleEntry(**item) + except TypeError: + continue + self._schedules[entry.id] = entry + if entry.enabled: + self._attach_job(entry) + + # ------------------------------------------------------------------ + # CRUD + # ------------------------------------------------------------------ + def list(self) -> List[Dict[str, object]]: + with self._lock: + return [asdict(x) for x in self._schedules.values()] + + def upsert(self, entry: ScheduleEntry) -> ScheduleEntry: + if self._scheduler is None: + raise RuntimeError( + "APScheduler 未安装。请执行:pip install apscheduler" + ) + if CronTrigger is None: + raise RuntimeError("CronTrigger 不可用") + # 预校验 cron 表达式 + _parse_cron(entry.cron) + + with self._lock: + self._schedules[entry.id] = entry + self._detach_job(entry.id) + if entry.enabled: + self._attach_job(entry) + self._persist() + return entry + + def delete(self, schedule_id: str) -> bool: + with self._lock: + if schedule_id not in self._schedules: + return False + del self._schedules[schedule_id] + self._detach_job(schedule_id) + self._persist() + return True + + def toggle(self, schedule_id: str, enabled: bool) -> Optional[ScheduleEntry]: + with self._lock: + entry = self._schedules.get(schedule_id) + if not entry: + return None + entry.enabled = enabled + self._detach_job(schedule_id) + if enabled: + self._attach_job(entry) + self._persist() + return entry + + # ------------------------------------------------------------------ + # Internal + # ------------------------------------------------------------------ + def _attach_job(self, entry: ScheduleEntry) -> None: + if self._scheduler is None or CronTrigger is None: + return + trigger = _parse_cron(entry.cron) + self._scheduler.add_job( + self._fire, + trigger=trigger, + id=entry.id, + replace_existing=True, + kwargs={"schedule_id": entry.id}, + misfire_grace_time=600, + coalesce=True, + ) + + def _detach_job(self, schedule_id: str) -> None: + if self._scheduler is None: + return + try: + self._scheduler.remove_job(schedule_id) + except Exception: # pylint: disable=broad-except # pragma: no cover + pass + + def _fire(self, schedule_id: str) -> None: + with self._lock: + entry = self._schedules.get(schedule_id) + if not entry or not entry.enabled: + return + logger.info("Scheduled run fired: %s (language=%s)", schedule_id, entry.language) + try: + self.runner.start(language=entry.language, fresh=entry.fresh) + except Exception as exc: # pylint: disable=broad-except # pragma: no cover + logger.exception("scheduled run failed to start: %s", exc) + + def _persist(self) -> None: + if not self._schedules_file: + return + tmp = self._schedules_file.with_suffix(".tmp") + payload = [asdict(x) for x in self._schedules.values()] + try: + self._schedules_file.parent.mkdir(parents=True, exist_ok=True) + with tmp.open("w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2) + tmp.replace(self._schedules_file) + except OSError as exc: # pragma: no cover + logger.warning("Failed to persist schedules.json: %s", exc) + + +def _parse_cron(expr: str) -> "CronTrigger": + """解析 ``分 时 日 月 周`` 5 字段 cron 表达式。""" + if CronTrigger is None: + raise RuntimeError("APScheduler 未安装") + parts = (expr or "").split() + if len(parts) != 5: + raise ValueError( + f"cron 表达式必须为 5 个字段(分 时 日 月 周),got: {expr!r}" + ) + minute, hour, day, month, day_of_week = parts + return CronTrigger( + minute=minute, hour=hour, day=day, month=month, day_of_week=day_of_week, + ) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/index.html b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b318e1aae85ade58f3ab1e081e38afd7b32ef05b --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/index.html @@ -0,0 +1,22 @@ + + + + + + TiMiHOKGameTranslator · 本地化流水线控制台 + + + + +
+ + + + + + + + + + + diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.css b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.css new file mode 100644 index 0000000000000000000000000000000000000000..e4b35f386f4b044cbc2283b0ac00d08cd2464d26 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.css @@ -0,0 +1,1166 @@ +/* ============================================================================ + * TiMiHOKGameTranslator Web Console —— 高级优雅主题 + * ---------------------------------------------------------------------------- + * 设计风格:深色侧边栏 + 浅色主内容区 + 蓝紫渐变主色 + 柔和阴影 + * ========================================================================== */ + +:root { + --primary: #4f46e5; + --primary-light: #6366f1; + --primary-dark: #3730a3; + --primary-gradient: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); + --sidebar-bg: #1a1f36; + --sidebar-hover: #262b47; + --sidebar-active: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); + --sidebar-text: #a0aec0; + --sidebar-text-active: #fff; + --bg-main: #f7f8fc; + --bg-card: #fff; + --border-color: #e5e7eb; + --text-primary: #1a202c; + --text-secondary: #6b7280; + --text-muted: #9ca3af; + --success: #10b981; + --warning: #f59e0b; + --danger: #ef4444; + --info: #3b82f6; + --radius: 10px; + --radius-sm: 6px; + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.03); + --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.06), 0 2px 4px rgba(0, 0, 0, 0.03); + --shadow-lg: 0 10px 32px rgba(0, 0, 0, 0.08), 0 4px 12px rgba(0, 0, 0, 0.04); +} + +* { + box-sizing: border-box; +} + +/* stylelint-disable selector-max-id -- `#app` 是 Vue SPA 根挂载点,必须以 ID 选择器匹配 */ +html, +body, +#app { + height: 100%; + margin: 0; + padding: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, + "Helvetica Neue", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", + sans-serif; + background: var(--bg-main); + color: var(--text-primary); + -webkit-font-smoothing: antialiased; +} +/* stylelint-enable selector-max-id */ + +/* ========== 布局 ========== */ +.layout { + display: flex; + min-height: 100vh; +} + +.sidebar { + width: 240px; + background: var(--sidebar-bg); + color: var(--sidebar-text); + padding: 20px 0; + box-sizing: border-box; + display: flex; + flex-direction: column; + position: relative; + overflow: hidden; +} + +.sidebar::before { + content: ""; + position: absolute; + top: 0; + right: 0; + left: 0; + height: 3px; + background: var(--primary-gradient); +} + +.sidebar .logo { + color: #fff; + font-size: 20px; + font-weight: 700; + padding: 8px 24px 24px 24px; + letter-spacing: 0.5px; + display: flex; + align-items: center; + gap: 10px; +} + +.sidebar .logo .logo-icon { + width: 36px; + height: 36px; + border-radius: 10px; + background: var(--primary-gradient); + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + box-shadow: 0 4px 12px rgba(79, 70, 229, 0.4); +} + +.sidebar .nav-group-title { + padding: 16px 24px 8px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 1.5px; + color: #6b7280; +} + +.sidebar .nav-item { + display: flex; + align-items: center; + padding: 10px 24px; + cursor: pointer; + font-size: 14px; + color: var(--sidebar-text); + transition: all 0.2s ease; + margin: 2px 12px; + border-radius: var(--radius-sm); + gap: 12px; +} + +.sidebar .nav-item:hover { + background: var(--sidebar-hover); + color: #fff; +} + +.sidebar .nav-item.active { + background: var(--sidebar-active); + color: var(--sidebar-text-active); + box-shadow: 0 4px 12px rgba(79, 70, 229, 0.35); +} + +.sidebar .nav-item .nav-icon { + font-size: 18px; + width: 20px; + text-align: center; + flex-shrink: 0; +} + +.sidebar .sidebar-footer { + margin-top: auto; + padding: 16px 24px; + font-size: 11px; + color: var(--text-muted); + border-top: 1px solid rgba(255, 255, 255, 0.05); + opacity: 0.6; +} + +.main { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.topbar { + height: 64px; + background: var(--bg-card); + border-bottom: 1px solid var(--border-color); + display: flex; + align-items: center; + padding: 0 32px; + justify-content: space-between; + box-shadow: var(--shadow-sm); +} + +.topbar .title { + font-size: 20px; + font-weight: 600; + color: var(--text-primary); + display: flex; + align-items: center; + gap: 10px; +} + +.topbar .subtitle { + font-size: 13px; + color: var(--text-secondary); + margin-left: 8px; +} + +.content { + flex: 1; + overflow: auto; + padding: 28px 32px; +} + +/* ========== 卡片 ========== */ +.card { + background: var(--bg-card); + border-radius: var(--radius); + padding: 24px; + box-shadow: var(--shadow-sm); + margin-bottom: 20px; + border: 1px solid var(--border-color); + transition: box-shadow 0.2s; +} + +.card:hover { + box-shadow: var(--shadow-md); +} + +.card-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 20px; + padding-bottom: 16px; + border-bottom: 1px solid var(--border-color); +} + +.card-header h3 { + margin: 0; + font-size: 16px; + font-weight: 600; + color: var(--text-primary); + display: flex; + align-items: center; + gap: 8px; +} + +.card-header h3 .emoji { + font-size: 20px; +} + +.card h3 { + margin: 0 0 16px 0; + font-size: 15px; + color: var(--text-primary); +} + +/* ========== 统计卡(Dashboard) ========== */ +.stat-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 16px; + margin-bottom: 20px; +} + +.stat-card { + background: var(--bg-card); + border-radius: var(--radius); + padding: 20px; + box-shadow: var(--shadow-sm); + border: 1px solid var(--border-color); + display: flex; + flex-direction: column; + gap: 8px; + position: relative; + overflow: hidden; + transition: all 0.2s; +} + +.stat-card:hover { + transform: translateY(-2px); + box-shadow: var(--shadow-md); +} + +.stat-card .stat-label { + color: var(--text-secondary); + font-size: 13px; + display: flex; + align-items: center; + gap: 6px; +} + +.stat-card .stat-value { + font-size: 28px; + font-weight: 700; + color: var(--text-primary); + line-height: 1; +} + +.stat-card .stat-sub { + font-size: 12px; + color: var(--text-muted); +} + +.stat-card.success { + border-left: 4px solid var(--success); +} + +.stat-card.warning { + border-left: 4px solid var(--warning); +} + +.stat-card.info { + border-left: 4px solid var(--info); +} + +.stat-card.primary { + border-left: 4px solid var(--primary); +} + +/* ========== 健康检查列表 ========== */ +.check-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.check-item { + display: flex; + align-items: flex-start; + gap: 14px; + padding: 14px 16px; + border-radius: var(--radius-sm); + background: #fafbfd; + border: 1px solid var(--border-color); + transition: all 0.2s; +} + +.check-item.status-ok { + background: #f0fdf4; + border-color: #bbf7d0; +} + +.check-item.status-fail { + background: #fef2f2; + border-color: #fecaca; +} + +.check-item.status-warn { + background: #fffbeb; + border-color: #fde68a; +} + +.check-item.status-skip { + background: #f9fafb; + border-color: #e5e7eb; + opacity: 0.75; +} + +.check-item .check-icon { + width: 32px; + height: 32px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + font-size: 16px; + font-weight: 700; + color: #fff; +} + +.check-item.status-ok .check-icon { + background: var(--success); +} + +.check-item.status-fail .check-icon { + background: var(--danger); +} + +.check-item.status-warn .check-icon { + background: var(--warning); +} + +.check-item.status-skip .check-icon { + background: var(--text-muted); +} + +.check-item .check-body { + flex: 1; +} + +.check-item .check-title { + font-weight: 600; + font-size: 14px; + color: var(--text-primary); + margin-bottom: 2px; +} + +.check-item .check-message { + font-size: 13px; + color: var(--text-secondary); +} + +.check-item .check-details { + margin-top: 8px; + padding-left: 16px; + font-size: 12px; + color: var(--text-secondary); +} + +.check-item .check-details li { + margin: 2px 0; +} + +.check-item .env-hints { + margin-top: 8px; + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.check-item .env-hint { + background: rgba(79, 70, 229, 0.08); + color: var(--primary-dark); + padding: 2px 8px; + border-radius: 4px; + font-family: Consolas, Monaco, monospace; + font-size: 11px; + font-weight: 500; +} + +/* ========== 字段表格(表单) ========== */ +.field-table { + display: flex; + flex-direction: column; + gap: 0; + border: 1px solid var(--border-color); + border-radius: var(--radius); + overflow: hidden; +} + +.field-row { + display: grid; + grid-template-columns: 260px 1fr; + gap: 20px; + padding: 16px 20px; + border-bottom: 1px solid var(--border-color); + transition: background 0.15s; + align-items: start; +} + +.field-row:last-child { + border-bottom: none; +} + +.field-row:hover { + background: #fafbfd; +} + +.field-row.required { + background: linear-gradient( + to right, + rgba(239, 68, 68, 0.02), + transparent 20% + ); +} + +.field-label { + display: flex; + flex-direction: column; + gap: 4px; +} + +.field-label .label-text { + font-weight: 600; + color: var(--text-primary); + font-size: 14px; + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; +} + +.field-label .label-key { + color: var(--text-muted); + font-family: Consolas, Monaco, monospace; + font-size: 11px; +} + +.badge { + display: inline-flex; + align-items: center; + padding: 1px 8px; + border-radius: 10px; + font-size: 11px; + font-weight: 600; + letter-spacing: 0.3px; +} + +.badge-required { + background: #fee2e2; + color: #b91c1c; +} + +.badge-optional { + background: #e0e7ff; + color: #3730a3; +} + +.badge-secret { + background: #fef3c7; + color: #92400e; +} + +.badge-env { + background: #ccfbf1; + color: #0f766e; + font-family: Consolas, Monaco, monospace; +} + +.field-input { + display: flex; + flex-direction: column; + gap: 6px; +} + +.field-help { + font-size: 12px; + color: var(--text-secondary); + line-height: 1.5; +} + +.field-example { + font-size: 11px; + color: var(--text-muted); + font-family: Consolas, Monaco, monospace; + margin-top: 2px; +} + +.field-example::before { + content: "💡 示例: "; + font-family: inherit; +} + +/* ========== 字段分组 ========== */ +.field-group { + margin-bottom: 20px; + border-radius: var(--radius); + overflow: hidden; + border: 1px solid var(--border-color); + background: var(--bg-card); +} + +.field-group-header { + padding: 14px 20px; + background: linear-gradient(to right, #f8fafc, #fff); + border-bottom: 1px solid var(--border-color); + font-weight: 600; + font-size: 14px; + color: var(--text-primary); + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + user-select: none; +} + +.field-group-header .group-arrow { + color: var(--text-muted); + transition: transform 0.2s; +} + +.field-group.collapsed .group-arrow { + transform: rotate(-90deg); +} + +.field-group.collapsed .field-table { + display: none; +} + +.field-group .field-table { + border: none; + border-radius: 0; +} + +/* ========== Setup Wizard —— 全新设计 ========== */ +.wizard-page { + max-width: 960px; + margin: 0 auto; + padding: 0 20px; +} + +.wizard-hero { + background: var(--primary-gradient); + color: #fff; + padding: 32px 36px; + border-radius: var(--radius); + box-shadow: var(--shadow-lg); + margin-bottom: 24px; + position: relative; + overflow: hidden; +} + +.wizard-hero::before { + content: ""; + position: absolute; + top: -60px; + right: -60px; + width: 240px; + height: 240px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.1); +} + +.wizard-hero::after { + content: ""; + position: absolute; + bottom: -40px; + right: 60px; + width: 140px; + height: 140px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.08); +} + +.wizard-hero h1 { + margin: 0 0 8px 0; + font-size: 26px; + font-weight: 700; + position: relative; + z-index: 1; +} + +.wizard-hero p { + margin: 0; + opacity: 0.95; + font-size: 14px; + line-height: 1.6; + position: relative; + z-index: 1; +} + +.wizard-step-indicator { + display: flex; + align-items: center; + justify-content: center; + gap: 0; + margin: 24px 0 28px; + padding: 0 20px; +} + +.wizard-step { + display: flex; + align-items: center; + gap: 10px; + color: var(--text-muted); + font-size: 13px; + font-weight: 500; +} + +.wizard-step .step-num { + width: 32px; + height: 32px; + border-radius: 50%; + background: #e5e7eb; + color: #9ca3af; + display: flex; + align-items: center; + justify-content: center; + font-weight: 700; + transition: all 0.3s; +} + +.wizard-step.active { + color: var(--primary); +} + +.wizard-step.active .step-num { + background: var(--primary); + color: #fff; + box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3); +} + +.wizard-step.done .step-num { + background: var(--success); + color: #fff; +} + +.wizard-connector { + flex: 1; + height: 2px; + background: #e5e7eb; + margin: 0 12px; + max-width: 100px; +} + +.wizard-connector.done { + background: var(--success); +} + +/* ========== 平台选择卡(Setup Step: 选择要启用的功能) ========== */ +.pick-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 14px; + margin-top: 12px; +} + +.pick-card { + padding: 20px; + border-radius: var(--radius); + border: 2px solid var(--border-color); + background: #fff; + cursor: pointer; + transition: all 0.2s; + position: relative; +} + +.pick-card:hover { + border-color: var(--primary-light); + transform: translateY(-2px); + box-shadow: var(--shadow-md); +} + +.pick-card.selected { + border-color: var(--primary); + background: linear-gradient( + 135deg, + rgba(79, 70, 229, 0.04), + rgba(124, 58, 237, 0.04) + ); +} + +.pick-card.selected::before { + content: "✓"; + position: absolute; + top: 10px; + right: 10px; + width: 22px; + height: 22px; + background: var(--primary); + color: #fff; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + font-weight: 700; +} + +.pick-card .pick-emoji { + font-size: 28px; + margin-bottom: 8px; +} + +.pick-card .pick-title { + font-weight: 600; + font-size: 15px; + color: var(--text-primary); + margin-bottom: 4px; +} + +.pick-card .pick-desc { + font-size: 12px; + color: var(--text-secondary); + line-height: 1.5; +} + +/* ========== 日志终端 ========== */ +.log-view { + background: #0d1117; + color: #c9d1d9; + font-family: "SF Mono", Consolas, "Courier New", Monaco, monospace; + font-size: 12px; + padding: 16px; + border-radius: var(--radius-sm); + height: 62vh; + overflow: auto; + white-space: pre-wrap; + word-break: break-all; + line-height: 1.6; +} + +.log-view .log-line.stream-stderr { + color: #ff7b72; +} + +.log-view .log-line.stream-meta { + color: #79c0ff; + font-style: italic; +} + +.yaml-editor { + font-family: "SF Mono", Consolas, Monaco, monospace; + font-size: 13px; +} + +/* ========== 运行状态标签 ========== */ +.run-status { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 10px; + font-size: 12px; + font-weight: 600; +} + +.run-status::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; +} + +.run-status.running { + background: #d1fae5; + color: #065f46; +} + +.run-status.running::before { + background: #10b981; + animation: pulse 1.4s ease-in-out infinite; +} + +.run-status.finished { + background: #dbeafe; + color: #1e40af; +} + +.run-status.finished::before { + background: #3b82f6; +} + +.run-status.failed { + background: #fee2e2; + color: #991b1b; +} + +.run-status.failed::before { + background: #ef4444; +} + +.run-status.killed { + background: #fed7aa; + color: #9a3412; +} + +.run-status.killed::before { + background: #f97316; +} + +@keyframes pulse { + 0%, + 100% { + opacity: 1; + transform: scale(1); + } + + 50% { + opacity: 0.5; + transform: scale(1.3); + } +} + +/* ========== 空态 ========== */ +.empty-state { + padding: 60px 20px; + text-align: center; + color: var(--text-muted); +} + +.empty-state .empty-icon { + font-size: 56px; + margin-bottom: 12px; +} + +.empty-state .empty-title { + font-size: 16px; + font-weight: 600; + color: var(--text-secondary); + margin-bottom: 6px; +} + +.empty-state .empty-desc { + font-size: 13px; + margin-bottom: 20px; +} + +/* ========== 按钮微调(基于 Element Plus) ========== */ +/* 下方样式用于覆盖 Element Plus 组件库默认样式,必须使用 !important 才能生效,故对此段落禁用 declaration-no-important 规则。 */ +/* stylelint-disable declaration-no-important */ +.el-button--primary { + background: var(--primary-gradient) !important; + border-color: transparent !important; + box-shadow: 0 2px 8px rgba(79, 70, 229, 0.25); +} + +.el-button--primary:hover { + background: linear-gradient(135deg, #5b53e8, #8b4de8) !important; + box-shadow: 0 4px 14px rgba(79, 70, 229, 0.4); +} + +/* ========== 对话框圆角 ========== */ +.el-dialog { + border-radius: var(--radius) !important; + overflow: hidden; +} + +.el-drawer { + border-radius: 0 !important; +} + +/* ========== 表格头部 ========== */ +.el-table th.el-table__cell { + background: #f8fafc !important; + color: var(--text-secondary) !important; + font-weight: 600 !important; + font-size: 13px !important; +} +/* stylelint-enable declaration-no-important */ + +/* ========== 工具栏 ========== */ +.toolbar { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; + gap: 12px; + flex-wrap: wrap; +} + +.toolbar .left, +.toolbar .right { + display: flex; + align-items: center; + gap: 10px; +} + +/* ========== Tab 切换 YAML 原文视图 ========== */ +.view-switch { + display: inline-flex; + background: #f3f4f6; + border-radius: 8px; + padding: 3px; +} + +.view-switch button { + background: transparent; + border: none; + padding: 6px 14px; + border-radius: 6px; + cursor: pointer; + font-size: 13px; + color: var(--text-secondary); + transition: all 0.15s; +} + +.view-switch button.active { + background: #fff; + color: var(--primary); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06); + font-weight: 600; +} + +/* ============================================================================ + * Workflow 状态编排 —— 带箭头的卡片式流程图 + * ========================================================================== */ + +/* 对大型复合输入(如 workflow 流程图),破除 "label 260px + input 1fr" 的 + 两列栅格,改为"label 在上、内容在下"的单列全宽布局,彻底消除左侧留白。 */ +.field-row.field-row-wide { + grid-template-columns: 1fr; + gap: 10px; +} + +.field-row.field-row-wide > .field-label { + flex-direction: row; + flex-wrap: wrap; + align-items: baseline; + gap: 8px; +} + +.field-row.field-row-wide > .field-label .label-key { + margin-left: 2px; +} + +.workflow-container { + width: 100%; +} + +.workflow-toolbar { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 10px; +} + +.workflow-flow { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 24px 32px; /* 行间距 24px / 列间距 32px,给箭头留位置 */ + padding: 16px 32px 16px 20px; /* 右侧多留 32px,用于容纳每行末尾过渡箭头 */ + background: #f8fafc; + border: 1px dashed #cbd5e1; + border-radius: 10px; +} + +.workflow-node { + position: relative; + width: 170px; + background: #fff; + border: 2px solid #e2e8f0; + border-radius: 10px; + padding: 10px 12px; + cursor: pointer; + transition: all 0.18s ease; + display: flex; + flex-direction: column; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04); +} + +/* 箭头:作为卡片的 ::before 伪元素呈现在卡片左侧。 + —— 整体首张 (.is-first) 不显示箭头; + —— 由 JS (ResizeObserver) 动态标注的"每行首张" (.row-first) 也不显示箭头, + 这样 flex-wrap 换行后不会再出现"孤立箭头在行首"的视觉错位。 + —— 关键优势:伪元素不是 flex 子元素,不参与 wrap 计算。 */ +.workflow-node::before { + content: "→"; + position: absolute; + left: -24px; /* 落在 32px gap 的中间(24+8=32) */ + top: 50%; + transform: translateY(-50%); + font-size: 20px; + font-weight: 700; + color: #94a3b8; + pointer-events: none; + user-select: none; +} + +.workflow-node.is-first::before, +.workflow-node.row-first::before { + content: none; /* 整体首张 / 每行首张不显示前置箭头 */ +} + +/* 行末过渡箭头 —— 由 Vue 动态渲染为真实 DOM(而非 ::after 伪元素, + 避开 is-recommended ⭐ 的占位),指示"流程从本行末尾衔接到下一行开头"。 + 绝对定位到卡片右侧外部,和前置 ::before 箭头对称。 */ +.workflow-node .wf-tail-arrow { + position: absolute; + right: -24px; + top: 50%; + transform: translateY(-50%); + font-size: 20px; + font-weight: 700; + color: #94a3b8; + pointer-events: none; + user-select: none; + line-height: 1; +} + +.workflow-node:hover { + border-color: var(--primary-light); + transform: translateY(-1px); + box-shadow: 0 4px 10px rgba(79, 70, 229, 0.12); +} + +.workflow-node.selected { + border-color: var(--primary); + background: linear-gradient(135deg, #eef2ff 0%, #faf5ff 100%); + box-shadow: 0 2px 8px rgba(79, 70, 229, 0.18); +} + +.workflow-node.is-recommended::after { + content: "⭐"; + position: absolute; + top: -8px; + right: -8px; + font-size: 14px; + background: #fff; + border-radius: 50%; + width: 20px; + height: 20px; + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); +} + +.workflow-node .wf-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 6px; +} + +.workflow-node .wf-order { + display: inline-block; + min-width: 20px; + height: 20px; + line-height: 20px; + padding: 0 6px; + border-radius: 10px; + background: var(--primary-gradient); + color: #fff; + font-size: 12px; + font-weight: 700; + text-align: center; +} + +.workflow-node .wf-body { + display: flex; + flex-direction: column; + gap: 2px; +} + +.workflow-node .wf-label { + font-weight: 600; + color: #1f2937; + font-size: 13px; +} + +.workflow-node .wf-key { + color: #94a3b8; + font-size: 11px; +} + +.workflow-node .wf-key code { + background: transparent; + padding: 0; + color: inherit; + font-size: 11px; +} + +.workflow-node .wf-desc { + color: #64748b; + font-size: 11px; + line-height: 1.4; + margin-top: 2px; +} + +/* ============================================================================ + * 抽屉自定义头部 —— 标题 + 右侧保存/取消按钮,永远可见无需滚动 + * ========================================================================== */ +.drawer-header-wrap { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + width: 100%; +} + +.drawer-title { + display: flex; + align-items: baseline; + gap: 6px; + font-size: 16px; + color: var(--text-primary); + font-weight: 600; +} + +.drawer-title-icon { + font-size: 18px; +} + +.drawer-title-sub { + margin-left: 14px; + padding-left: 14px; + border-left: 1px solid #e5e7eb; + color: var(--text-secondary); + font-weight: 400; + font-size: 13px; +} + +.drawer-actions { + display: flex; + gap: 8px; + flex-shrink: 0; +} + +/* 让 el-drawer 原生 header 高度稍微宽裕一些以容纳按钮 */ +.lang-editor-drawer .el-drawer__header { + padding: 14px 20px; + margin-bottom: 0; + border-bottom: 1px solid var(--border-color); +} diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.js b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.js new file mode 100644 index 0000000000000000000000000000000000000000..83427b33851660a64fc739ae313a4ebe8fd19ea4 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/server/frontend/static/app.js @@ -0,0 +1,2543 @@ +/* ============================================================================ + * TiMiHOKGameTranslator Web Console SPA + * ---------------------------------------------------------------------------- + * 架构: + * - 工具层:api / utils / FieldInput(动态表单控件)/ FieldRow / FieldGroupedForm + * - 页面层:Dashboard / SetupWizard / GlobalConfigView / LlmView / + * LanguagesView / RunsView / RunDetailView / SchedulesView + * - 顶层 App:带侧边栏布局 + 基于 hash 的路由 + * ========================================================================== */ + +const { createApp, ref, reactive, computed, onMounted, onBeforeUnmount, watch, h, defineComponent, nextTick } = Vue; +const { ElMessage, ElMessageBox, ElNotification } = ElementPlus; + +/* ========== API 封装 ========== */ +const api = { + async _req(method, url, body) { + const opts = { method, headers: { "Content-Type": "application/json" } }; + if (body !== undefined) opts.body = JSON.stringify(body); + const resp = await fetch(url, opts); + if (!resp.ok) { + let msg = `${resp.status} ${resp.statusText}`; + try { + const data = await resp.json(); msg = data.detail || JSON.stringify(data); +} catch (e) {} + throw new Error(msg); + } + const ct = resp.headers.get("content-type") || ""; + if (ct.includes("application/json")) return await resp.json(); + return await resp.text(); + }, + get(u) { + return this._req("GET", u); +}, + post(u, b) { + return this._req("POST", u, b); +}, + put(u, b) { + return this._req("PUT", u, b); +}, + del(u) { + return this._req("DELETE", u); +}, + + // setup + setupStatus() { + return this.get("/api/setup/status"); +}, + setupInit(payload) { + return this.post("/api/setup/init", payload); +}, + getGlobalConfig() { + return this.get("/api/setup/global-config"); +}, + putGlobalConfig(data) { + return this.put("/api/setup/global-config", data); +}, + getLlm() { + return this.get("/api/setup/llm"); +}, + putLlm(data) { + return this.put("/api/setup/llm", data); +}, + getSchema(kind) { + return this.get(`/api/setup/schema/${kind}`); +}, + getPreferences() { + return this.get("/api/setup/preferences"); +}, + putPreferences(data) { + return this.put("/api/setup/preferences", data); +}, + + // languages + listLanguages() { + return this.get("/api/languages"); +}, + getLanguage(id) { + return this.get(`/api/languages/${encodeURIComponent(id)}`); +}, + saveLanguage(id, data) { + return this.put(`/api/languages/${encodeURIComponent(id)}`, data); +}, + deleteLanguage(id) { + return this.del(`/api/languages/${encodeURIComponent(id)}`); +}, + duplicateLanguage(src, dst) { + return this.post(`/api/languages/${encodeURIComponent(src)}/duplicate`, { target_id: dst }); +}, + + // runs + startRun(payload) { + return this.post("/api/runs", payload); +}, + listRuns() { + return this.get("/api/runs"); +}, + getRun(id) { + return this.get(`/api/runs/${encodeURIComponent(id)}`); +}, + stopRun(id) { + return this.post(`/api/runs/${encodeURIComponent(id)}/stop`, {}); +}, + + // schedules + listSchedules() { + return this.get("/api/schedules"); +}, + saveSchedule(id, body) { + return this.put(`/api/schedules/${encodeURIComponent(id)}`, body); +}, + deleteSchedule(id) { + return this.del(`/api/schedules/${encodeURIComponent(id)}`); +}, + toggleSchedule(id, enabled) { + return this.post(`/api/schedules/${encodeURIComponent(id)}/toggle`, { enabled }); +}, + + // logs + tailLog(runId, limit) { + return this.get(`/api/logs/${encodeURIComponent(runId)}?limit=${limit || 500}`); +}, + + // meta + meta() { + return this.get("/api/meta"); +}, +}; + +/* ========== 共享:LLM profiles 缓存 ========== + * 用于 FieldInput 的 llm_profile_ref 下拉:避免每个实例独自 fetch,一次加载全局共享。 + * LlmView 新增/编辑/删除后应调用 refreshLlmProfiles() 失效缓存。 + */ +const llmProfilesCache = ref([]); // [{ name, provider, model }, ...] +const llmProfilesLoading = ref(false); +let _llmProfilesLoaded = false; +async function ensureLlmProfiles() { + if (_llmProfilesLoaded || llmProfilesLoading.value) return; + llmProfilesLoading.value = true; + try { + const reg = await api.getLlm(); + const profs = reg && reg.profiles ? reg.profiles : {}; + const list = []; + for (const name of Object.keys(profs)) { + const p = profs[name] || {}; + list.push({ name, provider: p.provider || "", model: p.model || "" }); + } + // 排序:非 _example 优先,_example 置后;再按 name 字母序 + list.sort((a, b) => { + const aEx = a.name.endsWith("_example") ? 1 : 0; + const bEx = b.name.endsWith("_example") ? 1 : 0; + if (aEx !== bEx) return aEx - bEx; + return a.name.localeCompare(b.name); + }); + llmProfilesCache.value = list; + _llmProfilesLoaded = true; + } catch (e) { + console.warn("ensureLlmProfiles failed:", e); + } finally { + llmProfilesLoading.value = false; + } +} +async function refreshLlmProfiles() { + _llmProfilesLoaded = false; + await ensureLlmProfiles(); +} + +/* ========== 工具函数 ========== */ +function fmtTime(iso) { + return iso ? String(iso).replace("T", " ") : "-"; +} +function tsToHms(ts) { + if (!ts) return ""; + const d = new Date(ts * 1000); + const pad = (n) => String(n).padStart(2, "0"); + return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; +} + +/** 从嵌套对象读取 "a.b.c" 路径的值 */ +function getByPath(obj, path, defaultValue = undefined) { + if (!obj) return defaultValue; + const parts = path.split("."); + let cur = obj; + for (const p of parts) { + if (cur == null || typeof cur !== "object") return defaultValue; + cur = cur[p]; + } + return cur === undefined ? defaultValue : cur; +} + +/** 在嵌套对象上按 "a.b.c" 路径设置值(自动创建中间节点) */ +function setByPath(obj, path, value) { + const parts = path.split("."); + let cur = obj; + for (let i = 0; i < parts.length - 1; i++) { + const key = parts[i]; + if (cur[key] == null || typeof cur[key] !== "object") cur[key] = {}; + cur = cur[key]; + } + cur[parts[parts.length - 1]] = value; +} + +/** YAML 工具(基于 CDN 引入的 js-yaml) */ +function jsyamlLoad(text) { + if (window.jsyaml) return window.jsyaml.load(text); + try { + return JSON.parse(text); +} catch (e) { + throw new Error("js-yaml 未加载完成,请刷新页面"); +} +} +function jsyamlDump(obj) { + if (window.jsyaml) return window.jsyaml.dump(obj, { noRefs: true, lineWidth: -1, sortKeys: false }); + return JSON.stringify(obj, null, 2); +} + +/* ========== 共享状态 + 路由 ========== */ +const AppState = reactive({ + setup: null, + meta: null, + route: "dashboard", + routeParam: null, +}); + +function navigateTo(route, param) { + const hash = param ? `#/${route}/${encodeURIComponent(param)}` : `#/${route}`; + if (window.location.hash !== hash) window.location.hash = hash; + else syncRouteFromHash(); +} + +function syncRouteFromHash() { + const h = (window.location.hash || "#/dashboard").slice(2); + const parts = h.split("/").filter(Boolean); + AppState.route = parts[0] || "dashboard"; + AppState.routeParam = parts[1] ? decodeURIComponent(parts[1]) : null; +} + +async function refreshSetup() { + try { + AppState.setup = await api.setupStatus(); +} catch (e) { + ElMessage.error(`无法连接到服务端:${ e.message}`); +} +} + +async function refreshMeta() { + try { + AppState.meta = await api.meta(); +} catch (e) {} +} + +/* ============================================================================ + * 组件:FieldInput —— 单字段控件(根据 schema.type 分派) + * ========================================================================== */ +const FieldInput = defineComponent({ + props: ["field", "modelValue"], + emits: ["update:modelValue"], + template: ` + + + + + + + + + + + `, + setup(props, { emit }) { + const val = computed(() => props.modelValue); + const numericVal = computed(() => { + const v = props.modelValue; + if (v === "" || v == null) return undefined; + const n = Number(v); + return Number.isNaN(n) ? undefined : n; + }); + // 若本字段是 llm_profile 引用,惰性加载一次全局 LLM profiles。 + if (props.field && props.field.type === "llm_profile_ref") { + ensureLlmProfiles(); + } + const emitVal = (v) => emit("update:modelValue", v); + const asJson = (v) => { + if (v == null || v === "") return ""; + // 兼容"历史脏数据":旧版本把 textarea 原文(字符串)直接存进了 + // 绑定值。此时 v 本应是 object/null,却是 string → 尝试解析一次 + // 还原回 object;仍失败则按原字符串显示(JSON.stringify 会给它加 + // 外层引号 + 转义 \n/\",就是用户看到的"没渲染"现象的来源)。 + if (typeof v === "string") { + const t = v.trim(); + if (!t) return ""; + try { + const parsed = JSON.parse(t); + return JSON.stringify(parsed, null, 2); + } catch (e) { + return v; + } + } + try { + return JSON.stringify(v, null, 2); +} catch (e) { + return String(v); +} + }; + + // ---- dict 类型专用:本地文本缓存 + JSON 错误提示 ---- + // 之前的实现在 JSON 解析失败时把"原始文本"回填到绑定值,导致 extra + // 字段被污染成字符串,保存后持久化;下次再打开,asJson 对字符串做 + // JSON.stringify 会多一层引号与转义,出现用户看到的"没渲染"现象。 + // + // 新实现:textarea 的值由 dictText 这个本地 ref 托管;用户输入时 + // - 空白:emit {}; + // - 合法 JSON:emit 解析后的 object,并清空 dictError; + // - 非法:**不改动** emit 的值,只把错误写到 dictError,让 UI 高亮提示。 + // 外部 modelValue 变化(如编辑另一条 profile 时的重入)通过 watch + // 同步到 dictText,不参与"每次按键 emit"的通路,避免抖动污染。 + const dictText = ref(asJson(props.modelValue)); + const dictError = ref(""); + watch(() => props.modelValue, (nv) => { + // 父级外部赋值(load / editProfile)→ 把 object 转文本写到本地镜像 + const expected = asJson(nv); + if (expected !== dictText.value) dictText.value = expected; + }); + const onDictInput = (text) => { + dictText.value = text; + const t = (text || "").trim(); + if (!t) { + dictError.value = ""; + emitVal({}); + return; + } + try { + const parsed = JSON.parse(t); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + dictError.value = "必须是对象,例如 {\"key\": \"value\"}"; + return; + } + dictError.value = ""; + emitVal(parsed); + } catch (e) { + // 保留本地文本便于用户继续编辑;**不触发 emit** —— 绑定值维持 + // 最后一次合法状态,不会被污染。 + dictError.value = e.message || "JSON 解析失败"; + } + }; + + const workflowStates = computed(() => AppState.meta?.workflow_states || []); + // workflow 状态的中文元数据(key / label / desc / group / recommended) + const workflowStatesMeta = computed(() => { + const meta = AppState.meta?.workflow_states_meta; + if (Array.isArray(meta) && meta.length) return meta; + // 后端未提供 meta 时退化为纯 key 列表 + return (AppState.meta?.workflow_states || []).map(k => ({ + key: k, label: k, desc: "", group: "", recommended: false, + })); + }); + const isWfSelected = (k) => Array.isArray(props.modelValue) && props.modelValue.includes(k); + const toggleWf = (k) => { + const cur = Array.isArray(props.modelValue) ? [...props.modelValue] : []; + const i = cur.indexOf(k); + if (i >= 0) { + cur.splice(i, 1); + } else { + // 新加入的状态按 workflowStatesMeta 的推荐顺序插入到正确位置, + // 保证"全选"后的默认顺序符合流水线逻辑;用户也可以通过先清空 + // 再按自己的顺序逐个勾选来定制。 + const metaOrder = workflowStatesMeta.value.map(m => m.key); + const targetIdx = metaOrder.indexOf(k); + let insertAt = cur.length; + for (let j = 0; j < cur.length; j++) { + if (metaOrder.indexOf(cur[j]) > targetIdx) { + insertAt = j; break; +} + } + cur.splice(insertAt, 0, k); + } + emitVal(cur); + }; + const wfSelectAll = () => emitVal(workflowStatesMeta.value.map(m => m.key)); + const wfSelectRecommended = () => emitVal( + workflowStatesMeta.value.filter(m => m.recommended).map(m => m.key) + ); + const wfClear = () => emitVal([]); + + // ----------------------------------------------------------------------- + // 换行感知:标注"每行第一个 / 最后一个"节点,用于 CSS 控制箭头显隐。 + // + // flex-wrap 布局下,CSS 无法原生检测"每行的第一个 flex item"(因为列数 + // 是响应式的、随容器宽度动态变化)。所以用 ResizeObserver 监听容器宽度 + // 变化,再读每个节点的 offsetTop:一旦某个节点的 offsetTop 大于上一个 + // 节点,就是"新一行的开头" —— 把该节点标为 row-first,让 CSS 隐藏其 + // 左侧 ::before 箭头;同时上一个节点标为 row-last。 + // ----------------------------------------------------------------------- + const workflowFlowRef = ref(null); + const rowFirstIndices = reactive(new Set([0])); + const rowLastIndices = reactive(new Set()); + + const recomputeRowBreaks = () => { + const container = workflowFlowRef.value; + if (!container) return; + const nodes = container.querySelectorAll(".workflow-node"); + if (!nodes.length) return; + const firsts = new Set([0]); + const lasts = new Set(); + let prevTop = nodes[0].offsetTop; + for (let i = 1; i < nodes.length; i++) { + const t = nodes[i].offsetTop; + if (t > prevTop + 2) { // 2px 容差,避免浮点误差误判 + firsts.add(i); + lasts.add(i - 1); + prevTop = t; + } + } + lasts.add(nodes.length - 1); + // 同步到 reactive Set(diff 后原地修改,避免整体替换触发无谓重渲染) + rowFirstIndices.clear(); firsts.forEach(v => rowFirstIndices.add(v)); + rowLastIndices.clear(); lasts.forEach(v => rowLastIndices.add(v)); + }; + + let resizeObserver = null; + onMounted(() => { + // 组件可能不是 workflow 类型,但是 setup 对所有 FieldInput 都会执行。 + // 这里只有在 ref 挂上后才会有效果;非 workflow 字段的 ref 永远是 null。 + nextTick(() => { + if (!workflowFlowRef.value) return; + recomputeRowBreaks(); + resizeObserver = new ResizeObserver(() => recomputeRowBreaks()); + resizeObserver.observe(workflowFlowRef.value); + }); + }); + // 状态数增减时也触发重算 + watch(() => workflowStatesMeta.value.length, () => nextTick(recomputeRowBreaks)); + onBeforeUnmount(() => { + if (resizeObserver) { + resizeObserver.disconnect(); resizeObserver = null; +} + }); + + return { + val, numericVal, emit: emitVal, asJson, + dictText, dictError, onDictInput, + workflowStates, workflowStatesMeta, + isWfSelected, toggleWf, wfSelectAll, wfSelectRecommended, wfClear, + workflowFlowRef, rowFirstIndices, rowLastIndices, + // LLM profile 下拉数据(供 type="llm_profile_ref" 使用) + llmProfiles: llmProfilesCache, llmProfilesLoading, + }; + }, +}); + +/* ============================================================================ + * 组件:FieldRow —— 一行字段(label + badge + input + help + example) + * ---------------------------------------------------------------------------- + * 支持 required_if 动态必填:当字段配置了 required_if + depends_on,且 + * 父字段当前值 ∈ required_if 列表时,视为必填。 + * ========================================================================== */ +const FieldRow = defineComponent({ + components: { FieldInput }, + props: ["field", "modelValue", "effectiveRequired"], + emits: ["update:modelValue"], + template: ` +
+
+
+ {{ field.label }} + 必填 + 选填 + 🔒 敏感 +
+
{{ field.key }}
+
+ {{ field.env_hint }} +
+
+
+ +
+
{{ field.example }}
+
+
+ `, + setup(props) { + const isRequired = computed(() => { + // 父组件若显式传入 effectiveRequired(如解析了 required_if 的结果),优先用它 + if (props.effectiveRequired !== undefined && props.effectiveRequired !== null) { + return !!props.effectiveRequired; + } + return !!props.field.required; + }); + // 极简的 help 文案渲染:仅处理 `code` 和 **bold** 两种内联标记 + const renderHelp = (text) => { + if (!text) return ""; + const escaped = String(text) + .replace(/&/g, "&").replace(//g, ">"); + return escaped + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*([^*]+)\*\*/g, '$1'); + }; + return { isRequired, renderHelp }; + }, +}); + +/* ============================================================================ + * 组件:FieldGroupedForm —— 分组渲染一组字段 + * ---------------------------------------------------------------------------- + * 【响应式】data 参数**必须是 reactive 对象**。本组件直接在 data 上原地 + * setByPath,不走 v-model、不克隆、不 emit。 + * + * 【条件渲染】字段 schema 支持两种内置条件(无需父组件传 showField): + * - depends_on + applies_to:仅当父字段值 ∈ applies_to 时才显示字段 + * - depends_on + required_if:当父字段值 ∈ required_if 时该字段为必填 + * 父组件通过 props.showField 传入的自定义过滤会在内置过滤之后再应用。 + * ========================================================================== */ +const FieldGroupedForm = defineComponent({ + components: { FieldRow }, + props: { + schema: { type: Array, default: () => [] }, + data: { type: Object, required: true }, + /** 可选:根据分组名决定是否展示,返回 false 则该整组隐藏 */ + showGroup: { type: Function, default: null }, + /** 可选:按单个字段 key 做额外过滤(在内置 depends_on 过滤后再执行) */ + showField: { type: Function, default: null }, + }, + template: ` +
+
+
+ 📁 {{ g.name }} ({{ g.fields.length }} 项) + ▼ +
+
+ +
+
+
+ `, + setup(props) { + const collapsed = reactive({}); + const toggle = (name) => { + collapsed[name] = !collapsed[name]; +}; + const isCollapsed = (name) => !!collapsed[name]; + + /** 判断 schema 的内置条件(depends_on + applies_to)是否满足 */ + const passesDependsOn = (f) => { + if (!f.depends_on || !Array.isArray(f.applies_to) || !f.applies_to.length) return true; + const parent = getByPath(props.data, f.depends_on); + return f.applies_to.includes(parent); + }; + + /** 计算字段"动态必填"结果:先看 required,再看 required_if */ + const computeRequired = (f) => { + if (f.required) return true; + if (f.depends_on && Array.isArray(f.required_if) && f.required_if.length) { + const parent = getByPath(props.data, f.depends_on); + return f.required_if.includes(parent); + } + return false; + }; + + const groups = computed(() => { + const map = new Map(); + for (const f of props.schema) { + if (!passesDependsOn(f)) continue; // 内置条件 + if (props.showField && !props.showField(f)) continue; // 外部过滤 + const name = f.group || "其他"; + if (props.showGroup && !props.showGroup(name)) continue; + if (!map.has(name)) map.set(name, { name, fields: [] }); + map.get(name).fields.push(f); + } + return Array.from(map.values()); + }); + + const getVal = (key, def) => { + const v = getByPath(props.data, key); + return v === undefined ? def : v; + }; + + /** 原地写:Vue 响应式系统会自动追踪 */ + const setVal = (key, v) => { + setByPath(props.data, key, v); + // 字段级联动:source.format 变更时同步 source.path 的后缀, + // 避免"选了 xlsx 但路径还是 .json 结尾"的典型配错。 + syncPathExtensionOnFormatChange(key, v); + }; + + /** + * 当 ``key === 'source.format'`` 时,把兄弟字段 ``source.path`` 末尾 + * 的扩展名改成和新 format 对应的扩展名;仅在 path 当前后缀**也是**已知 + * 翻译格式后缀时才替换,避免把用户手动写的非常规文件名(如 + * ``i18n/strings.properties``)误伤。 + */ + const syncPathExtensionOnFormatChange = (key, newFormat) => { + if (key !== "source.format" || !newFormat) return; + const currentPath = getByPath(props.data, "source.path"); + if (!currentPath || typeof currentPath !== "string") return; + + // format → 规范扩展名(含点);多备选扩展名用第一项作为默认写入值 + const FORMAT_EXT_MAP = { + json: [".json"], + xlsx: [".xlsx", ".xls"], + csv: [".csv"], + xml: [".xml"], + dtxml: [".dtxml"], + html: [".html", ".htm"], + yaml: [".yaml", ".yml"], + xliff: [".xlf", ".xliff"], + markdown: [".md", ".markdown"], + md: [".md", ".markdown"], + }; + const targetExts = FORMAT_EXT_MAP[String(newFormat).toLowerCase()]; + if (!targetExts || !targetExts.length) return; + const newExt = targetExts[0]; + + // 识别当前路径的后缀:扫描所有已知格式对应的扩展名,若命中则替换; + // 若已经是目标 format 对应后缀之一,则无需操作。 + const lower = currentPath.toLowerCase(); + if (targetExts.some((ext) => lower.endsWith(ext))) return; + + const KNOWN_EXTS = Object.values(FORMAT_EXT_MAP).flat(); + const matched = KNOWN_EXTS.find((ext) => lower.endsWith(ext)); + if (!matched) return; // 用户用的是非标后缀(如 .properties),不动它 + + // 保留原路径的大小写与目录部分,仅替换末尾后缀 + const newPath = currentPath.slice(0, currentPath.length - matched.length) + newExt; + if (newPath !== currentPath) { + setByPath(props.data, "source.path", newPath); + } + }; + + return { groups, toggle, isCollapsed, getVal, setVal, computeRequired }; + }, +}); + +/* ============================================================================ + * 组件:Dashboard + * ========================================================================== */ +const Dashboard = defineComponent({ + template: ` +
+ +
+
+
+

+ {{ setup?.initialized ? '👋 欢迎回来' : '🚀 开始配置您的本地化流水线' }} +

+

+ 所有核心配置就绪,可以创建语种 profile 并开始运行。 + 检测到初始化尚未完成,请前往设置向导。 +

+
+
+ + {{ setup?.initialized ? '🧰 重新初始化' : '🚀 初始化向导' }} + + 🌐 管理语种 +
+
+
+ + +
+
+
⚙️ 全局配置
+
{{ setup?.config_yaml_exists ? '✓' : '—' }}
+
{{ setup?.config_yaml_exists ? 'conf/config.yaml 已就绪' : '尚未创建' }}
+
+
+
🤖 LLM 注册表
+
{{ setup?.llm_yaml_exists ? '✓' : '—' }}
+
{{ setup?.llm_yaml_exists ? 'conf/llm.yaml 已就绪' : '尚未创建' }}
+
+
+
🌐 语种 Profile
+
{{ setup?.languages_count || 0 }}
+
conf/languages/*.yaml
+
+
+
📈 系统状态
+
{{ setup?.initialized ? '运行就绪' : '待初始化' }}
+
{{ setup?.initialized ? '可开始工作' : '请完成初始化' }}
+
+
+ + +
+
+

🩺 配置健康检查

+ 刷新 +
+
+
+
+ ✓ + ! + ⚠ + — +
+
+
{{ c.label }}
+
{{ c.message }}
+
    +
  • {{ d }}
  • +
+
+ export {{ h }}=... +
+
+
+ 去修复 +
+
+
+
+ + +
+
+

🕒 最近运行

+ 查看全部 → +
+
+
📭
+
还没有任何运行记录
+
配置好一个语种 profile,到"语种配置"页点"立即运行"开始
+ 去配置语种 +
+ + + + + + + + + + + + + + + + +
+
+ `, + setup() { + const setup = computed(() => AppState.setup); + const runs = ref([]); + const refreshIcon = ref("Refresh"); + let timer = null; + + const load = async () => { + try { + runs.value = await api.listRuns(); +} catch(e){} + }; + const refresh = async () => { + await refreshSetup(); await load(); ElMessage.success("已刷新"); +}; + const go = (k) => navigateTo(k); + const toRun = (id) => navigateTo("run", id); + const openWizard = () => navigateTo("setup"); + const jumpToFix = (module) => { + if (module === "llm") navigateTo("llm"); + else if (module === "languages") navigateTo("languages"); + else navigateTo("global-config"); + }; + + onMounted(() => { + load(); timer = setInterval(load, 5000); +}); + onBeforeUnmount(() => timer && clearInterval(timer)); + return { setup, runs, refreshIcon, refresh, go, toRun, openWizard, jumpToFix, fmtTime }; + }, +}); + +/* ============================================================================ + * 组件:SetupWizard —— 清爽的 4 步向导 + * ---------------------------------------------------------------------------- + * 核心设计: + * - 不再要求用户选"一审 / 二审"(它们是语种级配置,在"语种 Profile"创建时选) + * - 每一步直接显示该步的输入字段,不要先选再填 + * - 已有配置时自动带入作为初始值 + * ========================================================================== */ +const SetupWizard = defineComponent({ + components: { FieldGroupedForm }, + template: ` +
+ +
+

🎮 TiMiHOKGameTranslator 初始化向导

+

只需 4 步完成基础配置。一审 / 二审平台是语种级配置,稍后在"语种 Profile"页面创建时按需选择。

+
+ + +
+
+
+
✓{{ i + 1 }}
+ {{ name }} +
+
+
+
+ + +
+

⚙️ 项目基础 + 版本控制

+ + +
+ + +
+

🤖 LLM 大模型配置

+ + +
+ + +
+
+

🎨 审校平台(可选,一审 / 二审统一使用)

+ + + +
+
+
{{ opt.emoji }}
+
{{ opt.label }}
+
{{ opt.desc }}
+
+
+ +
+ +
+
+ +
+

📣 通知渠道(可选)

+
+
+
{{ opt.emoji }}
+
{{ opt.label }}
+
{{ opt.desc }}
+
+
+ +
+ +
+
+
+ + +
+
🎉
+

准备就绪

+

+ 点击下方按钮,将配置写入到 conf/config.yaml 与 conf/llm.yaml。
+ 完成后在"语种 Profile"页面创建第一个语种即可开始使用。 +

+
+
📋 本次配置概览
+
+ 项目:{{ form.project_code }}
+ VCS:{{ form.vcs.type }} · {{ form.vcs.url }}
+ LLM:{{ llmProfile.name }} ({{ llmProfile.provider }})
+ 全局平台:{{ form.platform.type }}
+ 通知:{{ form.notification.type }} +
+
+
+ + +
+ ← 上一步 +
+
步骤 {{ step + 1 }} / {{ stepNames.length }}
+ 下一步 → + + 🚀 完成并写入配置 + +
+
+ `, + setup() { + const step = ref(0); + const submitting = ref(false); + const stepNames = ["项目 & VCS", "LLM 模型", "审校 & 通知", "完成"]; + + const platformOptions = [ + { value: "none", emoji: "🚫", label: "不启用", desc: "跳过全局审校平台" }, + { value: "phrase", emoji: "📘", label: "Phrase TMS", desc: "原 Memsource,支持 EU/US 账户" }, + { value: "crowdin", emoji: "🌍", label: "Crowdin", desc: "Crowdin API v2" }, + ]; + + const notifyOptions = [ + { value: "none", emoji: "🔕", label: "不启用", desc: "不发送任何通知" }, + { value: "console", emoji: "💻", label: "控制台", desc: "仅打印到日志,无外部通知" }, + { value: "wecom", emoji: "💬", label: "企业微信", desc: "群机器人 webhook" }, + ]; + + // reactive 对象 —— FieldGroupedForm 直接原地修改 + const form = reactive({ + project_code: "my_game", + stage: "trunk_week", + source_locale: "zh-CN", + languages_dir: "conf/languages", + vcs: { type: "local", url: "", revision: "HEAD", local_path: "", username: "", password: "", + cli_timeout_seconds: 600, default_commit_message: "[TiMi_HOK_Game_Translator] commit translation data" }, + platform: { type: "none", api_base: "", api_token: "", project_id: "", extra: {} }, + notification: { type: "none", webhook: "", mentioned: [] }, + llm_profile: "default", + workspace: { root: "", subdir: "workspace", state_filename: "workflow_state.json" }, + logging: { level: "INFO", directory: "logs", filename: "TiMi_HOK_Game_Translator.log", console: true }, + }); + + const llmProfile = reactive({ + name: "default", provider: "echo", model: "echo-dev", api_base: "", api_key: "", + temperature: 0.2, max_tokens: 1024, batch_size: 16, + timeout_seconds: 60, retries: 3, retry_interval_seconds: 10, extra: {}, + }); + + const globalSchema = ref([]); + const llmProfileSchema = ref([]); + + // Step 0: 只显示 "项目基础" + "版本控制" 分组 + const basicVcsSchema = computed(() => + globalSchema.value.filter((f) => ["项目基础", "版本控制"].includes(f.group)) + ); + + // Step 1: 完整 LLM profile schema + const llmSchema = computed(() => llmProfileSchema.value); + + // Step 2: 全局审校平台字段(排除 platform.type 本身,根据平台类型过滤) + const platformFieldsSchema = computed(() => + globalSchema.value.filter((f) => f.group === "审校平台") + ); + + // 根据选中的平台类型决定显示哪些字段 + // - 排除 platform.type 本身(Setup 向导用卡片选择,而非下拉) + // - Phrase 专属字段的"选 Phrase 才显示"由 schema 的 applies_to 自动处理 + const shouldShowPlatformField = (f) => f.key !== "platform.type"; + + // Step 2: 通知字段 + const notifyFieldsSchema = computed(() => + globalSchema.value.filter((f) => f.group === "通知") + ); + + // 选中企业微信时才需要显示 webhook 字段 + const needsWebhook = computed(() => + form.notification.type === "wecom" + ); + + const selectPlatform = (v) => { + form.platform.type = v; + // 自动填充 api_base 常用默认 + if (v === "crowdin" && !form.platform.api_base) { + form.platform.api_base = "https://api.crowdin.com/api/v2"; + } else if (v === "phrase" && !form.platform.api_base) { + form.platform.api_base = "https://cloud.memsource.com/web/api2"; + } + }; + + const selectNotify = (v) => { + form.notification.type = v; +}; + + const loadSchemas = async () => { + try { + const [g, l] = await Promise.all([api.getSchema("global"), api.getSchema("llm_profile")]); + globalSchema.value = g.fields; + llmProfileSchema.value = l.fields; + } catch (e) { + ElMessage.error(`加载 schema 失败:${ e.message}`); +} + }; + + const nextStep = () => { + // 分步校验 + if (step.value === 0) { + if (!form.project_code) { + ElMessage.warning("project_code 必填"); return; +} + if (!form.vcs.type) { + ElMessage.warning("vcs.type 必填"); return; +} + // local_path 对所有 vcs.type(含 mock)都必填 —— 它是流水线落地的工作副本目录 + if (!form.vcs.local_path) { + ElMessage.warning("vcs.local_path 必填(流水线读写源文件/译文的根目录;local 推荐填绝对路径)"); + return; + } + // local 和老别名 mock 都不需要 vcs.url + if (form.vcs.type !== "local" && form.vcs.type !== "mock") { + if (!form.vcs.url) { + ElMessage.warning("vcs.url 必填"); return; +} + } + } + if (step.value === 1) { + if (!llmProfile.name) { + ElMessage.warning("LLM profile 名称必填"); return; +} + if (!/^[a-zA-Z0-9_-]+$/.test(llmProfile.name)) { + ElMessage.warning("profile 名称只允许字母、数字、下划线、连字符"); + return; + } + if (!llmProfile.provider) { + ElMessage.warning("provider 必填"); return; +} + // provider=echo(老别名 mock)不需要其它字段 + if (llmProfile.provider !== "echo" && llmProfile.provider !== "mock") { + if (!llmProfile.model) { + ElMessage.warning("model 必填"); return; +} + const needsBase = ["openai_compatible", "venus", "hunyuan_translation"]; + if (needsBase.includes(llmProfile.provider) && !llmProfile.api_base) { + ElMessage.warning(`provider=${llmProfile.provider} 需要填写 api_base`); + return; + } + const needsKey = ["openai", "openai_compatible", "anthropic", "gemini", "hunyuan_translation"]; + if (needsKey.includes(llmProfile.provider) && !llmProfile.api_key) { + ElNotification({ + type: "info", duration: 4000, title: "提示", + message: "api_key 为空 —— 请确认已通过环境变量 GAME_TRANS_TOOLCHAIN__LLM__API_KEY 注入", + }); + } + if (llmProfile.provider === "venus") { + const ex = llmProfile.extra || {}; + if (!ex.server_id || !ex.app_group_id) { + ElMessage.warning("venus 需要填写 extra.server_id 和 extra.app_group_id"); + return; + } + } + if (llmProfile.provider === "hunyuan_translation") { + const ex = llmProfile.extra || {}; + if (!ex.wsid) { + ElMessage.warning("hunyuan_translation 需要填写 extra.wsid"); + return; + } + } + } + } + if (step.value === 2) { + if (form.platform.type !== "none" && !form.platform.api_token + && !form.platform.extra?.subject_token) { + // 不强制 —— 允许走环境变量 + ElNotification({ + type: "info", duration: 3000, + title: "提示", message: "api_token 为空 —— 请确保已通过环境变量 GAME_TRANS_TOOLCHAIN__PLATFORM__API_TOKEN 注入", + }); + } + } + step.value += 1; + scrollWizardToTop(); + }; + + // 上一步:复用同一个滚动归位逻辑,避免用户进入下一个表单时还处于页面中段 + const prevStep = () => { + if (step.value > 0) { + step.value -= 1; + scrollWizardToTop(); + } + }; + + // 把 .content 滚动容器(见 app.css:.content { overflow: auto })滚回顶部。 + // 必须等 Vue 完成 DOM diff 后再滚,否则新表单还没渲染到位。 + const scrollWizardToTop = () => { + nextTick(() => { + const el = document.querySelector(".content"); + if (el && typeof el.scrollTo === "function") { + el.scrollTo({ top: 0, behavior: "smooth" }); + } else if (el) { + el.scrollTop = 0; + } + // 极端情况(如移动端)整个 window 也可能有滚动条,兜底归零 + try { + window.scrollTo({ top: 0, behavior: "smooth" }); +} catch { + window.scrollTo(0, 0); +} + }); + }; + + const onSubmit = async () => { + submitting.value = true; + try { + form.llm_profile = llmProfile.name || "default"; + // 只把**用户实际填入的字段**写进 payload,避免 undefined/空值 + // 覆盖 llm.yaml 里已有示例 profile 的 placeholder(如 ""、注释等)。 + const profilePayload = {}; + const KEYS = ["provider", "model", "api_base", "api_key", "temperature", + "max_tokens", "batch_size", "timeout_seconds", "retries", + "retry_interval_seconds"]; + for (const k of KEYS) { + const v = llmProfile[k]; + if (v !== undefined && v !== null && v !== "") { + profilePayload[k] = v; + } + } + // extra 单独处理:里面可能有嵌套字典(如 model_params / generation_config) + if (llmProfile.extra && typeof llmProfile.extra === "object") { + const cleanExtra = {}; + for (const k of Object.keys(llmProfile.extra)) { + const v = llmProfile.extra[k]; + if (v !== undefined && v !== null && v !== "") { + cleanExtra[k] = v; + } + } + if (Object.keys(cleanExtra).length) { + profilePayload.extra = cleanExtra; + } + } + const llm = { + default: llmProfile.name, + profiles: { [llmProfile.name]: profilePayload }, + }; + // 透出一份偏好便于下次向导恢复 + const preferences = { + platform_type: form.platform.type, + notification_type: form.notification.type, + }; + await api.setupInit({ config: form, llm, preferences }); + await refreshSetup(); + // 二次确认 setup 状态,确认已初始化再引导下一步 + const latest = AppState.setup; + if (latest && latest.initialized) { + try { + await ElMessageBox.confirm( + "配置已写入 conf/。接下来需要配置至少一个语种 profile(source.path / target_locale / 审校项目 ID 等),才能启动翻译流水线。", + "🎉 初始化完成", + { + confirmButtonText: "前往配置语种", + cancelButtonText: "回主控台", + type: "success", + center: true, + }, + ); + navigateTo("languages"); + } catch (_cancel) { + navigateTo("dashboard"); + } + } else { + // 不常见:init 成功但 status 未通过(例如用户配了 venus 但没填 secret_id) + const missing = (latest && latest.missing_fields) || []; + ElMessageBox.alert( + `配置已写入,但以下字段仍需补齐(可以在相应页面继续编辑后再次刷新状态):\n\n• ${ + missing.length ? missing.join("\n• ") : "(无详细信息,请在 Dashboard 查看 ⚠️ 配置健康检查)"}`, + "⚠️ 配置未完全就绪", + { confirmButtonText: "我知道了,去主控台看看", type: "warning" }, + ).finally(() => navigateTo("dashboard")); + } + } catch (e) { + ElMessage.error(`初始化失败:${ e.message}`); + } finally { + submitting.value = false; + } + }; + + onMounted(async () => { + await loadSchemas(); + // 带入已有配置作为初始值 + try { + const existing = await api.getGlobalConfig(); + if (existing && Object.keys(existing).length) { + // **只在已经初始化过**时才回填 vcs 配置,否则 config.yaml 的示例值 + // (如 vcs.type: svn)会覆盖我们对首次用户更友好的默认 'local'。 + const alreadyInitialized = !!AppState.setup?.initialized; + if (!alreadyInitialized && existing.vcs) { + // 克隆一份浅拷贝,剔除 type 以保留前端的 'local' 默认 + const vcsSafe = { ...existing.vcs }; + delete vcsSafe.type; + // 用剔除后的 vcs 覆盖原字段,但不动前端默认 type + const existingSafe = { ...existing, vcs: vcsSafe }; + deepMergeInto(form, existingSafe); + } else { + deepMergeInto(form, existing); + } + } + const existingLlm = await api.getLlm(); + if (existingLlm?.profiles && existingLlm.default && existingLlm.profiles[existingLlm.default]) { + const p = existingLlm.profiles[existingLlm.default]; + llmProfile.name = existingLlm.default; + for (const k of Object.keys(p || {})) llmProfile[k] = p[k]; + } + } catch (e) {} + }); + + return { + step, stepNames, submitting, + platformOptions, notifyOptions, + form, llmProfile, + basicVcsSchema, llmSchema, platformFieldsSchema, notifyFieldsSchema, needsWebhook, + shouldShowPlatformField, + selectPlatform, selectNotify, + nextStep, prevStep, onSubmit, + }; + }, +}); + +/** 原地深合并:把 source 的值合并到 target(reactive),保持引用不变 */ +function deepMergeInto(target, source) { + if (!source || typeof source !== "object") return; + for (const k of Object.keys(source)) { + const sv = source[k]; + if (sv && typeof sv === "object" && !Array.isArray(sv) + && target[k] && typeof target[k] === "object" && !Array.isArray(target[k])) { + deepMergeInto(target[k], sv); + } else { + target[k] = sv; + } + } +} + +/* ============================================================================ + * 组件:GlobalConfigView —— 结构化表单 + YAML 原文双视图 + * ========================================================================== */ +const GlobalConfigView = defineComponent({ + components: { FieldGroupedForm }, + template: ` +
+
+
+
+

⚙️ 全局配置 (conf/config.yaml)

+ 按分组填写 +
+
+
+ + +
+ 重新加载 + 💾 保存 +
+
+ + + + +
+
+ `, + setup() { + const view = ref("form"); + const data = reactive({}); + const yamlText = ref(""); + const schema = ref([]); + const saving = ref(false); + + const resetData = (next) => { + // 原地清空再合入,保持 reactive 引用 + for (const k of Object.keys(data)) delete data[k]; + if (next && typeof next === "object") Object.assign(data, next); + }; + + // 字段级条件渲染现已由 schema 的 depends_on + applies_to 元信息驱动, + // FieldGroupedForm 内置支持,无需在此处再做自定义过滤。 + + const load = async () => { + try { + const [cfg, sch] = await Promise.all([api.getGlobalConfig(), api.getSchema("global")]); + resetData(cfg || {}); + yamlText.value = jsyamlDump(cfg || {}); + schema.value = sch.fields; + } catch (e) { + ElMessage.error(`加载失败:${ e.message}`); +} + }; + + const switchView = (v) => { + if (v === view.value) return; + if (v === "yaml") { + // 表单 → YAML:把 data 序列化 + yamlText.value = jsyamlDump({ ...data }); + } else { + // YAML → 表单:解析回填 + try { + const next = jsyamlLoad(yamlText.value) || {}; + resetData(next); + } catch (e) { + ElMessage.warning(`YAML 解析失败,表单保留上次值:${ e.message}`); + return; + } + } + view.value = v; + }; + + const save = async () => { + let payload; + if (view.value === "yaml") { + try { + payload = jsyamlLoad(yamlText.value) || {}; +} catch (e) { + ElMessage.error(`YAML 解析失败:${ e.message}`); return; +} + } else { + payload = { ...data }; + } + saving.value = true; + try { + await api.putGlobalConfig(payload); + ElMessage.success("已保存"); + await refreshSetup(); + await load(); + } catch (e) { + ElMessage.error(`保存失败:${ e.message}`); +} finally { + saving.value = false; +} + }; + + onMounted(load); + return { view, data, yamlText, schema, saving, load, save, switchView }; + }, +}); + +/* ============================================================================ + * 组件:LlmView —— profile 列表 + 结构化编辑 + * ========================================================================== */ +const LlmView = defineComponent({ + components: { FieldGroupedForm }, + template: ` +
+
+
+
+

🤖 LLM 注册表 (conf/llm.yaml)

+ 当前默认 profile: {{ registry.default || '-' }} +
+
+ + 新建 Profile + 重新加载 +
+
+ +
+
🤖
+
还没有任何 LLM profile
+ + 新建 +
+ + + + + + + + + + + + + + +
+ + + + +
+ 取消 + 💾 保存 +
+
+
+ `, + setup() { + const registry = ref({ default: "", profiles: {} }); + const schema = ref([]); + const drawerVisible = ref(false); + const editing = ref(false); + const currentName = ref(""); + const currentProfile = reactive({}); + const saving = ref(false); + + const resetProfile = (obj) => { + for (const k of Object.keys(currentProfile)) delete currentProfile[k]; + if (obj) Object.assign(currentProfile, obj); + }; + + const profileList = computed(() => { + const arr = []; + for (const [name, prof] of Object.entries(registry.value.profiles || {})) { + arr.push({ name, ...(prof || {}) }); + } + return arr; + }); + + const load = async () => { + try { + const [reg, sch] = await Promise.all([api.getLlm(), api.getSchema("llm_profile")]); + registry.value = reg || { default: "", profiles: {} }; + schema.value = sch.fields; + } catch (e) { + ElMessage.error(`加载失败:${ e.message}`); +} + }; + + const editProfile = (name) => { + editing.value = true; + currentName.value = name; + resetProfile({ name, ...(registry.value.profiles[name] || {}) }); + drawerVisible.value = true; + }; + + const newProfile = () => { + editing.value = false; + currentName.value = ""; + resetProfile({ name: "", provider: "echo", model: "", api_base: "", api_key: "", + temperature: 0.2, max_tokens: 1024, batch_size: 16, + timeout_seconds: 60, retries: 3, retry_interval_seconds: 10, extra: {} }); + drawerVisible.value = true; + }; + + const saveProfile = async () => { + const p = currentProfile; + if (!p.name) { + ElMessage.warning("profile 名称必填"); return; +} + // 格式校验:仅允许字母、数字、下划线、连字符 + if (!/^[a-zA-Z0-9_-]+$/.test(p.name)) { + ElMessage.warning("profile 名称只允许字母、数字、下划线(_)、连字符(-)"); + return; + } + if (!p.provider) { + ElMessage.warning("provider 必填"); return; +} + // 唯一性校验:新建时若名字已存在、编辑时若改成一个已存在的别人的名字 → 冲突 + const existing = Object.keys(registry.value.profiles || {}); + const conflictTargetName = (!editing.value) ? p.name + : (p.name !== currentName.value ? p.name : null); + if (conflictTargetName && existing.includes(conflictTargetName)) { + ElMessage.error(`profile 名称 "${conflictTargetName}" 已存在。profile 名称必须全局唯一 —— config.yaml / 语种 profile 的 llm_profile 字段都是按此名引用的。`); + return; + } + // 根据 provider 做条件必填校验 + if (p.provider !== "echo" && p.provider !== "mock") { + if (!p.model) { + ElMessage.warning("model 必填"); return; +} + const needsBase = ["openai_compatible", "venus", "hunyuan_translation"]; + if (needsBase.includes(p.provider) && !p.api_base) { + ElMessage.warning(`provider=${p.provider} 需要填写 api_base`); return; + } + if (p.provider === "venus") { + const ex = p.extra || {}; + if (!ex.server_id || !ex.app_group_id) { + ElMessage.warning("venus 需要填写 extra.server_id 和 extra.app_group_id"); + return; + } + } + if (p.provider === "hunyuan_translation") { + const ex = p.extra || {}; + if (!ex.wsid) { + ElMessage.warning("hunyuan_translation 需要填写 extra.wsid"); + return; + } + } + } + saving.value = true; + try { + const next = JSON.parse(JSON.stringify(registry.value)); + next.profiles = next.profiles || {}; + if (editing.value && currentName.value && currentName.value !== p.name) { + delete next.profiles[currentName.value]; + if (next.default === currentName.value) next.default = p.name; + } + const { name, ...rest } = { ...p }; + next.profiles[name] = rest; + if (!next.default) next.default = name; + await api.putLlm(next); + ElMessage.success("已保存"); + drawerVisible.value = false; + await load(); + await refreshSetup(); + refreshLlmProfiles(); // 失效 LLM profile 下拉缓存 + } catch (e) { + ElMessage.error(`保存失败:${ e.message}`); +} finally { + saving.value = false; +} + }; + + const setDefault = async (name) => { + try { + const next = JSON.parse(JSON.stringify(registry.value)); + next.default = name; + await api.putLlm(next); + ElMessage.success(`已将 ${name} 设为默认`); + await load(); + refreshLlmProfiles(); + } catch (e) { + ElMessage.error(e.message); +} + }; + + const deleteProfile = async (name) => { + try { + await ElMessageBox.confirm(`删除 profile ${name}?`, "警告", { type: "warning" }); +} catch { + return; +} + try { + const next = JSON.parse(JSON.stringify(registry.value)); + delete next.profiles[name]; + if (next.default === name) next.default = Object.keys(next.profiles)[0] || ""; + await api.putLlm(next); + ElMessage.success("已删除"); + await load(); + refreshLlmProfiles(); + } catch (e) { + ElMessage.error(e.message); +} + }; + + onMounted(load); + return { + registry, schema, profileList, drawerVisible, editing, currentName, currentProfile, saving, + load, editProfile, newProfile, saveProfile, setDefault, deleteProfile, + }; + }, +}); + +/* ============================================================================ + * 组件:LanguagesView —— 列表 + 结构化编辑 + * ========================================================================== */ +const LanguagesView = defineComponent({ + components: { FieldGroupedForm }, + template: ` +
+
+
+
+

🌐 语种 Profile ({{ items.length }} 个)

+
+
+ + 新建语种 +
+
+ +
+
🌍
+
还没有任何语种 profile
+
创建一个语种 profile 来开始您的本地化流水线
+ + 新建第一个语种 +
+ + + + + + + + + + + + + + +
+ + + + + + + + + +
+
+ + +
+
+ + +
+ + + + + + + + + + + + + + + + +
+ + {{ p.name }} + [模板] + + + {{ p.provider }} · {{ p.model }} + +
+
+
+
+ ⚠️ 这是模板示例 profile,建议到「🤖 LLM 模型」页面复制一份、填好真实凭据后再引用。 +
+
+
+ +
+ + + + + + + + + +
+ `, + setup() { + const items = ref([]); + const schema = ref([]); + const editorVisible = ref(false); + const editing = ref(false); + const currentId = ref(""); + const currentData = reactive({}); + const yamlText = ref(""); + const view = ref("form"); + const saving = ref(false); + // 全局 config 快照,用于: + // 1) 新建语种时把 platform.project_id 默认带入 reviews.first/second.project_id + // 2) 顶部提醒"审校平台上必须存在对应 source_locale → target_locale 的项目" + const globalConfig = ref({}); + + const newDialog = ref(false); + const newForm = reactive({ id: "", display_name: "", target_locale: "", llm_profile: "" }); + + const dupDialog = ref(false); + const dupSrc = ref(""); + const dupId = ref(""); + + const resetCurrent = (obj) => { + for (const k of Object.keys(currentData)) delete currentData[k]; + if (obj) Object.assign(currentData, obj); + }; + + const load = async () => { + try { + const [list, sch, gc] = await Promise.all([ + api.listLanguages(), + api.getSchema("language"), + api.getGlobalConfig().catch(() => ({})), + ]); + items.value = list; + schema.value = sch.fields; + globalConfig.value = gc || {}; + // 顺手拉取一次 LLM profile 清单,新建对话框的下拉即可用 + ensureLlmProfiles(); + } catch (e) { + ElMessage.error(`加载失败:${ e.message}`); +} + }; + + const switchView = (v) => { + if (v === view.value) return; + if (v === "yaml") { + yamlText.value = jsyamlDump({ ...currentData }); + } else { + try { + const next = jsyamlLoad(yamlText.value) || {}; + resetCurrent(next); + } catch (e) { + ElMessage.warning("YAML 解析失败,表单保留上次值"); return; + } + } + view.value = v; + }; + + const openEdit = async (id) => { + try { + currentId.value = id; + editing.value = true; + const data = await api.getLanguage(id); + resetCurrent(data || {}); + yamlText.value = jsyamlDump(data || {}); + view.value = "form"; + editorVisible.value = true; + } catch (e) { + ElMessage.error(`加载失败:${ e.message}`); +} + }; + + const openNew = () => { + Object.assign(newForm, { id: "", display_name: "", target_locale: "", llm_profile: "" }); + newDialog.value = true; + }; + + const createNew = () => { + if (!newForm.id) { + ElMessage.warning("语种 ID 必填"); return; +} + currentId.value = newForm.id; + editing.value = false; + // 从全局 config 带入默认值(审校平台类型 + project_id + source_locale) + const gc = globalConfig.value || {}; + const platformProjectId = (gc.platform && gc.platform.project_id) || ""; + const platformType = (gc.platform && gc.platform.type) || ""; + const sourceLocale = gc.source_locale || "zh-CN"; + // 从全局 config.yaml 带入 notification。使用方可以: + // - 不改 → 直接复用全局 webhook + mentioned; + // - 清空 webhook / mentioned → 运行时字段级继承全局(见 cli._merge_notification); + // - 整段改为 { type: "console" } → 本语种改走控制台通知。 + const globalNotify = gc.notification || {}; + const defaultNotification = { + type: globalNotify.type || "console", + webhook: globalNotify.webhook || "", + mentioned: Array.isArray(globalNotify.mentioned) ? [...globalNotify.mentioned] : [], + }; + const defaults = { + id: newForm.id, + display_name: newForm.display_name || newForm.id, + source_locale: sourceLocale, + target_locale: newForm.target_locale || newForm.id, + locale_names: { cn: newForm.display_name || newForm.id, en: "" }, + source: { format: "xlsx", path: "", encoding: "utf-8" }, + llm_profile: newForm.llm_profile || "", + strategy_config: { + display_name: newForm.display_name || newForm.id, + use_concurrent_by_default: true, + default_max_workers: 32, + progress_log_interval: 100, + }, + // reviews 的 platform 字段由后端根据全局 config.yaml 的 platform.type 自动同步, + // 这里只填各阶段的 project_id / project_name 等业务字段。 + // 一审 / 二审默认带入全局 platform.project_id,便于单项目多语种共用同一个平台项目; + // 如需每语种独立项目 ID,在表单里改即可。 + reviews: { + light: { project_id: "", project_name: `${newForm.id}_Light` }, + first: { + project_id: platformProjectId, + project_name: `${newForm.id}_First`, + target_language_id: newForm.target_locale || newForm.id, + poll_interval_seconds: 60, + }, + second: { + project_id: platformProjectId, + project_name: `${newForm.id}_Second`, + target_language_id: newForm.target_locale || newForm.id, + poll_interval_seconds: 60, + }, + }, + notification: defaultNotification, + workflow: ["pull_vcs", "translate", "merge_data", "push_vcs"], + merge_start_time: "", + }; + // 提示用户:平台上必须预先创建该语种项目 + if (platformType && platformType !== "none" && platformProjectId) { + ElNotification({ + title: "💡 平台项目联动", + message: `已自动带入全局平台 ${platformType} 的 project_id = "${platformProjectId}"。\n请确认该项目在 ${platformType} 平台上已经为 ${sourceLocale} → ${newForm.target_locale || newForm.id} 开启了对应的目标语言。`, + type: "info", + duration: 8000, + dangerouslyUseHTMLString: false, + }); + } + resetCurrent(defaults); + yamlText.value = jsyamlDump(defaults); + view.value = "form"; + newDialog.value = false; + editorVisible.value = true; + }; + + const save = async () => { + let payload; + if (view.value === "yaml") { + try { + payload = jsyamlLoad(yamlText.value) || {}; +} catch (e) { + ElMessage.error(`YAML 解析失败:${ e.message}`); return; +} + } else { + payload = { ...currentData }; + } + saving.value = true; + try { + await api.saveLanguage(currentId.value, payload); + ElMessage.success("已保存"); + editorVisible.value = false; + await load(); + await refreshSetup(); + } catch (e) { + ElMessage.error(`保存失败:${ e.message}`); +} finally { + saving.value = false; +} + }; + + const runNow = async (id) => { + try { + await ElMessageBox.confirm(`立即运行语种 "${id}" 的工作流?`, "确认", { type: "warning" }); +} catch { + return; +} + try { + const rec = await api.startRun({ language: id, fresh: false }); + ElNotification({ title: "已启动", type: "success", message: rec.run_id }); + navigateTo("run", rec.run_id); + } catch (e) { + ElMessage.error(`启动失败:${ e.message}`); +} + }; + + const onDelete = async (id) => { + try { + await ElMessageBox.confirm(`确认删除语种 ${id}?文件将移到 conf/.backup/`, "警告", { type: "warning" }); +} catch { + return; +} + try { + await api.deleteLanguage(id); ElMessage.success("已删除"); await load(); +} catch (e) { + ElMessage.error(`删除失败:${ e.message}`); +} + }; + + const openDup = (id) => { + dupSrc.value = id; dupId.value = ""; dupDialog.value = true; +}; + + const doDuplicate = async () => { + if (!dupId.value) { + ElMessage.warning("请填写新语种 ID"); return; +} + try { + await api.duplicateLanguage(dupSrc.value, dupId.value); + ElMessage.success("已克隆"); + dupDialog.value = false; + await load(); + } catch (e) { + ElMessage.error(`克隆失败:${ e.message}`); +} + }; + + onMounted(load); + + /** + * 平台 / 语种联动提醒。 + * 根据全局 config.yaml 的 platform.type 和 project_id,以及**当前正在编辑的语种** + * 的 source_locale / target_locale,生成一条合适的提示: + * - 平台未启用(none / 空)→ info:无需平台 + * - 平台已启用但 project_id 未填 → warning:请先在 Dashboard / 全局配置填 project_id + * - 平台已启用且 project_id 已填 → success:提醒检查平台上该项目是否已开启目标语言 + */ + const platformHint = computed(() => { + if (!editorVisible.value) return null; + const gc = globalConfig.value || {}; + const plat = gc.platform || {}; + const platType = plat.type || "none"; + const platProjectId = plat.project_id || ""; + const srcLoc = currentData.source_locale || gc.source_locale || "zh-CN"; + const tgtLoc = currentData.target_locale || currentId.value || "<未填>"; + if (!platType || platType === "none") { + return { + type: "info", + title: "🌐 未启用审校平台", + body: `当前全局 config.yaml 的 platform.type = none,所有审校阶段将被跳过。
+ 如需启用 Phrase / Crowdin,请到 全局配置 页先完成平台配置。`, + }; + } + if (!platProjectId) { + return { + type: "warning", + title: `⚠️ ${platType} 平台已启用但 project_id 未填`, + body: `请先到 全局配置 页填入 platform.project_id(也可以在下方的 + reviews.first.project_id / reviews.second.project_id + 直接填写该语种独有的项目 ID)。
+ ⚡ 必须确保 ${platType} 平台上**已经创建了该项目**,并且为 + ${srcLoc} → ${tgtLoc} 这一语言对开启了对应的目标语言。`, + }; + } + return { + type: "success", + title: `✅ 已关联到 ${platType} 项目 #${platProjectId}`, + body: `一审 / 二审默认指向全局平台项目 ${platProjectId}(可在下方 reviews.* 中覆盖)。
+ ⚡ 请务必确认:${platType} 平台上的该项目**已经为 + ${srcLoc} → ${tgtLoc} 开启了目标语言**,否则推送任务时平台会拒绝接收。`, + }; + }); + + return { + items, schema, editorVisible, editing, currentId, currentData, yamlText, view, saving, + newDialog, newForm, dupDialog, dupSrc, dupId, + globalConfig, platformHint, + // 新建对话框的 LLM profile 下拉 + llmProfiles: llmProfilesCache, llmProfilesLoading, + openEdit, openNew, createNew, save, runNow, onDelete, openDup, doDuplicate, switchView, + }; + }, +}); + +/* ============================================================================ + * 组件:RunsView + * ========================================================================== */ +const RunsView = defineComponent({ + template: ` +
+
+

📜 运行历史

+ 刷新 +
+
+
📭
+
还没有任何运行记录
+ 去配置语种并运行 +
+ + + + + + + + + + + + + + + + + +
+ `, + setup() { + const runs = ref([]); + let timer = null; + const load = async () => { + try { + runs.value = await api.listRuns(); +} catch(e){} +}; + const stop = async (id) => { + try { + await api.stopRun(id); ElMessage.success("已发送停止"); await load(); +} catch(e){ + ElMessage.error(e.message); +} +}; + onMounted(() => { + load(); timer = setInterval(load, 5000); +}); + onBeforeUnmount(() => timer && clearInterval(timer)); + return { runs, fmtTime, stop, go: (k) => navigateTo(k), toRun: (id) => navigateTo("run", id) }; + }, +}); + +/* ============================================================================ + * 组件:RunDetailView + * ========================================================================== */ +const RunDetailView = defineComponent({ + template: ` +
+
+
+
+

🖥 Run: {{ runId }}

+
+ {{ rec.status }} + 开始 {{ fmtTime(rec.started_at) }} + 结束 {{ fmtTime(rec.finished_at) }} +
+
+
+ ← 返回列表 + ⏹ 停止 +
+
+
+ +
+

📋 实时日志(WebSocket)

+
+
[{{ tsToHms(e.ts) }}] {{ e.line }}
+
+
+
+ `, + setup() { + const runId = computed(() => AppState.routeParam); + const rec = ref(null); + const lines = ref([]); + const logEl = ref(null); + let ws = null; + let pollTimer = null; + + const refreshRec = async () => { + try { + rec.value = await api.getRun(runId.value); +} catch(e){} +}; + const scrollBottom = () => { + if (!logEl.value) return; + requestAnimationFrame(() => { + if (logEl.value) logEl.value.scrollTop = logEl.value.scrollHeight; +}); + }; + const addLine = (entry) => { + lines.value.push(entry); + if (lines.value.length > 10000) lines.value.splice(0, lines.value.length - 10000); + scrollBottom(); + }; + const stop = async () => { + try { + await api.stopRun(runId.value); ElMessage.success("已发送停止信号"); +} catch(e){ + ElMessage.error(e.message); +} +}; + const back = () => navigateTo("runs"); + + onMounted(() => { + api.tailLog(runId.value, 1000).then((resp) => { + lines.value = resp.entries || []; + scrollBottom(); + }).catch(()=>{}); + refreshRec(); + pollTimer = setInterval(refreshRec, 3000); + + const proto = window.location.protocol === "https:" ? "wss" : "ws"; + ws = new WebSocket(`${proto}://${window.location.host}/api/logs/ws?run_id=${encodeURIComponent(runId.value)}`); + ws.onmessage = (ev) => { + try { + addLine(JSON.parse(ev.data)); +} catch (e) { + addLine({ ts: 0, stream: "stdout", line: ev.data }); +} + }; + ws.onerror = () => addLine({ ts: 0, stream: "meta", line: "[ws] error" }); + ws.onclose = () => addLine({ ts: 0, stream: "meta", line: "[ws] closed" }); + }); + + onBeforeUnmount(() => { + try { + ws && ws.close(); +} catch(e){} pollTimer && clearInterval(pollTimer); +}); + return { runId, rec, lines, logEl, fmtTime, tsToHms, stop, back }; + }, +}); + +/* ============================================================================ + * 组件:SchedulesView + * ========================================================================== */ +const SchedulesView = defineComponent({ + template: ` +
+
+
+

⏰ 定时任务

+
+ 新建定时任务
+
+
+
⏰
+
还没有任何定时任务
+
像流水线一样让语种工作流按 cron 规则自动运行
+ + 新建 +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + +
+ 💡 0 2 * * * 每日 02:00 · */15 * * * * 每 15 分钟 · 30 9 * * 1-5 工作日 09:30 +
+
+ + + +
+ +
+
+ `, + setup() { + const items = ref([]); + const languages = ref([]); + const dialog = ref(false); + const editing = ref(false); + const saving = ref(false); + const form = reactive({ id: "", language: "", cron: "0 2 * * *", enabled: true, fresh: false, description: "" }); + + const load = async () => { + try { + items.value = await api.listSchedules(); +} catch(e){} + try { + languages.value = await api.listLanguages(); +} catch(e){} + }; + const openNew = () => { + editing.value = false; + Object.assign(form, { id: "", language: "", cron: "0 2 * * *", enabled: true, fresh: false, description: "" }); + dialog.value = true; + }; + const edit = (row) => { + editing.value = true; Object.assign(form, row); dialog.value = true; +}; + const save = async () => { + if (!form.id || !form.language || !form.cron) { + ElMessage.warning("ID / 语种 / Cron 均必填"); return; +} + saving.value = true; + try { + await api.saveSchedule(form.id, { ...form }); ElMessage.success("已保存"); dialog.value = false; await load(); +} catch (e) { + ElMessage.error(`保存失败:${ e.message}`); +} finally { + saving.value = false; +} + }; + const toggle = async (id, enabled) => { + try { + await api.toggleSchedule(id, enabled); await load(); +} catch (e) { + ElMessage.error(e.message); +} +}; + const onDelete = async (id) => { + try { + await ElMessageBox.confirm(`删除定时任务 ${id}?`, "警告", { type: "warning" }); +} catch { + return; +} + try { + await api.deleteSchedule(id); ElMessage.success("已删除"); await load(); +} catch (e) { + ElMessage.error(e.message); +} + }; + onMounted(load); + return { items, languages, dialog, editing, saving, form, openNew, edit, save, toggle, onDelete }; + }, +}); + +/* ============================================================================ + * 顶层 App + * ========================================================================== */ +const App = defineComponent({ + components: { + Dashboard, + SetupWizard, + GlobalConfigView, + LlmView, + LanguagesView, + RunsView, + RunDetailView, + SchedulesView, + }, + template: ` +
+ + +
+
+
+ {{ currentTitle }} + · {{ subtitle }} +
+
+ ⚠️ 尚未初始化 + ✓ 服务正常 +
+
+
+ +
+
+
+ `, + setup() { + const route = computed(() => AppState.route); + const setupReady = computed(() => !!AppState.setup?.initialized); + + const navMain = [ + { key: "dashboard", label: "控制台", icon: "🏠" }, + { key: "languages", label: "语种 Profile", icon: "🌐" }, + { key: "schedules", label: "定时任务", icon: "⏰" }, + { key: "runs", label: "运行历史", icon: "📜" }, + ]; + const navConfig = [ + { key: "setup", label: "初始化向导", icon: "🚀" }, + { key: "global-config", label: "全局配置", icon: "⚙️" }, + { key: "llm", label: "LLM 模型", icon: "🤖" }, + ]; + + const titles = { + dashboard: "控制台", + languages: "语种 Profile", + schedules: "定时任务", + runs: "运行历史", + run: "运行详情", + "global-config": "全局配置", + llm: "LLM 模型注册表", + setup: "初始化向导", + }; + + const subtitles = { + dashboard: "总览与健康检查", + languages: "每个语种一个 YAML 流水线", + schedules: "cron 调度自动触发", + runs: "历史任务与日志", + "global-config": "conf/config.yaml", + llm: "conf/llm.yaml", + setup: "4 步完成初始化", + }; + + const viewMap = { + dashboard: Dashboard, + languages: LanguagesView, + schedules: SchedulesView, + runs: RunsView, + run: RunDetailView, + "global-config": GlobalConfigView, + llm: LlmView, + setup: SetupWizard, + }; + + const currentView = computed(() => { + // 未初始化时,除非在"配置管理"类页面,否则强制跳转向导 + if (!setupReady.value && !["setup", "global-config", "llm"].includes(route.value)) { + return SetupWizard; + } + return viewMap[route.value] || Dashboard; + }); + const currentTitle = computed(() => { + if (!setupReady.value && !["setup", "global-config", "llm"].includes(route.value)) return "初始化向导"; + return titles[route.value] || "控制台"; + }); + const subtitle = computed(() => subtitles[route.value] || ""); + // 侧栏高亮用的"规范化路由":子视图映射到父菜单 + // run (运行详情) → runs (运行历史) + const navAlias = { run: "runs" }; + const activeNavKey = computed(() => { + // 未初始化时,所有非配置管理页都被强制渲染为 SetupWizard(见 currentView), + // 此时侧栏应高亮"初始化向导",而不是实际 hash 路由(通常是 dashboard)。 + if ( + !setupReady.value + && !["setup", "global-config", "llm"].includes(route.value) + ) { + return "setup"; + } + return navAlias[route.value] || route.value; + }); + const go = (k) => navigateTo(k); + + onMounted(async () => { + syncRouteFromHash(); + window.addEventListener("hashchange", syncRouteFromHash); + await refreshMeta(); + await refreshSetup(); + }); + + onBeforeUnmount(() => window.removeEventListener("hashchange", syncRouteFromHash)); + + return { route, setupReady, navMain, navConfig, currentView, currentTitle, subtitle, go, activeNavKey }; + }, +}); + +/* ========== 启动 ========== */ +const vueApp = createApp(App); +vueApp.use(ElementPlus); +if (window.ElementPlusIconsVue) { + for (const [name, comp] of Object.entries(window.ElementPlusIconsVue)) { + vueApp.component(name, comp); + } +} +vueApp.mount("#app"); diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd01aaa2eb92ad4d7a9e8be3b20dd583e6d79237 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__init__.py @@ -0,0 +1,43 @@ +"""TiMi_HOK_Game_Translator.sources 子包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.sources import ( + Entry, LocalizationSource, + JsonSource, YamlSource, XmlSource, CsvSource, DtxmlSource, XliffSource, + XlsxSource, + create_source, register_source, registered_formats, + ) +""" + +from .base import ( + Entry, + LocalizationSource, + get_source_class, + register_source, + registered_formats, +) +from .csv_source import CsvSource +from .dtxml_source import DtxmlSource +from .factory import create_source +from .json_source import JsonSource +from .xliff_source import XliffSource +from .xlsx_source import XlsxSource +from .xml_source import XmlSource +from .yaml_source import YamlSource + +__all__ = [ + "CsvSource", + "DtxmlSource", + "Entry", + "JsonSource", + "LocalizationSource", + "XliffSource", + "XlsxSource", + "XmlSource", + "YamlSource", + "create_source", + "get_source_class", + "register_source", + "registered_formats", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31067f76dbcc66d586e9a10e05aa1b6f28544391 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81c67ec27a3081e0dd3ec4b4275998f54fdfeb10 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/csv_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/csv_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9296474e6f659f008083d629038bf51242b19566 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/csv_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/dtxml_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/dtxml_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..356244e3d984e38d57065aafa031ab0f4ddf2fba Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/dtxml_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..619d0efcbf7c90cff803a7422ef56265758b6c1f Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/json_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/json_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8db294d7f7554ad62595821a9fe15ced58bdbb63 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/json_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xliff_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xliff_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e8be0c95d961c0cffb82e335f7ad1e492f36f1b Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xliff_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xlsx_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xlsx_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a340f1a949cc9ed402fa8f68ca9cce442cc5df20 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xlsx_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xml_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xml_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5662b5eac27df7dc8928ae6a8802c63223a6162 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/xml_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/yaml_source.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/yaml_source.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ff28a99c886beda954f506f4cfab81d2175ae7 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/__pycache__/yaml_source.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/base.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe82966838ffdf9d83cd99988ceedc0a8808c60 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/base.py @@ -0,0 +1,190 @@ +"""本地化源文件抽象。 + +每种支持的文件格式都继承 :class:`LocalizationSource` 并通过 +:func:`register_source` 装饰器注册。不要直接实例化子类,使用 +:func:`TiMi_HOK_Game_Translator.sources.create_source` 代替。 + +内存中的标准表示为 :class:`Entry` 列表;各后端需确保 +:attr:`Entry.metadata` 中的额外信息可在 ``load → dump`` 循环中完整往返。 +""" + +from __future__ import annotations + +import abc +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Type + +from ..commons import SourceError, UnknownSourceFormatError + + +# --------------------------------------------------------------------------- +# 数据模型 +# --------------------------------------------------------------------------- +@dataclass +class Entry: + """单个本地化条目。 + + 字段: + key: 稳定的条目标识(惯例上以小数点分隔)。 + source_text: 源语言文本。 + target_text: 目标语言译文;尚未翻译时为空串。 + context: 自由形式的上下文(展示给翻译者/LLM)。 + comment: 人工备注(术语、占位符说明等)。 + en_terms: 中→英术语对列表(``[(zh, en), ...]``)。两步翻译的 + Step 1(中→英)会把本字段作为术语参考注入提示词;一步策略 + 直译时忽略本字段。单元格内一般形如 + ``艾薇塔=Evita\\n护盾=shield``,由 :class:`XlsxSource` 解析。 + terms: 中→目标语术语对列表(``[(zh, target), ...]``)。 + * 一步策略(中→目标)直接作为术语参考注入; + * 两步策略 Step 2(英→目标)会与 :attr:`en_terms` 做映射, + 拼成"英→目标"术语对注入,详见 + :class:`~TiMi_HOK_Game_Translator.strategies.minor_language_strategy.TwoStepTranslationStrategy`。 + metadata: 后端自定义字段(如 XLIFF 的 ``state`` 属性、 + DTXML 的 struct 名、CSV 行号),会在 ``load → dump`` 循环中保留。 + """ + + key: str + source_text: str = "" + target_text: str = "" + context: str = "" + comment: str = "" + en_terms: List[Any] = field(default_factory=list) + terms: List[Any] = field(default_factory=list) + metadata: Dict[str, Any] = field(default_factory=dict) + + +# --------------------------------------------------------------------------- +# 抽象基类 +# --------------------------------------------------------------------------- +class LocalizationSource(abc.ABC): + """某一种文件格式的读/写接口。""" + + #: 本后端在注册表中的名称。 + format_name: str = "" + + #: 首选文件后缀(供工具与错误提示使用)。 + file_extensions: Sequence[str] = () + + def __init__(self, *, encoding: str = "utf-8", extra: Optional[Dict[str, Any]] = None) -> None: + self.encoding = encoding + self.extra: Dict[str, Any] = dict(extra or {}) + + # ------------------------------------------------------------------ + # 抽象 API + # ------------------------------------------------------------------ + @abc.abstractmethod + def load(self, path: str) -> List[Entry]: + """解析 ``path`` 文件并返回条目列表。""" + + @abc.abstractmethod + def dump(self, entries: Sequence[Entry], path: str) -> None: + """将 ``entries`` 序列化到 ``path``,会覆盖已有文件。""" + + # ------------------------------------------------------------------ + # 默认的合并实现 + # ------------------------------------------------------------------ + def merge(self, base: Sequence[Entry], patch: Sequence[Entry]) -> List[Entry]: + """合并 ``base`` 与 ``patch``。 + + 语义: + + * ``patch`` 中的条目**覆盖** ``base`` 中同 key 的条目(按 :attr:`Entry.key` 匹配); + * 仅在 ``patch`` 中存在的条目**按原顺序追加**; + * :attr:`Entry.metadata` 采用浅层合并(冲突时 patch 胜出)。 + + 后端如需更精细的合并逻辑(如 Crowdin 的批准标志)可覆盖本方法。 + """ + by_key: Dict[str, Entry] = {entry.key: entry for entry in base} + for patch_entry in patch: + if patch_entry.key in by_key: + original = by_key[patch_entry.key] + merged_metadata = {**original.metadata, **patch_entry.metadata} + by_key[patch_entry.key] = Entry( + key=patch_entry.key, + source_text=patch_entry.source_text or original.source_text, + target_text=patch_entry.target_text or original.target_text, + context=patch_entry.context or original.context, + comment=patch_entry.comment or original.comment, + en_terms=list(patch_entry.en_terms) if patch_entry.en_terms else list(original.en_terms), + terms=list(patch_entry.terms) if patch_entry.terms else list(original.terms), + metadata=merged_metadata, + ) + else: + by_key[patch_entry.key] = patch_entry + return list(by_key.values()) + + # ------------------------------------------------------------------ + # 工具方法 + # ------------------------------------------------------------------ + @staticmethod + def _read_text(path: str, encoding: str) -> str: + p = Path(path) + if not p.exists(): + raise SourceError(f"Source file not found: {path}") + try: + return p.read_text(encoding=encoding) + except OSError as exc: + raise SourceError(f"Failed to read {path}: {exc}") from exc + + @staticmethod + def _write_text(path: str, content: str, encoding: str) -> None: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + try: + p.write_text(content, encoding=encoding) + except OSError as exc: + raise SourceError(f"Failed to write {path}: {exc}") from exc + + +# --------------------------------------------------------------------------- +# 注册表 +# --------------------------------------------------------------------------- +_REGISTRY: Dict[str, Type[LocalizationSource]] = {} + + +def register_source(name: str) -> Callable[[Type[LocalizationSource]], Type[LocalizationSource]]: + """类装饰器:将一个 :class:`LocalizationSource` 实现注册为 ``name`` 格式。 + + 示例:: + + @register_source("json") + class JsonSource(LocalizationSource): + ... + """ + + def decorator(cls: Type[LocalizationSource]) -> Type[LocalizationSource]: + key = name.lower() + cls.format_name = key + _REGISTRY[key] = cls + return cls + + return decorator + + +def get_source_class(name: str) -> Type[LocalizationSource]: + """查找 ``name`` 对应的注册类。 + + 异常: + UnknownSourceFormatError: ``name`` 未注册时抛出。 + """ + key = (name or "").lower() + if key not in _REGISTRY: + raise UnknownSourceFormatError( + f"Unknown source format '{name}'. Registered: {sorted(_REGISTRY)}" + ) + return _REGISTRY[key] + + +def registered_formats() -> List[str]: + """返回当前已注册的格式名称列表(排序后)。""" + return sorted(_REGISTRY) + + +__all__ = [ + "Entry", + "LocalizationSource", + "get_source_class", + "register_source", + "registered_formats", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/csv_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/csv_source.py new file mode 100644 index 0000000000000000000000000000000000000000..1a6aacb0e38a0a0ef4ac0a15e064c34c942e9d59 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/csv_source.py @@ -0,0 +1,92 @@ +"""CSV 本地化源。 + +期望的列结构(必须含表头行): + + key, source_text[, target_text, context, comment] + +额外列会按列名保存到 :attr:`Entry.metadata` 中。 +``dump`` 时先写固定列,再按确定顺序写入所有 entries 中出现过的 metadata 列。 +""" + +from __future__ import annotations + +import csv +import io +from typing import Any, Dict, List, Sequence, Set + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source + +_FIXED_COLUMNS = ("key", "source_text", "target_text", "context", "comment") + + +@register_source("csv") +class CsvSource(LocalizationSource): + """:class:`LocalizationSource` 的 CSV 实现。""" + + file_extensions = (".csv",) + + def load(self, path: str) -> List[Entry]: + text = self._read_text(path, self.encoding) + if not text.strip(): + return [] + try: + reader = csv.DictReader(io.StringIO(text)) + except csv.Error as exc: + raise SourceError(f"Malformed CSV at {path}: {exc}") from exc + + if reader.fieldnames is None or "key" not in reader.fieldnames: + raise SourceError( + f"CSV at {path} must have a header row that includes a 'key' column." + ) + + entries: List[Entry] = [] + for row_no, row in enumerate(reader, start=2): + key = (row.get("key") or "").strip() + if not key: + continue + metadata: Dict[str, Any] = {} + for col, val in row.items(): + if col in _FIXED_COLUMNS or col is None: + continue + if val is not None and val != "": + metadata[col] = val + metadata.setdefault("csv_row", row_no) + entries.append( + Entry( + key=key, + source_text=row.get("source_text") or "", + target_text=row.get("target_text") or "", + context=row.get("context") or "", + comment=row.get("comment") or "", + metadata=metadata, + ) + ) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + extra_columns: Set[str] = set() + for entry in entries: + for meta_key in entry.metadata: + if meta_key != "csv_row": + extra_columns.add(str(meta_key)) + + fieldnames = list(_FIXED_COLUMNS) + sorted(extra_columns) + buffer = io.StringIO() + writer = csv.DictWriter(buffer, fieldnames=fieldnames) + writer.writeheader() + for entry in entries: + row: Dict[str, Any] = { + "key": entry.key, + "source_text": entry.source_text, + "target_text": entry.target_text, + "context": entry.context, + "comment": entry.comment, + } + for extra_col in extra_columns: + row[extra_col] = entry.metadata.get(extra_col, "") + writer.writerow(row) + self._write_text(path, buffer.getvalue(), self.encoding) + + +__all__ = ["CsvSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/dtxml_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/dtxml_source.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f6a6c4974f163bf05d9407951b70c816346664 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/dtxml_source.py @@ -0,0 +1,123 @@ +"""DTXML 本地化源。 + +DTXML 是本项目旧流水线使用的表格 XML 方言。开源框架只支持一个能跑通 +解析测试与 demo 的**最小子集**: + +* 一个根元素 ````(或自定义名称); +* 一个或多个 ```` 容器; +* 任意多个 ````,可选子元素为 + ```` / ```` / ```` / ````。 + +如需支持完整的生产方言,可继承本类并重写读写器,再通过 +:func:`register_source` 重新注册。 +""" + +from __future__ import annotations + +from typing import Dict, List, Sequence +from xml.etree import ElementTree as ET + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source +from .xml_source import _indent + + +@register_source("dtxml") +class DtxmlSource(LocalizationSource): + """:class:`LocalizationSource` 的 DTXML 实现。""" + + file_extensions = (".dtxml",) + + def load(self, path: str) -> List[Entry]: + text = self._read_text(path, self.encoding) + if not text.strip(): + return [] + try: + root = ET.fromstring(text) + except ET.ParseError as exc: + raise SourceError(f"Malformed DTXML at {path}: {exc}") from exc + + self.extra.setdefault("root_tag", _local(root.tag)) + self.extra.setdefault("root_attrib", dict(root.attrib)) + + entries: List[Entry] = [] + for struct in _iter_structs(root): + struct_name = struct.get("name", "") + struct_version = struct.get("version", "") + for entry_elem in struct: + if _local(entry_elem.tag) != "entry": + continue + key = (entry_elem.get("key") or "").strip() + if not key: + continue + entries.append( + Entry( + key=key, + source_text=_child_text(entry_elem, "source"), + target_text=_child_text(entry_elem, "target"), + context=_child_text(entry_elem, "context"), + comment=_child_text(entry_elem, "comment"), + metadata={ + "struct_name": struct_name, + "struct_version": struct_version, + }, + ) + ) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + root_tag = self.extra.get("root_tag", "metalib") + root_attrib: Dict[str, str] = { + str(k): str(v) for k, v in self.extra.get("root_attrib", {}).items() + } + root = ET.Element(root_tag, root_attrib) + + # 按 struct 分组汇总条目。 + groups: Dict[str, List[Entry]] = {} + struct_versions: Dict[str, str] = {} + for entry in entries: + struct_name = str(entry.metadata.get("struct_name") or "LocalizationEntry") + struct_version = str(entry.metadata.get("struct_version") or "1") + groups.setdefault(struct_name, []).append(entry) + struct_versions[struct_name] = struct_version + + for struct_name, struct_entries in groups.items(): + struct_elem = ET.SubElement( + root, "struct", {"name": struct_name, "version": struct_versions[struct_name]} + ) + for entry in struct_entries: + entry_elem = ET.SubElement(struct_elem, "entry", {"key": entry.key}) + for tag, value in ( + ("source", entry.source_text), + ("target", entry.target_text), + ("context", entry.context), + ("comment", entry.comment), + ): + if value: + child = ET.SubElement(entry_elem, tag) + child.text = value + + _indent(root) + xml_bytes = ET.tostring(root, encoding=self.encoding, xml_declaration=True) + self._write_text(path, xml_bytes.decode(self.encoding), self.encoding) + + +def _local(tag: str) -> str: + """去掉 XML 命名空间前缀(``{ns}tag`` → ``tag``)。""" + return tag.rsplit("}", 1)[-1] + + +def _iter_structs(root: ET.Element): + for child in root: + if _local(child.tag) == "struct": + yield child + + +def _child_text(elem: ET.Element, tag: str) -> str: + for child in elem: + if _local(child.tag) == tag: + return child.text or "" + return "" + + +__all__ = ["DtxmlSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..f95bd612ed0b077f90eec0833a8196609a35a9ce --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/factory.py @@ -0,0 +1,34 @@ +"""由 :class:`SourceConfig` 创建 :class:`LocalizationSource` 的工厂。 + +导入本模块的副作用:依次导入每个内置 source 实现,以触发它们上面的 +:func:`register_source` 装饰器。 +""" + +from __future__ import annotations + +from typing import Any, Dict + +from ..config.schema import SourceConfig + +# 导入内置格式以触发注册。用户自定义格式可在调用 +# ``create_source`` 前先导入对应模块或手动调用 ``register_source``。 +from . import ( # pylint: disable=unused-import + csv_source, # noqa: F401 + dtxml_source, # noqa: F401 + json_source, # noqa: F401 + xliff_source, # noqa: F401 + xlsx_source, # noqa: F401 + xml_source, # noqa: F401 + yaml_source, # noqa: F401 +) +from .base import LocalizationSource, get_source_class, registered_formats + + +def create_source(source_config: SourceConfig) -> LocalizationSource: + """根据 ``source_config`` 返回 :class:`LocalizationSource` 实例。""" + cls = get_source_class(source_config.format) + extra: Dict[str, Any] = dict(source_config.extra or {}) + return cls(encoding=source_config.encoding or "utf-8", extra=extra) + + +__all__ = ["create_source", "registered_formats"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/json_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/json_source.py new file mode 100644 index 0000000000000000000000000000000000000000..f3afd6da11e56eebc9d751849bb2224e609efd19 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/json_source.py @@ -0,0 +1,93 @@ +"""JSON 本地化源。 + +读写 ``docs/examples/data/example_game.en.json`` 中的标准结构: + +.. code-block:: json + + { + "meta": {...}, + "entries": [ + {"key": "...", "source_text": "...", "context": "...", "comment": "..."} + ] + } + +为了入站宽容,加载器也接受简单的 ``{"key": "text"}`` 映射。 +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List, Sequence + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source + + +@register_source("json") +class JsonSource(LocalizationSource): + """:class:`LocalizationSource` 的 JSON 实现。""" + + file_extensions = (".json",) + + def load(self, path: str) -> List[Entry]: + raw = self._read_text(path, self.encoding) + try: + data = json.loads(raw) if raw.strip() else {} + except json.JSONDecodeError as exc: + raise SourceError(f"Malformed JSON at {path}: {exc}") from exc + return _parse(data) + + def dump(self, entries: Sequence[Entry], path: str) -> None: + payload: Dict[str, Any] = { + "meta": self.extra.get("meta", {}), + "entries": [_entry_to_dict(e) for e in entries], + } + self._write_text( + path, json.dumps(payload, indent=2, ensure_ascii=False) + "\n", self.encoding + ) + + +def _parse(data: Any) -> List[Entry]: + if isinstance(data, dict) and "entries" in data: + return [_dict_to_entry(item) for item in data["entries"]] + # 回退:单层 key -> 字符串的映射。 + if isinstance(data, dict): + return [Entry(key=str(k), source_text=str(v)) for k, v in data.items()] + if isinstance(data, list): + return [_dict_to_entry(item) for item in data] + raise SourceError( + f"Unsupported JSON top-level structure: {type(data).__name__}. " + "Expected an object with an 'entries' array or a bare key→string mapping." + ) + + +def _dict_to_entry(item: Any) -> Entry: + if not isinstance(item, dict): + raise SourceError(f"Each JSON entry must be an object, got {type(item).__name__}.") + return Entry( + key=str(item.get("key", "")), + source_text=str(item.get("source_text", "")), + target_text=str(item.get("target_text", "")), + context=str(item.get("context", "")), + comment=str(item.get("comment", "")), + metadata=dict(item.get("metadata", {})), + ) + + +def _entry_to_dict(entry: Entry) -> Dict[str, Any]: + result: Dict[str, Any] = { + "key": entry.key, + "source_text": entry.source_text, + } + if entry.target_text: + result["target_text"] = entry.target_text + if entry.context: + result["context"] = entry.context + if entry.comment: + result["comment"] = entry.comment + if entry.metadata: + result["metadata"] = entry.metadata + return result + + +__all__ = ["JsonSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xliff_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xliff_source.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3d4ea7c235f4f40589b0c287e003e095db9f9a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xliff_source.py @@ -0,0 +1,159 @@ +"""XLIFF 1.2 本地化源(最小子集)。 + +支持读写如下结构:: + + + + + + Play + 播放 + 可选备注/上下文 + + ... + + + + +解析时为了简化会丢弃命名空间;``dump`` 时会重新附带 XLIFF 1.2 默认命名空间。 +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Sequence +from xml.etree import ElementTree as ET + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source +from .xml_source import _indent + +_XLIFF_NS = "urn:oasis:names:tc:xliff:document:1.2" + + +@register_source("xliff") +class XliffSource(LocalizationSource): + """:class:`LocalizationSource` 的 XLIFF 1.2 实现。""" + + file_extensions = (".xliff", ".xlf") + + def load(self, path: str) -> List[Entry]: + text = self._read_text(path, self.encoding) + if not text.strip(): + return [] + try: + root = ET.fromstring(text) + except ET.ParseError as exc: + raise SourceError(f"Malformed XLIFF at {path}: {exc}") from exc + + entries: List[Entry] = [] + for file_elem in _iter_local(root, "file"): + self.extra.setdefault("source_language", file_elem.get("source-language", "")) + self.extra.setdefault("target_language", file_elem.get("target-language", "")) + self.extra.setdefault("datatype", file_elem.get("datatype", "plaintext")) + + for unit in _iter_all_local(file_elem, "trans-unit"): + # XLIFF 1.2 语义: + # * ``resname`` 是业务层的"资源 key"(如 + # ``Guild_Construct_Building_Info_Text``),这才是上游 + # 翻译/合表要用的那个 key; + # * ``id`` 只保证"文件内 trans-unit 的唯一数字标识"(Crowdin + # 在导出 xliff 时填的是其内部的字符串 ID 如 ``11330230``, + # 与业务无关)。 + # 顺序必须是 resname → id → "" 。如果反过来(id → resname), + # 下游 ``split_approved_data`` 产出的 ``approved_keys`` 会 + # 变成一堆 Crowdin 数字 ID,与内存 ``ctx.entries[*].key`` + # (业务 key)永远匹配不上,把 20 → 0 擦掉审核结果。 + # (2026-10-09 实测事故现场) + key = (unit.get("resname") or unit.get("id") or "").strip() + if not key: + continue + source_elem = _find_local(unit, "source") + target_elem = _find_local(unit, "target") + note_elem = _find_local(unit, "note") + metadata: Dict[str, Any] = {} + if target_elem is not None and target_elem.get("state"): + metadata["state"] = target_elem.get("state", "") + if unit.get("approved"): + metadata["approved"] = unit.get("approved", "") + entries.append( + Entry( + key=key, + source_text=_text(source_elem), + target_text=_text(target_elem), + context=_text(_find_local(unit, "context-group")) if False else "", + comment=_text(note_elem), + metadata=metadata, + ) + ) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + source_lang = str(self.extra.get("source_language", "en")) + target_lang = str(self.extra.get("target_language", "")) + datatype = str(self.extra.get("datatype", "plaintext")) + + ET.register_namespace("", _XLIFF_NS) + root = ET.Element(f"{{{_XLIFF_NS}}}xliff", {"version": "1.2"}) + file_attrib = {"source-language": source_lang, "datatype": datatype} + if target_lang: + file_attrib["target-language"] = target_lang + file_elem = ET.SubElement(root, f"{{{_XLIFF_NS}}}file", file_attrib) + body = ET.SubElement(file_elem, f"{{{_XLIFF_NS}}}body") + + for entry in entries: + # 对称于 ``load``——业务 key 写进 ``resname``;``id`` 仍填相同 + # 值,仅作文件内唯一数字标识兜底(跨平台往返更稳)。 + unit_attrib: Dict[str, str] = { + "id": entry.key, + "resname": entry.key, + } + if "approved" in entry.metadata: + unit_attrib["approved"] = str(entry.metadata["approved"]) + unit = ET.SubElement(body, f"{{{_XLIFF_NS}}}trans-unit", unit_attrib) + src = ET.SubElement(unit, f"{{{_XLIFF_NS}}}source") + src.text = entry.source_text + if entry.target_text or "state" in entry.metadata: + tgt_attrib: Dict[str, str] = {} + if "state" in entry.metadata: + tgt_attrib["state"] = str(entry.metadata["state"]) + tgt = ET.SubElement(unit, f"{{{_XLIFF_NS}}}target", tgt_attrib) + tgt.text = entry.target_text + if entry.comment: + note = ET.SubElement(unit, f"{{{_XLIFF_NS}}}note") + note.text = entry.comment + + _indent(root) + xml_bytes = ET.tostring(root, encoding=self.encoding, xml_declaration=True) + self._write_text(path, xml_bytes.decode(self.encoding), self.encoding) + + +def _iter_local(root: ET.Element, tag: str): + for child in root: + if _localname(child.tag) == tag: + yield child + + +def _iter_all_local(root: ET.Element, tag: str): + for elem in root.iter(): + if _localname(elem.tag) == tag: + yield elem + + +def _find_local(parent: ET.Element, tag: str): + for child in parent: + if _localname(child.tag) == tag: + return child + return None + + +def _text(elem): + if elem is None or elem.text is None: + return "" + return elem.text + + +def _localname(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +__all__ = ["XliffSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xlsx_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xlsx_source.py new file mode 100644 index 0000000000000000000000000000000000000000..856739fa7627acf382b51fefbe23e713b00b8e93 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xlsx_source.py @@ -0,0 +1,256 @@ +"""Excel (xlsx) 本地化源。 + +用途: + 把 :class:`~TiMi_HOK_Game_Translator.sources.base.Entry` 列表序列化为 Crowdin / Phrase + 等审校平台能直接识别的表格文件。审校平台解析 xlsx 的能力远优于 dtxml、 + xml、csv,因此在 ``first_review`` / ``second_review`` 阶段应优先走 xlsx。 + +列结构(固定、通用):: + + | Key | Source | Target | Context | Comment | EnTerms | Terms | EnglishSide | + |-----|--------|--------|---------|---------|---------|-------|-------------| + + * ``EnTerms`` 列:中→英术语对(常驻),单元格内每行一个 ``源文=英译``, + 多条用换行分隔。两步翻译 Step 1(中→英)会把本列作为术语参考注入。 + * ``Terms`` 列:中→目标语术语对,格式与 ``EnTerms`` 一致。一步策略直接 + 注入;两步策略 Step 2 会与 ``EnTerms`` 做映射再注入。 + * ``EnglishSide`` 列:两步翻译 Step 1 的英文中间结果(只读不写入模型), + 仅做"排查痕迹"用。审校平台(Phrase/Crowdin)按前 5 列定位,**不读本列**, + 因此留存在 xlsx 里不会污染上传/审校流程。源表留空即可,由框架自动写回。 + * 旧 5 列文件(无 EnTerms/Terms/EnglishSide)仍可正常 load,缺失列视为空字符串。 + +设计约束: + * 可选依赖——仅在实际使用时才 import ``openpyxl``; + * 列头大小写宽容——load 时 ``KEY`` / ``source`` / ``Target`` / ``en_terms`` + / ``enterms`` / ``ENTERMS`` 都认; + * 空行自动跳过;``Key`` 为空的行视为无效,丢弃; + * ``metadata`` 以 ``row_number`` 字段携带原始行号,便于后续回写定位。 +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source + +logger = logging.getLogger(__name__) + +#: xlsx 使用的固定表头,顺序即列顺序。 +_HEADERS = ("Key", "Source", "Target", "Context", "Comment", "EnTerms", "Terms", "EnglishSide") + +#: 工作表默认名称。 +_DEFAULT_SHEET_NAME = "Translation" + +#: 术语单元格内:条目分隔符(换行)与源译分隔符(等号)。 +_TERM_ROW_SEP = "\n" +_TERM_PAIR_SEP = "=" + + +def _normalize_header(name: str) -> str: + """把列头规范化为小写 + 去下划线,便于容错识别。 + + 例如:``EnTerms`` / ``en_terms`` / ``EN_TERMS`` / ``enterms`` + 都会归一到 ``enterms``。 + """ + return (name or "").strip().lower().replace("_", "") + + +#: 列头规范化名 → 内部字段名。 +_HEADER_ALIASES: Dict[str, str] = { + "key": "key", + "source": "source", + "target": "target", + "context": "context", + "comment": "comment", + "enterms": "en_terms", + "terms": "terms", + # EnglishSide / english_side / englishpivot 都识别为同一个字段, + # 便于手工填/旧文件兼容。 + "englishside": "english_side", + "englishpivot": "english_side", +} + + +def _parse_terms(raw: str) -> List[Tuple[str, str]]: + """解析术语单元格字符串为 ``[(源文, 译文), ...]``。 + + 格式约定: + ``源文1=译文1\\n源文2=译文2\\n...`` + + 容错: + * 空字符串/None 返回空列表; + * 空行跳过; + * 缺少 ``=`` 的行记一行 debug 日志后跳过; + * ``=`` 两边自动 strip。 + """ + if not raw: + return [] + pairs: List[Tuple[str, str]] = [] + for line in str(raw).split(_TERM_ROW_SEP): + line = line.strip() + if not line: + continue + if _TERM_PAIR_SEP not in line: + logger.debug( + "XlsxSource: term row missing '%s' separator, skipped: %r", + _TERM_PAIR_SEP, line, + ) + continue + src, dst = line.split(_TERM_PAIR_SEP, 1) + src = src.strip() + dst = dst.strip() + if not src or not dst: + continue + pairs.append((src, dst)) + return pairs + + +def _dump_terms(terms: Sequence[Tuple[str, str]]) -> str: + """把 ``[(源文, 译文), ...]`` 还原为单元格字符串。空列表返回空串。""" + if not terms: + return "" + return _TERM_ROW_SEP.join(f"{src}{_TERM_PAIR_SEP}{dst}" for src, dst in terms) + + +@register_source("xlsx") +class XlsxSource(LocalizationSource): + """:class:`LocalizationSource` 的 xlsx 实现。""" + + file_extensions = (".xlsx",) + + def load(self, path: str) -> List[Entry]: + openpyxl = _require_openpyxl() + try: + wb = openpyxl.load_workbook(path, read_only=True, data_only=True) + except Exception as exc: # noqa: BLE001 — openpyxl 自己的异常类型众多 + raise SourceError(f"Failed to open xlsx {path}: {exc}") from exc + + # 优先取名为 Translation 的 sheet,没有则用第一个 sheet。 + sheet = wb[_DEFAULT_SHEET_NAME] if _DEFAULT_SHEET_NAME in wb.sheetnames else wb.active + rows_iter = sheet.iter_rows(values_only=True) + header_row = next(rows_iter, None) + if header_row is None: + wb.close() + return [] + + # 建立「标准化表头名 → 列索引」的映射,列顺序允许和 _HEADERS 不一致, + # 并且允许 EnTerms/en_terms/ENTERMS 等多种拼写。 + col_index: Dict[str, int] = {} + for idx, cell in enumerate(header_row): + if cell is None: + continue + norm = _normalize_header(str(cell)) + field_name = _HEADER_ALIASES.get(norm) + if field_name: + col_index[field_name] = idx + if "key" not in col_index: + wb.close() + raise SourceError( + f"xlsx {path}: header missing required column 'Key'. " + f"Got headers: {list(header_row)}" + ) + + entries: List[Entry] = [] + for row_number, row in enumerate(rows_iter, start=2): # 第 1 行是表头 + key_val = _cell_text(row, col_index.get("key")) + if not key_val: + continue + metadata: Dict[str, Any] = {"row_number": row_number} + # EnglishSide 列:两步翻译 Step 1 的英文中间结果;非空则塞进 + # metadata["english_side"],与 executor 层的写入点保持同一 key。 + english_side = _cell_text(row, col_index.get("english_side")) + if english_side: + metadata["english_side"] = english_side + entries.append( + Entry( + key=key_val, + source_text=_cell_text(row, col_index.get("source")), + target_text=_cell_text(row, col_index.get("target")), + context=_cell_text(row, col_index.get("context")), + comment=_cell_text(row, col_index.get("comment")), + en_terms=_parse_terms(_cell_text(row, col_index.get("en_terms"))), + terms=_parse_terms(_cell_text(row, col_index.get("terms"))), + metadata=metadata, + ) + ) + wb.close() + + # 把列头原顺序记录下来,供 dump 继承(可选能力,不是必须)。 + self.extra.setdefault("headers", list(_HEADERS)) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + openpyxl = _require_openpyxl() + wb = openpyxl.Workbook() + sheet = wb.active + sheet.title = _DEFAULT_SHEET_NAME + + sheet.append(list(_HEADERS)) + for entry in entries: + metadata = getattr(entry, "metadata", None) or {} + english_side = metadata.get("english_side", "") or "" + sheet.append( + [ + entry.key, + entry.source_text, + entry.target_text, + entry.context, + entry.comment, + _dump_terms(getattr(entry, "en_terms", []) or []), + _dump_terms(getattr(entry, "terms", []) or []), + english_side, + ] + ) + + # 简单的列宽设置,便于人工在 Crowdin UI 外预览时阅读。 + for col_idx, width in enumerate((40, 60, 60, 40, 40, 40, 40, 50), start=1): + sheet.column_dimensions[_col_letter(col_idx)].width = width + + try: + # 确保目录存在 + from pathlib import Path as _P + + _P(path).parent.mkdir(parents=True, exist_ok=True) + wb.save(path) + except OSError as exc: + raise SourceError(f"Failed to write xlsx {path}: {exc}") from exc + + +# --------------------------------------------------------------------------- +# 辅助函数 +# --------------------------------------------------------------------------- +def _require_openpyxl(): + """惰性导入 openpyxl;未安装时给出可操作的错误提示。""" + try: + import openpyxl # noqa: WPS433 — 局部导入 + except ImportError as exc: # pragma: no cover + raise SourceError( + "XlsxSource requires the optional 'openpyxl' package. " + "Install with `pip install openpyxl` or " + "`pip install TiMi_HOK_Game_Translator[excel]`." + ) from exc + return openpyxl + + +def _cell_text(row: Optional[Sequence[Any]], idx: Optional[int]) -> str: + """安全读单元格文本,所有 None/数值都转成字符串。""" + if row is None or idx is None or idx >= len(row): + return "" + value = row[idx] + if value is None: + return "" + return str(value) + + +def _col_letter(col_idx: int) -> str: + """1 → 'A',2 → 'B' ... 26 → 'Z',27 → 'AA' 的朴素实现。""" + result = "" + while col_idx > 0: + col_idx, remainder = divmod(col_idx - 1, 26) + result = chr(65 + remainder) + result + return result + + +__all__ = ["XlsxSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xml_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xml_source.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5fdb6ac3dd98ac68d21f6223e8a6cc8d3792a8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/xml_source.py @@ -0,0 +1,119 @@ +"""XML 本地化源。 + +采用如下标签布局:: + + + + ... + ... + + ... + + +根属性会保存到 :attr:`LocalizationSource.extra`,以便 ``dump`` 时回写。 +""" + +from __future__ import annotations + +from typing import Dict, List, Sequence +from xml.etree import ElementTree as ET + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source + + +@register_source("xml") +class XmlSource(LocalizationSource): + """:class:`LocalizationSource` 的 XML 实现。""" + + file_extensions = (".xml",) + + def load(self, path: str) -> List[Entry]: + text = self._read_text(path, self.encoding) + if not text.strip(): + return [] + try: + root = ET.fromstring(text) + except ET.ParseError as exc: + raise SourceError(f"Malformed XML at {path}: {exc}") from exc + + # 保留根元素属性,便于 round-trip。 + self.extra.setdefault("root_tag", root.tag) + self.extra.setdefault("root_attrib", dict(root.attrib)) + + entries: List[Entry] = [] + for elem in root.findall("entry"): + key = (elem.get("key") or "").strip() + if not key: + continue + source_text = _child_text(elem, "source") + target_text = _child_text(elem, "target") + entries.append( + Entry( + key=key, + source_text=source_text, + target_text=target_text, + context=elem.get("context", ""), + comment=elem.get("comment", ""), + metadata={ + f"attr:{name}": value + for name, value in elem.attrib.items() + if name not in {"key", "context", "comment"} + }, + ) + ) + return entries + + def dump(self, entries: Sequence[Entry], path: str) -> None: + root_tag = self.extra.get("root_tag", "localization") + root_attrib: Dict[str, str] = { + str(k): str(v) for k, v in self.extra.get("root_attrib", {}).items() + } + root = ET.Element(root_tag, root_attrib) + for entry in entries: + attrs: Dict[str, str] = {"key": entry.key} + if entry.context: + attrs["context"] = entry.context + if entry.comment: + attrs["comment"] = entry.comment + for meta_key, meta_val in entry.metadata.items(): + if isinstance(meta_key, str) and meta_key.startswith("attr:"): + attrs[meta_key[5:]] = str(meta_val) + elem = ET.SubElement(root, "entry", attrs) + source_elem = ET.SubElement(elem, "source") + source_elem.text = entry.source_text + if entry.target_text: + target_elem = ET.SubElement(elem, "target") + target_elem.text = entry.target_text + _indent(root) + xml_bytes = ET.tostring(root, encoding=self.encoding, xml_declaration=True) + # 因为请求了声明,``tostring`` 返回 bytes;解码后交给公共的 + # ``_write_text`` 写入。 + self._write_text(path, xml_bytes.decode(self.encoding), self.encoding) + + +def _child_text(elem: ET.Element, tag: str) -> str: + child = elem.find(tag) + if child is None or child.text is None: + return "" + return child.text + + +def _indent(elem: ET.Element, level: int = 0) -> None: + """就地美化缩进(避免使用仅 Python 3.9+ 可用的 ``ET.indent``)。""" + indent = "\n" + level * " " + if len(elem): # pylint: disable=len-as-condition + if not elem.text or not elem.text.strip(): + elem.text = indent + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = indent + for child in elem: + _indent(child, level + 1) + if not child.tail or not child.tail.strip(): # noqa: F821 — 循环变量仍在作用域 + child.tail = indent + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = indent + + +__all__ = ["XmlSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/yaml_source.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/yaml_source.py new file mode 100644 index 0000000000000000000000000000000000000000..f26930db04d80f338e4f92acbcdf7fa003e9afa9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/sources/yaml_source.py @@ -0,0 +1,56 @@ +"""YAML 本地化源。 + +复用 JSON 的结构,使一份条目文件可在两种格式之间无损互转。 +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Sequence + +from ..commons import SourceError +from .base import Entry, LocalizationSource, register_source +from .json_source import _entry_to_dict, _parse + + +@register_source("yaml") +class YamlSource(LocalizationSource): + """:class:`LocalizationSource` 的 YAML 实现。""" + + file_extensions = (".yaml", ".yml") + + def load(self, path: str) -> List[Entry]: + try: + import yaml + except ImportError as exc: # pragma: no cover + raise SourceError( + "PyYAML is required for YAML sources. Install with 'pip install PyYAML'." + ) from exc + + raw = self._read_text(path, self.encoding) + if not raw.strip(): + return [] + try: + data = yaml.safe_load(raw) + except yaml.YAMLError as exc: + raise SourceError(f"Malformed YAML at {path}: {exc}") from exc + return _parse(data if data is not None else {}) + + def dump(self, entries: Sequence[Entry], path: str) -> None: + try: + import yaml + except ImportError as exc: # pragma: no cover + raise SourceError( + "PyYAML is required for YAML sources. Install with 'pip install PyYAML'." + ) from exc + + payload: Dict[str, Any] = { + "meta": self.extra.get("meta", {}), + "entries": [_entry_to_dict(e) for e in entries], + } + content = yaml.safe_dump( + payload, allow_unicode=True, sort_keys=False, default_flow_style=False + ) + self._write_text(path, content, self.encoding) + + +__all__ = ["YamlSource"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dea33ef55fac7f04860bbf939fc3d0ac05b4bb4a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/__init__.py @@ -0,0 +1,33 @@ +"""TiMi_HOK_Game_Translator.strategies 子包。 + +本包提供可被 YAML/装饰器两种方式复用的翻译策略类。两种扩展方式: + +**方式一(推荐):YAML 配置化** + 在 ``conf/languages/.yaml`` 的 ``strategy_config`` 里加:: + + strategy_config: + class: TwoStepTranslationStrategy # 或 two_step + pivot_locale: en + + 零代码新增/切换语种。支持的内置短名见 + :data:`TiMi_HOK_Game_Translator.translation.factory._BUILTIN_STRATEGIES`。 + +**方式二:装饰器注册** + 继承 :class:`TwoStepTranslationStrategy` 或 + :class:`~TiMi_HOK_Game_Translator.translation.base.BaseTranslationStrategy`, + 追加 ``@register_translation_strategy("")``。适合策略类需要 + 重写 ``filter`` / ``translate`` 等方法的深度定制场景。 + +当前内置示例: + * :mod:`.minor_language_strategy` ——"中 → 英 → 目标"两步翻译模板, + 已注册 ``de``(德语);其它小语种可通过 YAML ``class: + TwoStepTranslationStrategy`` 直接复用,或继承后加装饰器注册。 + +注意: + import 本模块(``import TiMi_HOK_Game_Translator.strategies``)会触发所有子模块 + 的装饰器执行,从而完成注册。工厂层会在首次创建策略时统一导入。 +""" + +from . import minor_language_strategy # noqa: F401 — 导入即注册 + +__all__ = ["minor_language_strategy"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/minor_language_strategy.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/minor_language_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..78d36ef6debaf7b9b67694a68889186c74b4b6cb --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/strategies/minor_language_strategy.py @@ -0,0 +1,170 @@ +"""小语种两步翻译策略(中 → 英 → 目标语种)。 + +背景: + 游戏本地化场景中,部分小语种(德语/法语/土耳其语/俄语/阿拉伯语/ + 西班牙语/葡萄牙语等)直接用"中 → 目标语种"效果不稳定;采用 + **先中翻英、再英翻目标语** 的二级策略,译文质量显著提升。 + +本模块作用: + * 演示 ``strategies/`` 子包的扩展方式——不改框架,仅注册新策略; + * 提供一个典型小语种 (德语 ``de``) 示例,说明"两步翻译"的实现模板, + 其他小语种复用本类并追加 ``@register_translation_strategy("")`` + 即可,无需复制粘贴代码。 + +与通用 :class:`GenericTranslationStrategy` 的区别: + ``GenericTranslationStrategy`` 直接把 ``source_text`` 一次性丢给 LLM; + 本策略拆成两次 LLM 调用,中间结果写入 ``entry.metadata["english_side"]`` + 供下游状态(审校/质检)查阅。 + +扩展方式(新增一个小语种,不改代码): + 1. 复用本类,在 ``conf/languages/.json`` 中设置 + ``strategy_config.two_step = true``; + 2. 或继承本类并用 ``@register_translation_strategy("ru")`` 装饰器注册。 + +配置字段(``strategy_config`` 中可用的 key): + pivot_locale: + 中转语种 BCP-47 代码,默认 ``"en"``;也可配 ``"zh-CN"`` 等。 + skip_if_already_target: + True 时若原文已为目标语种直接返回;默认 False(无语种检测依赖)。 + 返回的英文中间结果恒写入 ``entry.metadata["english_side"]``(由 + executor 层自动完成,本策略只需返回 ``(target_text, english_text)``)。 +""" + +from __future__ import annotations + +import logging +from typing import List, Optional, Tuple + +from ..translation.base import BaseTranslationStrategy, Entry +from ..translation.factory import register_translation_strategy # pylint: disable=unused-import + +logger = logging.getLogger(__name__) + + +class TwoStepTranslationStrategy(BaseTranslationStrategy): + """两步翻译基类(中 → 中转 → 目标)。 + + 继承本类即可获得"先翻译到中转语种、再翻译到目标语种"的能力; + 两步均调用 ``self.llm.translate(...)``,模型由 ``llm_profile`` 决定。 + + 子类通常只需装饰 ``@register_translation_strategy("")``; + 其余配置通过 ``strategy_config`` 从 JSON 注入。 + """ + + #: 覆盖默认——两步翻译总是输出英文中间结果到 ``entry.metadata``。 + returns_english_data: bool = True + + def filter(self, source_text: str, *, entry: Entry) -> bool: + """空文本直接跳过;其余交由翻译。""" + return bool(source_text) + + def translate( + self, + source_text: str, + *, + entry: Entry, + source_locale: str, + target_locale: str, + context: str, + ) -> Tuple[str, Optional[str]]: + """执行两步翻译。 + + 流程: + + 1. ``source_text`` → ``pivot_locale``(默认 ``en``)得到中间结果; + 注入 ``entry.en_terms``(中→英术语对)。 + 2. 中间结果 → ``target_locale`` 得到最终译文; + 把 ``entry.en_terms`` 与 ``entry.terms`` 按**中文源文**做 inner-join + 映射为 **(英 → 目标语)** 术语对后注入——因为 Step 2 的原文已经是 + 英文,用"英→目标"术语对能被模型直接命中,比"中→目标"更有效。 + + 容错: + + * ``en_terms`` 或 ``terms`` 为空 → 对应步骤走无术语默认提示词; + * 中文 key 在两列中对不齐 → 只注入能对齐的那部分; + * 若任一步抛错,返回 ``("", english_or_None)``,由上层 + executor 统一记入 ``errors``;不吞错以便失败定位。 + """ + pivot_locale = str(self.strategy_config.get("pivot_locale", "en") or "en") + + en_terms = list(getattr(entry, "en_terms", []) or []) + tgt_terms = list(getattr(entry, "terms", []) or []) + + # ---- Step 1: source → pivot (通常是英语) -------------------- + # 注入 en_terms(中→英术语对)给 Step 1 + logger.info( + "[%s] Step 1/2 (%s→%s) key=%s terms=%d", + self.display_name, source_locale, pivot_locale, entry.key, len(en_terms), + ) + try: + pivot_response = self.llm.translate( + source_text, + source_locale=source_locale, + target_locale=pivot_locale, + context=context, + terms=en_terms, + ) + except Exception as exc: + logger.warning( + "[%s] step 1 (%s→%s) failed for key=%s: %s", + self.display_name, source_locale, pivot_locale, entry.key, exc, + ) + raise + + pivot_text = (pivot_response.text or "").strip() + if not pivot_text: + logger.warning( + "[%s] step 1 returned empty pivot text for key=%s", + self.display_name, entry.key, + ) + return "", None + + # ---- Step 2: pivot → target -------------------------------- + # 构造"英→目标语"术语对: + # {中文: 英文} join {中文: 目标语文} → [(英文, 目标语文), ...] + # 两列都有且中文 key 对齐的才注入;对不齐的跳过并记 debug 日志, + # 便于后续排查术语表质量。 + step2_terms: List[Tuple[str, str]] = [] + if tgt_terms: + en_map = {zh: en for zh, en in en_terms if zh and en} + for zh, tgt in tgt_terms: + if not zh or not tgt: + continue + en_text = en_map.get(zh) + if en_text: + step2_terms.append((en_text, tgt)) + else: + # EnTerms 里缺这条中文 key,Step 2 的英文原文中大概率 + # 没有对应的英文术语可供命中——跳过不注入,避免误导模型。 + logger.debug( + "[%s] key=%s: term '%s' missing in en_terms, " + "skip injection for step 2", + self.display_name, entry.key, zh, + ) + + logger.info( + "[%s] Step 2/2 (%s→%s) key=%s terms=%d", + self.display_name, pivot_locale, target_locale, entry.key, len(step2_terms), + ) + try: + target_response = self.llm.translate( + pivot_text, + source_locale=pivot_locale, + target_locale=target_locale, + context=context, + terms=step2_terms, + ) + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "[%s] step 2 (%s→%s) failed for key=%s: %s", + self.display_name, pivot_locale, target_locale, entry.key, exc, + ) + # 第二步失败时仍把已拿到的英文结果返回出去,便于后续兜底使用 + return "", pivot_text + + target_text = (target_response.text or "").strip() + return target_text, pivot_text + +__all__ = [ + "TwoStepTranslationStrategy", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..236bc45c63471fb46aa1c7991f2988d0ea601236 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__init__.py @@ -0,0 +1,51 @@ +"""可插拔的翻译策略层。 + +:mod:`TiMi_HOK_Game_Translator.llm` 负责**调用**底层服务(发送 prompt、拿返回); +本包负责**编排**: + +* 单语种过滤规则(如"目标为越南语时, + 已含泰文的条目不送翻"); +* 单语种 prompt / 模型选择; +* 串行 vs 并发执行模式; +* 译后钩子(术语校验、同行广播等); +* 结果格式化与去重。 + +用户可通过 :func:`register_translation_strategy` +装饰器注册自定义策略;内置的 +:class:`GenericTranslationStrategy` 纯配置驱动, +新增语种一般无需写代码。 + +对外 API:: + + from TiMi_HOK_Game_Translator.translation import ( + BaseTranslationStrategy, + GenericTranslationStrategy, + Entry, TranslationResult, + register_translation_strategy, + get_translation_strategy, + ) +""" + +from .base import ( + BaseTranslationStrategy, + Entry, + SiblingBroadcaster, + TranslationResult, +) +from .factory import ( + get_translation_strategy, + register_translation_strategy, + registered_languages, +) +from .generic_strategy import GenericTranslationStrategy + +__all__ = [ + "BaseTranslationStrategy", + "Entry", + "GenericTranslationStrategy", + "SiblingBroadcaster", + "TranslationResult", + "get_translation_strategy", + "register_translation_strategy", + "registered_languages", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..926d49cb4669ec2de9e38ff6df85723a5433ad69 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d25a5a04cdbe06b4e1238740e5e8b45942fed03 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..144aa3845a533b810cf2ae849e634a8f734bad0d Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/generic_strategy.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/generic_strategy.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1fc13448fed38d4292334132ecb3f734b6b15cf Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/__pycache__/generic_strategy.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f3ac75c8d6fcc535d1f5a5e70cbf528af1d9bd15 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/base.py @@ -0,0 +1,404 @@ +"""翻译策略层的基类与数据对象。 + +设计目标: + +* **三段式契约**:子类只需实现 + :meth:`BaseTranslationStrategy.filter`(判定源文本是否送译)与 + :meth:`BaseTranslationStrategy.translate`(实际调用 LLM/外部服务); + 完整流水线 :meth:`process` 由本基类提供。 +* **串行/并发模式**均位于 :mod:`.executors`,运行时透明选择。 +* **后端无关**:策略只依赖 :class:`~TiMi_HOK_Game_Translator.llm.LLMClient` 接口, + 不绑定具体厂商 SDK。LLM 实例由工厂注入。 +* **可插拔副作用**:去重完成后,:class:`SiblingBroadcaster` 会被调用, + 便于将已批准译文广播回具有相同源文本的其他行。 +* **不假设业务**:不硬编码 Excel 列名、不默认繁转简、不回退到某个厂商; + 这些行为均由**用户自定义**策略子类提供。 +""" + +from __future__ import annotations + +import abc +import logging +import threading +from dataclasses import dataclass, field +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Protocol, + Sequence, + Tuple, + runtime_checkable, +) + +from ..commons import DEFAULT_LLM_BATCH_SIZE +from ..llm import LLMClient, LocalMockLLM + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# 数据对象 +# --------------------------------------------------------------------------- +@dataclass +class Entry: + """单个翻译单元。 + + 本对象是 Source / Strategy / LLM / Platform 之间的**传输格式**。 + 它故意不携带 Excel 专属列;格式相关的字段一律放入 :attr:`metadata`。 + + 字段: + key: 条目的稳定标识(一般为 hash 或开发者自定义 key),在单个源中必须唯一。 + source_text: 待翻译的原文。 + target_text: 翻译后的目标文本(翻译前为空)。 + context: 选传给 LLM 的上下文提示(如发言角色、UI 位置等)。 + comment: 自由形式的备注,给翻译者/审校者看。 + en_terms: 中→英术语对(``[(zh, en), ...]``),两步翻译 Step 1 使用。 + terms: 中→目标语术语对(``[(zh, target), ...]``),一步策略直接使用, + 两步策略 Step 2 使用(会先与 en_terms 做映射转为英→目标语术语)。 + metadata: 后端自定义字段,Source 在 + :meth:`~TiMi_HOK_Game_Translator.sources.LocalizationSource.load` 时填充, + 在 :meth:`~TiMi_HOK_Game_Translator.sources.LocalizationSource.dump` 时读取。 + """ + + key: str + source_text: str = "" + target_text: str = "" + context: str = "" + comment: str = "" + en_terms: List[Tuple[str, str]] = field(default_factory=list) + terms: List[Tuple[str, str]] = field(default_factory=list) + metadata: Dict[str, Any] = field(default_factory=dict) + + +@dataclass +class TranslationResult: + """一次策略 :meth:`~BaseTranslationStrategy.process` 调用的聚合结果。 + + 字段: + translated: 已填充 ``target_text`` 的条目。 + untranslated: 被 :meth:`~BaseTranslationStrategy.filter` 拒绝、 + 或在 :meth:`~BaseTranslationStrategy.translate` 时失败的条目。 + errors: 以 :attr:`Entry.key` 为键的错误描述(缺失 key + 表示“被过滤但无错”)。 + stats: 计数器,供日志/监控使用(``total``/``success``/``failed``/ + ``duration_seconds`` 等)。 + """ + + translated: List[Entry] = field(default_factory=list) + untranslated: List[Entry] = field(default_factory=list) + errors: Dict[str, str] = field(default_factory=dict) + stats: Dict[str, Any] = field(default_factory=dict) + + +# --------------------------------------------------------------------------- +# 可选副作用 Protocol +# --------------------------------------------------------------------------- +@runtime_checkable +class SiblingBroadcaster(Protocol): + """将翻译结果广播到同行条目的可选回调。 + + 场景:源文件中多个行可能共享相同的 ``source_text`` 但不同 key; + 策略在送入 LLM 前会去重。审校通过后,需将结果广播回全部同行 + 行,保证最终 dump 完整。 + + ``SiblingBroadcaster`` 对每个去重后的已译条目调用一次,返回一个 + 正整数表示受影响的行数(仅供日志使用)。 + """ + + def broadcast(self, translated: Entry, all_entries: Sequence[Entry]) -> int: + ... + + +class NoopSiblingBroadcaster: + """默认的空 :class:`SiblingBroadcaster` 实现(什么也不做)。 + + 不需要同行广播时可将 ``sibling_broadcaster`` 参数置空,内部会使用本类。 + """ + + def broadcast(self, translated: Entry, all_entries: Sequence[Entry]) -> int: # noqa: D401,ARG002 + return 0 + + +# --------------------------------------------------------------------------- +# BaseTranslationStrategy +# --------------------------------------------------------------------------- +class BaseTranslationStrategy(abc.ABC): + """单语种翻译策略的抽象基类。 + + 子类通过类属性 :attr:`language_id`(或 ``@register_translation_strategy`` 装饰器) + 声明自己服务的语种,并实现两个方法: + + * :meth:`filter`——判定 ``source_text`` 是否应送入 LLM(“已翻译/包含禁用字符” + 等语种专属规则在此处); + * :meth:`translate`——实际调用 LLM 并返回译文(可选额外返回一份英文侧译, + 用于两步翻译策略)。 + + 其余所有能力——分批、并发、进度上报、错误汇总、去重、同行广播——均由 + :meth:`process` 内置实现。 + + 字段: + language_id: 本策略服务的 BCP-47/产品 slug。 + display_name: 日志中使用的人可读名称。 + source_locale / target_locale: BCP-47 标签。为空时可以从 + :meth:`translate` 的 context 参数中传入。 + use_concurrent_by_default: :meth:`process` 默认是否采用并发执行器。 + default_max_workers: 并发执行器的线程池大小。 + batch_size: 调用 :meth:`LLMClient.batch_translate` 时的首选批量大小。 + progress_log_interval: :meth:`process` 中记录进度日志的频率。 + llm: 默认 :meth:`translate` 使用的 LLM 客户端(子类可忽略它并自行选择)。 + strategy_config: 从 :attr:`LanguageProfile.strategy_config` 拷贝的自由字典, + 子类从中读取语种专用参数。 + sibling_broadcaster: 可选的译后副作用回调。 + """ + + # -- 类级默认值,子类按需覆盖。 ------------------------- + language_id: str = "" + display_name: str = "" + source_locale: str = "" + target_locale: str = "" + use_concurrent_by_default: bool = True + default_max_workers: int = 5 + batch_size: int = DEFAULT_LLM_BATCH_SIZE + progress_log_interval: int = 10 + returns_english_data: bool = False + + def __init__( + self, + *, + language_id: str = "", + llm: Optional[LLMClient] = None, + strategy_config: Optional[Dict[str, Any]] = None, + source_locale: str = "", + target_locale: str = "", + sibling_broadcaster: Optional[SiblingBroadcaster] = None, + ) -> None: + # 实例属性遮盖类属性,使子类既可通过类变量配置、也可通过构造参数配置。 + if language_id: + self.language_id = language_id + if source_locale: + self.source_locale = source_locale + if target_locale: + self.target_locale = target_locale + + self.strategy_config: Dict[str, Any] = dict(strategy_config or {}) + self._apply_strategy_config() + + # 默认使用 LocalMockLLM,保证开箱即用。 + self.llm: LLMClient = llm or LocalMockLLM() + self.sibling_broadcaster: SiblingBroadcaster = ( + sibling_broadcaster or NoopSiblingBroadcaster() + ) + + self._lock = threading.RLock() + + # ------------------------------------------------------------------ + # 配置管道 + # ------------------------------------------------------------------ + _CONFIG_ATTRS: Tuple[str, ...] = ( + "display_name", + "source_locale", + "target_locale", + "use_concurrent_by_default", + "default_max_workers", + "batch_size", + "progress_log_interval", + "returns_english_data", + ) + + def _apply_strategy_config(self) -> None: + """从 :attr:`strategy_config` 中拉取内置字段并赋值到 ``self``。 + + 不属于 :data:`_CONFIG_ATTRS` 的 key 会保留在字典中,供子类自行消费。 + """ + for name in self._CONFIG_ATTRS: + if name in self.strategy_config: + setattr(self, name, self.strategy_config[name]) + if not self.display_name: + self.display_name = self.language_id or self.__class__.__name__ + + # ------------------------------------------------------------------ + # 抽象接口 + # ------------------------------------------------------------------ + @abc.abstractmethod + def filter(self, source_text: str, *, entry: Entry) -> bool: + """当 ``source_text`` 应被翻译时返回 ``True``。 + + 在 :meth:`translate` **之前**调用;返回 ``False`` 时条目会被放入 + :attr:`TranslationResult.untranslated`,不会到达 LLM。 + """ + + @abc.abstractmethod + def translate( + self, + source_text: str, + *, + entry: Entry, + source_locale: str, + target_locale: str, + context: str, + ) -> Tuple[str, Optional[str]]: + """翻译 ``source_text`` 并返回 ``(target_text, english_side)``。 + + 第二个返回值是英文侧译(``en_data`` 位):同时产出英文枚译的策略可在此返回; + 否则为 ``None``。 + """ + + # ------------------------------------------------------------------ + # 可选钩子 + # ------------------------------------------------------------------ + def post_translate(self, result: TranslationResult) -> None: # noqa: B027 — 可选钩子 + """:meth:`process` 完成后回调。 + + 默认什么也不做。子类可重写以添加术语校验、质量门禁、写临时文件、 + POST 监控数据等副作用。 + """ + + # ------------------------------------------------------------------ + # 公共入口 + # ------------------------------------------------------------------ + def process( + self, + entries: Sequence[Entry], + *, + source_locale: str = "", + target_locale: str = "", + use_concurrent: Optional[bool] = None, + max_workers: Optional[int] = None, + progress_callback: Optional[Callable[[int, int], None]] = None, + ) -> TranslationResult: + """端到端翻译 ``entries``,遵循 filter / 并发策略。 + + 参数: + entries: 待处理的条目列表。``source_text`` 相同的条目会先去重, + 只发往 LLM 一次,完成后通过 :attr:`sibling_broadcaster` + 广播回同行行。 + source_locale / target_locale: 本次调用的覆盖。为空时使用策略自己的默认值。 + use_concurrent: ``None`` 时使用策略默认值。 + max_workers: ``None`` 时使用策略默认值。 + progress_callback: 可选回调,``(done, total)`` 为参数,按 + :attr:`progress_log_interval` 频率回调。 + + 返回: + :class:`TranslationResult`,包含已译/未译条目与汇总统计。 + """ + source_locale = source_locale or self.source_locale + target_locale = target_locale or self.target_locale + if use_concurrent is None: + use_concurrent = self.use_concurrent_by_default + if max_workers is None: + max_workers = self.default_max_workers + + # --- 按 source_text 去重,保证相同原文只送一次 LLM。 + deduped, siblings = _deduplicate(entries) + total = len(deduped) + logger.info( + "[%s] Processing %d entries (%d unique, concurrent=%s, workers=%d)", + self.display_name, len(entries), total, use_concurrent, max_workers, + ) + + result = TranslationResult(stats={"total_input": len(entries), "unique": total}) + + # --- 选择执行器。 + # 局部导入,保证 executors 为可选,并避免循环导入。 + if use_concurrent and total > 1: + from .executors.concurrent import run_concurrent + translated, untranslated, errors = run_concurrent( + self, deduped, + source_locale=source_locale, + target_locale=target_locale, + max_workers=max_workers, + progress_callback=progress_callback, + ) + else: + from .executors.serial import run_serial + translated, untranslated, errors = run_serial( + self, deduped, + source_locale=source_locale, + target_locale=target_locale, + progress_callback=progress_callback, + ) + + # --- 广播到同行行。 + sibling_extra: List[Entry] = [] + for tr in translated: + broadcast_count = 0 + try: + broadcast_count = self.sibling_broadcaster.broadcast(tr, entries) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 同行失败不致命 + logger.warning( + "[%s] Sibling broadcast failed for key=%s: %s", + self.display_name, tr.key, exc, + ) + if broadcast_count: + logger.debug( + "[%s] broadcaster touched %d sibling rows for key=%s", + self.display_name, broadcast_count, tr.key, + ) + # 即使没有外部 broadcaster,也需将译文写回去重后隐藏的同行条目, + # 保证调用方拿到完整的译文列表。 + for sibling in siblings.get(tr.source_text, ()): + if sibling.key == tr.key: + continue + sibling.target_text = tr.target_text + sibling_extra.append(sibling) + translated.extend(sibling_extra) + + result.translated = translated + result.untranslated = untranslated + result.errors = errors + result.stats.update({ + "success": len(translated), + "failed": len(untranslated), + }) + + self.post_translate(result) + return result + + # ------------------------------------------------------------------ + # 自省 + # ------------------------------------------------------------------ + def __repr__(self) -> str: # pragma: no cover - trivial + return ( + f"{self.__class__.__name__}" + f"(language_id={self.language_id!r}, display_name={self.display_name!r})" + ) + + +# --------------------------------------------------------------------------- +# 辅助函数 +# --------------------------------------------------------------------------- +def _deduplicate( + entries: Sequence[Entry], +) -> Tuple[List[Entry], Dict[str, List[Entry]]]: + """将 ``entries`` 拆分为 ``(按 source_text 去重后的列表, siblings_map)``。 + + 空的 ``source_text`` 作为各自独立的 key,避免不小心将多个空行合并。 + """ + unique: List[Entry] = [] + siblings: Dict[str, List[Entry]] = {} + seen: Dict[str, Entry] = {} + + for entry in entries: + text = entry.source_text or "" + if not text: + unique.append(entry) + continue + if text in seen: + siblings.setdefault(text, []).append(entry) + else: + seen[text] = entry + unique.append(entry) + + return unique, siblings + + +__all__ = [ + "BaseTranslationStrategy", + "Entry", + "NoopSiblingBroadcaster", + "SiblingBroadcaster", + "TranslationResult", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a098143f7d9801b273b1213ba8a0e5f573fc87c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/__init__.py @@ -0,0 +1,17 @@ +"""供 :class:`BaseTranslationStrategy.process` 使用的执行引擎。 + +内置两个实现: + +* :mod:`.serial`\u2014\u2014逐条串行处理。开销小、顺序确定、便于调试; + 当策略的独立条目少于 2 条或显式禁用并发时会选用它。 +* :mod:`.concurrent`\u2014\u2014使用固定大小线程池并发处理, + 适合 I/O 密集的 LLM 调用。 + +两个执行器**签名完全一致**,调用方切换时无需修改分支;返回值也一致, +均为 ``(translated, untranslated, errors)``。 +""" + +from .concurrent import run_concurrent +from .serial import run_serial + +__all__ = ["run_concurrent", "run_serial"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/concurrent.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/concurrent.py new file mode 100644 index 0000000000000000000000000000000000000000..105759cde311ba9da3b3b89bae0732d8e7ee883c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/concurrent.py @@ -0,0 +1,118 @@ +"""翻译策略的并发(线程池)执行引擎。 + +使用 :class:`concurrent.futures.ThreadPoolExecutor`:典型 LLM / HTTP 后端为 I/O 密集, +GIL 不是矶颈。最后会按原始顺序重新排序,保证确定性。 +""" + +from __future__ import annotations + +import concurrent.futures as _futures +import logging +import threading +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Sequence, Tuple + +if TYPE_CHECKING: + from ..base import BaseTranslationStrategy, Entry + +logger = logging.getLogger(__name__) + + +def run_concurrent( + strategy: BaseTranslationStrategy, + entries: Sequence[Entry], + *, + source_locale: str, + target_locale: str, + max_workers: int, + progress_callback: Optional[Callable[[int, int], None]] = None, +) -> Tuple[List[Entry], List[Entry], Dict[str, str]]: + """以并发方式执行 ``strategy``。 + + 返回值契约(与串行执行器完全一致): + + * ``translated``——``target_text`` 非空的条目,按输入顺序排列; + * ``untranslated``——被过滤或报错的条目; + * ``errors``——以 ``entry.key`` 为键的错误描述(过滤与报错都会在此出现)。 + """ + + total = len(entries) + translated: List[Tuple[int, Entry]] = [] + untranslated: List[Tuple[int, Entry]] = [] + errors: Dict[str, str] = {} + done_counter = {"n": 0} + counter_lock = threading.Lock() + + def _worker(idx: int, entry: Entry) -> None: + text = entry.source_text or "" + if not strategy.filter(text, entry=entry): + with strategy._lock: # noqa: SLF001 — 与策略内部状态协作 + untranslated.append((idx, entry)) + errors.setdefault(entry.key, "filtered out") + _bump(idx, entry) + return + + try: + target, english = strategy.translate( + text, + entry=entry, + source_locale=source_locale, + target_locale=target_locale, + context=entry.context, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 统一收集到 errors + logger.warning( + "[%s] translate() raised for key=%s: %s", + strategy.display_name, entry.key, exc, + ) + with strategy._lock: # noqa: SLF001 + untranslated.append((idx, entry)) + errors[entry.key] = f"{type(exc).__name__}: {exc}" + _bump(idx, entry) + return + + if not target: + with strategy._lock: # noqa: SLF001 + untranslated.append((idx, entry)) + errors.setdefault(entry.key, "empty target_text") + _bump(idx, entry) + return + + entry.target_text = target + if english is not None: + entry.metadata.setdefault("english_side", english) + with strategy._lock: # noqa: SLF001 + translated.append((idx, entry)) + _bump(idx, entry) + + def _bump(idx: int, entry: Entry) -> None: # noqa: ARG001 + with counter_lock: + done_counter["n"] += 1 + done = done_counter["n"] + interval = max(1, strategy.progress_log_interval) + if done % interval == 0 or done == total: + percent = (done / total * 100) if total else 100.0 + logger.info( + "[%s] progress %d/%d (%.1f%%)", + strategy.display_name, done, total, percent, + ) + if progress_callback is not None: + try: + progress_callback(done, total) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.debug("progress_callback failed: %s", exc) + + workers = max(1, min(max_workers, total)) + with _futures.ThreadPoolExecutor(max_workers=workers) as pool: + futures = [pool.submit(_worker, i, e) for i, e in enumerate(entries)] + # 等待所有 future;个体失败已在 _worker 内捕获,无需在此检查异常。 + for fut in _futures.as_completed(futures): + _ = fut.result() # 仅在 _worker 自身报错时重新抛出 + + # 回复原始输入顺序,保证下游日志确定。 + translated.sort(key=lambda pair: pair[0]) + untranslated.sort(key=lambda pair: pair[0]) + return ( + [e for _, e in translated], + [e for _, e in untranslated], + errors, + ) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/serial.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/serial.py new file mode 100644 index 0000000000000000000000000000000000000000..35a008ca9a5b98eba930af680cff0ace4720fca8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/executors/serial.py @@ -0,0 +1,96 @@ +"""翻译策略的串行(单线程)执行引擎。 + +逐个处理去重后的条目。顺序确定、无线程池开销—— +当输入量小或 LLM 后端非线程安全时优选。 +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Sequence, Tuple + +if TYPE_CHECKING: + from ..base import BaseTranslationStrategy, Entry + +logger = logging.getLogger(__name__) + + +def run_serial( + strategy: BaseTranslationStrategy, + entries: Sequence[Entry], + *, + source_locale: str, + target_locale: str, + progress_callback: Optional[Callable[[int, int], None]] = None, +) -> Tuple[List[Entry], List[Entry], Dict[str, str]]: + """按串行方式执行 ``strategy``。 + + 契约与 + :func:`TiMi_HOK_Game_Translator.translation.executors.concurrent.run_concurrent` 一致。 + """ + + translated: List[Entry] = [] + untranslated: List[Entry] = [] + errors: Dict[str, str] = {} + total = len(entries) + + for idx, entry in enumerate(entries, start=1): + text = entry.source_text or "" + if not strategy.filter(text, entry=entry): + untranslated.append(entry) + errors.setdefault(entry.key, "filtered out") + _maybe_report(strategy, idx, total, progress_callback) + continue + + try: + target, english = strategy.translate( + text, + entry=entry, + source_locale=source_locale, + target_locale=target_locale, + context=entry.context, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 统一收集到 errors + logger.warning( + "[%s] translate() raised for key=%s: %s", + strategy.display_name, entry.key, exc, + ) + untranslated.append(entry) + errors[entry.key] = f"{type(exc).__name__}: {exc}" + _maybe_report(strategy, idx, total, progress_callback) + continue + + if not target: + untranslated.append(entry) + errors.setdefault(entry.key, "empty target_text") + _maybe_report(strategy, idx, total, progress_callback) + continue + + entry.target_text = target + if english is not None: + entry.metadata.setdefault("english_side", english) + translated.append(entry) + _maybe_report(strategy, idx, total, progress_callback) + + return translated, untranslated, errors + + +def _maybe_report( + strategy: BaseTranslationStrategy, + done: int, + total: int, + callback: Optional[Callable[[int, int], None]], +) -> None: + """在进度边界处记录 INFO 日志并回调 ``callback``。""" + interval = max(1, strategy.progress_log_interval) + if done % interval == 0 or done == total: + percent = (done / total * 100) if total else 100.0 + logger.info( + "[%s] progress %d/%d (%.1f%%)", + strategy.display_name, done, total, percent, + ) + if callback is not None: + try: + callback(done, total) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 进度回调失败不致命 + logger.debug("progress_callback failed: %s", exc) diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe44e684f110ed3eb469748d5dbe0386262f6a2 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/factory.py @@ -0,0 +1,274 @@ +"""翻译策略的注册表与工厂。 + +框架支持三种策略绑定方式,优先级从高到低: + +* **YAML 配置声明**——在 ``conf/languages/.yaml`` 的 ``strategy_config`` + 里加 ``class: TwoStepTranslationStrategy``(或完整 import 路径,如 + ``my_pkg.strategies.MyStrategy``)。这是**推荐**方式,零代码扩展, + 运维/测试同学也能自助切换策略。 +* **语种专属子类**——用户继承 :class:`BaseTranslationStrategy` 并使用 + ``@register_translation_strategy("vi")`` 装饰器;当 ``language_id="vi"`` + 时,:func:`get_translation_strategy` 会返回该子类的实例。适合策略有 + 大量重写/定制逻辑的场景。 +* **纯配置内置回退**——以上两种都没匹配到时返回 + :class:`GenericTranslationStrategy`,以 profile 的 ``strategy_config`` 初始化。 + +本工厂**不携带**任何与具体游戏绑定的子类,保证这份开源包干净。 +""" + +from __future__ import annotations + +import importlib +import logging +from typing import Any, Callable, Dict, List, Optional, Type + +from .base import BaseTranslationStrategy, SiblingBroadcaster +from .generic_strategy import GenericTranslationStrategy + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# 注册表 +# --------------------------------------------------------------------------- +_REGISTRY: Dict[str, Type[BaseTranslationStrategy]] = {} + +#: 内置策略类"短名 → 类"映射表。 +#: +#: 用于 YAML 中 ``strategy_config.class`` 字段的声明式查找——用户在 +#: ``conf/languages/.yaml`` 里写 ``class: TwoStepTranslationStrategy`` +#: 即可直接把该语种绑定到两步翻译策略,无需在代码里加 +#: ``@register_translation_strategy`` 装饰器。 +#: +#: 支持三种写法(均不区分大小写): +#: 1. 短名:``"TwoStepTranslationStrategy"`` 或 ``"two_step"``; +#: 2. 完整 import 路径:``"my_pkg.my_mod.MyStrategy"``(含 ``.``); +#: 3. 留空 / 省略 ``class`` 字段 → 走装饰器注册表 → 兜底 Generic。 +#: +#: 注册表在 :func:`_ensure_builtin_strategies_loaded` 首次调用后填充, +#: 避免模块级循环 import。 +_BUILTIN_STRATEGIES: Dict[str, Type[BaseTranslationStrategy]] = {} + +#: 懒加载开关——首次调用 get_translation_strategy 时自动 import +#: ``TiMi_HOK_Game_Translator.strategies`` 子包,触发其内所有策略装饰器注册。 +#: 不在模块级 import 以避免循环依赖。 +_STRATEGIES_PKG_LOADED = False + + +def _ensure_builtin_strategies_loaded() -> None: + """首次调用时导入 ``TiMi_HOK_Game_Translator.strategies`` 以触发装饰器注册。 + + 使用模块级 ``_STRATEGIES_PKG_LOADED`` 标记保证只做一次; + 导入失败时记 debug 日志但不抛错,保证框架在没有 strategies 子包时 + 也能正常工作。 + + 同时填充 :data:`_BUILTIN_STRATEGIES` 短名表,供 + :func:`_resolve_strategy_class` 按 YAML ``class`` 字段查找。 + """ + global _STRATEGIES_PKG_LOADED + if _STRATEGIES_PKG_LOADED: + return + _STRATEGIES_PKG_LOADED = True + try: + import importlib + + importlib.import_module("TiMi_HOK_Game_Translator.strategies") + except ImportError as exc: # pragma: no cover — strategies 可被用户删除 + logger.debug( + "TiMi_HOK_Game_Translator.strategies not loaded (%s); only GenericTranslationStrategy available", + exc, + ) + + # 填充内置短名表(延迟 import 避免模块级循环依赖) + _BUILTIN_STRATEGIES["GenericTranslationStrategy"] = GenericTranslationStrategy + _BUILTIN_STRATEGIES["generic"] = GenericTranslationStrategy + try: + from ..strategies.minor_language_strategy import TwoStepTranslationStrategy + + _BUILTIN_STRATEGIES["TwoStepTranslationStrategy"] = TwoStepTranslationStrategy + _BUILTIN_STRATEGIES["two_step"] = TwoStepTranslationStrategy + except ImportError as exc: # pragma: no cover — strategies 子包可被用户删除 + logger.debug( + "TwoStepTranslationStrategy not available (%s); YAML class='TwoStepTranslationStrategy' will fail", + exc, + ) + + +def _resolve_strategy_class( + strategy_config: Optional[Dict[str, Any]], +) -> Optional[Type[BaseTranslationStrategy]]: + """解析 ``strategy_config.class`` 字段 → 策略类。 + + 支持三种写法: + + 1. **留空 / 省略**:返回 ``None``,调用方继续走装饰器注册表与兜底。 + 2. **短名**(无 ``.``):从 :data:`_BUILTIN_STRATEGIES` 查,不区分大小写。 + 3. **完整 import 路径**(含 ``.``):如 ``my_pkg.strategies.Russian``, + 走 :func:`importlib.import_module` + :func:`getattr`。 + + 若查找/导入失败,记 WARNING 日志并返回 ``None``,让调用方降级到装饰器 + 注册表或 Generic 兜底——保持配置错误时流水线仍可跑的宽容性。 + """ + if not strategy_config: + return None + raw = strategy_config.get("class") + if not raw: + return None + name = str(raw).strip() + if not name: + return None + + # 情况 3:完整 import 路径 + if "." in name: + module_path, _, class_name = name.rpartition(".") + try: + module = importlib.import_module(module_path) + cls = getattr(module, class_name) + except (ImportError, AttributeError) as exc: + logger.warning( + "strategy_config.class=%r: cannot import %s.%s (%s); " + "falling back to decorator registry", + name, module_path, class_name, exc, + ) + return None + if not isinstance(cls, type) or not issubclass(cls, BaseTranslationStrategy): + logger.warning( + "strategy_config.class=%r resolved to %r which is not a " + "BaseTranslationStrategy subclass; ignoring", + name, cls, + ) + return None + return cls + + # 情况 2:短名(不区分大小写精确匹配) + cls = _BUILTIN_STRATEGIES.get(name) + if cls is None: + # 大小写不敏感兜底查找 + lowered = name.lower() + for key, value in _BUILTIN_STRATEGIES.items(): + if key.lower() == lowered: + cls = value + break + if cls is None: + logger.warning( + "strategy_config.class=%r is not a known builtin short name " + "(available: %s); falling back to decorator registry", + name, sorted(_BUILTIN_STRATEGIES.keys()), + ) + return None + return cls + + +def register_translation_strategy( + language_id: str, + *, + replace: bool = False, +) -> Callable[[Type[BaseTranslationStrategy]], Type[BaseTranslationStrategy]]: + """类装饰器:将 ``cls`` 绑定到 ``language_id``。 + + 参数: + language_id: 本策略服务的 BCP-47 标签或产品 slug。 + replace: ``False``(默认)时,重复绑定会抛出 :class:`ValueError`; + 测试/插件 bootstrap 情景下可传 ``True`` 强行覆盖。 + + 示例:: + + @register_translation_strategy("vi") + class VietnameseStrategy(BaseTranslationStrategy): + ... + """ + + def _decorator(cls: Type[BaseTranslationStrategy]) -> Type[BaseTranslationStrategy]: + if not issubclass(cls, BaseTranslationStrategy): + raise TypeError( + f"{cls.__name__} must inherit from BaseTranslationStrategy" + ) + if not replace and language_id in _REGISTRY and _REGISTRY[language_id] is not cls: + raise ValueError( + f"Language id {language_id!r} is already bound to " + f"{_REGISTRY[language_id].__name__}. Pass replace=True to override." + ) + _REGISTRY[language_id] = cls + cls.language_id = language_id + return cls + + return _decorator + + +def registered_languages() -> List[str]: + """返回当前已注册的语种 id 列表(排序后)。""" + return sorted(_REGISTRY.keys()) + + +# --------------------------------------------------------------------------- +# 工厂 +# --------------------------------------------------------------------------- +def get_translation_strategy( + language_id: str, + *, + llm: Optional[Any] = None, + strategy_config: Optional[Dict[str, Any]] = None, + source_locale: str = "", + target_locale: str = "", + sibling_broadcaster: Optional[SiblingBroadcaster] = None, +) -> BaseTranslationStrategy: + """返回已初始化好的 ``language_id`` 对应策略实例。 + + 查找顺序(新): + + 1. **YAML 显式声明** ``strategy_config.class``(短名或完整 import 路径)—— + 推荐方式,零代码扩展; + 2. 装饰器注册表中的精确匹配(``@register_translation_strategy("vi")``); + 3. 通配符注册(如 ``@register_translation_strategy("vi_*")``)—— + 待实现; + 4. 以 ``strategy_config`` 初始化的 :class:`GenericTranslationStrategy`。 + + 返回的实例**不缓存**,多次调用之间 ``strategy_config`` 可以自由修改。 + """ + _ensure_builtin_strategies_loaded() + + # 优先级 1:YAML strategy_config.class 显式声明 + cls: Optional[Type[BaseTranslationStrategy]] = _resolve_strategy_class(strategy_config) + source = "yaml.class" + + # 优先级 2:装饰器注册表 + if cls is None: + cls = _REGISTRY.get(language_id) + if cls is not None: + source = "decorator" + + # 优先级 3:Generic 兜底 + if cls is None: + cls = GenericTranslationStrategy + source = "generic_fallback" + + strategy = cls( + language_id=language_id, + llm=llm, + strategy_config=strategy_config, + source_locale=source_locale, + target_locale=target_locale, + sibling_broadcaster=sibling_broadcaster, + ) + if source == "yaml.class": + logger.info( + "Translation strategy for %r resolved via YAML strategy_config.class → %s", + language_id, cls.__name__, + ) + elif source == "generic_fallback": + logger.debug( + "No bespoke strategy for %r — using GenericTranslationStrategy", + language_id, + ) + else: # decorator + logger.debug( + "Translation strategy for %r resolved via decorator registry → %s", + language_id, cls.__name__, + ) + return strategy + + +__all__ = [ + "get_translation_strategy", + "register_translation_strategy", + "registered_languages", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/generic_strategy.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/generic_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..45df97ea42831b7611feac484a3836c479199910 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/translation/generic_strategy.py @@ -0,0 +1,103 @@ +"""纯配置驱动的翻译策略。 + +新增一个语种一般无需写代码: + +1. 在 ``/.json`` 中声明 ``strategy_config``(展示名、 + 可选 prompt 模板等)——``languages_dir`` 由 ``config.yaml`` 指定, + 本仓库惯用 ``conf/languages``,demo 默认 ``configs/languages``; +2. 以 ``--language `` 运行流水线。 + +:class:`GenericTranslationStrategy` 会读取该 JSON,将非空条目送给当前配置的 +:class:`~TiMi_HOK_Game_Translator.llm.LLMClient`,并返回结果。 + +如需更复杂的能力(自定义过滤、多模型路由、同行广播等),请继承 +:class:`BaseTranslationStrategy` 并使用 :func:`register_translation_strategy` 注册。 +""" + +from __future__ import annotations + +import logging +from typing import Optional, Tuple + +from .base import BaseTranslationStrategy, Entry + +logger = logging.getLogger(__name__) + + +class GenericTranslationStrategy(BaseTranslationStrategy): + """完全由 ``strategy_config`` 驱动的零代码策略。 + + 支持的 ``strategy_config`` 字段: + + ================================ =============================================================== + Key 含义 + ================================ =============================================================== + ``display_name`` 日志中使用的人可读名称。 + ``prompt_template`` 非空时作为 ``context`` 传递给 LLM。 + ``allow_empty`` True 时接受空 ``source_text`` 并直接返回。 + ``skip_predicate`` 可调用对象 ``(text, entry) -> bool``;True 表示跳过翻译。 + ``use_concurrent_by_default`` :meth:`process` 默认是否使用并发执行。 + ``default_max_workers`` 并发执行器线程池大小。 + ``batch_size`` 首选批量大小(目前仅用于上报)。 + ``returns_english_data`` 同时向 LLM 索取英文侧译。 + ================================ =============================================================== + + 未知 key 保留在 :attr:`strategy_config` 中,子类可通过 + ``self.strategy_config[key]`` 读取。 + """ + + language_id = "generic" + + def filter(self, source_text: str, *, entry: Entry) -> bool: + # 用户自定义谓词优先于内置行为。 + predicate = self.strategy_config.get("skip_predicate") + if callable(predicate): + try: + return not bool(predicate(source_text, entry)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "[%s] skip_predicate raised for key=%s: %s — treating as skip", + self.display_name, entry.key, exc, + ) + return False + + if source_text: + return True + return bool(self.strategy_config.get("allow_empty", False)) + + def translate( + self, + source_text: str, + *, + entry: Entry, + source_locale: str, + target_locale: str, + context: str, + ) -> Tuple[str, Optional[str]]: + template = self.strategy_config.get("prompt_template", "") + if template: + try: + effective_context = template.format(text=source_text, context=context) + except (KeyError, IndexError) as exc: + logger.debug( + "[%s] prompt_template format failed (%s); using raw context", + self.display_name, exc, + ) + effective_context = context + else: + effective_context = context + + response = self.llm.translate( + source_text, + source_locale=source_locale, + target_locale=target_locale, + context=effective_context, + terms=list(getattr(entry, "terms", []) or []), + ) + english: Optional[str] = None + if self.returns_english_data: + english = response.metadata.get("english_side") if response.metadata else None + return response.text, english + + +__all__ = ["GenericTranslationStrategy"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..999093b4005e23765b4385f5902d07b0bacb0332 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__init__.py @@ -0,0 +1,32 @@ +"""TiMi_HOK_Game_Translator.utils 子包。""" + +from .sibling_broadcast import ( + broadcast_siblings_by_source, + collapse_by_source, + filter_against_pending, + load_pending_source_pairs, + save_incr_snapshot, +) +# 公共 API 从 2026-10-09 起统一走格式无关版 ``table_merger``。 +# ``dtxml_merger`` 模块仍保留,但其公共函数不再从此处转出—— +# 若有历史代码需要导入老接口,请显式 ``from .dtxml_merger import ...``。 +from .table_merger import ( + delete_entries_from_incremental, + infer_full_table_path, + load_full_table_keys, + merge_incremental_into_full, + split_translated, +) + +__all__ = [ + "broadcast_siblings_by_source", + "collapse_by_source", + "delete_entries_from_incremental", + "filter_against_pending", + "infer_full_table_path", + "load_full_table_keys", + "load_pending_source_pairs", + "merge_incremental_into_full", + "save_incr_snapshot", + "split_translated", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6738f8b67f61f62839fa13a03f6b5e78a1fa47fe Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/sibling_broadcast.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/sibling_broadcast.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50c7b5db4dc109602d659d397a29b715708e042f Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/sibling_broadcast.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/table_merger.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/table_merger.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0456677fd929d20835b873f71e5dc90076ac78ec Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/table_merger.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/think_leak_detector.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/think_leak_detector.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17514b847715c6e9ea200a6bb05786db8af9d0f3 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/__pycache__/think_leak_detector.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/dtxml_merger.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/dtxml_merger.py new file mode 100644 index 0000000000000000000000000000000000000000..ea71bb469fe28091373397bc1aba53916cb23401 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/dtxml_merger.py @@ -0,0 +1,310 @@ +"""DTXML 增量/全量表合并工具。 + +游戏本地化流水线中,待翻译文本通常先放到 **增量表**(如 ``99.*_增量.dtxml``) +处理,翻译完成后需要把这些条目迁移到 **全量表**(如 ``98.*_全量.dtxml``)。 +本模块提供与工作流框架解耦的纯函数实现,可被工作流 state、独立脚本或测试直接复用。 + +对外导出: + - :func:`infer_full_table_path` 由增量表路径推断全量表路径; + - :func:`split_translated` 按 ``target_text`` 划分已/未翻译条目; + - :func:`merge_incremental_into_full` 执行真正的"从增量移到全量"操作; + - :func:`load_full_table_keys` 读全量表的 key 集合(供"今日 incr vs 全量表 + 去重"场景使用); + - :func:`delete_entries_from_incremental` 从增量表删除指定 key 的条目 + (供"命中全量表的今日 incr 条目清理"场景使用)。 +""" + +from __future__ import annotations + +import logging +import re +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple +from xml.etree import ElementTree as ET + +from ..sources.base import Entry +from ..sources.dtxml_source import DtxmlSource + +logger = logging.getLogger(__name__) + +#: 增量表文件名匹配规则(按优先级向下尝试): +#: +#: 1. **英文命名**(推荐):``99.incr.dtxml`` / ``99._incr.dtxml`` / ``99..incr.dtxml`` +#: —— 适用于新项目和跨平台无中文坑的场景; +#: 2. **中文命名**(向后兼容):``99._增量.dtxml`` —— 老项目/线上游戏数据表沿用。 +_INCREMENTAL_PATTERN_EN = re.compile( + r"^(?P\d+)\.(?P.*?)(?:[._])?incr(?P\.dtxml)$", + re.IGNORECASE, +) +_INCREMENTAL_PATTERN_CN = re.compile( + r"^(?P\d+)\.(?P.+?)_增量(?P\.dtxml)$" +) + +#: 默认前缀映射:99(增量)↔ 98(全量) +_DEFAULT_INCREMENT_PREFIX = "99" +_DEFAULT_FULL_PREFIX = "98" + + +def infer_full_table_path(incremental_path: str) -> str: + """由增量表路径推断同目录下的全量表路径。 + + 参数: + incremental_path: 增量表绝对或相对路径。支持两套命名: + + * **英文**:``99.incr.dtxml``、``99.foo_incr.dtxml``、 + ``99.foo.incr.dtxml`` → 推断为 ``98.full.dtxml``、 + ``98.foo_full.dtxml``、``98.foo.full.dtxml``; + * **中文(向后兼容)**:``99._增量.dtxml`` → + ``98._全量.dtxml``。 + + 返回: + 推断出的全量表路径;两套规则都匹配不上时按"把 ``_增量`` 替换为 ``_全量``" + 或 ``_incr`` → ``_full`` 做字符串级退化,仍无法命中时在原 stem 后加 + ``.full`` 扩展。 + """ + p = Path(incremental_path) + stem_with_ext = p.name + + # 优先匹配英文模式(新规则) + m_en = _INCREMENTAL_PATTERN_EN.match(stem_with_ext) + if m_en: + prefix = m_en.group("prefix") + name = m_en.group("name") + new_prefix = _DEFAULT_FULL_PREFIX if prefix == _DEFAULT_INCREMENT_PREFIX else prefix + # 保留 name 和 incr 之间的分隔符风格:优先用原文件名里的分隔符 + # (下划线/点/无)与 "full" 拼接。 + sep = "" + if name: + # 查看原文件名里 incr 前的分隔符 + # 简化策略:如果 name 非空,用 "_";如果 name 空,就直接 "full" + sep = "_" + new_name = f"{new_prefix}.{name}{sep}full{m_en.group('ext')}" + else: + new_name = f"{new_prefix}.full{m_en.group('ext')}" + return str(p.with_name(new_name)) + + # 回退匹配中文模式(向后兼容) + m_cn = _INCREMENTAL_PATTERN_CN.match(stem_with_ext) + if m_cn: + prefix = m_cn.group("prefix") + new_prefix = _DEFAULT_FULL_PREFIX if prefix == _DEFAULT_INCREMENT_PREFIX else prefix + new_name = f"{new_prefix}.{m_cn.group('name')}_全量{m_cn.group('ext')}" + return str(p.with_name(new_name)) + + # 最后退化:字符串级替换 + for src, dst in (("_增量", "_全量"), ("_incr", "_full"), (".incr", ".full")): + if src in stem_with_ext: + return str(p.with_name(stem_with_ext.replace(src, dst))) + + # 兜底:既没匹配到数字前缀,也没找到 _增量 / _incr 子串 + return str(p.with_name(p.stem + ".full" + p.suffix)) + + +def split_translated( + entries: Sequence[Entry], +) -> Tuple[List[Entry], List[Entry]]: + """按 ``target_text`` 是否非空把条目分为已翻译/未翻译两组。 + + 参数: + entries: 原始条目列表。 + 返回: + ``(translated, untranslated)``——元素为原对象引用,不做深拷贝。 + """ + translated: List[Entry] = [] + untranslated: List[Entry] = [] + for e in entries: + if (e.target_text or "").strip(): + translated.append(e) + else: + untranslated.append(e) + return translated, untranslated + + +def _load_dtxml(path: Path, encoding: str = "utf-8") -> Tuple[DtxmlSource, List[Entry]]: + """加载 dtxml 文件;文件不存在时返回空列表但保留默认 root_tag。 + + 参数: + path: dtxml 绝对路径。 + encoding: 文件编码。 + 返回: + ``(source, entries)``——source 对象已记录 root_tag/root_attrib,可直接复用于 dump。 + """ + source = DtxmlSource(encoding=encoding) + if not path.exists(): + logger.info("dtxml_merger: file not found, will create on dump: %s", path) + return source, [] + entries = list(source.load(str(path))) + return source, entries + + +def merge_incremental_into_full( + *, + incremental_path: str, + full_path: Optional[str] = None, + translated_entries: Sequence[Entry], + untranslated_entries: Sequence[Entry], + encoding: str = "utf-8", +) -> Dict[str, object]: + """把已翻译条目从增量表移到全量表(按 ``entry.key``=```` upsert)。 + + 行为: + - 全量表以 ``entry.key``(即 dtxml 的 ```` 字段 / + 简化方言的 ```` 属性)为主键 upsert: + 已存在就覆盖、不存在就插入; + - 增量表只保留 ``untranslated_entries``; + - ``translated_entries`` 为空也会执行(无变更),便于无条件嵌入工作流。 + + 参数: + incremental_path: 增量表绝对路径。 + full_path: 全量表绝对路径;为 ``None`` 时按 :func:`infer_full_table_path` 推断。 + translated_entries: 本轮已翻译条目(写入全量表)。 + untranslated_entries: 本轮未翻译条目(保留在增量表)。 + encoding: dtxml 读写编码,默认 utf-8。 + 返回: + ``{"incremental": str, "full": str, "translated_count": int, "remaining_count": int}``。 + """ + inc_path = Path(incremental_path).resolve() + full = Path(full_path).resolve() if full_path else Path(infer_full_table_path(str(inc_path))) + + # 1) 读全量表(允许不存在,首次会创建) + full_source, full_entries = _load_dtxml(full, encoding=encoding) + + # 2) upsert 已翻译条目到全量表 + full_by_key: Dict[str, Entry] = {e.key: e for e in full_entries} + for te in translated_entries: + full_by_key[te.key] = te + merged_full_entries = list(full_by_key.values()) + + # 3) 写回全量表 + full.parent.mkdir(parents=True, exist_ok=True) + full_source.dump(merged_full_entries, str(full)) + + # 4) 写回增量表(只保留未翻译),尽量继承原文件头 + inc_source = DtxmlSource(encoding=encoding) + if inc_path.exists(): + try: + root = ET.fromstring(inc_path.read_text(encoding=encoding)) + inc_source.extra.setdefault("root_tag", root.tag.rsplit("}", 1)[-1]) + inc_source.extra.setdefault("root_attrib", dict(root.attrib)) + except ET.ParseError: + logger.warning( + "dtxml_merger: incremental table has invalid XML, overwriting: %s", + inc_path, + ) + inc_source.dump(list(untranslated_entries), str(inc_path)) + + return { + "incremental": str(inc_path), + "full": str(full), + "translated_count": len(translated_entries), + "remaining_count": len(untranslated_entries), + } + + +def load_full_table_keys( + full_path: str, + *, + encoding: str = "utf-8", +) -> Set[str]: + """读全量表所有 ``entry.key`` 作为一个集合返回。 + + 用途:translate 阶段用它来判断"今日 incr 的 entry.key 是否已经存在 + 于全量表"——命中则跳过翻译+审核(因为全量表的 Key 唯一性原则: + 同一个 key 只保留一条已审译文)。 + + 参数: + full_path: 全量表的绝对路径。为空或文件不存在均返回**空集合**, + 调用方因此得到"没有命中任何已存在 key"的结果——所有今日 incr + 条目正常走翻译流程(和首日 bootstrap 场景兼容)。 + encoding: 文件编码;一般和 incr 保持一致。 + + 返回: + key 集合(可能为空)。 + """ + if not full_path: + return set() + p = Path(full_path) + if not p.exists(): + return set() + try: + entries = DtxmlSource(encoding=encoding).load(str(p)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "dtxml_merger: load_full_table_keys failed (%s); treating as empty.", + exc, + ) + return set() + return {e.key for e in entries if e.key} + + +def delete_entries_from_incremental( + incremental_path: str, + keys_to_remove: Iterable[str], + *, + encoding: str = "utf-8", +) -> int: + """从增量表删除指定 key 的条目并覆盖写回(继承原文件头)。 + + 用途:translate 阶段把"命中全量表 key"的今日 incr 条目剔除后, + dtxml_merge 调用本函数把这些 key 从磁盘上的 incr 文件物理删掉—— + 否则下次 run 的 pull_vcs 又会把它们捞回来,陷入"每天过滤一次" + 的脏循环。 + + 参数: + incremental_path: 增量表绝对路径。 + keys_to_remove: 要删除的 key 集合(可迭代)。 + encoding: 文件编码。 + + 返回: + 实际被删除的条目数(0 表示 keys 不在 incr 里,无操作)。 + 文件不存在或读取失败时返回 ``0``。 + """ + keys = {str(k) for k in keys_to_remove if k} + if not keys: + return 0 + inc_path = Path(incremental_path) + if not inc_path.exists(): + return 0 + + source = DtxmlSource(encoding=encoding) + try: + entries = source.load(str(inc_path)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "dtxml_merger: delete_entries_from_incremental failed to read %s: %s", + inc_path, exc, + ) + return 0 + + before = len(entries) + kept = [e for e in entries if e.key not in keys] + removed = before - len(kept) + if removed == 0: + return 0 + + # 继承原文件头 + try: + root = ET.fromstring(inc_path.read_text(encoding=encoding)) + source.extra.setdefault("root_tag", root.tag.rsplit("}", 1)[-1]) + source.extra.setdefault("root_attrib", dict(root.attrib)) + except ET.ParseError: + logger.warning( + "dtxml_merger: incremental table has invalid XML header, overwriting: %s", + inc_path, + ) + + source.dump(kept, str(inc_path)) + logger.info( + "dtxml_merger: deleted %d entries from incremental %s (remaining=%d)", + removed, inc_path, len(kept), + ) + return removed + + +__all__ = [ + "infer_full_table_path", + "split_translated", + "merge_incremental_into_full", + "load_full_table_keys", + "delete_entries_from_incremental", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/sibling_broadcast.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/sibling_broadcast.py new file mode 100644 index 0000000000000000000000000000000000000000..d2ea69148bb1a9d5354597ab8fbb5fdc89aa3552 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/sibling_broadcast.py @@ -0,0 +1,337 @@ +"""兄弟行广播(same-source 一译多扩散)与"今日 vs 昨日 pending"去重工具。 + +实现 ``broadcast_siblings_by_origin`` 语义——把同一 ``source_text`` 的译文 +扩散到所有同源行,同时结合昨日 pending 快照做去重: + +* **不依赖 pandas**——直接用 :class:`Entry` dataclass 操作,内存小、单测易写; +* 快照文件沿用 :class:`XlsxSource` 的 ``Key/Source/Target/Context/Comment`` + 列头,便于人工打开排查。 + +典型调用链(在 ``translate`` 和 ``first_review``/``second_review`` 中接入):: + + # translate state 入口: + save_incr_snapshot(ctx.entries, snapshot_path) + # 按语种分区拿 last_tasks.json 路径(profile 多语种时各走各的子目录)。 + last_tasks_json_path = TailTaskStore.path_for(ctx.workspace, lang=_resolve_lang(ctx)) + pending_pairs = load_pending_source_pairs(last_tasks_json_path, stages=("first", "second")) + ctx.entries, overridden = filter_against_pending(ctx.entries, pending_pairs) + ctx.entries, siblings_map = collapse_by_source(ctx.entries) + # ... 翻译 / 审核都只处理代表 ... + + # first_review / second_review 的 split_approved 之后: + ctx.entries = broadcast_siblings_by_source( + approved_entries=ctx.entries, + snapshot_path=snapshot_path, + ) +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +from typing import Iterable, List, Sequence, Set, Tuple + +from ..sources.base import Entry +from ..sources.xlsx_source import XlsxSource + +logger = logging.getLogger(__name__) + +#: 单个 source_text 广播出的兄弟行上限(超过记一次 WARN,不阻塞流程)。 +_SIBLING_BROADCAST_WARN_THRESHOLD = 20 + + +# --------------------------------------------------------------------------- +# 快照 I/O +# --------------------------------------------------------------------------- +def save_incr_snapshot(entries: Sequence[Entry], snapshot_path: Path) -> None: + """把今日 incr 的完整 entries 落盘为 xlsx 快照(含所有兄弟行)。 + + 用途: + * ``translate`` 状态在**去重前**调用,保存今日 incr 的"全量真相"; + * ``first_review`` / ``second_review`` 的 split_approved 后,读这个 + 快照把同 source 的兄弟行回捞合入 approved_entries。 + + 参数: + entries: 今日 incr 的 Entry 列表(**去重前**,含所有兄弟行)。 + snapshot_path: 落盘路径(父目录会被自动创建)。 + """ + snapshot_path.parent.mkdir(parents=True, exist_ok=True) + XlsxSource(encoding="utf-8").dump(list(entries), str(snapshot_path)) + logger.info( + "sibling_broadcast: saved incr snapshot: %d entries → %s", + len(entries), snapshot_path, + ) + + +def load_pending_source_pairs( + last_tasks_json_path: Path, + *, + stages: Iterable[str] = ("first", "second"), +) -> Set[Tuple[str, str]]: + """读 ``workspace/last_tasks.json`` 的指定 slot,返回昨日 pending 的 ``(key, source)`` 集合。 + + 具体做法:对每个 slot 取 ``upload_path``(即昨日 pending.xlsx 的本地路径), + 用 :class:`XlsxSource` 加载后收集 ``(entry.key, entry.source_text)``。 + + 路径不存在或内容为空时静默返回**空集合**(无昨日遗留 ≠ 异常)。 + """ + pairs: Set[Tuple[str, str]] = set() + if not last_tasks_json_path.exists(): + return pairs + try: + raw = json.loads(last_tasks_json_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + logger.warning( + "sibling_broadcast: failed to read %s (%s); treating as no pending.", + last_tasks_json_path, exc, + ) + return pairs + for stage in stages: + slot = raw.get(stage) or {} + upload_path = slot.get("upload_path") or "" + if not upload_path: + continue + p = Path(upload_path) + if not p.exists(): + logger.warning( + "sibling_broadcast: last_tasks.json[%s].upload_path points to a " + "non-existent file %s — ignoring this slot.", + stage, upload_path, + ) + continue + try: + entries = XlsxSource(encoding="utf-8").load(str(p)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "sibling_broadcast: failed to load pending xlsx %s (%s); " + "ignoring this slot.", + p, exc, + ) + continue + for e in entries: + if e.key: + pairs.add((e.key, e.source_text or "")) + logger.info( + "sibling_broadcast: loaded %d pending (key,source) pairs from " + "last_tasks.json[%s] = %s", + len(entries), stage, p.name, + ) + return pairs + + +# --------------------------------------------------------------------------- +# 去重 1:今日 incr 过滤昨日 pending +# --------------------------------------------------------------------------- +def filter_against_pending( + entries: Sequence[Entry], + pending_pairs: Set[Tuple[str, str]], +) -> Tuple[List[Entry], List[Entry]]: + """按 (key, source) 元组和昨日 pending 做一致性比对。 + + 规则(和用户 Q 对齐): + + * **(K, S) ∈ pending_pairs**(key 和 source 都和昨日 pending 完全一致) + → **屏蔽今日这条**(昨日那条 tail task 还在审,等它审完即可, + 避免 Crowdin 侧出现同一个 (key, source) 的两条 task 相互覆盖)。 + * **key 在昨日 pending 但 source 不同** → **保留今日版本**(source 已更新, + 需要重新翻译 + 审核),同时打一条 WARN 日志提示:"今日 K 覆盖了 + 昨日 pending 的旧 source"。昨日的那条旧 task 仍在 Crowdin 继续审, + 审完后 approved 进 carry_over 时上游会按 (key, source) 兜底丢弃 + —— 保守方案 Q1-A(不主动去 Crowdin 侧撤销)。 + * **key 不在昨日 pending** → 保留今日版本。 + + 返回: + ``(kept, dropped)`` —— ``kept`` 是继续走流程的 entries; + ``dropped`` 是因 Rule 2a 命中而被屏蔽的今日条目(只用于日志,不扩散)。 + """ + if not pending_pairs: + return list(entries), [] + pending_keys = {k for k, _ in pending_pairs} + + kept: List[Entry] = [] + dropped: List[Entry] = [] + for e in entries: + pair = (e.key, e.source_text or "") + if pair in pending_pairs: + # Rule 2a:(key, source) 完全一致 → 屏蔽今日版本。 + dropped.append(e) + continue + if e.key in pending_keys: + # Rule 2b:同 key 但 source 变了 → 保留今日版本 + WARN。 + logger.warning( + "sibling_broadcast: key=%r source changed vs yesterday's " + "pending (today will override). Yesterday's tail task will " + "still live on Crowdin side; its late-approved result (if any) " + "will be dropped by carry-over source check.", + e.key, + ) + kept.append(e) + if dropped: + logger.info( + "sibling_broadcast: filtered against yesterday's pending: " + "%d → %d entries (dropped %d because (key, source) is still being " + "reviewed in a tail task).", + len(entries), len(kept), len(dropped), + ) + return kept, dropped + + +# --------------------------------------------------------------------------- +# 去重 2:按 source_text 分组,每组保留第一条代表 +# --------------------------------------------------------------------------- +def collapse_by_source( + entries: Sequence[Entry], +) -> Tuple[List[Entry], int]: + """按 ``source_text`` 分组,每组**保留第一条**作代表,其余作为兄弟剔除。 + + 兄弟不额外存"map"——它们在**快照文件**里备着,审完后由 + :func:`broadcast_siblings_by_source` 回捞扩散。 + + 返回: + ``(representatives, collapsed_count)``: + * ``representatives`` 是去重后的代表列表; + * ``collapsed_count`` 是被折叠掉的兄弟总数(仅用于日志)。 + + 边界: + * 空 source_text 的 entry 视为**独立组**(不与其他空 source 合并)。 + 空 source 的翻译无意义,但有 key 的条目保留以免下游处理崩溃。 + """ + seen_sources: Set[str] = set() + representatives: List[Entry] = [] + collapsed = 0 + for e in entries: + src = e.source_text or "" + if not src: + # 空 source:原样保留,不参与去重分组。 + representatives.append(e) + continue + if src in seen_sources: + collapsed += 1 + continue + seen_sources.add(src) + representatives.append(e) + if collapsed: + logger.info( + "sibling_broadcast: collapsed same-source entries: %d → %d " + "(folded %d siblings into representatives).", + len(entries), len(representatives), collapsed, + ) + return representatives, collapsed + + +# --------------------------------------------------------------------------- +# 扩散:审完后把 approved 的 target_text 复制给同 source 的兄弟 +# --------------------------------------------------------------------------- +def broadcast_siblings_by_source( + approved_entries: Sequence[Entry], + snapshot_path: Path, + *, + warn_threshold: int = _SIBLING_BROADCAST_WARN_THRESHOLD, +) -> List[Entry]: + """从快照回捞兄弟行,用 approved_entries 的 target 覆盖兄弟的 target。 + + 参数: + approved_entries: 代表审完后的 approved entries(已经从 approved.xlsx + 读回最新 target 的 ctx.entries)。 + snapshot_path: :func:`save_incr_snapshot` 落盘的快照 xlsx 路径。 + warn_threshold: 单 source 兄弟数超阈值记一次 WARN(不阻塞)。 + + 返回: + 扩散后的 Entry 列表:approved_entries 原样 + 同 source 的兄弟(target + 复制自代表)。按 ``key`` 去重防御式保证唯一。 + + 边界: + * approved_entries 为空 → 返回空列表(本轮审没通过任何代表); + * 快照不存在/读失败 → 返回 approved_entries 原样 + WARN; + * 兄弟的 source 对应的代表没在 approved_entries 里 → 跳过(代表没通过, + 兄弟也不扩散,交给下次 run 的 tail task 续审)。 + """ + if not approved_entries: + logger.info( + "sibling_broadcast: approved_entries is empty — nothing to broadcast.", + ) + return [] + if not snapshot_path.exists(): + logger.warning( + "sibling_broadcast: snapshot %s not found; skipping sibling " + "broadcast (approved=%d).", + snapshot_path, len(approved_entries), + ) + return list(approved_entries) + + try: + snapshot_entries = XlsxSource(encoding="utf-8").load(str(snapshot_path)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "sibling_broadcast: failed to load snapshot %s (%s); skipping.", + snapshot_path, exc, + ) + return list(approved_entries) + + # 1) 代表 source → approved 的 target + approved_target_by_source = {} + approved_by_key = {} + for e in approved_entries: + approved_by_key[e.key] = e + src = e.source_text or "" + if src and e.target_text and src not in approved_target_by_source: + approved_target_by_source[src] = e.target_text + + if not approved_target_by_source: + logger.info( + "sibling_broadcast: approved_entries have no (source, target) " + "pairs — nothing to broadcast (approved=%d).", + len(approved_entries), + ) + return list(approved_entries) + + # 2) 从快照里挑出"同 source 但 key 不在 approved_entries 里"的兄弟。 + siblings: List[Entry] = [] + sibling_count_by_source: dict = {} + for e in snapshot_entries: + src = e.source_text or "" + if not src or src not in approved_target_by_source: + continue + if e.key in approved_by_key: + continue # 已经在 approved 里了,不重复 + # 克隆一份,sibling 的 target 覆盖为代表的译文。 + sibling = Entry( + key=e.key, + source_text=e.source_text, + target_text=approved_target_by_source[src], + context=e.context, + comment=e.comment, + metadata=dict(e.metadata or {}), + ) + siblings.append(sibling) + sibling_count_by_source[src] = sibling_count_by_source.get(src, 0) + 1 + + # 3) 超阈值 WARN。 + for src, cnt in sibling_count_by_source.items(): + if cnt > warn_threshold: + logger.warning( + "sibling_broadcast: source has %d siblings (threshold=%d); " + "all will be broadcast but please verify this is intended. " + "source preview=%r", + cnt, warn_threshold, (src[:60] + "..." if len(src) > 60 else src), + ) + + result = list(approved_entries) + siblings + if siblings: + logger.info( + "sibling_broadcast: broadcast complete: approved=%d + siblings=%d " + "= %d total (sources=%d).", + len(approved_entries), len(siblings), len(result), + len(approved_target_by_source), + ) + return result + + +__all__ = [ + "save_incr_snapshot", + "load_pending_source_pairs", + "filter_against_pending", + "collapse_by_source", + "broadcast_siblings_by_source", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/table_merger.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/table_merger.py new file mode 100644 index 0000000000000000000000000000000000000000..a484f0e74a9fd51624761659eede00335bdf12c8 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/table_merger.py @@ -0,0 +1,301 @@ +"""通用增量/全量表合并工具(格式无关版)。 + +与 :mod:`TiMi_HOK_Game_Translator.utils.dtxml_merger` 的区别——本模块**不绑定 dtxml**, +而是通过 :class:`~TiMi_HOK_Game_Translator.sources.base.LocalizationSource` 协议抽象, +对任何已注册的 source 格式(dtxml / json / xliff / xlsx / csv / yaml / xml) +都能通用执行"按 key upsert 全量表、从增量表删除指定 keys、读取全量表 +key 集合"等操作。 + +设计原则: + * **只依赖 ``LocalizationSource`` 接口**——不假设任何格式细节; + * **文件头/元数据的保留由各 source 的 load/dump 自行负责**; + * **文件名推断支持任意扩展名**:``99.incr.`` → ``98.full.``, + 同时向后兼容老 dtxml 的中文命名 ``99._增量.dtxml`` → + ``98._全量.dtxml``。 + +对外导出: + - :func:`infer_full_table_path` + - :func:`split_translated` + - :func:`merge_incremental_into_full` + - :func:`load_full_table_keys` + - :func:`delete_entries_from_incremental` +""" + +from __future__ import annotations + +import logging +import re +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple + +from ..sources.base import Entry, LocalizationSource + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# 文件名推断 +# --------------------------------------------------------------------------- +#: 英文命名(通用、推荐,支持任意扩展名): +#: +#: 99.incr.dtxml → 98.full.dtxml +#: 99.incr.json → 98.full.json +#: 99.foo_incr.xliff → 98.foo_full.xliff +#: 99.foo.incr.yaml → 98.foo.full.yaml +_INCREMENTAL_PATTERN_EN = re.compile( + r"^(?P\d+)\.(?P.*?)(?:[._])?incr(?P\.[A-Za-z0-9]+)$", + re.IGNORECASE, +) + +#: 中文命名(向后兼容老 dtxml 项目): +#: +#: 99._增量.dtxml → 98._全量.dtxml +_INCREMENTAL_PATTERN_CN = re.compile( + r"^(?P\d+)\.(?P.+?)_增量(?P\.[A-Za-z0-9]+)$" +) + +_DEFAULT_INCREMENT_PREFIX = "99" +_DEFAULT_FULL_PREFIX = "98" + + +def infer_full_table_path(incremental_path: str) -> str: + """从增量表路径推断同目录下的全量表路径(格式无关)。 + + 支持的命名: + + * **英文(通用)**:任意扩展名 + - ``99.incr.`` → ``98.full.`` + - ``99._incr.`` → ``98._full.`` + - ``99..incr.`` → ``98..full.`` + * **中文(dtxml 向后兼容)**: + - ``99._增量.`` → ``98._全量.`` + + 匹配不到两套规则时,按字符串级替换 ``_增量``→``_全量`` / + ``_incr``→``_full`` / ``.incr``→``.full``;仍然无法命中时在 + 原 stem 后加 ``.full``。 + + 参数: + incremental_path: 增量表绝对或相对路径。 + 返回: + 推断出的全量表路径(字符串)。 + """ + p = Path(incremental_path) + stem_with_ext = p.name + + # 优先匹配英文模式 + m_en = _INCREMENTAL_PATTERN_EN.match(stem_with_ext) + if m_en: + prefix = m_en.group("prefix") + name = m_en.group("name") + new_prefix = _DEFAULT_FULL_PREFIX if prefix == _DEFAULT_INCREMENT_PREFIX else prefix + if name: + new_name = f"{new_prefix}.{name}_full{m_en.group('ext')}" + else: + new_name = f"{new_prefix}.full{m_en.group('ext')}" + return str(p.with_name(new_name)) + + # 回退:中文模式 + m_cn = _INCREMENTAL_PATTERN_CN.match(stem_with_ext) + if m_cn: + prefix = m_cn.group("prefix") + new_prefix = _DEFAULT_FULL_PREFIX if prefix == _DEFAULT_INCREMENT_PREFIX else prefix + new_name = f"{new_prefix}.{m_cn.group('name')}_全量{m_cn.group('ext')}" + return str(p.with_name(new_name)) + + # 字符串级退化 + for src, dst in (("_增量", "_全量"), ("_incr", "_full"), (".incr", ".full")): + if src in stem_with_ext: + return str(p.with_name(stem_with_ext.replace(src, dst))) + + # 兜底 + return str(p.with_name(p.stem + ".full" + p.suffix)) + + +# --------------------------------------------------------------------------- +# 条目划分 +# --------------------------------------------------------------------------- +def split_translated( + entries: Sequence[Entry], +) -> Tuple[List[Entry], List[Entry]]: + """按 ``target_text`` 是否非空把条目分为已翻译/未翻译两组。 + + 参数: + entries: 原始条目列表。 + 返回: + ``(translated, untranslated)``——元素为原对象引用,不做深拷贝。 + """ + translated: List[Entry] = [] + untranslated: List[Entry] = [] + for e in entries: + if (e.target_text or "").strip(): + translated.append(e) + else: + untranslated.append(e) + return translated, untranslated + + +# --------------------------------------------------------------------------- +# 核心:upsert 全量表 + 精简增量表 +# --------------------------------------------------------------------------- +def merge_incremental_into_full( + *, + source: LocalizationSource, + incremental_path: str, + full_path: Optional[str] = None, + translated_entries: Sequence[Entry], + untranslated_entries: Sequence[Entry], +) -> Dict[str, object]: + """按 ``entry.key`` 把已翻译条目从增量表 upsert 到全量表(格式无关)。 + + 行为: + * 读旧全量表(文件不存在视为空); + * 已存在的 key 覆盖、不存在的插入; + * 写回全量表(含上述合并结果); + * 增量表只保留 ``untranslated_entries`` 并写回; + * ``translated_entries`` 为空也会执行(增量表仍会被重写一次, + 便于清掉"删除 shadowed"后的空壳),返回 ``translated_count=0``。 + + 参数: + source: 从 :attr:`WorkflowContext.source` 传入的 source 实例, + 读写都用它——确保增量表和全量表共享文件头/元数据语义。 + incremental_path: 增量表绝对路径。 + full_path: 全量表路径;``None`` 时按 :func:`infer_full_table_path` 推断。 + translated_entries: 本轮已翻译条目(写入全量表)。 + untranslated_entries: 本轮未翻译条目(保留在增量表)。 + 返回: + ``{"incremental": str, "full": str, "translated_count": int, + "remaining_count": int}``。 + """ + inc_path = Path(incremental_path).resolve() + full = Path(full_path).resolve() if full_path else Path( + infer_full_table_path(str(inc_path)) + ) + + # 1) 读旧全量表(允许不存在) + full_entries: List[Entry] = [] + if full.exists(): + try: + full_entries = list(source.load(str(full))) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "table_merger: failed to load full table %s (%s); " + "treating as empty.", + full, exc, + ) + full_entries = [] + else: + logger.info("table_merger: full table not found, will create: %s", full) + + # 2) upsert:translated 覆盖同 key 的旧 entry + by_key: Dict[str, Entry] = {e.key: e for e in full_entries} + for te in translated_entries: + by_key[te.key] = te + merged_full_entries = list(by_key.values()) + + # 3) 写回全量表 + full.parent.mkdir(parents=True, exist_ok=True) + source.dump(merged_full_entries, str(full)) + + # 4) 写回增量表(只保留未翻译) + source.dump(list(untranslated_entries), str(inc_path)) + + return { + "incremental": str(inc_path), + "full": str(full), + "translated_count": len(translated_entries), + "remaining_count": len(untranslated_entries), + } + + +# --------------------------------------------------------------------------- +# 全量表 key 集合(供 translate 阶段去重用) +# --------------------------------------------------------------------------- +def load_full_table_keys( + source: LocalizationSource, + full_path: str, +) -> Set[str]: + """读全量表所有 ``entry.key`` 作为一个集合返回(格式无关)。 + + 用途:``translate`` 阶段判断"今日 incr 的 entry.key 是否已经存在于 + 全量表"——命中则跳过翻译+审核。 + + 参数: + source: 用于读全量表的 source 实例。 + full_path: 全量表绝对路径;为空或文件不存在均返回**空集合**。 + 返回: + key 集合(可能为空)。 + """ + if not full_path: + return set() + p = Path(full_path) + if not p.exists(): + return set() + try: + entries = source.load(str(p)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "table_merger: load_full_table_keys failed (%s); treating as empty.", + exc, + ) + return set() + return {e.key for e in entries if e.key} + + +# --------------------------------------------------------------------------- +# 从增量表物理删除指定 keys +# --------------------------------------------------------------------------- +def delete_entries_from_incremental( + source: LocalizationSource, + incremental_path: str, + keys_to_remove: Iterable[str], +) -> int: + """从增量表删除指定 key 的条目并覆盖写回(格式无关)。 + + 用途:``translate`` 阶段把"命中全量表 key"的今日 incr 条目剔除后, + ``merge_data`` 调用本函数把这些 key 从磁盘上的 incr 文件物理删掉—— + 否则下次 run 的 pull_vcs 又会把它们捞回来。 + + 参数: + source: 用于读写增量表的 source 实例。 + incremental_path: 增量表绝对路径。 + keys_to_remove: 要删除的 key 集合(可迭代)。 + 返回: + 实际被删除的条目数(0 表示 keys 不在 incr 里,无操作)。 + 文件不存在或读取失败时返回 ``0``。 + """ + keys = {str(k) for k in keys_to_remove if k} + if not keys: + return 0 + inc_path = Path(incremental_path) + if not inc_path.exists(): + return 0 + + try: + entries = source.load(str(inc_path)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "table_merger: delete_entries_from_incremental failed to read %s: %s", + inc_path, exc, + ) + return 0 + + before = len(entries) + kept = [e for e in entries if e.key not in keys] + removed = before - len(kept) + if removed == 0: + return 0 + + source.dump(kept, str(inc_path)) + logger.info( + "table_merger: deleted %d entries from incremental %s (remaining=%d)", + removed, inc_path, len(kept), + ) + return removed + + +__all__ = [ + "infer_full_table_path", + "split_translated", + "merge_incremental_into_full", + "load_full_table_keys", + "delete_entries_from_incremental", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/think_leak_detector.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/think_leak_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..8040b172b51755b55bef498f3ef41154d82fddf2 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/think_leak_detector.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +""" +思考过程外露检测器(纯检测,无副作用,仅依赖标准库) + +用途 +---- +翻译工具链在拿到模型返回后调用本模块;若判定为「思考过程外露」, +调用方丢弃本次结果并重新请求模型。 + +设计目标:**宁可漏判,不可误判** +------------------------------------ +误判的代价远大于漏判:误判会把正常译文丢掉并重复请求, +而漏判只是少拦一条、可由人工兜底。因此: + +1. 分级打分,弱信号单独出现不判定,必须与其他信号叠加; +2. 所有标记都做「源文反查」——若源文本身含该标记(例如游戏文案里 + 本来就有 "Note:"、"Final:"),一律不计分; +3. 对易误伤词做了严格约束(详见 `_FALSE_POSITIVE_NOTES`)。 + +适配模型 +-------- +混元 Hy-MT2 系 A3B_MoE_RL_* 游戏翻译模型。该系列已知问题: +SFT 语料混入 bad pattern,RL 阶段被放大(reward hack),表现为 +「先给出正确译文 → 随后自我点评/反复改写 → 直到 max_tokens 截断」。 + +实测触发率(5220 条 × 14 语种 = 73080 格): + 中文源 0.003% ~ 0.016% + 英文源 0.017% ~ 0.019% + 英文源发生率约为中文源的 5 倍。 + +关键特征:注释块会跟随**目标语言**本地化,而非固定英文。 +已覆盖:Note / Nota / Notă / Remarque / Hinweis / Catatan / Not / + Примечание / ملاحظة / 注 / 주석 / หมายเหตุ / Ghi chú + +用法 +---- + from think_leak_detector import detect, is_leaked + + r = detect(translation, source_text=src, target_lang='ar') + if r.leaked: + logger.warning('思考过程外露,重试: %s', r.describe()) + # 重新请求模型 + + # 或极简用法 + if is_leaked(translation, src): + ... + +命令行自检: + python think_leak_detector.py --selftest +""" + +from __future__ import annotations + +import re +import unicodedata +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +__all__ = ['detect', 'is_leaked', 'DetectionResult', 'DetectorConfig'] + +# =========================================================================== +# 一、判定阈值 +# =========================================================================== + +# 计分规则:命中项得分累加,总分 >= THRESHOLD_LEAKED 判定为外露。 +SCORE_DECISIVE = 100 # 决定性证据,单条即可判定 +SCORE_STRONG = 60 # 强证据,单条即可判定 +SCORE_MEDIUM = 35 # 中等证据,需与其他证据叠加 +SCORE_WEAK = 20 # 弱证据,仅作佐证,两条弱证据不足以判定 +THRESHOLD_LEAKED = 60 + +# 短文本不参与长度比/重复度判断,避免「绿茵宝贝面饰」这类短词误伤 +MIN_LEN_FOR_RATIO = 200 +MIN_LEN_FOR_REPEAT = 400 + +# 译文/源文长度比超过该倍数视为异常膨胀。 +# 实测各语种正常中位比:中文源 ≈ 1.0~3.5,英文源 ≈ 1.0~1.3, +# 取 6 倍留足余量(阿拉伯语、俄语等天然偏长)。 +DEFAULT_RATIO_LIMIT = 6.0 + +# 各目标语种相对「中文源文」的正常长度比上限(粗粒度,宁松勿紧) +_RATIO_LIMIT_BY_LANG = { + 'en': 8.0, 'vi': 9.0, 'th': 7.0, 'id': 8.0, 'zh-Hant': 3.0, + 'fr': 9.0, 'de': 8.0, 'ru': 8.0, 'ja': 4.0, 'pt-BR': 9.0, + 'ko': 4.0, 'ar': 8.0, 'es': 9.0, 'tr': 8.0, +} +# 英文源(en → 小语种)时,源文已是英文,正常比值接近 1,收紧到 4 倍 +_RATIO_LIMIT_EN_PIVOT = 4.0 + + +# =========================================================================== +# 二、规则库 +# =========================================================================== +# +# 命名约定: +# _RE_* -> 已编译正则 +# 每条规则形如 (正则, 得分, 说明) +# +# 注意:凡是可能出现在正常游戏文案中的词,一律不单独使用, +# 必须加位置约束(行首/行尾)或结构约束(Markdown 粗体、括号块)。 + +# --- A. 决定性证据 ---------------------------------------------------------- + +# A1. 显式思考标签。任何情况下出现都是泄漏。 +_RE_THINK_TAG = re.compile(r'||', re.I) + +# A2. 本地化注释块。模型自评时固定写成 `*(Note: ...)` / `*(Catatan: ...)`, +# Markdown 星号 + 左括号 + 注释词 的组合在正常译文中几乎不可能出现。 +_NOTE_WORDS = ( + r'Note|Nota|Notă|Noto|Remarque|Hinweis|Anmerkung|Catatan|Not|Nota Bene|' + r'Примечание|Прим|ملاحظة|ملحوظة|注|註|注记|注記|주석|참고|หมายเหตุ|Ghi chú|Lưu ý' +) +_RE_NOTE_BLOCK = re.compile( + r'\*\s*\(\s*(?:' + _NOTE_WORDS + r')\b' # *(Note / * (Catatan + r'|\(\s*(?:' + _NOTE_WORDS + r')\s*[::]', # (Note: / (Примечание: + re.I | re.U, +) + +# A3. Markdown 粗体包裹的「最终答案」标题——纯粹的元叙述结构。 +_RE_FINAL_HEADER = re.compile( + r'\*\*\s*(?:Final|Final\s+Answer|Final\s+Translation|Final\s+Version|' + r'Correct(?:ed)?\s+Translation|Translation|Answer|Output|Result)\b[^*\n]{0,40}\*\*' + r'|\*\*\s*(?:Note|Correction|Hinweis|Nota|Примечание)\s*[::]?\s*\*\*', + re.I, +) + +# A4. 输出终止标记。模型"写完了"的自我声明。 +_RE_END_MARKER = re.compile( + r'^\s*(?:\[End\]|\[END\]|End of (?:output|translation|text)\.?|' + r'<\s*/?\s*end\s*>)\s*$', + re.M, +) + +# A5. 显式自我纠错标题(行首 + 冒号,排除正文中的 "correction" 名词用法) +_RE_CORRECTION_HEADER = re.compile( + r'^\s*(?:\*+\s*)?(?:Correction|Corrected|Revised|Rewritten|Update)\s*[::]', + re.M, +) + +_DECISIVE_RULES: List[Tuple[re.Pattern, int, str]] = [ + (_RE_THINK_TAG, SCORE_DECISIVE, '显式思考标签()'), + (_RE_NOTE_BLOCK, SCORE_DECISIVE, '本地化注释块(*(Note/Catatan/ملاحظة...))'), + (_RE_FINAL_HEADER, SCORE_DECISIVE, 'Markdown最终答案标题(**Final**)'), + (_RE_END_MARKER, SCORE_DECISIVE, '输出终止标记([End]/End of output)'), + (_RE_CORRECTION_HEADER, SCORE_DECISIVE, '自我纠错标题(Correction:)'), +] + +# --- B. 强证据:第一人称元叙述 ---------------------------------------------- +# +# 这些短语的主语是"模型自己",在游戏文案(角色台词、道具描述、UI)中 +# 出现的概率极低。但仍做了收紧: +# * "I'll" 后必须接提交/撰写类动词,排除台词 "I'll go look for quests" +# * "put" 必须带 "it/that/this",排除叙事 "I will put an end to this" +# * "Let me" 后必须接复核类动词,排除台词 "Let me help you" + +_RE_FIRST_PERSON_META = re.compile( + r"\bI(?:'ll| will| am going to| shall)\s+" + r"(?:just\s+)?(?:go\s+with|stick\s+with|stick\s+to|submit|finalize|" + r"provide\s+(?:the|that|this|it)|write\s+(?:that|this|it)\b|" + r"put\s+(?:that|this|it)\b|use\s+(?:that|this|it|the)|" + r"keep\s+(?:that|this|it)|accept\s+(?:that|this|it)|output\s+(?:that|this|it))\b" + r"|\bI\s+(?:submit|accept)\s+(?:that|this|it)\b" + r"|^\s*I\s+submit\.?\s*$" + r"|\bLet\s+me\s+(?:re-?check|recheck|verify|re-?read|reconsider|re-?examine|" + r"try\s+again|correct\s+(?:that|this|it)|fix\s+(?:that|this|it)|redo|rewrite)\b", + re.M, +) + +# B1b. "But wait" / "Wait—" 单独出现时可能是角色台词 +# (实测误判:"Alright, all set this time. Wait—I... I forgot to lock the door..."), +# 故降为中等证据,必须与其他信号叠加才判定。 +_RE_WAIT_HESITATION = re.compile( + r"(?:^|[.!?;:—\-\n]\s*)But\s+wait\b" + r"|\bWait\s*[,—–-]\s*(?:the\s+(?:original|source|user)|that'?s\s+not|" + r"no\s*[,.]|actually|I\s+(?:need|should|must|think))\b", + re.M | re.I, +) + +# B2. 谈论"原文/译文/用户指令"——把翻译任务本身当成话题。 +_RE_TASK_TALK = re.compile( + r"\boriginal\s+(?:text|Chinese|English|sentence|phrase|string)\s+" + r"(?:says|said|is|was|has|have|uses|reads|seems|appears|contains)\b" + r"|\bthe\s+(?:translat(?:ion|ed\s+\w+)|output|result)\s+(?:is|should|would|must)\s+" + r"(?:be|now|correct|final|as)\b" + r"|\btranslated\s+result\s+is\b" + r"|\bIf\s+the\s+user\s+(?:intended|meant|wants|wanted|prefers)\b" + r"|\b(?:per|following|as\s+per)\s+(?:the\s+)?user'?s?\s+instructions?\b" + r"|\bthe\s+user'?s?\s+(?:instruction|request|requirement)s?\b", + re.I, +) + +# B3. 本地化的「最终版本是:」句式(俄/阿/德/法/西/葡/印尼) +_RE_FINAL_LOCALIZED = re.compile( + r'^\s*(?:Final|Итог(?:овый)?\s*(?:перевод|вариант)|' + r'الترجمة\s+النهائية|Endgültige\s+Übersetzung|Traduction\s+finale|' + r'Traducción\s+final|Tradução\s+final|Terjemahan\s+akhir)\s*[::]\s*$', + re.M | re.I, +) + +_STRONG_RULES: List[Tuple[re.Pattern, int, str]] = [ + (_RE_FIRST_PERSON_META, SCORE_STRONG, '第一人称元叙述(I\'ll go with/Let me recheck)'), + (_RE_TASK_TALK, SCORE_STRONG, '谈论原文或用户指令(original text says/user instruction)'), + (_RE_FINAL_LOCALIZED, SCORE_STRONG, '本地化最终版本标题'), +] + +# --- C. 中等证据 ------------------------------------------------------------ + +# C1. 中文思考词(源自仓库 json_translation_main.py 的 THINKING_KEYWORDS, +# 但**大幅收紧**:原版含"注""即""可能""需要"等单字/常用词, +# 在游戏文案中误报极高,此处只保留元叙述性强的多字组合, +# 且仅在「目标语种非中日繁」时启用)。 +_RE_CN_META = re.compile( + r'原文(?:的意思|中|是指|应该|可能|似乎|有误|写作)' + r'|译文(?:应该|应为|改为|如下|为[::])' + r'|翻译(?:成|为)?(?:如下|结果如下)' + r'|这里(?:应该|需要|可能)(?:翻译|译|改)' + r'|(?:最终|最后)(?:的)?(?:译文|翻译|版本|答案)\s*[::]' + r'|注意[::]\s*(?:原文|译文|这里|此处)' + r'|(?:我|咱们)(?:会|将|应该|需要)(?:使用|采用|保留|改成)' +) + +# C2. 译文结尾处的括号说明块(紧贴结尾、以括号包裹、含注释词) +_RE_TRAILING_PAREN_NOTE = re.compile( + r'[\n\r]\s*[((][^(())]{0,20}(?:' + _NOTE_WORDS + r')\b[^(())]{0,400}[))]\s*$', + re.I | re.U, +) + +_MEDIUM_RULES: List[Tuple[re.Pattern, int, str]] = [ + (_RE_TRAILING_PAREN_NOTE, SCORE_MEDIUM, '结尾括号注释块'), + (_RE_WAIT_HESITATION, SCORE_MEDIUM, '犹豫式转折(But wait/Wait—)'), +] + +# --- D. 结构性弱证据(长度膨胀、自我重复)在函数内动态计算 ------------------ + +_FALSE_POSITIVE_NOTES = """ +以下词**故意不作为独立判据**,因为实测会误伤正常游戏文案: + actually -> "is actually the most distinctive form of drama" + hmm / Hmm -> 角色台词拟声词 "Ha hmm... He said your head..." + the user -> 技能描述 "the user's damage output is reduced by 30%" + wait -> 台词 "wait for me" + final: -> 西语/葡语正文 "el efecto final:" / "o efeito final:" + Note: -> 原文「注意:」的正常翻译(已由源文反查排除) + explanation / instruction -> 游戏帮助文案高频词 +""" + + +# =========================================================================== +# 三、配置与结果结构 +# =========================================================================== + +@dataclass +class DetectorConfig: + """检测器配置。默认值已按「宁漏勿误」调校,一般无需修改。""" + threshold: int = THRESHOLD_LEAKED + enable_length_ratio: bool = True + enable_repetition: bool = True + enable_cn_meta: bool = True + ratio_limit: Optional[float] = None # None -> 按语种自动取 + min_len_for_ratio: int = MIN_LEN_FOR_RATIO + min_len_for_repeat: int = MIN_LEN_FOR_REPEAT + # 目标语种为这些时,跳过中文元叙述检测(译文本身就是中日文) + cn_meta_skip_langs: Tuple[str, ...] = ( + 'zh-Hant', 'zh-Hans', 'zh', 'ja', '繁体中文', '日语', + 'Traditional Chinese', 'Japanese', + ) + + +@dataclass +class Evidence: + rule: str + score: int + sample: str = '' + + +@dataclass +class DetectionResult: + leaked: bool + score: int + evidences: List[Evidence] = field(default_factory=list) + length_ratio: Optional[float] = None + text_len: int = 0 + source_len: int = 0 + + @property + def confidence(self) -> str: + if self.score >= SCORE_DECISIVE: + return 'high' + if self.score >= THRESHOLD_LEAKED: + return 'medium' + return 'none' + + @property + def reasons(self) -> List[str]: + return [e.rule for e in self.evidences] + + def describe(self) -> str: + if not self.evidences: + return '未检出' + parts = [] + for e in self.evidences: + s = f'{e.rule}(+{e.score})' + if e.sample: + s += f' 样例={e.sample!r}' + parts.append(s) + head = f'score={self.score} conf={self.confidence} len={self.text_len}' + if self.length_ratio is not None: + head += f' ratio={self.length_ratio:.1f}' + return head + ' | ' + '; '.join(parts) + + def __bool__(self) -> bool: + return self.leaked + + +# =========================================================================== +# 四、内部工具 +# =========================================================================== + +def _norm(s) -> str: + if s is None: + return '' + if not isinstance(s, str): + # 容忍 float('nan') / None 等脏数据 + try: + import math + if isinstance(s, float) and math.isnan(s): + return '' + except Exception: # pylint: disable=broad-except + pass + s = str(s) + return s + + +def _strip_markup(s: str) -> str: + """去掉富文本标签与占位符,避免标签内容干扰长度与重复判断。""" + s = re.sub(r'<[^<>\n]{0,80}>', '', s) + s = re.sub(r'\{[^{}\n]{0,80}\}', '', s) + s = re.sub(r'%[sd]|\\n|_x000D_', ' ', s) + return s + + +def _in_source(sample: str, source_norm: str) -> bool: + """源文反查:若该片段在源文中已存在,则不是模型添加的元叙述。""" + if not source_norm or not sample: + return False + return sample.strip().lower() in source_norm + + +def _match_rules(text: str, source_norm: str, + rules: List[Tuple[re.Pattern, int, str]]) -> List[Evidence]: + out = [] + for pat, score, name in rules: + m = pat.search(text) + if not m: + continue + sample = m.group(0).strip() + if len(sample) > 60: + sample = sample[:60] + '…' + if _in_source(sample, source_norm): + continue + out.append(Evidence(name, score, sample)) + return out + + +def _repetition_ratio(text: str, min_len: int = MIN_LEN_FOR_REPEAT) -> float: + """ + 自我重复度:模型反复改写时,同一段落会出现多次。 + 返回最长重复片段占全文的比例(0~1)。 + + min_len 可下调,用于「源文反查」——源文往往比译文短, + 但只要它自身就是重复文案,译文的重复就是忠实翻译。 + """ + s = re.sub(r'\s+', ' ', text).strip() + n = len(s) + if n < min_len: + return 0.0 + seg_len = max(40, min(240, n // 4)) + best = 0.0 + # 密集采样:按 1/8 文长步进扫描,覆盖「首段不同但正文重复」的情况 + step = max(20, seg_len // 2) + for start in range(0, max(1, n - seg_len), step): + seg = s[start:start + seg_len] + if len(seg) < seg_len: + break + cnt = s.count(seg) + if cnt >= 2: + best = max(best, (cnt * seg_len) / n) + if best >= 0.9: + break + return best + + +def _ratio_limit_for(target_lang: Optional[str], src_lang: str, + cfg: DetectorConfig) -> float: + if cfg.ratio_limit is not None: + return cfg.ratio_limit + if src_lang == 'en': + return _RATIO_LIMIT_EN_PIVOT + if target_lang and target_lang in _RATIO_LIMIT_BY_LANG: + return _RATIO_LIMIT_BY_LANG[target_lang] + return DEFAULT_RATIO_LIMIT + + +def _looks_truncated(text: str) -> bool: + """被 max_tokens 截断的典型特征:结尾没有任何终止标点。""" + tail = text.rstrip() + if len(tail) < MIN_LEN_FOR_RATIO: + return False + last = tail[-1] + if last in '.!?。!?」』"\'))]】>…·::;;,,': + return False + return unicodedata.category(last)[0] in ('L', 'N') + + +# =========================================================================== +# 五、主入口 +# =========================================================================== + +def detect(translation, + source_text=None, + target_lang: Optional[str] = None, + src_lang: str = 'zh', + config: Optional[DetectorConfig] = None) -> DetectionResult: + """ + 检测译文中是否外露了模型的思考过程。 + + Args: + translation : 模型返回的译文(必填) + source_text : 本次请求送进去的源文。强烈建议传入—— + 用于「源文反查」,可显著降低误判。 + 英文源(en→小语种)时请传英文源文,而非中文原文。 + target_lang : 目标语种代码,如 'ar' / 'pt-BR'。用于选择长度比阈值 + 及决定是否启用中文元叙述检测。 + src_lang : 'zh'(中文源)或 'en'(英文源/以英文为轴)。 + config : 可选,覆盖默认阈值。 + + Returns: + DetectionResult;`result.leaked` 为 True 时建议丢弃并重试。 + """ + cfg = config or DetectorConfig() + text = _norm(translation) + source = _norm(source_text) + + res = DetectionResult(leaked=False, score=0, text_len=len(text), + source_len=len(source)) + if not text.strip(): + return res + + source_norm = source.lower() + evidences: List[Evidence] = [] + + # --- A/B/C 文本规则 --- + evidences += _match_rules(text, source_norm, _DECISIVE_RULES) + evidences += _match_rules(text, source_norm, _STRONG_RULES) + evidences += _match_rules(text, source_norm, _MEDIUM_RULES) + + # 中文元叙述:仅当目标语种不是中/日时才有意义 + if cfg.enable_cn_meta and (target_lang not in cfg.cn_meta_skip_langs): + m = _RE_CN_META.search(text) + if m and not _in_source(m.group(0), source_norm): + evidences.append(Evidence('中文元叙述', SCORE_STRONG, m.group(0)[:60])) + + # --- D. 结构性证据 --- + body = _strip_markup(text) + src_body = _strip_markup(source) + + if cfg.enable_length_ratio and source and len(body) >= cfg.min_len_for_ratio: + ratio = len(body) / max(len(src_body), 1) + res.length_ratio = round(ratio, 2) + limit = _ratio_limit_for(target_lang, src_lang, cfg) + if ratio >= limit * 2: + evidences.append(Evidence( + f'长度异常膨胀(>{limit * 2:.0f}x)', SCORE_STRONG, f'{ratio:.1f}x')) + elif ratio >= limit: + evidences.append(Evidence( + f'长度偏大(>{limit:.0f}x)', SCORE_MEDIUM, f'{ratio:.1f}x')) + + if cfg.enable_repetition and len(body) >= cfg.min_len_for_repeat: + rep = _repetition_ratio(body) + # 源文反查:源文本身就是重复文案(游戏里常见的复制粘贴条目)时, + # 译文跟着重复属于忠实翻译,不计分。 + # 源文通常比译文短,故放宽长度门槛(100 字即可参与反查)。 + src_rep = _repetition_ratio(src_body, min_len=100) if src_body else 0.0 + if src_rep >= 0.25: + rep = 0.0 + if rep >= 0.5: + evidences.append(Evidence('大段自我重复', SCORE_STRONG, f'{rep:.0%}')) + elif rep >= 0.25: + evidences.append(Evidence('存在自我重复', SCORE_MEDIUM, f'{rep:.0%}')) + + # 截断本身不构成泄漏(长源文正常会被截断),仅在已有其他证据时加权 + if evidences and _looks_truncated(text): + evidences.append(Evidence('疑似被max_tokens截断', SCORE_WEAK, '')) + + res.evidences = evidences + res.score = sum(e.score for e in evidences) + res.leaked = res.score >= cfg.threshold + return res + + +def is_leaked(translation, source_text=None, target_lang: Optional[str] = None, + src_lang: str = 'zh') -> bool: + """detect() 的布尔简化版。""" + return detect(translation, source_text, target_lang, src_lang).leaked + + +# =========================================================================== +# 六、自检用例 +# =========================================================================== + +# (译文, 源文, 语种, 源语言, 期望是否判定为外露, 说明) +_SELFTEST_CASES = [ + # ---------- 应判定为外露(取自实测)---------- + ('زينة وجه محبوبة كرة القدم \n*(ملاحظة: النص الأصلي يحتوي على...)', + '绿茵宝贝面饰', 'ar', 'zh', True, '阿拉伯语本地化注释块'), + ('Dekorasi Wajah \n*(Catatan: Terjemahan ini...)', + 'Face Decor', 'id', 'en', True, '印尼语注释块'), + ('Перевод текста \n*(Примечание: в последней части...)', + 'Some text', 'ru', 'en', True, '俄语注释块'), + ('Die Blätter können als Medizin verwendet werden.\n' + '*(Correction: The original text says "Stealth Radish")\n' + "I'll just submit that.\n\n**Final Answer:**\nDie Blätter...", + 'The leaves can be used as medicine.', 'de', 'en', True, '德语多重证据'), + ('Translation here.\n\nI submit.\n\nBut wait, the original text says something else.', + 'Source here.', 'fr', 'en', True, '第一人称元叙述'), ('let me translate thisBonjour', + 'Hello', 'fr', 'en', True, '显式think标签'), + ('Some output\n\n[End]\n', 'Some input', 'es', 'en', True, '输出终止标记'), + ('Texte traduit.\n**Final:**\nTexte traduit.', + 'Translated text.', 'fr', 'en', True, 'Markdown最终答案标题'), + + # ---------- 不应判定(历史误判案例)---------- + ('Ouling theater is actually the most distinctive form of drama in our Dragon Kingdom.', + '偶灵戏可是我们龙之国最有特色的戏剧形式呢。', 'en', 'zh', False, + 'actually 出现在正文'), + ('The user\'s damage output is reduced by 30% while the shield is active.', + '激活期间该单位造成的伤害降低30%。', 'en', 'zh', False, + 'the user 指游戏角色'), + ('Cuantos más compañeros tengan activado el Modo de Alerta, ' + 'mayor será el efecto final:\n\n- Recibes un 10% adicional.', + 'The more teammates have Alert Mode activated, the greater the final effect:' + '\n\n- You receive an additional 10%.', 'es', 'en', False, + '西语正文 efecto final:'), + ('... Ha hmm... He said your head... Aaah hmm, ha... got a pretty hard hit...', + '就前些天……呣……我刚和那个小嫩枝……啊啦呣……', 'en', 'zh', False, + 'hmm 为拟声词'), + ('You go gain experience, and I\'ll go look for quests. Let\'s meet up later!', + '你去历练,我去找任务,晚些时候集合吧!', 'en', 'zh', False, + "I'll go look 为角色台词"), + ('Shipment from Fishing Village:\n\nFive cases of fish\n\n' + 'Note: Rebels have been sighted recently.', + '渔村发往云根镇:\n\n优质梦影鱼 五箱\n\n注意:近期有破门生出没。', 'en', 'zh', False, + '原文含「注意:」,译文 Note: 属正常翻译'), + ('Soccer Sweetheart Face Decor', '绿茵宝贝面饰', 'en', 'zh', False, '正常短译文'), + ('Let me help you with that, traveler.', '让我来帮你吧,旅行者。', 'en', 'zh', False, + 'Let me help 为台词'), + ('Please wait for the correction to be applied.', + '请等待修正生效。', 'en', 'zh', False, 'correction 为正文名词'), + ('Alright, all set this time. Wait—I... I forgot to lock the door...', + '行,这次都妥了。不对,我......我忘记锁门了......', 'en', 'zh', False, + 'Wait— 为角色台词停顿'), + ('Tiền tệ kiếm được thông qua Battle Pass. ' * 6, + '通过战斗通行证赚取的货币。' * 6, 'vi', 'zh', False, + '源文本身重复,译文跟随重复属忠实翻译'), + ('큰플라밍고는 유럽, 중동, 아시아에 분포하는 대형 철새이다. ' * 3, + '大红鹳是一种大型候鸟,遍布于欧洲、中东地区、亚洲。' * 3, 'ko', 'zh', False, + '正常长文本,比例正常'), + ('', '源文', 'en', 'zh', False, '空译文'), + (None, '源文', 'en', 'zh', False, 'None 译文'), +] + + +def _selftest() -> int: + passed = failed = 0 + print('=' * 78) + print('think_leak_detector 自检') + print('=' * 78) + for text, src, lang, slang, expect, desc in _SELFTEST_CASES: + r = detect(text, src, lang, slang) + ok = (r.leaked == expect) + flag = 'PASS' if ok else 'FAIL' + passed, failed = (passed + 1, failed) if ok else (passed, failed + 1) + print(f'[{flag}] 期望={"外露" if expect else "正常"} ' + f'实际={"外露" if r.leaked else "正常"} | {desc}') + if not ok or r.evidences: + print(f' {r.describe()}') + print('-' * 78) + print(f'通过 {passed} / {passed + failed},失败 {failed}') + return 0 if failed == 0 else 1 + + +if __name__ == '__main__': + import sys + if '--selftest' in sys.argv: + sys.exit(_selftest()) + print(__doc__) + print(_FALSE_POSITIVE_NOTES) + print('运行 python think_leak_detector.py --selftest 执行自检') diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/tm_file_builder.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/tm_file_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..930e1da818e2243e88af6fcdf23aa8948e3e93f9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/utils/tm_file_builder.py @@ -0,0 +1,231 @@ +"""翻译记忆(TM)文件构建器。 + +**用途**: + 把 ``workspace/batches/_*//*_approved.xlsx`` 下所有历史已审 + 文件扫一遍,去重后生成一份两列的 TM xlsx(源语/目标语),交给 + :mod:`workflow.states.update_tm_state` / + :mod:`workflow.states.update_grn_tm_state` 调用审校平台 + ``upload_tm`` 接口回灌到对应项目的默认 TM 库,让审校人员在平台界面上 + 能看到历史翻译参考。 + +**实现要点**: + * **不做"增量合并 vs 全量扫描"的分层基线**——目前 workspace 积累的 + 历史数据量不大,首轮直接走全量扫描即可;需要优化时再引入 + ``MERGE__ALL.xlsx`` 快照。 + * **不依赖 pandas**——用 :class:`~TiMi_HOK_Game_Translator.sources.xlsx_source.XlsxSource` + 读写,保持与框架其他部分一致的列结构。 + * **统一列名约定**——xlsx 列头统一为 ``Key/Source/Target/...``; + 生成的 TM 文件沿用两列 ``Source/Target``,可被 Crowdin / Phrase + 的 TM import 接口正确解析。 + +**TM 文件格式**: + 输出到 ``workspace/tm/__tm.xlsx``,两列:: + + Source | Target + -------+------- + 你好 | Xin chào + ... | ... + +**失败处理**: + 函数不吞异常;调用方(state)自行 try/except → 告警 + 继续。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import List, Optional, Sequence, Tuple + +logger = logging.getLogger(__name__) + + +#: 审校阶段标识(输入) → batches 下的子目录名。 +_STAGE_SUBDIR = { + "first": "first_review", + "second": "second_review", + "light": "light_review", +} + +#: 用于生成 TM 文件名的阶段简写(输出)。 +_STAGE_FILENAME = { + "first": "first", + "second": "second", + "light": "light", +} + + +def collect_approved_entries( + *, + workspace: Path, + target_locale: str, + review_stage: str, +) -> List[Tuple[str, str]]: + """扫描本地已审历史文件,返回去重后的 ``[(source, target), ...]``。 + + 扫描范围: + + ``/batches/_*/{stage}/*_approved.xlsx`` + + 其中 ``{stage}`` 根据 ``review_stage`` 映射: + * ``"first"`` → ``first_review`` + * ``"second"`` → ``second_review`` + * ``"light"`` → ``light_review`` + + 参数: + workspace: workspace 根目录(通常 ``ctx.workspace``)。 + target_locale: 目标语种标识,用于过滤 batch 目录前缀。 + review_stage: 审校阶段标识。 + + 返回: + ``[(source, target), ...]``,按 ``source`` 去重保留最后一次出现的 target。 + 若未扫到任何文件或均为空,返回空列表。 + """ + from ..sources.xlsx_source import XlsxSource # 局部导入,避免循环 + + stage_sub = _STAGE_SUBDIR.get(review_stage) + if not stage_sub: + logger.warning( + "collect_approved_entries: unknown review_stage=%r, nothing to collect", + review_stage, + ) + return [] + + batches_root = Path(workspace) / "batches" + if not batches_root.exists(): + logger.info( + "collect_approved_entries: batches root %s does not exist yet", + batches_root, + ) + return [] + + # 遍历所有以 ``_`` 开头的批次目录 + pairs: dict = {} # source → target(后出现的覆盖先出现的) + scanned_files = 0 + for batch_dir in sorted(batches_root.glob(f"{target_locale}_*")): + if not batch_dir.is_dir(): + continue + stage_dir = batch_dir / stage_sub + if not stage_dir.exists(): + continue + for approved_file in sorted(stage_dir.glob("*_approved.xlsx")): + try: + entries = XlsxSource(encoding="utf-8").load(str(approved_file)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "collect_approved_entries: failed to load %s (%s), skip", + approved_file, exc, + ) + continue + scanned_files += 1 + for entry in entries: + src = (entry.source_text or "").strip() + tgt = (entry.target_text or "").strip() + if not src or not tgt: + continue + pairs[src] = tgt + + logger.info( + "collect_approved_entries: scanned %d approved files, collected %d unique " + "(source, target) pairs for %s/%s", + scanned_files, len(pairs), target_locale, review_stage, + ) + return list(pairs.items()) + + +def build_tm_xlsx( + pairs: Sequence[Tuple[str, str]], + *, + output_path: Path, + source_locale: str = "zh-CN", + target_locale: str = "", +) -> Optional[Path]: + """把 ``pairs`` 写入双列 xlsx,供平台 TM import 接口上传。 + + 输出格式(两列、首行为语种代码表头,兼容 Crowdin 的 ``translation`` + 列映射规则 ``key=0, text=1, translation=2`` 的最小子集;Phrase 的 + TMX import 对 Excel 列头也宽容):: + + | + ----------------+----------------- + 你好 | Xin chào + + 参数: + pairs: ``[(source, target), ...]``。空列表则返回 ``None``(不写文件)。 + output_path: 输出 xlsx 路径。父目录会自动创建。 + source_locale: 第一列列头(默认 ``zh-CN``)。 + target_locale: 第二列列头;为空时报错。 + + 返回: + 成功时返回写入的路径;``pairs`` 为空或 ``target_locale`` 为空时返回 ``None``。 + """ + if not pairs: + logger.info("build_tm_xlsx: no pairs provided, skip writing") + return None + if not target_locale: + logger.warning("build_tm_xlsx: target_locale is empty, skip") + return None + + try: + import openpyxl # 本地化已有依赖 + except ImportError: # pragma: no cover + logger.error( + "build_tm_xlsx: openpyxl is required for TM file generation; " + "install with `pip install openpyxl`" + ) + return None + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + + wb = openpyxl.Workbook() + ws = wb.active + ws.title = "TM" + ws.append([source_locale, target_locale]) + for src, tgt in pairs: + ws.append([src, tgt]) + + # 适度加宽列宽,便于平台 UI 预览 + ws.column_dimensions["A"].width = 60 + ws.column_dimensions["B"].width = 60 + + wb.save(str(output_path)) + logger.info("build_tm_xlsx: wrote %d TM pairs to %s", len(pairs), output_path) + return output_path + + +def build_tm_file_for_stage( + *, + workspace: Path, + target_locale: str, + source_locale: str, + review_stage: str, +) -> Optional[Path]: + """一步到位:扫历史 approved 文件 → 产出 TM xlsx 文件。 + + 这是对外主入口;state 代码只需要调这一个函数。 + + 输出路径:``/tm/__tm.xlsx`` + """ + pairs = collect_approved_entries( + workspace=workspace, + target_locale=target_locale, + review_stage=review_stage, + ) + if not pairs: + return None + + stage_name = _STAGE_FILENAME.get(review_stage, review_stage) + output_path = Path(workspace) / "tm" / f"{target_locale}_{stage_name}_tm.xlsx" + return build_tm_xlsx( + pairs, + output_path=output_path, + source_locale=source_locale or "zh-CN", + target_locale=target_locale, + ) + + +__all__ = [ + "build_tm_file_for_stage", + "build_tm_xlsx", + "collect_approved_entries", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8afb4439224127336032645024dc683a24a03fa0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__init__.py @@ -0,0 +1,30 @@ +"""TiMi_HOK_Game_Translator.vcs 子包。 + +对外 API:: + + from TiMi_HOK_Game_Translator.vcs import ( + VcsClient, VcsCredentials, VcsStatus, + SvnClient, GitClient, PerforceClient, MockClient, + create_vcs_client, register_vcs_client, + ) +""" + +from .base import VcsClient, VcsCommandResult, VcsCredentials, VcsStatus +from .factory import create_vcs_client, register_vcs_client +from .git_client import GitClient +from .mock_client import MockClient +from .perforce_client import PerforceClient +from .svn_client import SvnClient + +__all__ = [ + "GitClient", + "MockClient", + "PerforceClient", + "SvnClient", + "VcsClient", + "VcsCommandResult", + "VcsCredentials", + "VcsStatus", + "create_vcs_client", + "register_vcs_client", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c18be6a6bb1963f84971796188b348701a31f402 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/base.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/base.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6476246e379c551e275e6ea7a41162968295bfc8 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/base.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/factory.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/factory.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16418a9d7855b7a1ad3eab660fdbbe7f32b9b956 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/factory.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/git_client.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/git_client.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1adf1e11883bbccc59dc9199882e13ccd1be0456 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/git_client.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/mock_client.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/mock_client.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..141c4389ced63fe5c3bd16746c9449c1ae1c9947 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/mock_client.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/perforce_client.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/perforce_client.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9e778e17196d579ad863cfaf1e246c03a8f902f Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/perforce_client.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/svn_client.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/svn_client.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75f88bdd587afbb796dd0c6771d5787dbff550db Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/__pycache__/svn_client.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/base.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/base.py new file mode 100644 index 0000000000000000000000000000000000000000..93ddcff8146d29959c2426f8e7c592f074320980 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/base.py @@ -0,0 +1,238 @@ +"""版本控制抽象层。 + +``TiMi_HOK_Game_Translator`` 中所有 VCS 操作都经由 :class:`VcsClient` 接口。 +具体后端(:class:`~.svn_client.SvnClient` 、 :class:`~.git_client.GitClient` 、 +:class:`~.perforce_client.PerforceClient` 、 :class:`~.mock_client.MockClient`) +实现本接口,由 :func:`~.factory.create_vcs_client` 在运行时选择。 + +设计目标: + +* 方法名与后端无关——不暴露 svn / git / p4 的术语; +* 重试与错误处理位于客户端内部,而不侵入工作流; +* 外部 CLI(``svn`` / ``git`` / ``p4``)统一通过 + :meth:`VcsClient._run` 子进程调用,保证单测 mock 只需处理一个接口。 +""" + +from __future__ import annotations + +import abc +import shutil +import subprocess +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterable, List, Optional, Sequence + +from ..commons import ( + DEFAULT_VCS_CLI_TIMEOUT_SECONDS, + DEFAULT_VCS_COMMIT_MESSAGE, + VcsCliMissingError, + VcsCommandError, +) + + +# --------------------------------------------------------------------------- +# 数据对象 +# --------------------------------------------------------------------------- +@dataclass +class VcsCredentials: + """VCS 后端的鉴权信息。 + + 字段均为可选,因为部分后端(如启用 SSO 的 Perforce、走 SSH 的 Git、 + 还有 mock 后端)不需要显式凭据。 + """ + + username: str = "" + password: str = "" + + +@dataclass +class VcsCommandResult: + """单次 CLI 调用的捕获结果。""" + + returncode: int + stdout: str = "" + stderr: str = "" + + @property + def ok(self) -> bool: + return self.returncode == 0 + + +@dataclass +class VcsStatus: + """操作后工作副本的粗粒度状态。 + + 后端自定义细节(如冲突文件列表)可放入 :attr:`extra`,不影响接口契约。 + """ + + revision: str = "" + modified_paths: List[str] = field(default_factory=list) + conflicts: List[str] = field(default_factory=list) + extra: dict = field(default_factory=dict) + + +# --------------------------------------------------------------------------- +# 抽象基类 +# --------------------------------------------------------------------------- +class VcsClient(abc.ABC): + """所有 VCS 后端需实现的接口。 + + 子类需提供类属性 ``cli_name: str``(``"svn"`` / ``"git"`` / ``"p4"``), + 工厂会在首次命令之前预检 PATH。 + """ + + #: PATH 上必须存在的可执行文件;``None`` 时跳过检查(适用于 mock + #: 后端和纯 Python 实现)。 + cli_name: Optional[str] = None + + def __init__( + self, + url: str, + local_path: str, + credentials: Optional[VcsCredentials] = None, + *, + cli_timeout_seconds: int = DEFAULT_VCS_CLI_TIMEOUT_SECONDS, + default_commit_message: str = DEFAULT_VCS_COMMIT_MESSAGE, + ) -> None: + self.url = url + self.local_path = str(Path(local_path).expanduser()) if local_path else "" + self.credentials = credentials or VcsCredentials() + self.cli_timeout_seconds = cli_timeout_seconds + self.default_commit_message = default_commit_message + + # ------------------------------------------------------------------ + # 类级别辅助方法 + # ------------------------------------------------------------------ + @classmethod + def ensure_cli_available(cls) -> None: + """当所需 CLI 不存在时抛出 :class:`VcsCliMissingError`。 + + 子类可覆写,以支持多个开发包或提供更友好的提示。 + """ + if cls.cli_name is None: + return + if shutil.which(cls.cli_name) is None: + raise VcsCliMissingError( + f"The required VCS CLI '{cls.cli_name}' was not found on PATH. " + f"Install it (or adjust your PATH) and try again." + ) + + # ------------------------------------------------------------------ + # 抽象 API + # ------------------------------------------------------------------ + @abc.abstractmethod + def checkout(self) -> VcsStatus: + """从 ``self.url`` 拉取一份全新工作副本到 ``self.local_path``。""" + + @abc.abstractmethod + def update(self, revision: Optional[str] = None) -> VcsStatus: + """将工作副本同步到 ``revision``(``None`` 时同步到最新)。""" + + @abc.abstractmethod + def add(self, paths: Sequence[str]) -> None: + """将指定路径添加到下一次提交的暂存区。""" + + @abc.abstractmethod + def commit(self, paths: Sequence[str], message: Optional[str] = None) -> VcsStatus: + """提交已暂存的路径。 + + 支持原子 add+commit 的后端可一步完成;默认行为为: + 暂存 → 提交 → 返回状态。 + """ + + @abc.abstractmethod + def revert(self, paths: Sequence[str]) -> None: + """丢弃指定路径的本地修改。""" + + @abc.abstractmethod + def status(self, paths: Optional[Sequence[str]] = None) -> VcsStatus: + """返回当前工作副本状态。""" + + @abc.abstractmethod + def cleanup(self) -> None: + """从中断的操作中恢复工作副本(锁、未完成事务等)。""" + + @abc.abstractmethod + def get_revision(self) -> str: + """返回当前 revision / commit / changelist 的字符串表示。""" + + # ------------------------------------------------------------------ + # 可选钩子(有默认实现,子类按需覆写) + # ------------------------------------------------------------------ + def prepare_for_write(self, paths: Sequence[str]) -> None: + """在**对外部写**磁盘之前通知 VCS 后端 "即将修改这些路径"。 + + * SVN / Git / mock:无需操作(工作副本文件天然可写)→ 默认 no-op; + * Perforce:必须先 ``p4 edit``,否则本地文件是只读的, + Python 直接 ``open(..., "w")`` 会抛 ``PermissionError``。 + + 调用方(``MergeDataState`` / ``PushVcsState``)在 ``source.dump()`` + 或 ``merge_incremental_into_full()`` **之前**调用本方法;对后端 + 而言这是"幂等 + 容错"的——文件不存在、CLI 调用失败都**不应** + 中断主流程(真正的 commit 失败由 ``commit()`` 自己负责报告)。 + """ + return None + + # ------------------------------------------------------------------ + # 共享基础设施 + # ------------------------------------------------------------------ + def _run( + self, + cmd: Sequence[str], + *, + cwd: Optional[str] = None, + check: bool = True, + ) -> VcsCommandResult: + """执行 ``cmd`` 并返回 :class:`VcsCommandResult`。 + + 参数: + cmd: 完整 argv,首元素必须为 CLI 可执行文件。 + cwd: 工作目录;默认为 ``self.local_path``。 + check: 为 ``True`` 时(默认),非零退出码会在脱敏并 + 记录后抛出 :class:`VcsCommandError`。 + + 备注: + 子类不应重写本方法,应在自己的方法里拼接命令后委托本方法, + 以保证单测只需 mock 一处。 + """ + proc = subprocess.run( # noqa: S603 — 命令仅内部拼接 + list(cmd), + cwd=cwd or self.local_path or None, + capture_output=True, + text=True, + timeout=self.cli_timeout_seconds, + ) + result = VcsCommandResult( + returncode=proc.returncode, + stdout=proc.stdout or "", + stderr=proc.stderr or "", + ) + if check and not result.ok: + masked_cmd = self._mask_cmd(cmd) + raise VcsCommandError( + f"Command failed with code {result.returncode}: {masked_cmd}\n" + f"stderr: {result.stderr.strip()}" + ) + return result + + def _mask_cmd(self, cmd: Iterable[str]) -> str: + """将命令串化输出,并对密码参数进行脱敏。""" + masked: List[str] = [] + skip_next = False + for token in cmd: + if skip_next: + masked.append("***") + skip_next = False + continue + if token in {"--password", "-p"}: + skip_next = True + masked.append(token) + return " ".join(masked) + + +__all__ = [ + "VcsClient", + "VcsCommandResult", + "VcsCredentials", + "VcsStatus", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/factory.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..2074afc41653837c7be96cfdafac050d37c42659 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/factory.py @@ -0,0 +1,100 @@ +"""根据 :class:`VcsConfig` 创建具体 :class:`VcsClient` 的工厂。""" + +from __future__ import annotations + +from typing import Any, Dict, Type + +from ..commons import VcsType +from ..config.schema import VcsConfig +from .base import VcsClient, VcsCredentials +from .git_client import GitClient +from .mock_client import MockClient +from .perforce_client import PerforceClient +from .svn_client import SvnClient + +_REGISTRY: Dict[str, Type[VcsClient]] = { + VcsType.SVN.value: SvnClient, + VcsType.GIT.value: GitClient, + VcsType.PERFORCE.value: PerforceClient, + VcsType.LOCAL.value: MockClient, +} + +#: 老配置向后兼容:早期版本把"无 VCS、直接读写本地目录"的后端命名为 +#: ``mock``;重命名为 ``local`` 之后,这里把老值翻译回新值,保证既有 +#: ``config.yaml`` / ``languages/*.yaml`` 不升级就能继续加载。 +_VCS_TYPE_ALIASES: Dict[str, str] = { + "mock": VcsType.LOCAL.value, +} + + +def register_vcs_client(name: str, client_cls: Type[VcsClient]) -> None: + """以 ``name`` 为名注册自定义 :class:`VcsClient` 实现。 + + 下游插件如需新增后端,无需 fork 本框架。 + """ + _REGISTRY[name.lower()] = client_cls + + +def create_vcs_client(vcs_config: VcsConfig, *, workspace: str = "") -> VcsClient: + """根据 ``vcs_config`` 返回已初始化好的 :class:`VcsClient`。 + + 参数: + vcs_config: 根配置下的 :class:`VcsConfig` 区域。 + workspace: 已解析的 workspace 目录;当 ``vcs.local_path`` 为相对路径时以其为基准。 + + 异常: + VcsCliMissingError: PATH 上缺失需要的二进制。 + ValueError: ``vcs_config.type`` 未注册。 + """ + key = (vcs_config.type or "").lower() + key = _VCS_TYPE_ALIASES.get(key, key) # 兼容老的 "mock" → "local" + if key not in _REGISTRY: + raise ValueError( + f"Unknown vcs.type '{vcs_config.type}'. " + f"Registered backends: {sorted(_REGISTRY)}" + ) + cls = _REGISTRY[key] + cls.ensure_cli_available() + + local_path = _resolve_local_path(vcs_config.local_path, workspace) + credentials = VcsCredentials( + username=vcs_config.username, password=vcs_config.password, + ) + extra: Dict[str, Any] = dict(vcs_config.extra or {}) + return cls( + url=vcs_config.url, + local_path=local_path, + credentials=credentials, + cli_timeout_seconds=vcs_config.cli_timeout_seconds, + default_commit_message=vcs_config.default_commit_message, + **extra, + ) + + +def _resolve_local_path(local_path: str, workspace: str) -> str: + """返回绝对的工作副本路径。 + + * ``local_path`` 为绝对路径时直接返回; + * ``local_path`` 为相对路径且提供了 ``workspace`` 时,拼接两者; + * ``local_path`` 为空时回退为 ``{workspace}/vcs``; + * ``local_path`` 中出现 ``{workspace}`` 占位符时,先展开再按上述规则处理 + (避免模板里写了 ``{workspace}/svn/test_translation`` 导致被当成文字路径分量)。 + """ + import os + + if local_path and "{workspace}" in local_path: + local_path = local_path.replace("{workspace}", workspace or "") + # 展开后可能变成绝对路径(workspace 本身是绝对路径),走下方分支即可。 + + if local_path: + if os.path.isabs(local_path): + return local_path + if workspace: + return os.path.join(workspace, local_path) + return os.path.abspath(local_path) + if workspace: + return os.path.join(workspace, "vcs") + return os.path.abspath("vcs") + + +__all__ = ["create_vcs_client", "register_vcs_client"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/git_client.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/git_client.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b14ad6c385812f8def527cd44c74d14118165c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/git_client.py @@ -0,0 +1,122 @@ +"""基于 ``git`` CLI 的 Git 后端。 + +仅提供工作流使用到的最小能力集(clone / pull / add / commit / push)。 +分支切换、cherry-pick、submodule、LFS 等高阶特性不包含在默认实现中, +如需可通过继承拓展。 +""" + +from __future__ import annotations + +import time +from pathlib import Path +from typing import List, Optional, Sequence + +from ..commons import DEFAULT_HTTP_RETRIES, DEFAULT_HTTP_RETRY_INTERVAL_SECONDS +from .base import VcsClient, VcsCommandResult, VcsCredentials, VcsStatus + + +class GitClient(VcsClient): + """:class:`VcsClient` 的 Git 实现。""" + + cli_name = "git" + + def __init__( + self, + url: str, + local_path: str, + credentials: Optional[VcsCredentials] = None, + *, + branch: str = "main", + push: bool = True, + retries: int = DEFAULT_HTTP_RETRIES, + retry_interval_seconds: int = DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + **kwargs: object, + ) -> None: + super().__init__(url=url, local_path=local_path, credentials=credentials, **kwargs) # type: ignore[arg-type] + self.branch = branch + self.push_on_commit = push + self.retries = max(1, int(retries)) + self.retry_interval_seconds = max(0, int(retry_interval_seconds)) + + # ------------------------------------------------------------------ + # VcsClient 接口实现 + # ------------------------------------------------------------------ + def checkout(self) -> VcsStatus: + Path(self.local_path).parent.mkdir(parents=True, exist_ok=True) + cmd = ["git", "clone", self.url, self.local_path] + if self.branch: + cmd.extend(["--branch", self.branch]) + self._retry(cmd, cwd=None) + return VcsStatus(revision=self.get_revision()) + + def update(self, revision: Optional[str] = None) -> VcsStatus: + if revision: + self._run(["git", "fetch", "origin"], check=True) + self._run(["git", "checkout", revision], check=True) + else: + self._retry(["git", "pull", "--ff-only"]) + return VcsStatus(revision=self.get_revision()) + + def add(self, paths: Sequence[str]) -> None: + if not paths: + return + self._run(["git", "add", "--", *paths], check=True) + + def commit(self, paths: Sequence[str], message: Optional[str] = None) -> VcsStatus: + if paths: + self.add(paths) + effective_msg = message or self.default_commit_message + self._run(["git", "commit", "-m", effective_msg], check=True) + if self.push_on_commit: + self._retry(["git", "push", "origin", self.branch or "HEAD"]) + return VcsStatus(revision=self.get_revision(), modified_paths=list(paths)) + + def revert(self, paths: Sequence[str]) -> None: + if not paths: + return + self._run(["git", "checkout", "--", *paths], check=True) + + def status(self, paths: Optional[Sequence[str]] = None) -> VcsStatus: + result = self._run(["git", "status", "--porcelain", *(paths or ())], check=False) + modified: List[str] = [] + conflicts: List[str] = [] + for line in result.stdout.splitlines(): + if not line: + continue + code = line[:2] + path = line[3:].strip() + if "U" in code or code.strip() == "AA": + conflicts.append(path) + else: + modified.append(path) + return VcsStatus(revision=self.get_revision(), modified_paths=modified, conflicts=conflicts) + + def cleanup(self) -> None: + # 尽力而为的恢复:中止未完成的 merge / rebase / cherry-pick, + # 保留本地修改以便调用方检查。 + for cmd in ( + ["git", "merge", "--abort"], + ["git", "rebase", "--abort"], + ["git", "cherry-pick", "--abort"], + ): + self._run(cmd, check=False) + + def get_revision(self) -> str: + result = self._run(["git", "rev-parse", "HEAD"], check=False) + return result.stdout.strip() + + # ------------------------------------------------------------------ + def _retry(self, cmd: Sequence[str], *, cwd: Optional[str] = None) -> VcsCommandResult: + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._run(cmd, cwd=cwd, check=True) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — VcsCommandError 既属异常后续会重新抛出 + last_error = exc + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + +__all__ = ["GitClient"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/mock_client.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/mock_client.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc01ea259bf1404b9d4bb9cf1d6efbaa455720d --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/mock_client.py @@ -0,0 +1,95 @@ +"""供 demo/单测使用的内存 mock VCS 后端。 + +本后端**不进行任何网络与子进程调用**,仅在本地目录中模拟工作副本, +并将每一次操作记录到 :attr:`MockClient.history`,便于单测断言。 + +典型用法:: + + client = MockClient(url="mock://demo", local_path="/tmp/wc") + client.checkout() + (Path(client.local_path) / "hello.txt").write_text("hi") + client.add(["hello.txt"]) + client.commit(["hello.txt"], message="init") +""" + +from __future__ import annotations + +import itertools +from pathlib import Path +from typing import List, Optional, Sequence, Tuple + +from .base import VcsClient, VcsCredentials, VcsStatus + + +class MockClient(VcsClient): + """适用于本地 demo 与单测的空操作 VCS 后端。""" + + cli_name = None # 无需任何外部二进制。 + + def __init__( + self, + url: str, + local_path: str, + credentials: Optional[VcsCredentials] = None, + **kwargs: object, + ) -> None: + super().__init__(url=url, local_path=local_path, credentials=credentials, **kwargs) # type: ignore[arg-type] + self._counter = itertools.count(start=1) + self._current_revision = "r0" + self._staged: List[str] = [] + self.history: List[Tuple[str, tuple]] = [] + + # ------------------------------------------------------------------ + def _record(self, op: str, *args: object) -> None: + self.history.append((op, tuple(args))) + + def _ensure_local_dir(self) -> Path: + path = Path(self.local_path or "") + path.mkdir(parents=True, exist_ok=True) + return path + + # ------------------------------------------------------------------ + # VcsClient 接口实现 + # ------------------------------------------------------------------ + def checkout(self) -> VcsStatus: + self._ensure_local_dir() + self._current_revision = f"r{next(self._counter)}" + self._record("checkout", self.url, self.local_path) + return VcsStatus(revision=self._current_revision) + + def update(self, revision: Optional[str] = None) -> VcsStatus: + self._ensure_local_dir() + self._current_revision = revision or f"r{next(self._counter)}" + self._record("update", self._current_revision) + return VcsStatus(revision=self._current_revision) + + def add(self, paths: Sequence[str]) -> None: + self._staged.extend(paths) + self._record("add", tuple(paths)) + + def commit(self, paths: Sequence[str], message: Optional[str] = None) -> VcsStatus: + self._ensure_local_dir() + effective = message or self.default_commit_message + self._current_revision = f"r{next(self._counter)}" + modified = list(dict.fromkeys([*self._staged, *paths])) + self._staged.clear() + self._record("commit", tuple(paths), effective, self._current_revision) + return VcsStatus(revision=self._current_revision, modified_paths=modified) + + def revert(self, paths: Sequence[str]) -> None: + self._staged = [p for p in self._staged if p not in paths] + self._record("revert", tuple(paths)) + + def status(self, paths: Optional[Sequence[str]] = None) -> VcsStatus: + self._record("status", tuple(paths or ())) + return VcsStatus(revision=self._current_revision, modified_paths=list(self._staged)) + + def cleanup(self) -> None: + self._staged.clear() + self._record("cleanup") + + def get_revision(self) -> str: + return self._current_revision + + +__all__ = ["MockClient"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/perforce_client.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/perforce_client.py new file mode 100644 index 0000000000000000000000000000000000000000..63d7d4faec43a76e5df37553430a8ea80a8cda40 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/perforce_client.py @@ -0,0 +1,193 @@ +"""基于 ``p4`` CLI 的 Perforce(Helix Core)后端。 + +Perforce 以 workspace 为中心,与 SVN/Git 思维不同;本适配器将 :class:`VcsClient` +操作映射到最接近的 Perforce 命令: + +* :meth:`checkout`——``p4 sync`` 到已配置的 client workspace。 +* :meth:`update`——``p4 sync``。 +* :meth:`add`——``p4 add`` / ``p4 edit``(已纳管文件需 ``edit`` 才能编辑, + 新文件需 ``add``)。 +* :meth:`commit`——``p4 submit`` 提交当前 changelist。 +* :meth:`revert`——``p4 revert``。 +* :meth:`cleanup`——空实现,Perforce 无工作副本锁。 + +若使用 SSO / MFA,请在进入前完成鉴权;本适配器不会自动执行 ``p4 login``。 +""" + +from __future__ import annotations + +import time +from typing import List, Optional, Sequence + +from ..commons import DEFAULT_HTTP_RETRIES, DEFAULT_HTTP_RETRY_INTERVAL_SECONDS +from .base import VcsClient, VcsCommandResult, VcsCredentials, VcsStatus + + +class PerforceClient(VcsClient): + """:class:`VcsClient` 的 Perforce 实现。""" + + cli_name = "p4" + + def __init__( + self, + url: str, + local_path: str, + credentials: Optional[VcsCredentials] = None, + *, + p4port: str = "", + p4client: str = "", + retries: int = DEFAULT_HTTP_RETRIES, + retry_interval_seconds: int = DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + **kwargs: object, + ) -> None: + super().__init__(url=url, local_path=local_path, credentials=credentials, **kwargs) # type: ignore[arg-type] + # ``url`` 在 Perforce 下被视为 depot spec(如 ``//depot/loc/...``)。 + self.depot_spec = url or "//..." + self.p4port = p4port + self.p4client = p4client + self.retries = max(1, int(retries)) + self.retry_interval_seconds = max(0, int(retry_interval_seconds)) + + # ------------------------------------------------------------------ + # VcsClient 接口实现 + # ------------------------------------------------------------------ + def checkout(self) -> VcsStatus: + self._retry(["p4", *self._global_args(), "sync", self.depot_spec]) + return VcsStatus(revision=self.get_revision()) + + def update(self, revision: Optional[str] = None) -> VcsStatus: + # P4 的 revision 表达法与 SVN/Git 不同: + # * ``@HEAD`` 不合法(HEAD 是 SVN/Git 语义); + # * 不加任何后缀即同步到最新; + # * 若需要 pin 到具体 changelist,用 ``@12345``。 + # 为了与通用上游(``PullVcsState``)兼容,这里把 "HEAD"(或空) + # 都归一为"不加后缀"。 + spec = self._build_sync_spec(revision) + self._retry(["p4", *self._global_args(), "sync", spec]) + return VcsStatus(revision=self.get_revision()) + + def _build_sync_spec(self, revision: Optional[str]) -> str: + """把通用 ``revision`` 翻译成 P4 ``depot_spec`` 后缀。 + + * ``None`` / ``""`` / ``"HEAD"`` / ``"head"``:同步到最新 → 不加后缀; + * 纯数字(例如 ``"12345"``):当作 changelist → ``@12345``; + * 其它字符串:原样作为 P4 revision 修饰符(``@label``、``@date``、 + ``@client``、``#have`` 等)直接拼接——若用户已自带 ``@`` / ``#`` + 前缀则不再追加。 + """ + if not revision: + return self.depot_spec + rev = str(revision).strip() + if not rev or rev.upper() == "HEAD": + return self.depot_spec + if rev.startswith("@") or rev.startswith("#"): + return f"{self.depot_spec}{rev}" + return f"{self.depot_spec}@{rev}" + + def add(self, paths: Sequence[str]) -> None: + if not paths: + return + # 'p4 add' 处理新文件;'p4 edit' 打开已有文件。先试 edit(未打开时开销很小), + # 再试 add;两命令均会忽略已打开的文件。 + self._run(["p4", *self._global_args(), "edit", *paths], check=False) + self._run(["p4", *self._global_args(), "add", *paths], check=False) + + def commit(self, paths: Sequence[str], message: Optional[str] = None) -> VcsStatus: + """提交当前 workspace 的默认 changelist。 + + ``paths`` 的作用是:**让它们先被 ``p4 edit`` / ``p4 add`` 加入默认 + changelist**(由 :meth:`add` 完成)。``p4 submit`` **本身不接受 + 多文件参数**(Usage: ``submit [-d description] [file]`` 的 ``[file]`` + 是单数,且要求是 depot path / wildcard,不是绝对路径),因此 + 这里不把 ``paths`` 追加到 submit 命令后面——否则会报 + ``Missing/wrong number of arguments``。 + + **副作用提醒**:``p4 submit -d msg`` 会提交 workspace **默认 changelist + 里的所有 open 文件**。如果用户在本流程之外手动 ``p4 edit`` 了别的 + 文件、且未关进其它 changelist,会被一并提交。TiMi_HOK_Game_Translator 的 + 标准运行场景下,workspace 由本工具独占,不会出现此情况。 + """ + if paths: + self.add(paths) + effective_msg = message or self.default_commit_message + cmd = ["p4", *self._global_args(), "submit", "-d", effective_msg] + self._retry(cmd) + return VcsStatus(revision=self.get_revision(), modified_paths=list(paths)) + + def revert(self, paths: Sequence[str]) -> None: + if not paths: + return + self._run(["p4", *self._global_args(), "revert", *paths], check=True) + + def prepare_for_write(self, paths: Sequence[str]) -> None: + """P4 工作副本文件默认是只读的;写入前必须 ``p4 edit``。 + + * 对**已纳管**的文件:``p4 edit`` 会取消本地只读属性并把文件加入 + 默认 changelist; + * 对**不存在于 depot** 的新文件:``p4 edit`` 会报 "file(s) not on + client"——这是预期;真正的 ``p4 add`` 由后续 ``commit() → add()`` + 自动处理。 + * 不存在于磁盘的路径(例如本轮尚未落地的 full 表)跳过。 + * 任何 CLI 失败都**不中断主流程**——真正的提交由 ``commit()`` 兜底, + 本方法只是"事前最佳努力去只读"。 + """ + from pathlib import Path as _Path # noqa: WPS433 — 局部,避免顶层多一处 import + + existing = [p for p in paths if p and _Path(p).exists()] + if not existing: + return + self._run( + ["p4", *self._global_args(), "edit", *existing], + check=False, + ) + + def status(self, paths: Optional[Sequence[str]] = None) -> VcsStatus: + result = self._run(["p4", *self._global_args(), "opened", *(paths or ())], check=False) + modified: List[str] = [] + for line in result.stdout.splitlines(): + if line: + modified.append(line.strip()) + return VcsStatus(revision=self.get_revision(), modified_paths=modified) + + def cleanup(self) -> None: + # Perforce 无工作副本锁;保留方法仅为了接口完整。 + return None + + def get_revision(self) -> str: + result = self._run( + ["p4", *self._global_args(), "changes", "-m", "1", f"{self.depot_spec}#have"], + check=False, + ) + # 输出格式:"Change 12345 on 2024/01/01 by user@client 'msg'" + parts = result.stdout.split() + if len(parts) >= 2 and parts[0] == "Change": + return parts[1] + return result.stdout.strip() + + # ------------------------------------------------------------------ + def _global_args(self) -> List[str]: + args: List[str] = [] + if self.p4port: + args.extend(["-p", self.p4port]) + if self.p4client: + args.extend(["-c", self.p4client]) + if self.credentials.username: + args.extend(["-u", self.credentials.username]) + if self.credentials.password: + args.extend(["-P", self.credentials.password]) + return args + + def _retry(self, cmd: Sequence[str]) -> VcsCommandResult: + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._run(cmd, check=True) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + last_error = exc + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + +__all__ = ["PerforceClient"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/svn_client.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/svn_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c44fcfc1fb5da9c37fb3360c2c3309f71a5187 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/vcs/svn_client.py @@ -0,0 +1,151 @@ +"""基于 ``svn`` CLI 的 SVN 后端。 + +提供工程中实际用到的核心 SVN 操作,剥离了业务耦合的内容 +(项目专用操作模板、缺陷 ID 等)。重试与工作副本锁的恢复策略 +简化为少量可理解的步骤;如需扩展行为,可通过继承或插入 +:meth:`_run_with_retry` 实现。 +""" + +from __future__ import annotations + +import re +import time +from pathlib import Path +from typing import List, Optional, Sequence + +from ..commons import ( + DEFAULT_HTTP_RETRIES, + DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + VcsCommandError, +) +from .base import VcsClient, VcsCommandResult, VcsCredentials, VcsStatus + +# 匹配工作副本锁/脏状态错误的正则,不区分大小写。 +_WC_LOCKED_RE = re.compile(r"E155004|is locked|previous operation has not finished", re.IGNORECASE) +_TREE_CONFLICT_RE = re.compile(r"remains in conflict|conflict discovered", re.IGNORECASE) + + +class SvnClient(VcsClient): + """:class:`VcsClient` 的 SVN 实现。""" + + cli_name = "svn" + + def __init__( + self, + url: str, + local_path: str, + credentials: Optional[VcsCredentials] = None, + *, + retries: int = DEFAULT_HTTP_RETRIES, + retry_interval_seconds: int = DEFAULT_HTTP_RETRY_INTERVAL_SECONDS, + **kwargs: object, + ) -> None: + super().__init__(url=url, local_path=local_path, credentials=credentials, **kwargs) # type: ignore[arg-type] + self.retries = max(1, int(retries)) + self.retry_interval_seconds = max(0, int(retry_interval_seconds)) + + # ------------------------------------------------------------------ + # VcsClient 接口实现 + # ------------------------------------------------------------------ + def checkout(self) -> VcsStatus: + Path(self.local_path).mkdir(parents=True, exist_ok=True) + cmd = [ + "svn", "checkout", self.url, self.local_path, + *self._auth_args(), "--non-interactive", + ] + self._run_with_retry(cmd, cwd=None) + return VcsStatus(revision=self.get_revision()) + + def update(self, revision: Optional[str] = None) -> VcsStatus: + cmd = ["svn", "update"] + if revision: + cmd.extend(["-r", revision]) + cmd.extend([*self._auth_args(), "--non-interactive"]) + self._run_with_retry(cmd) + return VcsStatus(revision=self.get_revision()) + + def add(self, paths: Sequence[str]) -> None: + if not paths: + return + cmd = ["svn", "add", "--force", *paths, *self._auth_args(), "--non-interactive"] + self._run(cmd, check=True) + + def commit(self, paths: Sequence[str], message: Optional[str] = None) -> VcsStatus: + if paths: + self.add(paths) + cmd = [ + "svn", + "commit", + "-m", + message or self.default_commit_message, + *paths, + *self._auth_args(), + "--non-interactive", + ] + self._run_with_retry(cmd) + return VcsStatus(revision=self.get_revision(), modified_paths=list(paths)) + + def revert(self, paths: Sequence[str]) -> None: + if not paths: + return + cmd = ["svn", "revert", "--recursive", *paths] + self._run(cmd, check=True) + + def status(self, paths: Optional[Sequence[str]] = None) -> VcsStatus: + cmd = ["svn", "status", *(paths or ())] + result = self._run(cmd, check=False) + modified: List[str] = [] + conflicts: List[str] = [] + for line in result.stdout.splitlines(): + if not line or line.startswith("?"): + continue + code = line[0] + path = line[8:].strip() if len(line) > 8 else "" + if code == "C": + conflicts.append(path) + elif code in {"M", "A", "D", "R"}: + modified.append(path) + return VcsStatus(revision=self.get_revision(), modified_paths=modified, conflicts=conflicts) + + def cleanup(self) -> None: + cmd = ["svn", "cleanup", self.local_path or "."] + self._run(cmd, check=False) + + def get_revision(self) -> str: + result = self._run(["svn", "info", "--show-item", "revision"], check=False) + return result.stdout.strip() + + # ------------------------------------------------------------------ + # 内部实现 + # ------------------------------------------------------------------ + def _auth_args(self) -> List[str]: + args: List[str] = [] + if self.credentials.username: + args.extend(["--username", self.credentials.username]) + if self.credentials.password: + args.extend(["--password", self.credentials.password]) + return args + + def _run_with_retry( + self, cmd: Sequence[str], *, cwd: Optional[str] = None + ) -> VcsCommandResult: + """运行 ``cmd``,遇到工作副本锁/树冲突时自动恢复后重试。""" + last_error: Optional[Exception] = None + for attempt in range(1, self.retries + 1): + try: + return self._run(cmd, cwd=cwd, check=True) + except VcsCommandError as exc: + stderr = str(exc) + if _WC_LOCKED_RE.search(stderr): + self.cleanup() + elif _TREE_CONFLICT_RE.search(stderr): + self._run(["svn", "resolve", "--accept", "working", "--recursive", + self.local_path or "."], check=False) + last_error = exc + if attempt < self.retries: + time.sleep(self.retry_interval_seconds) + assert last_error is not None + raise last_error + + +__all__ = ["SvnClient"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e187c3d10a6880f5f99c4f4daddcfcaa78f4c642 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__init__.py @@ -0,0 +1,40 @@ +"""TiMi_HOK_Game_Translator.workflow——基于状态机的流水线。 + +对外 API:: + + from TiMi_HOK_Game_Translator.workflow import ( + WorkflowContext, WorkflowStateBase, + StatesManager, AutoSaveDict, + WorkflowRunner, + register_state, build_state, build_workflow, registered_state_names, + ) + +导入本包时会自动通过 :mod:`TiMi_HOK_Game_Translator.workflow.states` 注册内置 17 个状态。 +""" + +# 导入内置状态包,依靠其副作用完成自动注册。 +from . import states as _bundled_states # noqa: F401 +from .auto_save_dict import AutoSaveDict +from .runner import WorkflowRunner +from .state import WorkflowContext, WorkflowStateBase +from .state_registry import ( + build_state, + build_workflow, + register_state, + registered_state_names, + unregister_state, +) +from .states_manager import StatesManager + +__all__ = [ + "AutoSaveDict", + "StatesManager", + "WorkflowContext", + "WorkflowRunner", + "WorkflowStateBase", + "build_state", + "build_workflow", + "register_state", + "registered_state_names", + "unregister_state", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf554610257b96b680365e7bd7588874d2a23f5d Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/_tail_tasks.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/_tail_tasks.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7925a11ac0e62a15da8d24ca7f99890c73d40d52 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/_tail_tasks.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/auto_save_dict.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/auto_save_dict.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..789e2fa9094a071c3b64610b1d286517286a2e79 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/auto_save_dict.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/runner.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/runner.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb8c4b8faa237b86cd972422e1c445c44c693bd Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/runner.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99ea2bb3531f27409a37cbcdd3ebaba7203c16cf Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state_registry.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state_registry.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e83ee14095b1ceb84e380603c835a88baa08b89e Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/state_registry.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/states_manager.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/states_manager.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54e9a2cdd255af25b375796d91c02d59b42f4c57 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/__pycache__/states_manager.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/_tail_tasks.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/_tail_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..0fa2411db2d758645556d6a4e8c8440311323196 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/_tail_tasks.py @@ -0,0 +1,147 @@ +"""跨批次持久化的"尾巴任务"存储。 + +**背景** + +:mod:`_review_state_helpers` 在一个审校阶段轮询到 ``stop_time`` 仍未 +100% approved 时,会把**未 approved 的那部分条目**单独上传成一个新 +的 Crowdin task("尾巴 task"),其 ``task_id`` 需要**跨批次**存活, +以便下一天 run 时在 ``last_first_review`` / ``last_second_review`` 状态 +里把它接回继续处理。 + +本模块就是这个跨批次 ``task_id`` 的落盘位置: + +.. code-block:: text + + workspace/ + ├── last_tasks.json ← 本模块的唯一落盘文件(跨批次不归档) + ├── workflow_state.json ← 当前批次的 state(归档走) + ├── project_run_data.json ← 当前批次的 state_data(归档走) + └── batches//... + +落盘结构:: + + { + "first_review": { + "task_id": "38428", + "file_id": "40886", + "batch_name": "vi_20261008204338", + "upload_path": "...xlsx", # 原始尾巴 xlsx 的本地路径 + "created_at": "2026-10-08T20:43:43+08:00", + "pending_count": 10 + }, + "second_review": { ... } # 可选,二审遗留走同样结构 + } + +**为什么单独一份文件而不是复用 state_data?** + +:class:`AutoSaveDict`(``project_run_data.json``)在当天 run 结束时会被 +:class:`WorkflowRunner` 的"归档"逻辑移动到批次目录,无法被下一天 run +直接读到。``last_tasks.json`` **不参与归档**,是跨批次持久化的 +"单一真相源"。 + +**只保留"最新一条"** + +每个 stage 的 slot 永远只持有**最新的尾巴 task_id**。老的尾巴 +如果没审完就滚进更新的尾巴 → 更新的尾巴继续覆盖本 slot。 +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +#: 落盘文件名;位于 ``workspace/`` 根下。 +TAIL_TASKS_FILENAME = "last_tasks.json" + + +class TailTaskStore: + """``workspace//last_tasks.json`` 的轻量读写器(按语种隔离)。 + + 线程不安全——框架单进程串行使用,不加锁。所有写都是**全文件覆盖**, + 读失败时回退为空 dict(而非抛错),避免因为初次运行文件不存在就挂掉。 + + **按语种分区**(2026-10-09 方案 2): + * ``lang`` 非空 → 落盘位置 ``workspace//last_tasks.json`` + (避免多语种并发时 ``first`` / ``second`` 槽被不同语种相互覆盖); + * ``lang`` 为空 → 向后兼容,落盘到 ``workspace/last_tasks.json``。 + 调用方若不传 ``lang``,等同于旧行为——方便单语种 / 旧测试复用。 + """ + + def __init__(self, workspace: Path, lang: str = "") -> None: + self.workspace: Path = Path(workspace) + self.lang: str = (lang or "").strip() + self.path: Path = self.path_for(self.workspace, self.lang) + + @classmethod + def path_for(cls, workspace: Path, lang: str = "") -> Path: + """返回按 ``lang`` 分区后的 ``last_tasks.json`` 绝对路径。 + + 供 ``translate_state`` / ``sibling_broadcast`` 等**只读**调用方拼路径 + 用——它们不需要构造完整 ``TailTaskStore`` 实例,只要一个 ``Path``。 + 与 ``__init__`` 的分区规则严格一致,二者改一处另一处自动跟随。 + """ + workspace = Path(workspace) + lang = (lang or "").strip() + if lang: + return workspace / lang / TAIL_TASKS_FILENAME + return workspace / TAIL_TASKS_FILENAME + + # ------------------------------------------------------------------ + def load_all(self) -> Dict[str, Any]: + """返回整个 ``last_tasks.json`` 的 dict 视图(不存在时返回空 dict)。""" + if not self.path.exists(): + return {} + try: + raw = self.path.read_text(encoding="utf-8") + except OSError as exc: + logger.warning("TailTaskStore: failed to read %s: %s", self.path, exc) + return {} + if not raw.strip(): + return {} + try: + data = json.loads(raw) + except json.JSONDecodeError as exc: + logger.warning("TailTaskStore: malformed %s: %s — treating as empty.", + self.path, exc) + return {} + return data if isinstance(data, dict) else {} + + def get(self, review_stage: str) -> Optional[Dict[str, Any]]: + """按阶段取出一条尾巴记录;不存在返回 ``None``。""" + data = self.load_all() + record = data.get(review_stage) + return record if isinstance(record, dict) and record else None + + def put(self, review_stage: str, record: Dict[str, Any]) -> None: + """插入/覆盖指定阶段的尾巴记录;立即落盘。""" + data = self.load_all() + data[review_stage] = dict(record) + self._save(data) + + def clear(self, review_stage: str) -> None: + """移除指定阶段的尾巴记录;立即落盘。若不存在则是幂等 no-op。""" + data = self.load_all() + if review_stage in data: + del data[review_stage] + self._save(data) + + # ------------------------------------------------------------------ + def _save(self, data: Dict[str, Any]) -> None: + try: + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix(self.path.suffix + ".tmp") + tmp.write_text( + json.dumps(data, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + import os as _os + _os.replace(tmp, self.path) + except OSError as exc: + logger.warning("TailTaskStore: failed to write %s: %s", self.path, exc) + + +__all__ = ["TailTaskStore", "TAIL_TASKS_FILENAME"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/auto_save_dict.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/auto_save_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c9e3a730c73359708dc8a4b28ae273b355200e --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/auto_save_dict.py @@ -0,0 +1,171 @@ +"""工作流业务数据的自动持久化字典。 + +:class:`~.states_manager.StatesManager`(管理状态完成位)与基于 +``project_run_data.json`` 的**业务数据**字典成对使用:字典任意改动 +都会立即写回磁盘,保证崩溃/受 SIGTERM 后能断点续跑。 + +:class:`AutoSaveDict` 继承 ``dict``,以产品无关的形式复现上述契约: + +* 每次 ``__setitem__`` / ``update`` / ``pop`` / ``setdefault`` + 都会回调 ``save_callback``; +* :attr:`non_serialisable_keys` 中的 key 仅位于内存,**不会**写入磁盘磁盘(适合 + 存放 DataFrame / 文件句柄等活对象); +* 线程安全:所有变更方法均受 ``RLock`` 保护。 + +本类本身不开文件,持久化交给 ``save_callback``(一般由包封的 +:class:`WorkflowContext` 提供),测试时可注入内存 sink。 +""" + +from __future__ import annotations + +import threading +from typing import Any, Callable, Dict, Iterable, Optional, Set + + +class AutoSaveDict(dict): + """每次变更后自动落盘的 ``dict``。 + + 字段: + save_callback: ``() -> None`` 回调,变更后自动调用;为 ``None`` 时 + 禁用自动保存(适用于初始化阶段)。 + non_serialisable_keys: 列入此集的 key,:meth:`serialisable_items` + 不会将它们包含在内。 + """ + + def __init__( + self, + *args: Any, + save_callback: Optional[Callable[[], None]] = None, + non_serialisable_keys: Optional[Iterable[str]] = None, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self._save_callback: Optional[Callable[[], None]] = save_callback + self._non_serialisable: Set[str] = set(non_serialisable_keys or ()) + self._lock = threading.RLock() + # ``_saves_enabled`` 同时作为重入保护:如果 ``save_callback`` + # 自己又修改了字典(如写时间戳),避免无限递归。 + self._saves_enabled = True + # ------------------------------------------------------------------ + # 配置 + # ------------------------------------------------------------------ + def set_save_callback(self, callback: Optional[Callable[[], None]]) -> None: + """安装或清除 ``save_callback``。""" + with self._lock: + self._save_callback = callback + + def add_non_serialisable_key(self, key: str) -> None: + """将 ``key`` 标为“不写入持久化输出”。""" + with self._lock: + self._non_serialisable.add(key) + + @property + def non_serialisable_keys(self) -> Set[str]: + with self._lock: + return set(self._non_serialisable) + + def suspend_saves(self) -> _SavesSuspended: + """上下文管理器:``with`` 块内暂停自动保存。 + + 用于一个状态需要原子地更新多个 key——只触发一次保存:: + + with ctx.state_data.suspend_saves(): + ctx.state_data["a"] = 1 + ctx.state_data["b"] = 2 + # 仅在此处触发一次写盘。 + """ + return _SavesSuspended(self) + + # ------------------------------------------------------------------ + # dict 变更入口——所有修改均经由 ``_touch`` + # ------------------------------------------------------------------ + def __setitem__(self, key: Any, value: Any) -> None: + with self._lock: + super().__setitem__(key, value) + self._touch(key) + + def __delitem__(self, key: Any) -> None: + with self._lock: + super().__delitem__(key) + self._touch(key) + + def update(self, *args: Any, **kwargs: Any) -> None: # type: ignore[override] + with self._lock: + super().update(*args, **kwargs) + self._touch(None) + + def pop(self, key: Any, *args: Any) -> Any: + with self._lock: + value = super().pop(key, *args) + self._touch(key) + return value + + def popitem(self) -> Any: + with self._lock: + item = super().popitem() + self._touch(item[0] if item else None) + return item + + def setdefault(self, key: Any, default: Any = None) -> Any: # type: ignore[override] + with self._lock: + if key in self: + return super().__getitem__(key) + super().__setitem__(key, default) + self._touch(key) + return default + + def clear(self) -> None: # type: ignore[override] + with self._lock: + super().clear() + self._touch(None) + + # ------------------------------------------------------------------ + # 持久化辅助 + # ------------------------------------------------------------------ + def serialisable_items(self) -> Dict[str, Any]: + """返回不包含 :attr:`non_serialisable_keys` 的 dict 副本。""" + with self._lock: + return { + key: value + for key, value in self.items() + if key not in self._non_serialisable + } + + def _touch(self, key: Optional[Any]) -> None: + """触发 ``save_callback``;修改非持久化 key 时不触发。""" + if not self._saves_enabled or self._save_callback is None: + return + if key is not None and key in self._non_serialisable: + return + try: # noqa: SIM105 + self._save_callback() + except Exception: # pylint: disable=broad-except # noqa: BLE001 — 不从变更钩子抛出 + # 持久化错误由上层上下文记日志;向外抛出会弄脏未处理持久化异常的用户代码。 + pass + + +class _SavesSuspended: + """:meth:`AutoSaveDict.suspend_saves` 返回的上下文管理器。""" + + def __init__(self, target: AutoSaveDict) -> None: + self._target = target + self._previous: bool = True + + def __enter__(self) -> AutoSaveDict: + # 避免同一个管理器重入。 + with self._target._lock: # noqa: SLF001 — 友元类 + self._previous = self._target._saves_enabled + self._target._saves_enabled = False + return self._target + + def __exit__(self, exc_type, exc, tb) -> None: # noqa: D401 + with self._target._lock: # noqa: SLF001 + self._target._saves_enabled = self._previous + if exc is None and self._target._save_callback is not None: # noqa: SLF001 + try: # noqa: SIM105 + self._target._save_callback() # noqa: SLF001 + except Exception: # pylint: disable=broad-except # noqa: BLE001 + pass + + +__all__ = ["AutoSaveDict"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/runner.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..d821835a77d2e2c285d62f091555b862409ecfa0 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/runner.py @@ -0,0 +1,486 @@ +"""工作流驱动器。 + +给定一份 :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile`(或一组显式状态名), +驱动器依次: + +1. 通过 :func:`TiMi_HOK_Game_Translator.workflow.state_registry.build_workflow` 实例化工作流; +2. 初始化 :class:`~.states_manager.StatesManager`(全部为“未完成”); +3. 组装 :class:`WorkflowContext`(含 :class:`AutoSaveDict` 写入 ``project_run_data.json``, + :class:`StatesManager` 写入 ``project_status.json``); +4. 逐个执行状态 :meth:`execute`,支持 ``skip_after_current`` / ``finish`` 等提示; +5. 最后进入终态 :class:`FinishedState`。 +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +from typing import Any, Callable, Iterable, List, Optional + +from ..commons import DEFAULT_STATE_FILENAME +from ..commons import WorkflowState as StateEnum +from ..config.schema import Config, LanguageProfile +from .auto_save_dict import AutoSaveDict +from .state import WorkflowContext, WorkflowStateBase +from .state_registry import build_state, build_workflow +from .states_manager import StatesManager + +logger = logging.getLogger(__name__) + +_RUN_DATA_FILENAME = "project_run_data.json" + + +class WorkflowRunner: + """驱动一种语种的工作流至完成。 + + 典型用法:: + + runner = WorkflowRunner( + config=config, + profile=config.language_profile("vi"), + vcs=vcs, source=source, llm=llm, platform=platform, + notifier=notifier, + ) + runner.run() + + 本类故意保持短小;可重用的拼装逻辑(后端创建、通知接线)均在 CLI。 + """ + + def __init__( + self, + *, + config: Config, + profile: Optional[LanguageProfile] = None, + vcs: Any, + source: Any, + llm: Any, + platform: Any, + notifier: Optional[Any] = None, + workflow_names: Optional[Iterable[str]] = None, + workspace: Optional[Path] = None, + state_filename: Optional[str] = None, + ) -> None: + self.config = config + self.profile = profile + self.vcs = vcs + self.source = source + self.llm = llm + self.platform = platform + self.notifier = notifier + + self.workspace = workspace or config.workspace_path() + self.workspace.mkdir(parents=True, exist_ok=True) + + # 【按语种分区】每条语种 profile 占用一个子目录,存放 state 文件和 + # last_tasks.json。多语种并发时各走各的子目录,互不覆盖。 + # - profile.id 非空(conf/languages/.json 的 "id" 字段,和文件名一致)→ 用 profile.id + # - 否则回退 config.target_locale(命令行传入或 config.yaml 顶层) + # - 都没有 → 空串(等同旧行为,state 直接落 workspace 根) + lang_dir_name = "" + if profile is not None and (profile.id or "").strip(): + lang_dir_name = profile.id.strip() + elif (config.target_locale or "").strip(): + lang_dir_name = config.target_locale.strip() + self._lang_dir_name: str = lang_dir_name + self._lang_scoped_workspace: Path = ( + self.workspace / lang_dir_name if lang_dir_name else self.workspace + ) + if lang_dir_name: + # 预创建语种子目录,避免首次写 state 时 parent 不存在。 + self._lang_scoped_workspace.mkdir(parents=True, exist_ok=True) + + # 确定本次执行的状态名列表。 + if workflow_names is not None: + self._state_names: List[str] = list(workflow_names) + elif profile is not None and profile.workflow: + self._state_names = list(profile.workflow) + else: + self._state_names = _default_workflow() + + # 状态文件(完成位记录)与业务数据文件——落到按语种分区的子目录。 + self._state_file_path = self._lang_scoped_workspace / ( + state_filename or DEFAULT_STATE_FILENAME + ) + self._run_data_path = self._lang_scoped_workspace / _RUN_DATA_FILENAME + + # ------------------------------------------------------------------ + # 对外 API + # ------------------------------------------------------------------ + def run(self, *, fresh: bool = False, batch: str | None = None) -> str: + """执行工作流并返回最终状态名。 + + 参数: + fresh: ``True`` 时先删除上次持久化的 state 与 run_data,强制从头跑。 + 与 ``batch`` 互斥。 + batch: 指定一个历史批次名(如 ``"vi_20261008204338"``),从该批次 + 的 ``_archive/`` 目录把 state 与 run_data 还原回 workspace 根, + 然后 Runner 的 "skip already completed" 逻辑会自动跳过已完成的 + state,从第一个未完成的 state 继续。与 ``fresh`` 互斥。 + (两者都为默认值时)**M 语义**:等同于"新开批次 + 软清理"—— + 删除 workspace 根下残留的 state 文件,但**保留** ``last_tasks.json`` + 等跨批次持久化状态。 + """ + if fresh and batch: + # 调用方传入的互斥由 CLI 层拦截;这里再兜底一次。 + raise ValueError("Runner.run: fresh=True and batch is set — mutually exclusive.") + + if batch: + # --batch:从归档恢复 state;若恢复不到,日志告警后按新批次处理。 + restored = self._restore_from_archive(batch) + if restored: + logger.info( + "WorkflowRunner: resuming batch %s from %s", + batch, restored, + ) + else: + logger.warning( + "WorkflowRunner: --batch %s given but no archive found; " + "starting a fresh batch instead.", + batch, + ) + self._delete_persistent_files() + else: + # 无 --batch:删 workspace 根的 state 残留。 + # last_tasks.json 由 _delete_persistent_files 本就不碰,等同 M 语义。 + # 【方案 2 友好提示】若发现现场有未完成的 state,提示用户可以 + # 用 --batch 续跑;但为了不破坏 Day-N 日常"自动开新批次" + # 的习惯,这里**不阻塞**,只告警。 + if not fresh: + existing_batch = self._read_batch_name_from_workspace() + if existing_batch: + logger.warning( + "WorkflowRunner: detected incomplete state in %s " + "belonging to batch %r. Starting a NEW batch and " + "DISCARDING this progress. " + "If you intended to resume, Ctrl+C now and re-run with " + "'--batch %s'; if you really want a fresh batch, " + "re-run with '--fresh' to silence this warning.", + self._state_file_path, existing_batch, existing_batch, + ) + self._delete_persistent_files() + + # 实例化具体状态。 + states = build_workflow(self._state_names) + + manager = StatesManager(self._state_file_path) + manager.initialize({name: False for name in self._state_names}) + + # 加载已持久化的业务数据。 + run_data = self._load_run_data() + + ctx = self._build_context(run_data, manager) + + # -- 驱动状态机。 + try: + for idx, state in enumerate(states): + state_name = state.name + if manager.is_completed(state_name): + logger.info( + "WorkflowRunner: %s already completed — skipping.", + state_name, + ) + continue + + logger.info( + "WorkflowRunner: entering %s (%d/%d)", + state_name, idx + 1, len(states), + ) + next_hint = state.execute(ctx) + + # 每个状态执行后都将业务数据写盘,避免中途崩溃丢失进度。 + self._save_run_data(run_data) + + if isinstance(next_hint, str) and next_hint: + # 显式跳转——前推指针。 + target_idx = _index_of(states, next_hint) + if target_idx is not None: + # ``for`` 循环会自然推进 idx;此处将当前+1 至 + # target 之间的状态标为“已完成”,完成快进。 + for skipped_state in states[idx + 1: target_idx]: + manager.mark_completed(skipped_state.name) + continue + else: + logger.warning( + "WorkflowRunner: %s requested jump to unknown state %r", + state_name, next_hint, + ) + + # 终态。 + finished = build_state(StateEnum.FINISHED.value) + logger.info("WorkflowRunner: entering %s (terminal)", finished.name) + finished.execute(ctx) + + # 【批次归档】仅在正常完成时触发:把当前批次的 state 文件移到 + # ``workspace/batches//_archive/``,为下一天的 run 清出 workspace。 + # 异常/中断路径不归档,让续跑能看到残留 state 继续。 + self._archive_batch_state(ctx) + + return finished.name + + except Exception: + logger.exception("WorkflowRunner: pipeline failed") + # 失败时仍尽量写盘当前进度后重新抛出,方便事后排查。 + try: + self._save_run_data(run_data) + manager.save() + except Exception: # pylint: disable=broad-except # noqa: BLE001 + pass + raise + + # ------------------------------------------------------------------ + # 内部实现 + # ------------------------------------------------------------------ + def _build_context( + self, + run_data: AutoSaveDict, + manager: StatesManager, + ) -> WorkflowContext: + profile = self.profile + if profile is None: + profile = self.config.language_profile( + self.config.target_locale or "target", + ) + return WorkflowContext( + config=self.config, + vcs=self.vcs, + source=self.source, + llm=self.llm, + platform=self.platform, + notifier=self.notifier, + language_profile=profile, + entries=[], + state_payload={}, + state_data=run_data, + workspace=self.workspace, + states_manager=manager, + ) + + def _load_run_data(self) -> AutoSaveDict: + """从磁盘初始化并返回一份新的 :class:`AutoSaveDict`。""" + callback = self._save_run_data_callback() + data = AutoSaveDict(save_callback=None) # 加载时暂不写盘 + if self._run_data_path.exists(): + try: + raw = json.loads(self._run_data_path.read_text(encoding="utf-8")) + if isinstance(raw, dict): + data.update(raw) + except (OSError, json.JSONDecodeError) as exc: + logger.warning( + "WorkflowRunner: failed to load run data %s: %s", + self._run_data_path, exc, + ) + data.set_save_callback(callback) + # 将 dict 本身绑定到回调闭包上,以便内部序列化。 + self._run_data_ref = data + return data + + def _save_run_data_callback(self) -> Callable[[], None]: + def _cb() -> None: + data = getattr(self, "_run_data_ref", None) + if data is None: + return + self._save_run_data(data) + return _cb + + def _save_run_data(self, data: AutoSaveDict) -> None: + try: + self._run_data_path.parent.mkdir(parents=True, exist_ok=True) + payload = data.serialisable_items() + tmp = self._run_data_path.with_suffix(self._run_data_path.suffix + ".tmp") + tmp.write_text( + json.dumps(payload, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + import os as _os + _os.replace(tmp, self._run_data_path) + except OSError as exc: + logger.warning( + "WorkflowRunner: failed to write %s: %s", + self._run_data_path, exc, + ) + + def _delete_persistent_files(self) -> None: + for path in (self._state_file_path, self._run_data_path): + try: + path.unlink(missing_ok=True) + except OSError as exc: + logger.warning("WorkflowRunner: could not delete %s: %s", path, exc) + + # ------------------------------------------------------------------ + def _restore_from_archive(self, batch_name: str) -> Path | None: + """为续跑 ``--batch `` 恢复 state 文件。 + + 恢复优先级(2026-10-09 方案 2 增强): + + 1. **优先:workspace 现场**。若按语种分区的 state 文件(本次 Runner + 预先指向 ``workspace//workflow_state.json``)**已经存在** + 且其对应的 ``project_run_data.json`` 里 ``review.batch_name`` + 恰好等于传入的 ``batch_name``——说明这就是上次崩溃/中断留下 + 的现场,**原地续跑**(不动文件)。这解决了"归档只在 + FinishedState 跑完才做、崩溃时 _archive/ 不存在"的缺陷。 + 2. **其次:归档目录**。从 ``batches//_archive/`` 复制归档 + 的 state 文件到 workspace 的语种子目录。 + 3. 以上都失败 → 返回 ``None``,调用方会走"启新批次"路径。 + + 流程: + * 情况 1 命中:返回 workspace 的语种子目录路径(用于日志); + **不**清理、**不**复制,让 Runner 的 "skip is_completed" 跳转 + 到第一个未完成的 state。 + * 情况 2 命中: + a) 定位 ``_archive`` 目录;不存在则跳到 3; + b) 先清掉现场的 state / run_data(避免和归档内容混杂); + c) 分别把 ``workflow_state.json`` 和 ``project_run_data.json`` + 从归档**复制**(不是移动)回现场——保留归档完整,便于反 + 复续跑; + d) 返回归档目录绝对路径。 + + 若归档存在但两份 state 都读不到(空归档),仍返回 ``None`` 使调用方 + 回落到"新开批次"路径,这是比"静默跑一个空工作流"更安全的行为。 + """ + # ------- Case 1: 优先用 workspace 现场 ------- + workspace_batch = self._read_batch_name_from_workspace() + if workspace_batch and workspace_batch == batch_name: + logger.info( + "WorkflowRunner: found live workspace state for batch %s " + "(workflow_state.json=%s). Resuming in place without archive restore.", + batch_name, self._state_file_path, + ) + return self._lang_scoped_workspace + + # ------- Case 2: 从 _archive/ 归档恢复 ------- + archive_dir = self.workspace / "batches" / batch_name / "_archive" + if not archive_dir.exists() or not archive_dir.is_dir(): + return None + + src_state = archive_dir / self._state_file_path.name + src_run_data = archive_dir / self._run_data_path.name + if not src_state.exists() and not src_run_data.exists(): + return None + + # 清掉 workspace 现场残留的 state 文件,避免和归档内容混杂。 + self._delete_persistent_files() + + import shutil + copied = 0 + for src, dst in ( + (src_state, self._state_file_path), + (src_run_data, self._run_data_path), + ): + if not src.exists(): + continue + try: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(str(src), str(dst)) + copied += 1 + logger.debug( + "WorkflowRunner: restored %s ← %s", dst.name, src, + ) + except OSError as exc: + logger.warning( + "WorkflowRunner: failed to restore %s ← %s: %s", + dst, src, exc, + ) + + return archive_dir if copied > 0 else None + + def _read_batch_name_from_workspace(self) -> str: + """读 workspace 现场 ``project_run_data.json`` 里的 ``review.batch_name``。 + + 用于判断 workspace 根(按语种分区后的子目录)里残留的 state 文件 + 是否属于用户想续跑的那个 batch_name。读失败/字段缺失/文件不存在都 + 返回空串——调用方会据此继续走归档恢复路径。 + """ + if not self._run_data_path.exists(): + return "" + try: + raw = json.loads(self._run_data_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + logger.debug( + "WorkflowRunner: _read_batch_name_from_workspace failed on %s: %s", + self._run_data_path, exc, + ) + return "" + if not isinstance(raw, dict): + return "" + name = raw.get("review.batch_name") or raw.get("translate.batch_name") or "" + return str(name or "").strip() + + # ------------------------------------------------------------------ + def _archive_batch_state(self, ctx: Any) -> None: + """流水线正常完成后,把当前批次的 state 文件归档到批次目录。 + + 移动的文件(现均位于按语种分区的子目录 ``workspace//``): + + * ``workspace//workflow_state.json`` + * ``workspace//project_run_data.json`` + + **不**移动的文件(跨批次保留): + + * ``workspace//last_tasks.json``——下一天 ``last_first_review`` / + ``last_second_review`` state 要靠它接回昨日尾巴 task。 + * ``workspace/svn/``、``workspace/git/``、``workspace/p4/`` 等 VCS 工作副本。 + * ``workspace/batches//`` 下的审校产物本身。 + + 归档位置:``workspace/batches//_archive/``;若当前批次 + 名不可解析(state_data 没写)则跳过归档——保守行为优先。 + """ + batch_name: str = "" + try: + # 以 review 流程写入的 batch_name 作为归档目录依据。 + batch_name = str(ctx.state_data.get("review.batch_name", "") or "") + except Exception: # pylint: disable=broad-except # noqa: BLE001 + batch_name = "" + + if not batch_name: + logger.info( + "WorkflowRunner: no batch_name in state_data; skipping archive. " + "state files remain in workspace root." + ) + return + + archive_dir = self.workspace / "batches" / batch_name / "_archive" + try: + archive_dir.mkdir(parents=True, exist_ok=True) + except OSError as exc: + logger.warning( + "WorkflowRunner: cannot create archive dir %s: %s", archive_dir, exc, + ) + return + + import shutil + for src in (self._state_file_path, self._run_data_path): + if not src.exists(): + continue + dst = archive_dir / src.name + try: + shutil.move(str(src), str(dst)) + logger.info("WorkflowRunner: archived %s → %s", src.name, dst) + except OSError as exc: + logger.warning( + "WorkflowRunner: failed to archive %s → %s: %s", + src, dst, exc, + ) + + +# --------------------------------------------------------------------------- +# 辅助函数 +# --------------------------------------------------------------------------- +def _default_workflow() -> List[str]: + """未提供 profile 时的最小可行工作流。""" + return [ + StateEnum.PULL_VCS.value, + StateEnum.TRANSLATE.value, + StateEnum.VALIDATE_DATA.value, + StateEnum.PUSH_VCS.value, + ] + + +def _index_of(states: List[WorkflowStateBase], name: str) -> Optional[int]: + for i, s in enumerate(states): + if s.name == name: + return i + return None + + +__all__ = ["WorkflowRunner"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state.py new file mode 100644 index 0000000000000000000000000000000000000000..d84c514b0686793dad87b9f21e749abd20627ebc --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state.py @@ -0,0 +1,123 @@ +"""工作流上下文与状态基类。 + +工作流建模为线性状态机,由 :class:`~.runner.WorkflowRunner` 驱动。 +每个状态收到一份 :class:`WorkflowContext` 快照,执行副作用后返回下一个状态名 +或 ``None``(流水线结束)。持久化与并发由 +:class:`~.states_manager.StatesManager` 与上下文中自动落盘的 +:class:`~.auto_save_dict.AutoSaveDict` 处理。 +""" + +from __future__ import annotations + +import abc +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ..commons import WorkflowState as StateEnum +from ..config.schema import Config, LanguageProfile +from ..llm.base import LLMClient +from ..platforms.base import TranslationPlatform +from ..sources.base import Entry, LocalizationSource +from ..vcs.base import VcsClient +from .auto_save_dict import AutoSaveDict + + +@dataclass +class WorkflowContext: + """供状态使用的共享上下文。 + + 上下文在状态之间**共享**,前一状态的修改对后续状态可见。提供两类持久化面: + + * :attr:`state_payload`——普通 dict,驱动器(:class:`~.runner.WorkflowRunner`) + 在每次状态切换时会将它写入状态文件。适合少量、JSON 安全的转移标记。 + * :attr:`state_data`——:class:`AutoSaveDict`,每次变更均即时落盘;适合存放 + 必须存活进程重启的业务数据(任务 id、DataFrame、中间输出)。 + 使用 :meth:`AutoSaveDict.add_non_serialisable_key` 注册的 key + 保留在内存但不写入磁盘。 + + 字段: + config: 完整合并后的 :class:`Config`。 + language_profile: 当前生效的 :class:`LanguageProfile`;当用户未提供 profile 时, + 它是由 :meth:`Config.language_profile` 合成的一份。 + vcs / source / llm / platform / notifier: 本次选择的同名后端。 + entries: 流经流水线的内存条目列表。 + state_payload: 少量、JSON 安全的转移标记。 + state_data: :class:`AutoSaveDict`,存放业务关键数据。 + workspace: workspace 绝对路径(启动时等于 ``config.workspace_path()``)。 + states_manager: 可选,指向驱动的 + :class:`~.states_manager.StatesManager`,方便状态调用 + :meth:`~.states_manager.StatesManager.is_completed` 实现幂等重启。 + """ + + config: Config + vcs: VcsClient + source: LocalizationSource + llm: LLMClient + platform: TranslationPlatform + notifier: Optional[Any] = None # 来自 ``notify`` 子包的 ``Notifier``。 + + language_profile: Optional[LanguageProfile] = None + + #: 流经流水线的内存条目列表。 + entries: List[Entry] = field(default_factory=list) + + #: 与当前状态名一同持久化的自由 payload。 + #: 保持为普通 dict,方便 :meth:`~.runner.WorkflowRunner.save` 一次性原子写入。 + state_payload: Dict[str, Any] = field(default_factory=dict) + + #: 自动持久化的业务数据表(参见类 docstring)。 + state_data: AutoSaveDict = field(default_factory=AutoSaveDict) + + #: workspace 绝对路径(启动时等于 ``config.workspace_path()``)。 + workspace: Path = field(default_factory=Path.cwd) + + #: 由 :class:`~.runner.WorkflowRunner` 回塑,供子状态查看其他状态的完成标志。 + states_manager: Optional[Any] = None + + +class WorkflowStateBase(abc.ABC): + """所有工作流状态的基类。 + + 子类需设置类属性 :attr:`name` 为 + :class:`~TiMi_HOK_Game_Translator.commons.WorkflowState` 中的某个值(或通过 + :func:`TiMi_HOK_Game_Translator.workflow.state_registry.register_state` 注册的自定义名), + 并实现 :meth:`execute` 执行副作用。 + """ + + #: 状态唯一名(参见 :class:`~TiMi_HOK_Game_Translator.commons.WorkflowState`)。 + name: str = "" + + # ------------------------------------------------------------------ + # 具体状态常用的辅助方法 + # ------------------------------------------------------------------ + def _already_completed(self, ctx: WorkflowContext) -> bool: + """当本状态已被标为完成时返回 True。 + + 子类一般在 :meth:`execute` 开头调用,实现“断点重跑时跳过已完成状态”。 + """ + mgr = ctx.states_manager + return bool(mgr and mgr.is_completed(self.name)) + + def _mark_completed(self, ctx: WorkflowContext) -> None: + """将本状态的完成位在 states_manager 上置位。""" + mgr = ctx.states_manager + if mgr is not None: + mgr.mark_completed(self.name) + + @abc.abstractmethod + def execute(self, ctx: WorkflowContext) -> Optional[str]: + """执行本状态的副作用,并返回下一个状态名。 + + 返回值: + + * ``None``——按驱动器的序列推进到下一个状态(无下一状态时结束); + * 字符串名称——直接跳到目标状态(用于遗留处理/快进逻辑)。 + """ + + # ------------------------------------------------------------------ + def __repr__(self) -> str: # pragma: no cover - trivial + return f"<{type(self).__name__} name={self.name!r}>" + + +__all__ = ["WorkflowContext", "WorkflowStateBase", "StateEnum"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state_registry.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5002a0e23f60d38e76e2895b5b80d10e25718065 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/state_registry.py @@ -0,0 +1,100 @@ +"""工作流状态注册表。 + +框架内置一套**标准** 17 个状态(参见 +:class:`TiMi_HOK_Game_Translator.commons.WorkflowState`),但任一语种 profile 只列出 +实际需要的那一子集。本注册表就是运行时的 ``state_name → state_instance`` 映射, +供 :class:`~.runner.WorkflowRunner` 从 :class:`~TiMi_HOK_Game_Translator.config.LanguageProfile` +实例化完整工作流。 + +注册方式 +-------- +内置状态在导入时自行调用 :func:`register_state`;第三方状态可采同样方式, +既可在模块导入时产生副作用,也可在插件入口中延迟调用。 + +覆盖已有状态 +------------ +重复注册时必须传 ``replace=True``;这份提时可以避免无关导入静默覆盖关键状态。 +""" + +from __future__ import annotations + +import logging +from typing import Callable, Dict, Iterable, List, Type, Union + +from .state import WorkflowStateBase + +logger = logging.getLogger(__name__) + +# name → class-or-factory +_REGISTRY: Dict[str, Union[Type[WorkflowStateBase], Callable[[], WorkflowStateBase]]] = {} + + +def register_state( + name: str, + factory: Union[Type[WorkflowStateBase], Callable[[], WorkflowStateBase]], + *, + replace: bool = False, +) -> Union[Type[WorkflowStateBase], Callable[[], WorkflowStateBase]]: + """将状态类或无参工厂注册为 ``name``。 + + ``factory`` 可为类或无参可调用对象,后者方便“部分应用后再注册”。 + + ``name`` 已存在时必须传 ``replace=True``,否则抛 :class:`ValueError`。 + """ + if not replace and name in _REGISTRY and _REGISTRY[name] is not factory: + existing = _REGISTRY[name] + existing_repr = getattr(existing, "__name__", repr(existing)) + raise ValueError( + f"State {name!r} is already registered to {existing_repr}. " + "Pass replace=True to override." + ) + _REGISTRY[name] = factory + return factory + + +def unregister_state(name: str) -> None: + """从注册表中移除 ``name``(主要供测试使用)。""" + _REGISTRY.pop(name, None) + + +def registered_state_names() -> List[str]: + """返回已注册状态名称列表(排序后)。""" + return sorted(_REGISTRY) + + +def build_state(name: str) -> WorkflowStateBase: + """实例化 ``name`` 对应的状态。 + + 异常: + KeyError: ``name`` 未注册。 + """ + if name not in _REGISTRY: + raise KeyError( + f"No workflow state registered under {name!r}. " + f"Registered states: {registered_state_names()}." + ) + factory = _REGISTRY[name] + instance = factory() # type: ignore[operator] + if not isinstance(instance, WorkflowStateBase): + raise TypeError( + f"Factory for state {name!r} produced {type(instance).__name__}, " + "which is not a WorkflowStateBase." + ) + # 当类属性 ``name`` 未设置时,以注册时传入的名称为准。 + if not instance.name: + instance.name = name + return instance + + +def build_workflow(names: Iterable[str]) -> List[WorkflowStateBase]: + """依次解析 ``names``,返回已实例化的工作流列表。""" + return [build_state(name) for name in names] + + +__all__ = [ + "build_state", + "build_workflow", + "register_state", + "registered_state_names", + "unregister_state", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__init__.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9db2909942937584c40a1222d08e448a4601f2f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__init__.py @@ -0,0 +1,75 @@ +"""内置工作流状态实现。 + +导入本子包会自动调用 +:func:`~TiMi_HOK_Game_Translator.workflow.state_registry.register_state` +对每个内置状态进行注册;第三方插件可采同样方式新增自定义状态。 + +目录结构——一个状态一个模块,保持完全的产品无关性 +(无 Excel 假设、无繁简预处理、无特定通知器)。 +""" + +from ...commons import WorkflowState as _S +from ..state_registry import register_state +from .finished_state import FinishedState +from .first_review_state import FirstReviewState +from .increment_match_state import IncrementMatchState +from .last_first_review_state import LastFirstReviewState +from .last_merge_data_state import LastMergeDataState +from .last_second_review_state import LastSecondReviewState +from .light_review_state import LightReviewState +from .merge_data_state import MergeDataState +from .pull_vcs_state import PullVcsState +from .push_multi_vcs_state import PushMultiVcsState +from .push_vcs_state import PushVcsState +from .second_review_state import SecondReviewState +from .translate_state import TranslateState +from .update_grn_tm_state import UpdateGrnTmState +from .update_tm_state import UpdateTmState +from .validate_data_state import ValidateDataState + +# ---- 将内置状态以标准名称注册到注册表 ------------------------- +register_state(_S.PULL_VCS.value, PullVcsState, replace=True) +register_state(_S.PUSH_VCS.value, PushVcsState, replace=True) +register_state(_S.PUSH_MULTI_VCS.value, PushMultiVcsState, replace=True) +register_state(_S.TRANSLATE.value, TranslateState, replace=True) +register_state(_S.LIGHT_REVIEW.value, LightReviewState, replace=True) +register_state(_S.FIRST_REVIEW.value, FirstReviewState, replace=True) +register_state(_S.SECOND_REVIEW.value, SecondReviewState, replace=True) +register_state(_S.LAST_FIRST_REVIEW.value, LastFirstReviewState, replace=True) +register_state(_S.LAST_SECOND_REVIEW.value, LastSecondReviewState, replace=True) +register_state(_S.LAST_MERGE_DATA.value, LastMergeDataState, replace=True) +register_state(_S.MERGE_DATA.value, MergeDataState, replace=True) +register_state(_S.VALIDATE_DATA.value, ValidateDataState, replace=True) +register_state(_S.UPDATE_TM.value, UpdateTmState, replace=True) +register_state(_S.UPDATE_GRN_TM.value, UpdateGrnTmState, replace=True) +register_state(_S.INCREMENT_MATCH.value, IncrementMatchState, replace=True) +register_state(_S.FINISHED.value, FinishedState, replace=True) + +# ⚠️ 已移除:``dtxml_merge`` 的 workflow 别名注册 +# --------------------------------------------------------------- +# 历史背景:旧版本把 ``dtxml_merge`` 作为 workflow 的一个可选状态注册; +# 自 2026-10-09 起 ``MergeDataState`` 已成为统一实现,``dtxml_merge`` +# 别名无实际价值,并会污染前端"状态编排"面板。 +# 相关的 ``state_payload["dtxml_merge.*"]`` 兼容 key 由 MergeDataState +# 继续双写(push_vcs 旧实现据此读取),不受本注册移除影响。 +# 老的 ``conf/languages/*.yaml`` 若仍在 workflow 中写了 ``dtxml_merge``, +# 需迁移为 ``merge_data``(本次已随 YAML 批量更新同步修复)。 + +__all__ = [ + "FinishedState", + "FirstReviewState", + "IncrementMatchState", + "LastFirstReviewState", + "LastMergeDataState", + "LastSecondReviewState", + "LightReviewState", + "MergeDataState", + "PullVcsState", + "PushMultiVcsState", + "PushVcsState", + "SecondReviewState", + "TranslateState", + "UpdateGrnTmState", + "UpdateTmState", + "ValidateDataState", +] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/__init__.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f949fcc053346ed8c9772890c9b848861946169 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/__init__.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/_review_state_helpers.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/_review_state_helpers.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f2e987092d876d9394eeefe9dc22cee5fa7035d Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/_review_state_helpers.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/finished_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/finished_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22ce0aac4484017fb1ae7986a2ce6ba8d8a051ba Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/finished_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/first_review_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/first_review_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c29b8c70bb4dbbdd4d68569f4355f701892372e0 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/first_review_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/increment_match_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/increment_match_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7be1cd44a7ef604095d29014825fb19f183a285c Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/increment_match_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_first_review_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_first_review_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f51b83103c68b1c90fb5db3a6a3e3a86943ff67 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_first_review_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_merge_data_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_merge_data_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4507df7cfc391bb8f9b6c1d119fd8c393fceb495 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_merge_data_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_second_review_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_second_review_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..986f3c0ce9bf09227ccd67e46e6823706d01f4d4 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/last_second_review_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/light_review_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/light_review_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92865b557e3decf9be78dd72fa415c0efbefc633 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/light_review_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/merge_data_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/merge_data_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2597e07e929c2122dcc85799f6e308de3474c41b Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/merge_data_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/pull_vcs_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/pull_vcs_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e325294343f44f9065878d648fceb63531046090 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/pull_vcs_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_multi_vcs_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_multi_vcs_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c945c4a412d98ed90c0f8715b96674dc25af9d79 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_multi_vcs_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_vcs_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_vcs_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..006010b6d138350a46dd8431c138f94d0bd84bf6 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/push_vcs_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/second_review_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/second_review_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17b0fadfe71757167b60f31a59ef65cf7e07b23d Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/second_review_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/translate_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/translate_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c366b695dd0dbb54006581df6ce64a5d13d784c3 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/translate_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_grn_tm_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_grn_tm_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a64f35a7c32bbc0ba1b9e26a91a8db9fef4b76ad Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_grn_tm_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_tm_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_tm_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1a6224529df75b673c5ad5d9416fab1ea51a06 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/update_tm_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/validate_data_state.cpython-314.pyc b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/validate_data_state.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f749659617269b6f8e3eba3f5ddc5945902e1468 Binary files /dev/null and b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/__pycache__/validate_data_state.cpython-314.pyc differ diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/_review_state_helpers.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/_review_state_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f59face2210c2b641e8c99bf00465d391e5ead --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/_review_state_helpers.py @@ -0,0 +1,1140 @@ +""":mod:`light_review_state` 、 :mod:`first_review_state` 与 +:mod:`second_review_state` 共享的辅助。 + +三个审校状态骨架一致: + +1. 为对应 :class:`~TiMi_HOK_Game_Translator.commons.ReviewStage` 解析出平台; +2. **以批次为单位**把当前条目写成 **xlsx**(审校平台通用,Crowdin / Phrase + 都能解析——相比直接上传 dtxml / xml 等源文件格式,xlsx 的字段级 UI + 质量显著更好); +3. 上传并在平台上创建审校任务; +4. 将任务 id、批次目录、上传文件 id 写入 + :attr:`WorkflowContext.state_data`,方便重启续跑; +5. **轮询** :meth:`TranslationPlatform.get_task_status` 直到 Crowdin 侧审校任务 + 完成(``TaskStatus.APPROVED``)或达到 :attr:`ReviewConfig.stop_time` + 截止时间; +6. 把平台导出的译文(xliff)解析回 :attr:`WorkflowContext.entries`, + 供后续 ``validate_data`` / ``dtxml_merge`` / ``push_vcs`` 消费。 + +轮询策略 +-------- +* 间隔::attr:`ReviewConfig.poll_interval_seconds`,默认 + :const:`DEFAULT_REVIEW_POLL_INTERVAL_SECONDS` 秒; +* 截止::attr:`ReviewConfig.stop_time`(``"HH:MM"``,本地时区;为空代表 + **不设截止、一直轮询**,适合夜间作业或长任务场景); +* 未完成即到达截止 → 抛 :class:`PlatformError`,runner 把当前 state + 保留为"未完成";下次 ``python main.py run --language vi``(**不要 + --fresh**)会继续轮询同一个 ``task_id``(state_data 中已持久化)。 +""" + +from __future__ import annotations + +import json +import logging +import time +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, Optional + +from ...commons import DEFAULT_REVIEW_POLL_INTERVAL_SECONDS, PlatformError +from ...platforms._batch import build_batch_name, stage_dir, stage_file_stem +from ...platforms.base import TaskStatus +from ...platforms.factory import build_review_tool +from ...sources import XliffSource, XlsxSource +from .._tail_tasks import TailTaskStore +from ..state import WorkflowContext + +logger = logging.getLogger(__name__) + +#: 上传到平台的中间文件格式。Crowdin / Phrase 等都原生识别 xlsx。 +_UPLOAD_FORMAT = "xlsx" + + +def _build_platform_url(platform_name: str, project_id: str) -> str: + """根据平台名 + project_id 拼出该项目在平台 Web UI 上的入口 URL。 + + 不同平台 URL 规则: + * Phrase TMS:``https://cloud.memsource.com/web/project2/show/`` + (EU/US 账户 UI 共用 memsource 主域;``region`` 字段仅影响 IDM 鉴权); + * Crowdin:``https://crowdin.com/project//tasks`` + (数字 project_id 会被 302 到 identifier;直接跳到任务列表页更有用); + * 其他平台 / 未配置 ID:返回空串,调用方应回落到裸文本。 + + 通知消息里直接把该 URL 作为"项目入口"链接展示,审核人员一键跳转, + 无需在正文里罗列 ``project_id`` / ``task_id`` 这类对人阅读无直接价值的裸 ID。 + """ + if not project_id: + return "" + name = (platform_name or "").lower() + if name == "phrase": + return f"https://cloud.memsource.com/web/project2/show/{project_id}" + if name == "crowdin": + return f"https://crowdin.com/project/{project_id}/tasks" + return "" + +#: 平台导出译文的格式。Crowdin 默认导出 XLIFF 1.2。 +_EXPORT_FORMAT = "xliff" + + +def _resolve_lang(ctx: WorkflowContext) -> str: + """从 :class:`WorkflowContext` 解析语种标识,用于按语种分区的落盘路径。 + + 优先级与 :class:`WorkflowRunner` 的分区规则保持一致: + + * ``ctx.language_profile.id`` 非空 → 用 profile id(和 + ``conf/languages/.json`` 文件名一致,稳定); + * 否则 ``ctx.config.target_locale`` → 退回 config 顶层语种码; + * 都为空 → 空串(``TailTaskStore`` 会向后兼容地落到 ``workspace`` 根)。 + + 保持为"**共享 helper**"而非 Runner 的方法,是因为 state 层拿不到 Runner + 实例;由 ctx 推导是最 cheap 的方式。 + """ + profile = getattr(ctx, "language_profile", None) + if profile is not None: + pid = (getattr(profile, "id", "") or "").strip() + if pid: + return pid + cfg = getattr(ctx, "config", None) + if cfg is not None: + tl = (getattr(cfg, "target_locale", "") or "").strip() + if tl: + return tl + return "" + + +def run_review_stage( + ctx: WorkflowContext, + *, + review_stage: str, + resume_key_prefix: str, +) -> Optional[str]: + """执行一个审校阶段。 + + 成功时返回 ``None``(runner 会自然推进到下一个状态)。 + + 参数: + ctx: 工作流上下文。 + review_stage: :class:`ReviewStage` 之一。 + resume_key_prefix: 写入 :attr:`WorkflowContext.state_data` 时的 key 前缀( + 一般为 ``"first_review"`` / ``"second_review"`` / ``"light_review"``)。 + """ + profile = ctx.language_profile + review_cfg = profile.review(review_stage) if profile else None + target_locale = ( + (profile.target_locale if profile else "") + or ctx.config.target_locale + ) + + platform = build_review_tool( + profile if profile is not None else _synthetic_profile(ctx), + review_stage, + global_platform=ctx.config.platform, + ) + + # ------------------------------------------------------------------ + # 2026-10-09 方案 ①-🅱 + 方案 ②:二审入口的"昨日跨阶段条目"注入。 + # + # 当前阶段是 second_review 时,有**两类昨日遗留条目**要在打包前 + # prepend 到 ctx.entries ——它们都已经过了昨日的一审,不应该回头 + # 重走今日 first_review: + # + # A) ``last_review.second_only_entries``(方案 ② 新增) + # ← 由 ``LastMergeDataState`` 从一审遗留 approved 路由过来; + # 昨日一审通过、但二审尚未开始/完成。 + # + # B) ``last_second_review.pending_rollover_entries``(方案 ①-🅱) + # ← 由 ``LastSecondReviewState`` 从二审遗留 pending 直接填充; + # 昨日一审通过、二审到 deadline 时仍未审完的那部分。 + # + # 为什么注入点在"空 entries 检查"之前? + # 如果今天 pull_vcs 没有新增条目、first_review 也没产出 approved, + # 但有上述两类昨日遗留 → ctx.entries 为空、existing_task_id 为空 + # → 原来会被"空 entries 优雅跳过"分支消化掉 → 条目丢失。 + # 注入在前,让 ctx.entries 先补齐,就能走正常流程。 + # ------------------------------------------------------------------ + if review_stage == "second": + _SECOND_ONLY_ENTRIES_KEY = "last_review.second_only_entries" # pylint: disable=invalid-name + _SECOND_PENDING_ROLLOVER_KEY = "last_second_review.pending_rollover_entries" # pylint: disable=invalid-name + + second_only_raw = ctx.state_payload.get(_SECOND_ONLY_ENTRIES_KEY) or [] + pending_rollover_raw = ctx.state_payload.get(_SECOND_PENDING_ROLLOVER_KEY) or [] + + combined_raw = list(second_only_raw) + list(pending_rollover_raw) + if combined_raw: + from ...sources.base import Entry # noqa: WPS433 — 局部导入避免循环 + + # 反序列化为 Entry 列表。 + rolled: list = [] + for raw in combined_raw: + if not isinstance(raw, dict): + continue + try: + rolled.append( + Entry( + key=str(raw.get("key", "")), + source_text=str(raw.get("source_text", "") or ""), + target_text=str(raw.get("target_text", "") or ""), + context=str(raw.get("context", "") or ""), + comment=str(raw.get("comment", "") or ""), + metadata=dict(raw.get("metadata") or {}), + ) + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review[second]: skip malformed yesterday rollover item: %s", + exc, + ) + + if rolled: + # 【Rule 2b 精确版】对每条昨日条目做 key 冲突判定: + # * key 不冲突 → prepend 到 ctx.entries 头部; + # * key 冲突 + source 相同 → **原地替换** ctx.entries + # 里对应的今日版本(保留昨日 target_text 和审员进度); + # * key 冲突 + source 不同 → WARN 并丢弃昨日版本; + # * 通道间同 key 冲突(second_only 和 pending_rollover 撞) + # → 丢弃(防御性,正常不发生)。 + today_by_key = {e.key: e for e in ctx.entries} + today_entries_mutable: list = list(ctx.entries) + today_index_by_key = {e.key: i for i, e in enumerate(today_entries_mutable)} + seen_in_rolled: set = set() + + prepend_entries: list = [] + replaced_in_today = 0 + dropped_diff_source = 0 + dropped_cross_channel = 0 + + for e in rolled: + if e.key in seen_in_rolled: + # 通道内两条相同 key —— 保守丢第二条。 + dropped_cross_channel += 1 + continue + seen_in_rolled.add(e.key) + + if e.key not in today_by_key: + prepend_entries.append(e) + continue + + today_version = today_by_key[e.key] + if today_version.source_text == e.source_text: + # 保留昨日版本——它承载审员进度。 + idx = today_index_by_key[e.key] + today_entries_mutable[idx] = e + today_by_key[e.key] = e + replaced_in_today += 1 + else: + logger.warning( + "review[second]: dropping yesterday entry key=%r " + "because today has the same key with a DIFFERENT " + "source (today's version wins).", + e.key, + ) + dropped_diff_source += 1 + + before = len(ctx.entries) + ctx.entries = prepend_entries + today_entries_mutable + logger.info( + "review[second]: injected yesterday-rollover: new=%d, " + "replaced_in_today=%d (same source), dropped_diff_source=%d, " + "dropped_cross_channel=%d. " + "ctx.entries: %d → %d. " + "(sources: second_only=%d, second_pending=%d) " + "— these skip first_review and go directly into today's " + "second review task.", + len(prepend_entries), replaced_in_today, dropped_diff_source, + dropped_cross_channel, before, len(ctx.entries), + len(second_only_raw), len(pending_rollover_raw), + ) + + # 清空通道,防止下次 run 重复注入。 + ctx.state_payload.pop(_SECOND_ONLY_ENTRIES_KEY, None) + ctx.state_payload.pop(_SECOND_PENDING_ROLLOVER_KEY, None) + + # ------------------------------------------------------------------ + # 空 entries 的处理策略: + # + # 1) 没有续跑 task_id 且 entries 为 0 → 当天没有新增需要翻译的条目 + # (pull_vcs 加载到 0 条,或 translate 全部失败被过滤)。此时**优雅跳过** + # 本审校阶段:不建 Crowdin 任务、不写批次目录,直接返回 None 让 runner + # 推进到下一个 state。后续 process_pending(若已启用)会继续处理昨日遗留。 + # + # 2) 有续跑 task_id 但 entries 为 0 → 这是上一轮 run 已经把条目消费掉、 + # 现在只是来拉 xliff 回写的"续跑场景",不是异常。继续原路径即可 + # (下面 if not task_id 分支会被自动跳过,直接走轮询 + xliff 回写)。 + # ------------------------------------------------------------------ + existing_task_id = ctx.state_data.get(f"{resume_key_prefix}.task_id", "") or "" + if not ctx.entries and not existing_task_id: + logger.info( + "review[%s]: ctx.entries is empty and no resumable task_id — " + "nothing to review this round, skipping.", + review_stage, + ) + return None + + # 0. 解析/创建批次。整个 WorkflowContext 共享一个 batch_name, + # first/second review 两次会落到同一个批次目录的不同子目录下。 + batch_name = _resolve_batch_name(ctx, target_locale) + stage_root = stage_dir(Path(ctx.workspace), batch_name, review_stage) + stem = stage_file_stem(batch_name, review_stage) + upload_path = stage_root / f"{stem}.{_UPLOAD_FORMAT}" + export_path = stage_root / f"{stem}.{_EXPORT_FORMAT}" + meta_path = stage_root / f"{review_stage}.meta.json" + + # resume key 预声明,供后续各步骤复用。 + file_id_key = f"{resume_key_prefix}.file_id" + task_id_key = f"{resume_key_prefix}.task_id" + batch_key = f"{resume_key_prefix}.batch_name" + upload_key = f"{resume_key_prefix}.upload_path" + export_key = f"{resume_key_prefix}.export_path" + + task_id: str = ctx.state_data.get(task_id_key, "") or "" + is_resume = bool(task_id) + + if not task_id: + # 1. 把当前 entries 写成 xlsx(审校平台通用)。 + XlsxSource(encoding=ctx.config.source.encoding or "utf-8").dump( + ctx.entries, str(upload_path) + ) + logger.info( + "review[%s]: wrote xlsx %s (%d entries)", + review_stage, upload_path, len(ctx.entries), + ) + + # 2. 上传 + 创建任务。 + upload = platform.upload_source(str(upload_path), remote_path=upload_path.name) + ctx.state_data[file_id_key] = upload.file_id + ctx.state_data[batch_key] = batch_name + ctx.state_data[upload_key] = str(upload_path) + + # 2.1 把 Target 列的 LLM 预译作为"已有翻译"上传到 Crowdin。 + # Crowdin ``/files`` 挂载只接受源串;要让 Crowdin 侧看到预译文, + # 必须再调一次 ``/translations/{languageId}`` 接口。 + # 平台如果没实现该方法则跳过。 + _upload_translations_if_supported( + platform=platform, + file_id=upload.file_id, + target_locale=target_locale, + xlsx_path=upload_path, + review_stage=review_stage, + ) + + task = platform.create_task( + [upload.file_id], + target_locale, + review_stage=review_stage, + title=( + (review_cfg.project_name if review_cfg else "") + or f"{ctx.config.project_code} — {review_stage} — {batch_name}" + ), + ) + task_id = task.task_id + ctx.state_data[task_id_key] = task_id + logger.info( + "review[%s]: created task_id=%s on platform=%s (batch=%s)", + review_stage, task_id, platform.platform_name, batch_name, + ) + # 任务创建通知(中文、含关键信息) + stage_cn = { + "light": "轻量审校", + "first": "一审", + "second": "二审", + }.get(review_stage, review_stage) + upload_filename = upload_path.name + platform_url = _build_platform_url(platform.platform_name, platform.project_id) + entry_line = ( + f"平台入口:{platform_url}" if platform_url + else f"平台:{platform.platform_name}(project_id={platform.project_id})" + ) + _notify( + ctx, + review_stage, + f"📢 【{ctx.config.project_code}】{stage_cn}任务已创建\n" + f"目标语种:{target_locale}\n" + f"{entry_line}\n" + f"批次名:{batch_name}\n" + f"上传文件:{upload_filename}\n" + f"条目数:{len(ctx.entries)}\n" + f"请及时登录平台处理。", + ) + else: + logger.info( + "review[%s]: resuming with existing task_id=%s (batch=%s)", + review_stage, task_id, batch_name, + ) + + # 3. 写一份人类可读的批次元信息(便于后续排错 / 定位 Crowdin 任务)。 + _write_meta( + meta_path, + { + "review_stage": review_stage, + "batch_name": batch_name, + "project_id": platform.project_id, + "platform": platform.platform_name, + "task_id": task_id, + "file_id": ctx.state_data.get(file_id_key, ""), + "upload_path": str(upload_path), + "export_path": str(export_path), + "target_locale": target_locale, + "entry_count": len(ctx.entries), + "resumed": is_resume, + }, + ) + + # 4. 轮询等待 Crowdin 侧审校完成。 + poll_interval = _resolve_poll_interval(review_cfg) + # 【task 创建后立即计算 deadline】——相对格式(如 "+3m")的起点就是 + # 这里的 ``datetime.now()``(即"task 刚建好的时刻"),符合"审员从 + # 接到任务起 N 分钟内审完"的现实语义。续跑场景(is_resume=True) + # 已有 task_id 的时候 now 也是本轮进入 review state 的时刻——相对 + # deadline 本就是"从本次 run 开始算 N 分钟"的测试友好设定,续跑时也 + # 自然给审员新的 N 分钟窗口,不会立刻超时。 + deadline = _resolve_deadline(review_cfg, reference_time=datetime.now()) + logger.info( + "review[%s]: polling task_id=%s every %ds until %s", + review_stage, + task_id, + poll_interval, + deadline.isoformat(timespec="seconds") if deadline else "", + ) + final_info, hit_deadline = _poll_until_done_or_deadline( + platform=platform, + task_id=task_id, + review_stage=review_stage, + poll_interval_seconds=poll_interval, + deadline=deadline, + ctx=ctx, + ) + + # 5. 【条目级拆分】把本任务已 approved 的部分回写到 ctx.entries; + # 未 approved 的部分**立即在同一天建新尾巴 task**(审校员次日继续审), + # 并把新 task_id 持久化到跨批次的 ``workspace/last_tasks.json``。 + approved_xlsx = stage_root / f"{stem}_approved.xlsx" + pending_xlsx = stage_root / f"{stem}_pending.xlsx" + split = platform.split_approved_data( + task_id, + save_approved_path=str(approved_xlsx), + save_pending_path=str(pending_xlsx), + review_stage=review_stage, + ) + logger.info( + "review[%s]: split task_id=%s → approved=%d, pending=%d (is_complete=%s)", + review_stage, task_id, + len(split.extra.get("approved_keys", [])), + len(split.extra.get("pending_keys", [])), + split.is_complete, + ) + + # 5.1 approved 条目回写到 ctx.entries;pending 条目在当前 ctx.entries 中被 + # 清除,这样下游 validate_data / dtxml_merge / push_vcs 只处理已审部分。 + _apply_split_to_entries(ctx, approved_xlsx, split) + + # 5.2 pending 非空 → 建新尾巴 task,持久化到 last_tasks.json。 + tail_store = TailTaskStore(Path(ctx.workspace), lang=_resolve_lang(ctx)) + pending_keys = split.extra.get("pending_keys", []) or [] + if pending_keys: + _create_tail_task( + ctx=ctx, + platform=platform, + review_stage=review_stage, + target_locale=target_locale, + batch_name=batch_name, + pending_xlsx_path=pending_xlsx, + pending_count=len(pending_keys), + tail_store=tail_store, + review_cfg=review_cfg, + hit_deadline=hit_deadline, + ) + else: + # 整单审完 → 清空该阶段的历史尾巴(如果上一天还留着就一起清掉, + # 防止被 last_*_review state 误读为新尾巴)。 + tail_store.clear(review_stage) + + # 5.3 删除旧 task(Crowdin 侧已经把内容分到 approved_xlsx + 新尾巴 task, + # 旧 task 保留会污染 Crowdin 项目列表)。 + try: + platform.delete_task(task_id, review_stage=review_stage) + logger.info( + "review[%s]: deleted original task_id=%s on platform=%s " + "(contents split into approved=%d + new tail task)", + review_stage, + task_id, + platform.platform_name, + len(split.extra.get("approved_keys", [])), + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review[%s]: delete_task(%s) failed (continuing): %s", + review_stage, task_id, exc, + ) + + # 5.3.1 删除旧 task 关联的 file。task 已走到"条目拆分 + 建新尾巴"阶段, + # 原始上传的 xlsx 对后续轮次没有价值;不清掉会在 Crowdin 项目 + # 侧堆积(2026-10-09 实测确认缺这一步会残留文件)。 + old_file_id = str(ctx.state_data.get(file_id_key, "") or "") + if old_file_id: + try: + platform.delete_file(old_file_id, review_stage=review_stage) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review[%s]: delete_file(%s) failed (continuing): %s", + review_stage, old_file_id, exc, + ) + + # 5.4 保留 xliff 导出路径到 state_data,便于排错回溯。 + ctx.state_data[export_key] = str(export_path) + + # 6. 完成通知。 + stage_cn = { + "light": "轻量审校", + "first": "一审", + "second": "二审", + }.get(review_stage, review_stage) + if split.is_complete: + status_text = "✅ 全部通过" + else: + status_text = f"⚠️ 部分通过({len(pending_keys)} 条未完成,已滚入次日续审任务)" + platform_url = _build_platform_url(platform.platform_name, platform.project_id) + entry_line = ( + f"平台入口:{platform_url}" if platform_url + else f"平台:{platform.platform_name}(project_id={platform.project_id})" + ) + _notify( + ctx, + review_stage, + f"🏁 【{ctx.config.project_code}】{stage_cn}已结束\n" + f"目标语种:{target_locale}\n" + f"{entry_line}\n" + f"批次名:{batch_name}\n" + f"完成进度:{final_info.percent_completed:.1f}%\n" + f"结果:{status_text}", + ) + + return None + + +def _resolve_poll_interval(review_cfg: Any) -> int: + """按优先级解析本阶段的轮询间隔秒数。""" + if review_cfg is not None: + configured = int(getattr(review_cfg, "poll_interval_seconds", 0) or 0) + if configured > 0: + return configured + return DEFAULT_REVIEW_POLL_INTERVAL_SECONDS + + +def _resolve_deadline( + review_cfg: Any, + *, + reference_time: Optional[datetime] = None, +) -> Optional[datetime]: + """把 ``stop_time`` 解析为**绝对**的截止时刻。 + + 支持两种格式: + + 1. **绝对时刻** ``"HH:MM"`` —— 生产语义,"审员今日的审校截止时间": + * 空串或未配置 → 返回 ``None``(不设截止,一直轮询到任务完成); + * 解析成功 → 返回**今天**同时区下的绝对时刻; + * 若该时刻**已经早于当前时间**(例如今天 15:15 启动 run,而 + ``stop_time=15:10``),**不**顺延到明天——原样返回"今天的 + HH:MM"。调用方 :func:`_poll_until_done_or_deadline` 第一次 poll + 就会发现 ``now >= deadline`` → 直接走 ``split_approved_data`` + 分支,让明天的 ``last_*_review`` state 接手; + 2. **相对偏移** ``"+Nm"`` / ``"+Nh"`` / ``"+N"`` —— 测试语义, + "距离本次计算的参考时刻(``reference_time``,默认 ``datetime.now()``) + 向后 N 分钟/小时/分钟": + * ``"+3m"`` → reference_time + 3 分钟; + * ``"+2h"`` → reference_time + 2 小时; + * ``"+5"`` → 等价于 ``"+5m"`` (默认分钟); + * 这个格式便于测试时不手动改时间戳;上线前记得改回绝对 ``HH:MM``。 + + 格式错误 → 记一次 warning 后退化为"不设截止"。 + + 参数: + review_cfg: 当前阶段的 :class:`ReviewConfig`(可能为 ``None``); + reference_time: 解析相对格式时的"起点"。调用方应该在 **task 创建 + 成功之后**立即传入 ``datetime.now()``,这样相对偏移反映 + "审员从接到任务起 N 分钟"的真实窗口。默认 ``None`` → 用 + ``datetime.now()`` 的即时值。 + """ + if review_cfg is None: + return None + stop_time = (getattr(review_cfg, "stop_time", "") or "").strip() + if not stop_time: + return None + + ref = reference_time or datetime.now() + + # 相对格式:+Nm / +Nh / +N + if stop_time.startswith("+"): + return _parse_relative_deadline(stop_time, ref) + + # 绝对格式:HH:MM + try: + hh, mm = stop_time.split(":", 1) + hour = int(hh) + minute = int(mm) + except (ValueError, AttributeError): + logger.warning( + "review: invalid stop_time %r (expected 'HH:MM' or '+Nm'/'+Nh'); " + "ignoring deadline.", + stop_time, + ) + return None + now = datetime.now() + deadline = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if deadline <= now: + # 今日 HH:MM 已过:**不**顺延到明天,让轮询循环第一次就触发 deadline 分支。 + logger.info( + "review: stop_time %s is already in the past (now=%s) — " + "deadline will fire on the first poll attempt.", + stop_time, now.strftime("%H:%M:%S"), + ) + return deadline + + +def _parse_relative_deadline(stop_time: str, reference_time: datetime) -> Optional[datetime]: + """解析 ``"+Nm"`` / ``"+Nh"`` / ``"+N"`` 相对偏移。 + + 返回 ``reference_time + 偏移``;格式非法时记 warning 并返回 ``None``。 + + 支持单位: + * ``m`` / ``min`` / ``mins`` —— 分钟 + * ``h`` / ``hr`` / ``hrs`` —— 小时 + * 省略单位 —— 默认分钟 + + 示例:: + + _parse_relative_deadline("+3m", now) → now + 3min + _parse_relative_deadline("+2h", now) → now + 2h + _parse_relative_deadline("+5", now) → now + 5min + _parse_relative_deadline("+abc", now) → None (warning) + """ + body = stop_time[1:].strip().lower() # 去掉 '+' + if not body: + logger.warning( + "review: empty relative stop_time %r; ignoring deadline.", stop_time, + ) + return None + + # 拆数字部分和单位部分 + import re as _re + m = _re.match(r"^(\d+)\s*([a-z]*)$", body) + if not m: + logger.warning( + "review: invalid relative stop_time %r (expected '+Nm'/'+Nh'/'+N'); " + "ignoring deadline.", + stop_time, + ) + return None + + try: + n = int(m.group(1)) + except ValueError: + logger.warning( + "review: invalid number in relative stop_time %r; ignoring deadline.", + stop_time, + ) + return None + + unit = m.group(2) or "m" + if unit in ("m", "min", "mins", "minute", "minutes"): + delta_minutes = n + elif unit in ("h", "hr", "hrs", "hour", "hours"): + delta_minutes = n * 60 + else: + logger.warning( + "review: unknown unit %r in relative stop_time %r " + "(expected m/min/h/hr); ignoring deadline.", + unit, stop_time, + ) + return None + + from datetime import timedelta as _td + deadline = reference_time + _td(minutes=delta_minutes) + logger.info( + "review: relative stop_time %r → deadline=%s (reference=%s, +%dmin)", + stop_time, + deadline.isoformat(timespec="seconds"), + reference_time.isoformat(timespec="seconds"), + delta_minutes, + ) + return deadline + + +def _poll_until_done_or_deadline( + *, + platform: Any, + task_id: str, + review_stage: str, + poll_interval_seconds: int, + deadline: Optional[datetime], + ctx: WorkflowContext, +): + """阻塞轮询 ``task_id`` 直到 ``TaskStatus.APPROVED`` **或** ``deadline`` 到达。 + + 返回 ``(info, hit_deadline)``: + + * ``info``——最后一次 :class:`TaskInfo`; + * ``hit_deadline``——``True`` 表示到达 ``deadline`` 时仍未完成(下游会 + 按"部分审完"流程走 split_approved_data + 建新尾巴 task,而不是抛错)。 + + * ``REJECTED`` → 立即抛 :class:`PlatformError`(人工取消的任务,没必要再等); + * ``APPROVED`` → 返回 ``(info, False)``; + * 到达 ``deadline`` 仍未 APPROVED → 返回 ``(info, True)``,由调用方 + 继续走条目级拆分流程。 + """ + attempt = 0 + last_percent = -1.0 + while True: + attempt += 1 + info = platform.get_task_status(task_id, review_stage=review_stage) + percent = float(info.percent_completed or 0.0) + all_confirmed = bool(info.extra.get("all_confirmed", False)) + # 日志策略: + # * 进度有变动 (>=0.1%) 时**必打** INFO(关键节点可见); + # * 否则每 5 次轮询打一次心跳 INFO(让用户看到流水线仍在工作, + # 而不是误以为"假死"——Phrase 的 progress 在审员没点 Complete + # 之前即使 UI 显示 90% 也可能被 segmentsCount 读到真实比例, + # 但如果审员一直不操作则 progress 不变,不打日志会让用户焦虑); + # * 其余轮次走 DEBUG,不污染生产日志。 + progress_changed = abs(percent - last_percent) >= 0.1 + heartbeat_due = (attempt == 1) or (attempt % 5 == 0) + if progress_changed or heartbeat_due: + logger.info( + "review[%s]: poll attempt=%d status=%s progress=%.1f%% " + "all_confirmed=%s (raw=%s)", + review_stage, + attempt, + info.status.value if hasattr(info.status, "value") else info.status, + percent, + all_confirmed, + info.extra.get("raw_status", ""), + ) + last_percent = percent + else: + logger.debug( + "review[%s]: poll attempt=%d (silent, progress unchanged at %.1f%%)", + review_stage, attempt, percent, + ) + + if info.status == TaskStatus.APPROVED: + return info, False + + # Phrase 场景:审员在 UI 把全部段都 confirm 了,但没点 + # "Complete this job" 按钮——此时 ``job.status`` 还是 NEW/ACCEPTED, + # 但 segmentsCount 返回 ``allConfirmed=true``。为了避免白白等到 + # deadline,提前进入 split 流程把全部 approved 条目带入下游。 + if all_confirmed: + logger.info( + "review[%s]: platform reports all segments confirmed " + "(attempt=%d, progress=%.1f%%) — early-exit polling, " + "treating as fully reviewed.", + review_stage, attempt, percent, + ) + return info, False + + if info.status == TaskStatus.REJECTED: + raise PlatformError( + f"review[{review_stage}]: task {task_id} was rejected / cancelled " + f"on the platform (raw_status={info.extra.get('raw_status', '')}). " + f"Fix the task on Crowdin or delete state_data['{review_stage}." + f"task_id'] and re-run with --fresh." + ) + + # 未完成——判断是否已到截止。 + if deadline is not None and datetime.now() >= deadline: + logger.info( + "review[%s]: deadline %s reached with progress=%.1f%% — " + "proceeding to split_approved_data (partial run).", + review_stage, + deadline.isoformat(timespec="minutes"), + percent, + ) + return info, True + + time.sleep(max(1, int(poll_interval_seconds))) + + +def _apply_split_to_entries( + ctx: WorkflowContext, + approved_xlsx: Path, + split: Any, +) -> None: + """把 split 结果回写到 ``ctx.entries``。 + + 具体做法: + + * 用 ``extra["approved_keys"]`` 的集合筛掉 ``ctx.entries`` 中未 approved 的条目; + * 从 ``approved_xlsx`` 读回 approved 条目的最新 ``target_text`` 覆盖内存条目的译文。 + + 这样下游 ``validate_data`` / ``dtxml_merge`` / ``push_vcs`` 只会处理已审部分; + pending 的条目被显式从 ctx.entries 移除,避免未审译文被当成合法结果写出去。 + + **极简平台兜底**:若 ``extra`` 既没给 ``approved_keys`` 也没给 + ``pending_keys``(例如 :class:`NoopPlatform` 的空实现),说明该平台 + 并不区分 approved/pending 条目——此时保留 ``ctx.entries`` 原状, + 由 ``is_complete`` 自身决定下游是否正常走通。 + """ + from ...sources import XlsxSource # noqa: WPS433 + + approved_keys_raw = split.extra.get("approved_keys") + pending_keys_raw = split.extra.get("pending_keys") + + # 极简平台兜底——两组 keys 都没给 → 不动 ctx.entries。 + if approved_keys_raw is None and pending_keys_raw is None: + logger.info( + "review: platform did not provide approved_keys/pending_keys; " + "keeping ctx.entries unchanged (%d entries).", + len(ctx.entries), + ) + return + + approved_keys = set(approved_keys_raw or []) + if not approved_keys: + logger.info("review: split produced 0 approved entries; clearing ctx.entries.") + ctx.entries = [] + return + + # 1) 从 approved xlsx 读回最新译文(映射 key → target_text)。 + try: + latest = XlsxSource(encoding="utf-8").load(str(approved_xlsx)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review: failed to re-read approved xlsx %s (%s); " + "falling back to current in-memory targets.", + approved_xlsx, exc, + ) + latest = [] + target_by_key = {e.key: e.target_text for e in latest if e.target_text} + + # 2) 保留 approved_keys 对应的条目,并刷新译文。 + kept: list = [] + for entry in ctx.entries: + if entry.key not in approved_keys: + continue + new_target = target_by_key.get(entry.key) + if new_target: + entry.target_text = new_target + kept.append(entry) + before = len(ctx.entries) + + # 硬保护:approved_keys 非空(claim 有 N 条已审),但过滤后 kept 为空, + # 意味着 approved_keys 和 ctx.entries 完全无交集——通常是 key 维度错配 + # (如把 xliff 里 Crowdin 的数字 ``id`` 当成业务 key 填进了 + # approved_keys,而内存里是 ``resname`` 业务 key,2026-10-09 实测 + # 事故现场)。此时**不能**让 ctx.entries 被擦空,必须显式报错让 + # runner 保留 state_data 等排查,杜绝 silent data loss。 + if not kept and ctx.entries and approved_keys: + from ...commons.exceptions import PlatformError # noqa: WPS433 + sample_approved = sorted(approved_keys)[:3] + sample_entries = [e.key for e in ctx.entries[:3]] + raise PlatformError( + f"review: approved_keys has {len(approved_keys)} items but none " + f"matched any of {len(ctx.entries)} ctx.entries — this is a " + f"KEY MISMATCH between the platform-side approved keys and " + f"in-memory entry keys. Did XliffSource read Crowdin's numeric " + f"'id' instead of 'resname'? " + f"approved_keys sample={sample_approved!r}, " + f"entries sample={sample_entries!r}." + ) + + ctx.entries = kept + logger.info( + "review: ctx.entries filtered to approved subset: %d → %d", + before, len(ctx.entries), + ) + + # 5.1a 【兄弟行广播】translate 阶段把同 source 的多条压成了一条代表走审核; + # 现在代表 approved,需要从 incr 快照回捞兄弟行并复用代表的 target。 + # pending 的代表不扩散兄弟(它们随代表一起由 tail task 续审)。 + _broadcast_siblings_from_snapshot(ctx) + + +def _broadcast_siblings_from_snapshot(ctx: WorkflowContext) -> None: + """如果 translate 阶段保存了 incr 快照,就从快照把 approved 代表的 + 兄弟行回捞合入 ``ctx.entries``。 + + 具体规则见 :func:`TiMi_HOK_Game_Translator.utils.sibling_broadcast.broadcast_siblings_by_source`。 + """ + snapshot_raw = ctx.state_payload.get("translate.incr_snapshot_path") or "" + if not snapshot_raw: + # 没走过 translate 的 same-source 折叠(可能是空 entries 分支), + # 不扩散。 + return + snapshot_path = Path(snapshot_raw) + from ...utils import broadcast_siblings_by_source # noqa: WPS433 — 局部避免循环 + + before = len(ctx.entries) + expanded = broadcast_siblings_by_source( + approved_entries=ctx.entries, + snapshot_path=snapshot_path, + ) + if len(expanded) != before: + logger.info( + "review: sibling broadcast expanded ctx.entries %d → %d.", + before, len(expanded), + ) + ctx.entries = expanded + + +def _create_tail_task( + *, + ctx: WorkflowContext, + platform: Any, + review_stage: str, + target_locale: str, + batch_name: str, + pending_xlsx_path: Path, + pending_count: int, + tail_store: Any, + review_cfg: Any, + hit_deadline: bool, +) -> None: + """把 ``pending_xlsx_path`` 上传到平台生成**新尾巴 task**,并把 task_id + 落到 ``workspace/last_tasks.json`` 的对应 slot。 + + 约定: + * 文件名复用 ``pending_xlsx_path``(``..._pending.xlsx``); + * 任务标题带 ``[tail]`` 前缀,方便平台侧区分; + * 产生的 task_id 存到 TailTaskStore(而不是 state_data),下一天 run + 时由 ``last_first_review`` / ``last_second_review`` 读走。 + """ + from datetime import datetime as _dt + + from ...commons.exceptions import PlatformError # noqa: WPS433 + + if not pending_xlsx_path.exists(): + logger.warning( + "review[%s]: pending xlsx %s does not exist — skipping tail task creation.", + review_stage, pending_xlsx_path, + ) + return + + # 构造唯一的远端文件名——加时间戳后缀(单下划线)。 + # 若直接用 ``pending_xlsx_path.name`` 作 remote_path,连续多次 roll-over + # 或同一批次 re-run 时会撞到 Crowdin 的 ``HTTP 400 Invalid name given. + # Name must be unique``(Crowdin 项目文件名需唯一)。 + # 2026-10-09 分隔符从 "__" 改为 "_",与 last_first/last_second 的命名 + # 风格统一(和同目录 approved.xlsx/pending.xlsx 一个下划线一致)。 + timestamp = _dt.now().strftime("%Y%m%d%H%M%S") + remote_filename = f"{pending_xlsx_path.stem}_{timestamp}{pending_xlsx_path.suffix}" + + try: + upload = platform.upload_source( + str(pending_xlsx_path), + remote_path=remote_filename, + ) + except Exception as exc: # noqa: BLE001 + # 必须抛错——否则下游会继续 delete_task 把本轮刚拆分出的原始 task + # 一并清掉,导致 pending 条目在 Crowdin + last_tasks.json 两边都 + # 丢失(2026-10-09 last_first_review_state 实测事故现场复盘)。 + raise PlatformError( + f"review[{review_stage}]: failed to upload tail xlsx " + f"{pending_xlsx_path} as {remote_filename!r}: {exc}. " + f"Aborting pipeline so the original review task is NOT deleted; " + f"next run can retry split_approved_data cleanly." + ) from exc + + # 把 pending xlsx 的 Target 列(上一轮 LLM 预译)作为"已有翻译"同步上传。 + _upload_translations_if_supported( + platform=platform, + file_id=upload.file_id, + target_locale=target_locale, + xlsx_path=pending_xlsx_path, + review_stage=review_stage, + ) + + title_prefix = "[tail]" + try: + task = platform.create_task( + [upload.file_id], + target_locale, + review_stage=review_stage, + title=( + f"{title_prefix} " + f"{(review_cfg.project_name if review_cfg else '') or ctx.config.project_code} " + f"— {review_stage} — {batch_name}" + ), + ) + except Exception as exc: # noqa: BLE001 + # 建 tail task 失败——先 best-effort 清掉刚上传的 file,再抛错让 + # runner 保留 state_data(原始 task_id 仍在 state_data 里,下次 + # 重跑会从 split_approved_data 开始走)。 + try: # noqa: SIM105 — intentional best-effort swallow for cleanup + platform.delete_file(upload.file_id, review_stage=review_stage) + except Exception: # pylint: disable=broad-except # noqa: BLE001, S110 + pass + raise PlatformError( + f"review[{review_stage}]: failed to create tail task from " + f"new file_id={upload.file_id}: {exc}. " + f"Rolled back the new file upload; aborting pipeline so the " + f"original review task is NOT deleted." + ) from exc + + record = { + "task_id": task.task_id, + "file_id": upload.file_id, + "batch_name": batch_name, + "upload_path": str(pending_xlsx_path), + "remote_filename": remote_filename, + "target_locale": target_locale, + "project_id": platform.project_id, + "platform": platform.platform_name, + "created_at": _dt.now().isoformat(timespec="seconds"), + "pending_count": pending_count, + "hit_deadline": hit_deadline, + } + tail_store.put(review_stage, record) + logger.info( + "review[%s]: created TAIL task_id=%s (pending=%d entries) → persisted to last_tasks.json", + review_stage, task.task_id, pending_count, + ) + stage_cn = { + "light": "轻量审校", + "first": "一审", + "second": "二审", + }.get(review_stage, review_stage) + platform_url = _build_platform_url(platform.platform_name, platform.project_id) + entry_line = ( + f"平台入口:{platform_url}" if platform_url + else f"平台:{platform.platform_name}(project_id={platform.project_id})" + ) + _notify( + ctx, + review_stage, + f"⏭️ 【{ctx.config.project_code}】{stage_cn}续审任务已创建\n" + f"剩余待审条目:{pending_count} 条\n" + f"{entry_line}\n" + f"将在次日的 last_{review_stage}_review 阶段继续处理。", + ) + + +def _notify(ctx: WorkflowContext, review_stage: str, message: str) -> None: + """安全地发送一条通知;通知失败不影响主流程。 + + 会自动从 ``ctx.config.notification.mentioned`` 取出需要 @ 的用户列表 + 透传给 notifier(企业微信群机器人 ``mentioned_list`` 字段),避免在每个 + 调用点重复书写。 + """ + if ctx.notifier is None: + return + try: + mentioned = tuple( + (ctx.config.notification.mentioned or []) + if getattr(ctx.config, "notification", None) + else () + ) + ctx.notifier.notify(message, mentioned=mentioned) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("review[%s]: notifier failed: %s", review_stage, exc) + + +def _resolve_batch_name(ctx: WorkflowContext, target_locale: str) -> str: + """从 state_data 复用、或新建一个本次运行的批次名。 + + 保证 first_review / second_review 两次使用同一个 batch_name, + 便于用户在 ``workspace/batches/`` 下一眼看到一次 run 的全部产物。 + """ + key = "review.batch_name" + existing = ctx.state_data.get(key, "") or "" + if existing: + return str(existing) + batch_name = build_batch_name( + project_code=ctx.config.project_code or "project", + target_locale=target_locale or ctx.config.target_locale or "target", + ) + ctx.state_data[key] = batch_name + return batch_name + + +def _write_meta(path: Path, data: Dict[str, Any]) -> None: + """把审校元数据落到 ``*.meta.json``,忽略 I/O 错误。""" + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + except OSError as exc: # pragma: no cover — 调试辅助 + logger.warning("review: failed to write meta %s: %s", path, exc) + + +def _apply_xliff_to_entries(ctx: WorkflowContext, xliff_path: Path) -> None: + """把 Crowdin 导出的 xliff 中非空 target 字段按 Key 回写到 ctx.entries。 + + 参数: + ctx: 工作流上下文;修改其 ``entries`` 列表的 ``target_text``。 + xliff_path: 刚下载的 xliff 文件绝对路径。 + + 注意: + 若文件不是合法 xliff(例如 ``NoopPlatform`` 回传的原始 xlsx 二进制、 + 或审校员人工干预导致的格式异常),此处记一次 warning 后**保留 + 现有 target_text 原状**——不会让主流程因此崩溃。真实 Crowdin + 场景会正常走通,不会命中该分支。 + """ + if not xliff_path.exists(): + return + try: + translated = XliffSource(encoding="utf-8").load(str(xliff_path)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review: failed to parse xliff %s (%s); keeping existing targets unchanged.", + xliff_path, exc, + ) + return + by_key = {e.key: e for e in translated} + hits = 0 + for entry in ctx.entries: + remote = by_key.get(entry.key) + if remote is not None and remote.target_text: + entry.target_text = remote.target_text + hits += 1 + logger.info( + "review: xliff -> entries: %d of %d updated", hits, len(ctx.entries), + ) + + +def _upload_translations_if_supported( + *, + platform: Any, + file_id: str, + target_locale: str, + xlsx_path: Path, + review_stage: str, +) -> None: + """若平台实现了 ``upload_translations``,就把 ``xlsx_path`` 的 Target 列 + 作为"已有翻译"上传。 + + * 用于把 LLM 预译结果(本地 Target 列)同步到 Crowdin,这样审校员在 + Crowdin 页面能看到预译文而不是只有源串; + * 失败不致命——继续后续 ``create_task``,审校员仍能从源串开始审(只是 + 没有 LLM 预译参考); + * 对 PhrasePlatform / NoopPlatform 等不实现该方法的平台,自动跳过。 + """ + if not hasattr(platform, "upload_translations"): + logger.debug( + "review[%s]: platform=%s does not implement upload_translations — skip.", + review_stage, getattr(platform, "platform_name", type(platform).__name__), + ) + return + if not file_id or not target_locale: + logger.warning( + "review[%s]: upload_translations missing file_id=%r or target_locale=%r — skip.", + review_stage, file_id, target_locale, + ) + return + try: + platform.upload_translations( + file_id=file_id, + target_locale=target_locale, + local_xlsx_path=str(xlsx_path), + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "review[%s]: upload_translations failed (continuing without pre-translations): %s", + review_stage, exc, + ) + + +def _synthetic_profile(ctx: WorkflowContext): + """当 runner 未提供 profile 时合成一份。""" + from ...config.schema import LanguageProfile + return LanguageProfile(id=ctx.config.target_locale or "target") + + +__all__ = ["run_review_stage"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/finished_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/finished_state.py new file mode 100644 index 0000000000000000000000000000000000000000..359162de6f9f40f651d4e275491f7c7c75d2ad37 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/finished_state.py @@ -0,0 +1,76 @@ +"""``finished`` 状态——流水线终态。 + +驱动器跳完所有状态后进入。默认实现做三件通用清理: + +* 强制 flush 未写盘的 :class:`AutoSaveDict`; +* 强制 :meth:`StatesManager.save`,保证磁盘状态停在“完成”形态; +* 调用 :meth:`VcsClient.cleanup`(大多数后端为空操作,有工作副本锁 + 时进行解锁)。 + +真实项目可继承本类进行扩展,例如发送完成通知、打 git tag 等。 +""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + + +class FinishedState(WorkflowStateBase): + """终态状态——执行清理并(可选)发送通知。""" + + name = StateEnum.FINISHED.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + # 1. 显式 flush state_data(autosave 通常已处理,但子类暂停 + # 自动保存时此处作为兵)。 + try: + cb = getattr(ctx.state_data, "_save_callback", None) + if callable(cb): + cb() + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.debug("FinishedState: state_data flush failed: %s", exc) + + # 2. 强制 StatesManager 落盘。 + mgr = ctx.states_manager + if mgr is not None: + try: + mgr.save() + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("FinishedState: StatesManager save failed: %s", exc) + + # 3. VCS 清理——best effort。 + try: + ctx.vcs.cleanup() + except AttributeError: + # 部分老适配器未暴露 cleanup(),忽略。 + pass + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("FinishedState: vcs.cleanup failed: %s", exc) + + # 4. 通知。流水线结束的关键节点,自动 @ notification.mentioned 名单。 + if ctx.notifier is not None: + try: + mentioned = tuple( + (ctx.config.notification.mentioned or []) + if getattr(ctx.config, "notification", None) + else () + ) + target = ctx.config.target_locale or "target" + ctx.notifier.notify( + f"✅ [{ctx.config.project_code}] 翻译流水线已完成(目标语种:{target})。", + mentioned=mentioned, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("FinishedState: notifier failed: %s", exc) + + logger.info("FinishedState: pipeline complete.") + return None + + +__all__ = ["FinishedState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/first_review_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/first_review_state.py new file mode 100644 index 0000000000000000000000000000000000000000..7fb7f8d712f26c916810df605f82a24c830d48a5 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/first_review_state.py @@ -0,0 +1,34 @@ +"""``first_review`` 状态——一次式审校首轮。""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import run_review_stage + +logger = logging.getLogger(__name__) + + +class FirstReviewState(WorkflowStateBase): + """使用为 :class:`ReviewStage.FIRST` 配置的平台执行首轮审校。""" + + name = StateEnum.FIRST_REVIEW.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("FirstReviewState: already completed — skipping.") + return None + run_review_stage( + ctx, + review_stage=ReviewStage.FIRST.value, + resume_key_prefix="first_review", + ) + self._mark_completed(ctx) + return None + + +__all__ = ["FirstReviewState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/increment_match_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/increment_match_state.py new file mode 100644 index 0000000000000000000000000000000000000000..47d9722d512093f5dd6864fab53fe56f03e2227f --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/increment_match_state.py @@ -0,0 +1,60 @@ +"""``increment_match`` 状态——按阈值触发增量 TM 命中。 + +当当日增量汉字(或更广义的“源语言字符”)总量超过配置阈值时, +多跑一轮预翻译 TM 匹配,提高命中率后再调用 LLM。 + +默认实现**仅统计**增量大小;阈值来自 +``profile.strategy_config["increment_match_threshold"]``(默认 0,表示禁用)。 +真正的 TM sweep 通过子类实现。 +""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + + +class IncrementMatchState(WorkflowStateBase): + """测量增量输入并(可选)触发 TM sweep。""" + + name = StateEnum.INCREMENT_MATCH.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("IncrementMatchState: already completed — skipping.") + return None + + profile = ctx.language_profile + threshold = 0 + if profile is not None: + threshold = int(profile.strategy_config.get("increment_match_threshold", 0) or 0) + + total_source_chars = sum(len(e.source_text or "") for e in ctx.entries) + triggered = threshold > 0 and total_source_chars >= threshold + + ctx.state_payload["increment_match.total_source_chars"] = total_source_chars + ctx.state_payload["increment_match.threshold"] = threshold + ctx.state_payload["increment_match.triggered"] = triggered + + if triggered: + logger.info( + "IncrementMatchState: threshold %d exceeded (chars=%d) — " + "subclass to plug in an incremental TM sweep.", + threshold, total_source_chars, + ) + else: + logger.info( + "IncrementMatchState: below threshold (chars=%d, threshold=%d) — skipping sweep.", + total_source_chars, threshold, + ) + + self._mark_completed(ctx) + return None + + +__all__ = ["IncrementMatchState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_first_review_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_first_review_state.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a37759a67ef8fc1bb05af0e3009d3777050033 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_first_review_state.py @@ -0,0 +1,248 @@ +"""``last_first_review`` 状态——处理上一日一审遗留的尾巴 task。 + +"尾巴 task" 指上一日 ``first_review`` 轮询到 stop_time 仍未审完 → 由 +:mod:`_review_state_helpers` 立即新建的"装载 pending 条目"的平台任务。 +它的 task_id 存在**跨批次持久化**的 +:class:`~.._tail_tasks.TailTaskStore`(``workspace/last_tasks.json``)里。 + +本 state 在当天 run 的最前面被调度(``pull_vcs`` 之前)。它的职责是: + +1. 读 ``last_tasks.json`` → 若 ``first_review`` slot 为空,直接跳过; +2. 若有 ``task_id`` → 调 ``split_approved_data`` 继续按条目拆: + * **approved 条目** → 累积到 ``ctx.state_payload["last_review.carry_over_entries"]``, + 由后续 :class:`LastMergeDataState` 合入 ``ctx.entries`` 和今日新增一起走流程; + * **pending 条目** → 回流到 ``ctx.state_payload["last_review.pending_rollover_entries"]`` + → 由后续 :class:`LastMergeDataState` prepend 到 ``ctx.entries`` + → 和今日新增条目**合并进同一个大 first_review task**; +3. 清理旧尾巴 task + file(内容已安全备份到 state_payload),清空 slot。 + +**为什么本 state 不自己建新尾巴 task**:若在当日 run 内把 pending 条目立即 +新建尾巴 task,并写回 ``last_tasks.json[first_review]`` slot,会被当日 +``first_review`` 阶段的 ``_create_tail_task`` 覆盖 → **前者成为平台孤儿 task+file** +(既不被 last_tasks.json 追踪、也不被回收)。因此本 state 不调 ``tail_store.put``, +整个 run 中只有 ``first_review`` 的 roll-over 会写一次 slot。 + +**不丢数据保证**:pending 条目在 ``delete_task`` 前就已经被解包装成 +``Entry`` 存到了 ``state_payload``;即使平台端 delete 失败,内存 + payload 也会被 runner 持久化到 ``project_run_data.json``,下次 run 可 +从 ``last_merge_data`` 恢复。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ...platforms.factory import build_review_tool +from ...sources import XlsxSource +from .._tail_tasks import TailTaskStore +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import _notify, _resolve_lang # noqa: PLC2701 — 内部共享辅助 + +logger = logging.getLogger(__name__) + +#: 一审遗留在 state_payload 里累积的 approved 条目 key +_CARRY_OVER_KEY = "last_review.carry_over_entries" + +#: 一审遗留 **pending** 条目回流通道。 +#: +#: 本通道的设计暂身:若在当日 run 内把 pending 条目立即新建尾巴 +#: task,并把 task_id 写回 ``last_tasks.json[first_review]`` —— 该 slot +#: 在同一次 run 内会被 ``first_review`` 阶段的 ``_create_tail_task`` 覆盖, +#: 导致旧 pending 的平台 task+file 成为**孤儿**。 +#: 现方案:pending 条目从 pending_xlsx 读回 Entry → prepend 到 ctx.entries → +#: 跟今日新增条目**合并成一个大 task** 上传。slot 在本 state 不再被 put, +#: 整个 run 中只会被 ``first_review`` 的 roll-over 写一次 —— 杜绝孤儿。 +_PENDING_ROLLOVER_KEY = "last_review.pending_rollover_entries" + +#: 当前阶段枚举值。 +_STAGE = ReviewStage.FIRST.value + + +class LastFirstReviewState(WorkflowStateBase): + """接回上一日一审遗留的尾巴 task 并继续按条目拆分。""" + + name = StateEnum.LAST_FIRST_REVIEW.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("LastFirstReviewState: already completed — skipping.") + return None + + tail_store = TailTaskStore( + Path(ctx.workspace), + lang=_resolve_lang(ctx), + ) + record = tail_store.get(_STAGE) + if not record: + logger.info( + "LastFirstReviewState: no tail task in last_tasks.json[%s] — skipping.", + _STAGE, + ) + self._mark_completed(ctx) + return None + + task_id = str(record.get("task_id") or "") + if not task_id: + logger.warning( + "LastFirstReviewState: last_tasks.json[%s] has no task_id — clearing slot.", + _STAGE, + ) + tail_store.clear(_STAGE) + self._mark_completed(ctx) + return None + + logger.info( + "LastFirstReviewState: processing tail task_id=%s (batch=%s, pending=%s)", + task_id, record.get("batch_name", ""), record.get("pending_count", ""), + ) + + profile = ctx.language_profile + platform = build_review_tool( + profile, + _STAGE, + global_platform=ctx.config.platform, + ) + target_locale = ( # pylint: disable=unused-variable + (profile.target_locale if profile else "") + or ctx.config.target_locale + or record.get("target_locale", "") + ) + batch_name = str(record.get("batch_name") or "") + if not batch_name: + # 极端情况:旧记录缺字段。回退到 "last__"。 + batch_name = f"last_{_STAGE}_{task_id}" + + # 1. split_approved_data —— 按条目拆分 + # 命名约定(2026-10-09 对齐 first_review state 的中文命名): + # 目录:workspace/batches//first_review/ (和 Day-1 同一目录,便于审员追溯批次) + # 文件:_第一轮审核_approved.xlsx / _pending.xlsx + # 这样 Day-N 的 roll-over 文件和 Day-1 原始文件在同一目录、同一前缀, + # 只是 _pending.xlsx 的时间戳后缀会递增(由 _roll_over_tail 处理)。 + from ...platforms._batch import stage_dir, stage_file_stem # noqa: WPS433 + last_dir = stage_dir(Path(ctx.workspace), batch_name, _STAGE) + stem = stage_file_stem(batch_name, _STAGE) + approved_xlsx = last_dir / f"{stem}_approved.xlsx" + pending_xlsx = last_dir / f"{stem}_pending.xlsx" + split = platform.split_approved_data( + task_id, + save_approved_path=str(approved_xlsx), + save_pending_path=str(pending_xlsx), + review_stage=_STAGE, + ) + approved_keys: List[str] = list(split.extra.get("approved_keys", []) or []) + pending_keys: List[str] = list(split.extra.get("pending_keys", []) or []) + logger.info( + "LastFirstReviewState: tail split → approved=%d, pending=%d, is_complete=%s", + len(approved_keys), len(pending_keys), split.is_complete, + ) + + # 2. 已审部分 → 读 approved xlsx → 作为"遗留结转条目"存入 state_payload, + # 让 LastMergeDataState 稍后合入 ctx.entries。 + if approved_keys and approved_xlsx.exists(): + try: + carried = XlsxSource(encoding="utf-8").load(str(approved_xlsx)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastFirstReviewState: failed to read %s (%s); carry-over will be empty.", + approved_xlsx, exc, + ) + carried = [] + payload = ctx.state_payload.setdefault(_CARRY_OVER_KEY, []) + payload.extend(_entry_to_dict(e) for e in carried) + logger.info( + "LastFirstReviewState: carried %d approved entries forward (total carry-over=%d).", + len(carried), len(payload), + ) + + # 3. pending 非空 → 把条目回流到 state_payload(由 last_merge_data + # 合入 ctx.entries 的头部),**不再在当日建新尾巴 task**。 + # 这是 2026-10-09 方案 ①-🅱 的核心修复: + # * 旧实现在同一次 run 内 last_first_review + first_review 都会 + # ``tail_store.put(first_review, ...)``,后者覆盖前者 → 前者 + # 的 Crowdin task+file 成为孤儿(见 _PENDING_ROLLOVER_KEY 的 + # 注释)。 + # * 新实现:pending 回流 ctx.entries → 和今日新增一起被 first_review + # 大 task 承载 → run 内 slot 只被 first_review 的 roll-over 写 + # 一次 → 杜绝孤儿。 + if pending_keys and pending_xlsx.exists(): + try: + rolled = XlsxSource(encoding="utf-8").load(str(pending_xlsx)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastFirstReviewState: failed to read pending xlsx %s (%s); " + "pending roll-over will be empty — THIS LOSES %d ENTRIES, investigate ASAP.", + pending_xlsx, exc, len(pending_keys), + ) + rolled = [] + payload = ctx.state_payload.setdefault(_PENDING_ROLLOVER_KEY, []) + payload.extend(_entry_to_dict(e) for e in rolled) + logger.info( + "LastFirstReviewState: rolled over %d pending entries into " + "state_payload[%s] (will be merged into ctx.entries by last_merge_data).", + len(rolled), _PENDING_ROLLOVER_KEY, + ) + + # 4. 无论 pending 是否存在:现在都要**清理旧 task + 旧 file + 清空 slot**。 + # * approved 已通过 state_payload[_CARRY_OVER_KEY] 回流; + # * pending 已通过 state_payload[_PENDING_ROLLOVER_KEY] 回流; + # → 旧 Crowdin task 和 file 的全部内容都已安全备份到内存+payload, + # 可以放心删除。slot 清空后,first_review 阶段的 roll-over + # 才是本 run 唯一的 slot 写入者。 + tail_store.clear(_STAGE) + try: + platform.delete_task(task_id, review_stage=_STAGE) + logger.info( + "LastFirstReviewState: deleted old tail task_id=%s on platform=%s " + "(approved=%d carried over, pending=%d rolled into ctx.entries).", + task_id, platform.platform_name, + len(approved_keys), len(pending_keys), + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastFirstReviewState: delete_task(%s) failed (continuing — " + "content already backed up to state_payload): %s", + task_id, exc, + ) + old_file_id = str(record.get("file_id") or "") + if old_file_id: + try: + platform.delete_file(old_file_id, review_stage=_STAGE) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastFirstReviewState: delete_file(%s) failed (continuing): %s", + old_file_id, exc, + ) + + _notify( + ctx, + _STAGE, + f"📝 【{ctx.config.project_code}】昨日一审续审任务已处理\n" + f"任务 ID:{task_id}\n" + f"✅ 已通过:{len(approved_keys)} 条\n" + f"⏭️ 滚入下轮:{len(pending_keys)} 条", + ) + self._mark_completed(ctx) + return None + + +def _entry_to_dict(entry: Any) -> Dict[str, Any]: + """把 :class:`Entry` 序列化成 JSON 安全的 dict(供 state_payload 落盘)。 + + state_payload 要能被 StatesManager 序列化到 ``workflow_state.json``, + 因此不能直接存 Entry dataclass 对象。 + """ + return { + "key": entry.key, + "source_text": entry.source_text, + "target_text": entry.target_text, + "context": entry.context, + "comment": entry.comment, + "metadata": dict(entry.metadata or {}), + } + + +__all__ = ["LastFirstReviewState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_merge_data_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_merge_data_state.py new file mode 100644 index 0000000000000000000000000000000000000000..26e735bc0b4dfc1afe3b8c662c2947d12abfe5f9 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_merge_data_state.py @@ -0,0 +1,419 @@ +"""``last_merge_data`` 状态——把昨日审完的遗留条目**精确地**分发到今日流水线的各个阶段。 + +**设计意图**:把一审遗留和二审遗留的 approved 条目精确路由到各自的 +"下一个阶段",而不是统一塞回工作流从头走一遍。 + +**执行时机**:**在 ``pull_vcs`` + ``translate`` 之后,``first_review`` 之前**。 + +**为什么要按来源精确路由(而不是全部塞回 ``ctx.entries``)**: + +若把三类遗留条目**全部 prepend 到 ``ctx.entries``**——它们会无差别走完 +``first_review → second_review → merge_data`` 的完整链。在 TM 100% 命中 +的生产场景下尚可(Crowdin 秒 approved),但只要 deadline 过短或 TM 失 +配,这些**本来已经审过的条目**会被当成"今日 first/second 的 pending" +再次ۭa进新 tail,造成**无止境的重复审核**。 + +**按条目来源精确路由**: + +* **一审遗留 approved**(``last_review.carry_over_entries``) + → **根据 profile 是否配置二审动态路由**: + + - 有二审(``reviews.second.platform`` 非空非 ``"none"`` 且 workflow + 包含 ``second_review``)→ 存到 ``last_review.second_only_entries`` + 通道 → ``second_review_state`` 在开工前 prepend 到 ``ctx.entries`` + → **跳过 first_review**,走今日 second_review。 + 语义:昨天已过一审,今天不该重走一审。 + + - 无二审("仅一审"编排)→ 存到 ``last_review.merge_only_entries`` + 通道(和二审 approved 共用) → ``merge_data_state`` 在合入 full 表 + 前 prepend 到 ``ctx.entries`` → **跳过所有审核**,直接合入 full 表。 + 语义:昨天已过系统的最终审核阶段,今天不该重走任何审核。 + (修复 2026-10-13:旧实现无条件走 second_only 通道,仅一审时数据丢失。) + +* **一审遗留 pending**(``last_review.pending_rollover_entries``) + → **本 state 直接 prepend 到 ``ctx.entries``** + → 和今日新增一起走 ``first_review``。 + 语义:它们昨天没过一审,走一审天经地义。 + +* **二审遗留 approved**(``last_second_review.carry_over_entries``) + → 存到 ``last_review.merge_only_entries`` 通道 + → ``merge_data_state`` 在合入 full 表前 prepend 到 ``ctx.entries`` + → **跳过 first_review 和 second_review**,直接合入 full 表。 + 语义:昨天已过二审,今天不该重走任何审核。 + +* **二审遗留 pending**(``last_second_review.pending_rollover_entries``; + 由 :class:`LastSecondReviewState` 直接填充)→ **本 state 不处理** + → ``second_review_state`` 开工前 prepend 到 ``ctx.entries`` + → **跳过 first_review**,直接走二审。 + 语义:昨天已过一审但二审没审完,不该回头重走一审。 + +执行后清空 ``_FIRST_CARRY_OVER_KEY``、``_SECOND_CARRY_OVER_KEY``、 +``_FIRST_PENDING_ROLLOVER_KEY`` 三个 slot,避免二次合入; +``_SECOND_PENDING_ROLLOVER_KEY`` / ``_SECOND_ONLY_ENTRIES`` / +``_MERGE_ONLY_ENTRIES`` 分别由对应的下游 state 自己清。 +""" + +from __future__ import annotations + +import logging +from typing import Any, List, Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ...sources.base import Entry +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + +#: 一审遗留 **approved** 条目的来源通道(由 LastFirstReviewState 填充)。 +_FIRST_CARRY_OVER_KEY = "last_review.carry_over_entries" + +#: 二审遗留 **approved** 条目的来源通道(由 LastSecondReviewState 填充)。 +_SECOND_CARRY_OVER_KEY = "last_second_review.carry_over_entries" + +#: 一审遗留 **pending** 条目回流通道(由 LastFirstReviewState 填充)。 +#: 本 state 消费 → 合入 ctx.entries → 走今日 first_review。 +_FIRST_PENDING_ROLLOVER_KEY = "last_review.pending_rollover_entries" + +#: "仅走今日 second_review"通道。 +#: +#: 本 state 把一审遗留 approved(它们昨天过了一审)路由到这里 → +#: :class:`SecondReviewState` 在 ``run_review_stage`` 入口处 prepend 到 +#: ctx.entries → 跳过 ``first_review``,直接进入二审。 +_SECOND_ONLY_ENTRIES_KEY = "last_review.second_only_entries" + +#: "直接合入 full 表"通道。 +#: +#: 本 state 把二审遗留 approved(它们昨天已过二审)路由到这里 → +#: :class:`MergeDataState` 在合入 full 表前 prepend 到 ctx.entries → +#: 彻底跳过 ``first_review`` + ``second_review``。 +_MERGE_ONLY_ENTRIES_KEY = "last_review.merge_only_entries" + + +class LastMergeDataState(WorkflowStateBase): + """精确路由昨日遗留条目(根据 profile 审核链路自适应): + + * 一审 approved: + - profile 有二审 → 走今日 second_review(跳过一审) + - profile 仅一审 → 直接合入 full 表(跳过所有审核) + * 二审 approved → 直接合入 full 表 + * 一审 pending → 回今日 first_review 续审 + """ + + name = StateEnum.LAST_MERGE_DATA.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("LastMergeDataState: already completed — skipping.") + return None + + first_carry = _dict_list_to_entries( + ctx.state_payload.get(_FIRST_CARRY_OVER_KEY, []) or [] + ) + second_carry = _dict_list_to_entries( + ctx.state_payload.get(_SECOND_CARRY_OVER_KEY, []) or [] + ) + first_pending_rollover = _dict_list_to_entries( + ctx.state_payload.get(_FIRST_PENDING_ROLLOVER_KEY, []) or [] + ) + + if not first_carry and not second_carry and not first_pending_rollover: + logger.info("LastMergeDataState: no carry-over entries — skipping.") + self._mark_completed(ctx) + return None + + # ------------------------------------------------------------ + # 【修复 2026-10-13】判断本语种 profile 是否配置了二审。 + # + # 没有二审时(``reviews.second.platform`` 为空或 ``"none"``,或 + # workflow 中不含 ``second_review``),一审 approved 在语义上 + # 等价于"已过所有审核"——必须走和二审 approved 相同的 **直接 + # 合入 full 表**通道(``_MERGE_ONLY_ENTRIES_KEY``),由 + # :class:`MergeDataState` 消费。 + # + # 否则(历史 bug):一审 approved 会被路由到 + # ``_SECOND_ONLY_ENTRIES_KEY``,而该通道只在 ``SecondReviewState`` + # 里被消费——没有二审状态时,这批昨日 approved 条目将**永远被遗弃** + # 在 state_payload 里,既不进 ctx.entries 也不进 full 表、更不被 + # commit 回 VCS,造成数据丢失。 + # ------------------------------------------------------------ + has_second_review = _profile_has_second_review(ctx) + logger.info( + "LastMergeDataState: profile has_second_review=%s — first-review " + "approved carry-over will be routed to %s channel.", + has_second_review, + "_SECOND_ONLY_ENTRIES_KEY (→ today's second_review)" + if has_second_review + else "_MERGE_ONLY_ENTRIES_KEY (→ merge_data directly, skipping all reviews)", + ) + + # ------------------------------------------------------------ + # 【Rule 2b 精确版】对每条昨日遗留条目做 key 冲突判定: + # + # * **key 不冲突** → 正常路由到对应通道。 + # * **key 冲突 + source 相同** → **保留昨日版本**,把 ctx.entries + # 里对应条目**替换**为昨日版本(它承载了审员的部分进度,不该 + # 被今日"又跑了一遍 LLM"的新版本覆盖)。今日版本在 ctx.entries + # 中被原地替换;不再往通道推。 + # * **key 冲突 + source 不同** → 丢弃昨日 + WARN。今日策划改了 + # 内容,昨日的译文已失效,必须让今日版本重走翻译/审核。 + # + # 这是 2026-10-09 方案 ②+ 的修复:旧实现 "key 冲突一律丢弃昨日" + # 丢数据,哪怕 source 相同、哪怕昨日已走到后半段审核。 + # ------------------------------------------------------------ + today_by_key = {e.key: e for e in ctx.entries} + # today_entries_mutable 用于支持"原地替换"。list 共享内部对象,但 + # 若替换则需要重建;为了语义清晰,先做一次浅拷贝再操作。 + today_entries_mutable: List[Entry] = list(ctx.entries) + # 由 key → 在 today_entries_mutable 中的索引,便于 O(1) 替换。 + today_index_by_key = {e.key: i for i, e in enumerate(today_entries_mutable)} + + # 跨所有通道的"全局已见"集合——避免同一个 key 既被替换又被路由。 + # 初始化为今日所有 key,后续路由的新 key 也累积进来。 + existing_keys: set = set(today_by_key) + + # —— 通道 1:一审 pending rollover → 走今日 first_review —— + first_pending_prepend: List[Entry] = [] + first_pending_replaced = 0 + first_pending_dropped_diff = 0 + for src in first_pending_rollover: + outcome = _rule2b_route( + src=src, + today_by_key=today_by_key, + today_entries_mutable=today_entries_mutable, + today_index_by_key=today_index_by_key, + existing_keys=existing_keys, + ) + if outcome == "new": + first_pending_prepend.append(src) + existing_keys.add(src.key) + elif outcome == "replaced_in_today": + first_pending_replaced += 1 + elif outcome == "dropped_diff_source": + first_pending_dropped_diff += 1 + + # —— 通道 2:一审 approved → 根据是否有二审动态选择目标通道 —— + # + # 有二审 → _SECOND_ONLY_ENTRIES_KEY(走今日 second_review,跳过 first_review) + # 无二审 → _MERGE_ONLY_ENTRIES_KEY(直接合入 full 表,跳过所有审核) + # + # 【修复 2026-10-13】旧实现无条件写 _SECOND_ONLY_ENTRIES_KEY,在 + # "仅一审"编排下该通道没有消费者 → 数据丢失。 + first_approved_target: List[Entry] = [] + first_approved_replaced = 0 + first_approved_dropped_diff = 0 + for src in first_carry: + outcome = _rule2b_route( + src=src, + today_by_key=today_by_key, + today_entries_mutable=today_entries_mutable, + today_index_by_key=today_index_by_key, + existing_keys=existing_keys, + ) + if outcome == "new": + first_approved_target.append(src) + existing_keys.add(src.key) + elif outcome == "replaced_in_today": + first_approved_replaced += 1 + elif outcome == "dropped_diff_source": + first_approved_dropped_diff += 1 + + # —— 通道 3:二审 approved → _MERGE_ONLY_ENTRIES_KEY → 直接合入 full 表 —— + merge_only: List[Entry] = [] + merge_only_replaced = 0 + merge_only_dropped_diff = 0 + for src in second_carry: + outcome = _rule2b_route( + src=src, + today_by_key=today_by_key, + today_entries_mutable=today_entries_mutable, + today_index_by_key=today_index_by_key, + existing_keys=existing_keys, + ) + if outcome == "new": + merge_only.append(src) + existing_keys.add(src.key) + elif outcome == "replaced_in_today": + merge_only_replaced += 1 + elif outcome == "dropped_diff_source": + merge_only_dropped_diff += 1 + + # ------------------------------------------------------------ + # 应用路由。 + # ------------------------------------------------------------ + before = len(ctx.entries) + # Step A: 先把今日已被替换过的 ctx.entries 写回(可能保留了昨日 + # 版本的 target_text / metadata)。 + ctx.entries = today_entries_mutable + + # Step B: 再把三类"没撞 key"的昨日条目分别 prepend 或路由。 + if first_pending_prepend: + ctx.entries = first_pending_prepend + list(ctx.entries) + + # 【修复 2026-10-13】一审 approved 的路由目标由 has_second_review 决定。 + if first_approved_target: + target_key = ( + _SECOND_ONLY_ENTRIES_KEY if has_second_review else _MERGE_ONLY_ENTRIES_KEY + ) + payload = ctx.state_payload.setdefault(target_key, []) + payload.extend(_entry_to_dict(e) for e in first_approved_target) + + if merge_only: + payload = ctx.state_payload.setdefault(_MERGE_ONLY_ENTRIES_KEY, []) + payload.extend(_entry_to_dict(e) for e in merge_only) + + logger.info( + "LastMergeDataState: routed carry-over → ctx.entries %d→%d. " + "first_pending (go to first_review): new=%d, replaced=%d, dropped_diff_source=%d. " + "first_approved (%s): new=%d, replaced=%d, dropped_diff_source=%d. " + "merge_only (skip first & second → merge): new=%d, replaced=%d, dropped_diff_source=%d.", + before, len(ctx.entries), + len(first_pending_prepend), first_pending_replaced, first_pending_dropped_diff, + "skip first → second_review" if has_second_review else "skip first & second → merge", + len(first_approved_target), first_approved_replaced, first_approved_dropped_diff, + len(merge_only), merge_only_replaced, merge_only_dropped_diff, + ) + + # 清空来源 slot,避免下次 run 再次合入。 + # 注意:**不清** _SECOND_PENDING_ROLLOVER_KEY —— 那是 LastSecondReviewState + # 直接写、SecondReviewState 直接读的通道,不经本 state 中转。 + # **不清** _SECOND_ONLY_ENTRIES_KEY / _MERGE_ONLY_ENTRIES_KEY —— + # 它们由各自的下游 state 消费后自清。 + ctx.state_payload.pop(_FIRST_CARRY_OVER_KEY, None) + ctx.state_payload.pop(_SECOND_CARRY_OVER_KEY, None) + ctx.state_payload.pop(_FIRST_PENDING_ROLLOVER_KEY, None) + + self._mark_completed(ctx) + return None + + +def _rule2b_route( + *, + src: Entry, + today_by_key: dict, + today_entries_mutable: List[Entry], + today_index_by_key: dict, + existing_keys: set, +) -> str: + """按 Rule 2b 判定昨日条目 ``src`` 的归宿。 + + 返回值: + + * ``"new"`` —— ``src`` 的 key 不冲突,调用方应把它路由到对应通道; + * ``"replaced_in_today"`` —— key 冲突 + source 相同;本函数已经把 + ``today_entries_mutable`` 中对应条目替换为 ``src``(保留昨日的 + target_text 和审员进度),调用方不需要再路由; + * ``"dropped_diff_source"`` —— key 冲突 + source 不同;本函数已打 + WARN,调用方应该直接丢弃 ``src``; + * ``"dropped_cross_channel"`` —— key 和前一个通道刚插入的条目冲突, + 丢弃(防御性,正常场景下极少触发)。 + + 副作用: + * 命中 ``"replaced_in_today"`` 时**原地**替换 ``today_entries_mutable``; + * 其他情况**不**修改外部参数。``existing_keys`` 由调用方按 ``"new"`` + 自行累加。 + """ + key = src.key + if key not in existing_keys: + return "new" + + # 优先级 1:和今日 ctx.entries 冲突 —— 做 source 比对决定保留谁。 + today_version = today_by_key.get(key) + if today_version is not None: + if today_version.source_text == src.source_text: + # source 相同 —— 保留昨日版本(它有审员进度,优于今日新跑的 LLM)。 + idx = today_index_by_key[key] + today_entries_mutable[idx] = src + # today_by_key 也要同步更新,防止后续通道的"同 key"条目看到 + # 旧版本做出错误判定。 + today_by_key[key] = src + return "replaced_in_today" + else: + # source 不同 —— 今日策划改了内容,昨日已完成的旧译文作废。 + logger.warning( + "LastMergeDataState: dropping yesterday entry key=%r because " + "today has the same key with a DIFFERENT source (today's " + "version wins and will be re-translated/reviewed as a fresh " + "entry).", + key, + ) + return "dropped_diff_source" + + # 优先级 2:没出现在今日 ctx.entries 里,但出现在前面某条通道的 + # new 列表中 —— 跨通道同 key 冲突(如一审 approved 和二审 approved + # 同 key,正常业务不该发生)。保守丢弃。 + logger.warning( + "LastMergeDataState: dropping yesterday entry key=%r because it " + "collides with an earlier channel's entry in the same run.", + key, + ) + return "dropped_cross_channel" + + +def _profile_has_second_review(ctx: WorkflowContext) -> bool: + """判断当前语种 profile 是否配置了二审(且 workflow 中包含 second_review 状态)。 + + 判定规则(任一不满足即视为"无二审"): + + 1. profile 的 ``reviews.second.platform`` 非空且 ``!= "none"``; + 2. profile 的 ``workflow`` 中显式包含 ``second_review`` 状态。 + + 这两点必须同时成立——仅配置平台不足:若 workflow 把 ``second_review`` + 状态裁掉了,``_SECOND_ONLY_ENTRIES_KEY`` 通道仍然没人消费。 + """ + profile = ctx.language_profile + if profile is None: + return False + + try: + review_cfg = profile.review(ReviewStage.SECOND.value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 — profile 不规范时保守认为"无二审" + return False + + platform = (review_cfg.platform or "").strip() + if not platform or platform == "none": + return False + + workflow_states = tuple(getattr(profile, "workflow", ()) or ()) + if StateEnum.SECOND_REVIEW.value not in workflow_states: + return False + + return True + +def _entry_to_dict(entry: Entry) -> dict: # noqa: E302 + """把 :class:`Entry` 序列化成 state_payload 可持久化的 dict。""" + return { + "key": entry.key, + "source_text": entry.source_text, + "target_text": entry.target_text, + "context": entry.context, + "comment": entry.comment, + "metadata": dict(entry.metadata or {}), + } + + +def _dict_list_to_entries(items: Any) -> List[Entry]: + """把 state_payload 里的 dict 列表反序列化为 :class:`Entry` 列表。""" + result: List[Entry] = [] + if not isinstance(items, list): + return result + for raw in items: + if not isinstance(raw, dict): + continue + try: + result.append( + Entry( + key=str(raw.get("key", "")), + source_text=str(raw.get("source_text", "") or ""), + target_text=str(raw.get("target_text", "") or ""), + context=str(raw.get("context", "") or ""), + comment=str(raw.get("comment", "") or ""), + metadata=dict(raw.get("metadata") or {}), + ) + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("LastMergeDataState: skip malformed carry-over item: %s", exc) + return result + + +__all__ = ["LastMergeDataState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_second_review_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_second_review_state.py new file mode 100644 index 0000000000000000000000000000000000000000..9e8aa0dfa9e5c241a9d1d585730c6ef27bb24dcc --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/last_second_review_state.py @@ -0,0 +1,235 @@ +"""``last_second_review`` 状态——处理上一日二审遗留的尾巴 task。 + +骨架与 :class:`~.last_first_review_state.LastFirstReviewState` 相同, +但目标 slot 是 :attr:`ReviewStage.SECOND`。若 profile 未配置二审平台 +(``platform == "none"``),本 state 直接跳过。 + +**与一审的关键差异**: + +* **approved 条目** → ``last_second_review.carry_over_entries`` + → 由 :class:`LastMergeDataState` 合入 ``ctx.entries``。 + (语义上已过二审,应该跳过今日 first/second。当前简化实现是 + 合入 ``ctx.entries`` 走完整工作流——见 :class:`LastMergeDataState` + 的 docstring)。 +* **pending 条目** → ``last_second_review.pending_rollover_entries`` + → 由 ``second_review`` 阶段在开始工作前把它们 prepend 到 + ``ctx.entries`` → **跳过今日 first_review**,直接进入 second_review。 + 核心语义:二审的 pending 本来就已经过了 first,不应该回头重走 + first_review。 + +**消除孤儿 task 的理由**:若在当日把 pending 立即建新尾巴 task 并写 +``last_tasks.json[second_review]``,该 slot 会被当日 ``second_review`` 阶 +段覆盖 → **前者成为平台孤儿**。因此本 state 不调 ``tail_store.put``, +整个 run 中只有 ``second_review`` 的 roll-over 会写一次 slot。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ...platforms.factory import build_review_tool +from ...sources import XlsxSource +from .._tail_tasks import TailTaskStore +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import _notify, _resolve_lang # noqa: PLC2701 + +logger = logging.getLogger(__name__) + +_STAGE = ReviewStage.SECOND.value + +#: 二审遗留 approved 条目在 state_payload 中的落位——交给 +#: :class:`LastMergeDataState` 合入 ctx.entries。 +_SECOND_CARRY_OVER_KEY = "last_second_review.carry_over_entries" + +#: 二审遗留 **pending** 条目回流通道。 +#: +#: pending 条目解包装成 Entry 存到 state_payload,由今日 +#: ``second_review`` 阶段在开工前 prepend 到 ``ctx.entries``,跳过 +#: ``first_review`` 直接参与二审。slot 在本 run 内只被 +#: ``second_review`` 的 roll-over 写一次,没有覆盖,没有孤儿。 +_SECOND_PENDING_ROLLOVER_KEY = "last_second_review.pending_rollover_entries" + + +class LastSecondReviewState(WorkflowStateBase): + """接回上一日二审遗留的尾巴 task 并继续按条目拆分。""" + + name = StateEnum.LAST_SECOND_REVIEW.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("LastSecondReviewState: already completed — skipping.") + return None + + profile = ctx.language_profile + if profile is not None: + review_cfg = profile.review(_STAGE) + if not review_cfg.platform or review_cfg.platform == "none": + logger.info( + "LastSecondReviewState: no second-review platform configured — skipping.", + ) + self._mark_completed(ctx) + return None + + tail_store = TailTaskStore( + Path(ctx.workspace), + lang=_resolve_lang(ctx), + ) + record = tail_store.get(_STAGE) + if not record: + logger.info( + "LastSecondReviewState: no tail task in last_tasks.json[%s] — skipping.", + _STAGE, + ) + self._mark_completed(ctx) + return None + + task_id = str(record.get("task_id") or "") + if not task_id: + logger.warning( + "LastSecondReviewState: last_tasks.json[%s] has no task_id — clearing slot.", + _STAGE, + ) + tail_store.clear(_STAGE) + self._mark_completed(ctx) + return None + + logger.info( + "LastSecondReviewState: processing tail task_id=%s (batch=%s, pending=%s)", + task_id, record.get("batch_name", ""), record.get("pending_count", ""), + ) + + platform = build_review_tool( + profile, + _STAGE, + global_platform=ctx.config.platform, + ) + target_locale = ( # pylint: disable=unused-variable + (profile.target_locale if profile else "") + or ctx.config.target_locale + or record.get("target_locale", "") + ) + batch_name = str(record.get("batch_name") or f"last_{_STAGE}_{task_id}") + + # 命名约定(2026-10-09 对齐 second_review state 的中文命名): + # 目录:workspace/batches//second_review/ + # 文件:_第二轮审核_approved.xlsx / _pending.xlsx + from ...platforms._batch import stage_dir, stage_file_stem # noqa: WPS433 + last_dir = stage_dir(Path(ctx.workspace), batch_name, _STAGE) + stem = stage_file_stem(batch_name, _STAGE) + approved_xlsx = last_dir / f"{stem}_approved.xlsx" + pending_xlsx = last_dir / f"{stem}_pending.xlsx" + + split = platform.split_approved_data( + task_id, + save_approved_path=str(approved_xlsx), + save_pending_path=str(pending_xlsx), + review_stage=_STAGE, + ) + approved_keys: List[str] = list(split.extra.get("approved_keys", []) or []) + pending_keys: List[str] = list(split.extra.get("pending_keys", []) or []) + logger.info( + "LastSecondReviewState: tail split → approved=%d, pending=%d, is_complete=%s", + len(approved_keys), len(pending_keys), split.is_complete, + ) + + # approved → 落到 state_payload,由 last_merge_data 合入 ctx.entries + if approved_keys and approved_xlsx.exists(): + try: + carried = XlsxSource(encoding="utf-8").load(str(approved_xlsx)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastSecondReviewState: failed to read %s (%s); carry-over will be empty.", + approved_xlsx, exc, + ) + carried = [] + payload = ctx.state_payload.setdefault(_SECOND_CARRY_OVER_KEY, []) + payload.extend(_entry_to_dict(e) for e in carried) + logger.info( + "LastSecondReviewState: carried %d approved entries forward (total=%d).", + len(carried), len(payload), + ) + + # pending → 解包装成 Entry 存到 state_payload 的**二审专用回流通道** + # → 由今日 second_review 在开工前 prepend 到 ctx.entries → 跳过 + # first_review 直接走二审。 + # + # 2026-10-09 方案 ①-🅱 核心修复:不再当日建新 tail task,彻底 + # 消除"本 state 和 second_review 都 put slot、后者覆盖前者→孤儿" + # 的 bug。见 _SECOND_PENDING_ROLLOVER_KEY 的注释。 + if pending_keys and pending_xlsx.exists(): + try: + rolled = XlsxSource(encoding="utf-8").load(str(pending_xlsx)) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastSecondReviewState: failed to read pending xlsx %s (%s); " + "pending roll-over will be empty — THIS LOSES %d ENTRIES, investigate ASAP.", + pending_xlsx, exc, len(pending_keys), + ) + rolled = [] + payload = ctx.state_payload.setdefault(_SECOND_PENDING_ROLLOVER_KEY, []) + payload.extend(_entry_to_dict(e) for e in rolled) + logger.info( + "LastSecondReviewState: rolled over %d pending entries into " + "state_payload[%s] (will be prepended to ctx.entries by second_review, " + "bypassing first_review).", + len(rolled), _SECOND_PENDING_ROLLOVER_KEY, + ) + + # 无论 pending 是否存在:都要清理旧 task + 旧 file + 清空 slot。 + # approved 已通过 state_payload[_SECOND_CARRY_OVER_KEY] 回流; + # pending 已通过 state_payload[_SECOND_PENDING_ROLLOVER_KEY] 回流。 + # 旧 Crowdin task 和 file 的全部内容都已安全备份,可以放心删除。 + tail_store.clear(_STAGE) + try: + platform.delete_task(task_id, review_stage=_STAGE) + logger.info( + "LastSecondReviewState: deleted old tail task_id=%s on platform=%s " + "(approved=%d carried over, pending=%d rolled over for direct second_review).", + task_id, platform.platform_name, + len(approved_keys), len(pending_keys), + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastSecondReviewState: delete_task(%s) failed (continuing — " + "content already backed up to state_payload): %s", + task_id, exc, + ) + old_file_id = str(record.get("file_id") or "") + if old_file_id: + try: + platform.delete_file(old_file_id, review_stage=_STAGE) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "LastSecondReviewState: delete_file(%s) failed (continuing): %s", + old_file_id, exc, + ) + + _notify( + ctx, + _STAGE, + f"📝 【{ctx.config.project_code}】昨日二审续审任务已处理\n" + f"任务 ID:{task_id}\n" + f"✅ 已通过:{len(approved_keys)} 条\n" + f"⏭️ 滚入下轮:{len(pending_keys)} 条", + ) + self._mark_completed(ctx) + return None + + +def _entry_to_dict(entry: Any) -> Dict[str, Any]: + """把 :class:`Entry` 序列化成 JSON 安全的 dict。""" + return { + "key": entry.key, + "source_text": entry.source_text, + "target_text": entry.target_text, + "context": entry.context, + "comment": entry.comment, + "metadata": dict(entry.metadata or {}), + } + + +__all__ = ["LastSecondReviewState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/light_review_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/light_review_state.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe1c295a1641534b3e75fb7abcc25cf6f65c283 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/light_review_state.py @@ -0,0 +1,52 @@ +"""``light_review`` 状态——正式一审前的轻量审校。 + +与一审/二审共享平台契约,仅以 ``review_stage="light"`` 区分。 +""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import run_review_stage + +logger = logging.getLogger(__name__) + + +class LightReviewState(WorkflowStateBase): + """轻度审校:在人工审校看到文件前先做一轮快速 QA。 + + 若 profile 未配置 ``light`` 阶段(即 ``profile.reviews["light"].platform`` + 为空或 ``"none"``)将直接跳过。 + """ + + name = StateEnum.LIGHT_REVIEW.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("LightReviewState: already completed — skipping.") + return None + + profile = ctx.language_profile + if profile is not None: + review_cfg = profile.review(ReviewStage.LIGHT.value) + if not review_cfg.platform or review_cfg.platform == "none": + logger.info( + "LightReviewState: profile has no light-review platform — skipping.", + ) + self._mark_completed(ctx) + return None + + run_review_stage( + ctx, + review_stage=ReviewStage.LIGHT.value, + resume_key_prefix="light_review", + ) + self._mark_completed(ctx) + return None + + +__all__ = ["LightReviewState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/merge_data_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/merge_data_state.py new file mode 100644 index 0000000000000000000000000000000000000000..650a894f454984951dc74bc85dad94bc84cbe2fa --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/merge_data_state.py @@ -0,0 +1,504 @@ +"""``merge_data`` 状态——通用的"把已翻译条目从增量表迁移到全量表"实现。 + +**本 state 与格式无关**:通过 :class:`~TiMi_HOK_Game_Translator.sources.base.LocalizationSource` +协议读写文件,适用于已注册的任何 source 格式(dtxml / json / xliff / xlsx / +csv / yaml / xml 等)。增量/全量二元模型要求"增量表和全量表格式一致", +文件名默认用 ``99.incr.`` ↔ ``98.full.`` 的命名约定自动推断。 + +实际合并算法在 :mod:`TiMi_HOK_Game_Translator.utils.table_merger` 中以纯函数形式提供。 +本模块只负责从 :class:`WorkflowContext` 收集参数并调用它,再把结果写回 +上下文供下游 state 使用。 + +**导表时间窗口**: + 支持在语种 profile 中通过 ``merge_start_time`` 字段(``"HH:MM"`` + 格式,本地时区)配置"导表目标启动时间"。设置后,本 state 在真正 + 合表前会阻塞等待到该时刻;下游 ``push_vcs`` 紧接着跑,等价于 + "合表 + commit 压到指定窗口"。为空则立即执行。 + +**向后兼容**: + 老 profile 若在 ``workflow`` 中写了 ``dtxml_merge``——通过 + :mod:`dtxml_merge_state` 的别名注册继续生效,内部直接复用本 state 的实现。 +""" + +from __future__ import annotations + +import json +import logging +import shutil +import time +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ...commons import WorkflowState as StateEnum +from ...utils.table_merger import ( + delete_entries_from_incremental, + infer_full_table_path, + merge_incremental_into_full, + split_translated, +) +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + +#: 允许在语种 profile 中覆盖全量表路径的 key(``profile.extra`` 与 +#: ``profile.strategy_config`` 都查)。为空时按文件名自动推断。 +_FULL_PATH_KEYS = ("full_table_path",) + +#: 等待目标时间时每轮唤醒的最大 sleep 秒数,用于定期打进度日志。 +_WAIT_HEARTBEAT_SECONDS = 60 + + +class MergeDataState(WorkflowStateBase): + """把本轮已翻译条目从增量表迁移到全量表(格式无关的通用实现)。 + + 上游依赖: + - ``translate``:在 ``ctx.entries`` 上填好 ``target_text``; + - ``validate_data``(可选):清洗非法条目。 + 下游影响: + - 替换 ``ctx.entries`` 为未翻译子集 → ``push_vcs`` 自然把 + 精简后的增量表 commit 回 VCS; + - 通过 ``ctx.state_payload["merge_data.full_path"]`` 把全量表 + 绝对路径告知后续状态,供需要时一并提交; + - 为兼容老代码,也会把同样的值写入 + ``ctx.state_payload["dtxml_merge.full_path"]``(push_vcs 读的 key)。 + """ + + name = StateEnum.MERGE_DATA.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("MergeDataState: already completed — skipping.") + return None + + # 0. 若配置了导表目标时间,先阻塞等待到达该时刻。 + _wait_until_merge_time(ctx) + + # 0.1 【2026-10-09 方案 ② 新增】消费 merge-only 通道。 + # + # ``LastMergeDataState`` 把**昨日二审 approved** 的条目路由到 + # ``last_review.merge_only_entries`` —— 它们已经过了昨日二审, + # 今日不该再走 first_review / second_review,直接合入 full 表。 + # + # 做法:把它们 prepend 到 ``ctx.entries`` 的头部,下面的 + # ``split_translated(ctx.entries)`` 会把 target_text 非空的条目 + # 划到 ``translated``,和今日二审 approved 一起被 + # ``merge_incremental_into_full`` 合入 full 表。 + _consume_merge_only_entries(ctx) + + incremental_path = str(ctx.state_payload.get("pull_vcs.source_path") or "") + if not incremental_path: + logger.warning( + "MergeDataState: no incremental source path available — " + "did pull_vcs run? Skipping merge." + ) + self._mark_completed(ctx) + return None + + # 解析全量表路径:profile 显式配置 > 文件名推断。 + profile = ctx.language_profile + full_path: Optional[str] = None + if profile is not None: + for key in _FULL_PATH_KEYS: + candidate = ( + profile.extra.get(key) + or profile.strategy_config.get(key) + ) + if candidate: + full_path = str(candidate) + break + if not full_path: + full_path = infer_full_table_path(incremental_path) + + # 从 ctx 直接拿 source 实例——它是 workflow runner 按 profile.source.format + # 构造的 LocalizationSource,适用于任何已注册格式。 + source = ctx.source + + # 【P4 兼容钩子】真正写磁盘前通知 VCS 后端 "即将修改这些路径"。 + # 对 svn/git/mock 是 no-op;对 perforce 会跑 `p4 edit` 取消本地 + # 文件的只读属性,否则 Python 直接 open(..., "w") 会 PermissionError。 + # 两份文件都要通知——merge_incremental_into_full 会同时写入 + # full 和(间接)incremental。 + _paths_to_prepare = [incremental_path] + if full_path: + _paths_to_prepare.append(full_path) + try: + ctx.vcs.prepare_for_write(_paths_to_prepare) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 不致命,仅记日志。 + logger.warning( + "MergeDataState: vcs.prepare_for_write failed (continuing): %s", + exc, + ) + + # 【Q2 方案 B 消费点】translate 阶段把"key 已存在于全量表"的今日 + # incr 条目剔除出 ctx.entries,但磁盘上的 incr 文件还留着它们 + # ——这里物理删除,彻底闭环 full-table 去重。**必须在** + # split_translated 之前执行,否则"translated=0 走早返回"分支里 + # shadowed 永远不被清理,形成每天过滤一次的脏循环。 + shadowed = ctx.state_payload.get("translate.shadowed_by_full_table_keys") or [] + removed = 0 + if shadowed: + removed = delete_entries_from_incremental( + source, incremental_path, shadowed, + ) + logger.info( + "MergeDataState: pre-merge cleanup — deleted %d full-table-shadowed " + "entries from %s (keys=%s%s).", + removed, incremental_path, + shadowed[:3], + "..." if len(shadowed) > 3 else "", + ) + ctx.state_payload["merge_data.shadowed_removed_count"] = removed + + translated, untranslated = split_translated(ctx.entries) + if not translated: + logger.info( + "MergeDataState: no translated entries this round " + "(incremental=%s), nothing to merge.", + incremental_path, + ) + ctx.state_payload["merge_data.translated_count"] = 0 + # 【关键决策】当 shadowed>0 时,incr 文件已被物理修改(删除行), + # push_vcs **必须 commit** 让 VCS 侧也同步删除——不能 skip。 + # 没 shadowed 时才走原来的 "0 translated → skip" 短路。 + if not shadowed or removed == 0: + ctx.state_payload["push_vcs.skipped"] = True + ctx.state_payload["push_vcs.skip_reason"] = ( + "merge_data produced 0 translated entries this round " + "and no shadowed entries removed" + ) + else: + logger.info( + "MergeDataState: translated=0 but shadowed removed=%d → " + "letting push_vcs commit the pruned incremental file.", + removed, + ) + self._mark_completed(ctx) + return None + + result = merge_incremental_into_full( + source=source, + incremental_path=incremental_path, + full_path=full_path, + translated_entries=translated, + untranslated_entries=untranslated, + ) + + # 新 key(通用命名)+ 老 key(dtxml_merge.* )双写,保持 push_vcs + # 等下游的向后兼容。 + ctx.state_payload["merge_data.full_path"] = result["full"] + ctx.state_payload["merge_data.incremental_path"] = result["incremental"] + ctx.state_payload["merge_data.translated_count"] = int(result["translated_count"]) + ctx.state_payload["merge_data.remaining_count"] = int(result["remaining_count"]) + ctx.state_payload["dtxml_merge.full_path"] = result["full"] + ctx.state_payload["dtxml_merge.incremental_path"] = result["incremental"] + ctx.state_payload["dtxml_merge.translated_count"] = int(result["translated_count"]) + ctx.state_payload["dtxml_merge.remaining_count"] = int(result["remaining_count"]) + + # 关键:下一个 push_vcs 从 ctx.entries 写回增量表; + # 替换为未翻译子集 → 提交内容=「移除已翻译后的增量表」。 + ctx.entries = list(untranslated) + + logger.info( + "MergeDataState: merged %s translated entries into %s; " + "%s entries remain in %s (format=%s).", + result["translated_count"], result["full"], + result["remaining_count"], result["incremental"], + getattr(source, "format_name", type(source).__name__), + ) + + # 向批次目录落一份"合表快照"——即便 push_vcs 跳过/失败,这份快照 + # 也**独立于 VCS** 保留,是最后一道现场证据。 + _write_debug_snapshot( + ctx=ctx, + full_path=str(result["full"]), + incremental_path=str(result["incremental"]), + translated=translated, + untranslated=untranslated, + ) + + self._mark_completed(ctx) + return None + + +def _wait_until_merge_time(ctx: WorkflowContext) -> None: + """若 profile 配置了 ``merge_start_time``,阻塞睡眠到该本地时刻。 + + * 空串/未配置 → 立即返回; + * ``"HH:MM"`` 解析成功: + - 若本日该时刻**仍未到**,sleep 到那时才返回; + - 若本日该时刻**已过**(例如 "02:00" 现在 10:00),顺延到次日同点; + * 格式非法 → 记 warning,退化为立即执行。 + """ + profile = ctx.language_profile + raw = (getattr(profile, "merge_start_time", "") or "").strip() if profile else "" + if not raw: + return + try: + hh, mm = raw.split(":", 1) + hour = int(hh) + minute = int(mm) + except (ValueError, AttributeError): + logger.warning( + "MergeDataState: invalid merge_start_time %r (expected 'HH:MM'); " + "executing immediately.", + raw, + ) + return + + now = datetime.now() + target = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if target <= now: + target = target + timedelta(days=1) + + total_seconds = (target - now).total_seconds() + if total_seconds <= 0: + return + + logger.info( + "MergeDataState: waiting until %s (%.1f minutes) before merging — " + "merge_start_time=%s", + target.isoformat(timespec="seconds"), + total_seconds / 60.0, + raw, + ) + + _notify( + ctx, + f"⏳ 【{ctx.config.project_code}】等待合并窗口\n" + f"目标时间:{target.isoformat(timespec='minutes')}\n" + f"配置项 merge_start_time={raw}", + ) + + while True: + remaining = (target - datetime.now()).total_seconds() + if remaining <= 0: + break + chunk = min(_WAIT_HEARTBEAT_SECONDS, remaining) + time.sleep(chunk) + remaining_after = (target - datetime.now()).total_seconds() + if remaining_after > 0: + logger.info( + "MergeDataState: still waiting — %.1f minutes to %s", + remaining_after / 60.0, + target.isoformat(timespec="seconds"), + ) + + logger.info( + "MergeDataState: merge window reached (%s), proceeding.", + target.isoformat(timespec="seconds"), + ) + _notify( + ctx, + f"🔀 【{ctx.config.project_code}】合并窗口已到,开始执行 merge_data。", + ) + + +def _notify(ctx: WorkflowContext, message: str) -> None: + """安全地发一条通知;失败不影响主流程。 + + 会自动从 ``ctx.config.notification.mentioned`` 取出需要 @ 的用户列表 + 透传给 notifier。 + """ + if ctx.notifier is None: + return + try: + mentioned = tuple( + (ctx.config.notification.mentioned or []) + if getattr(ctx.config, "notification", None) + else () + ) + ctx.notifier.notify(message, mentioned=mentioned) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning("MergeDataState: notifier failed: %s", exc) + + +def _write_debug_snapshot( + *, + ctx: WorkflowContext, + full_path: str, + incremental_path: str, + translated: List[Any], + untranslated: List[Any], +) -> None: + """把本轮合表产物复制一份到 ``workspace/batches//merge_data/``。 + + 快照目录名保持为 ``dtxml_merge``(历史目录名)以免破坏运维脚本—— + 真实合并算法与格式无关,但目录名保留以减少迁移风险。 + 产出三份文件: + + * ``full_after_merge``——合入 translated 之后的全量表完整副本; + * ``incremental_after_merge``——剔除 approved 之后的增量表完整副本; + * ``merged_entries.json``——本轮合入了哪些 key 的清单。 + + 失败不致命——任何 I/O 错误都仅告警,不影响主流程继续推进 push_vcs。 + """ + batch_name = str(ctx.state_data.get("review.batch_name") or "") + if not batch_name: + batch_name = "merge_only_" + datetime.now().strftime("%Y%m%d%H%M%S") + + # 历史目录名保留为 "dtxml_merge"(即便现在用通用版 merge_data), + # 避免破坏现有的产物浏览路径/运维脚本。 + snapshot_dir = Path(ctx.workspace) / "batches" / batch_name / "dtxml_merge" + try: + snapshot_dir.mkdir(parents=True, exist_ok=True) + except OSError as exc: + logger.warning( + "MergeDataState: cannot create snapshot dir %s: %s", snapshot_dir, exc, + ) + return + + # 拷贝两份快照——保留原文件后缀,便于肉眼直接打开。 + full_ext = Path(full_path).suffix or ".dat" + inc_ext = Path(incremental_path).suffix or ".dat" + for src, dst_name in ( + (full_path, f"full_after_merge{full_ext}"), + (incremental_path, f"incremental_after_merge{inc_ext}"), + ): + if not src: + continue + try: + shutil.copyfile(src, str(snapshot_dir / dst_name)) + except OSError as exc: + logger.warning( + "MergeDataState: snapshot copy %s → %s failed: %s", + src, dst_name, exc, + ) + + # 写合入条目清单 json。 + payload: Dict[str, Any] = { + "batch_name": batch_name, + "translated_count": len(translated), + "remaining_count": len(untranslated), + "merged_at": datetime.now().isoformat(timespec="seconds"), + "full_path": full_path, + "incremental_path": incremental_path, + "source_format": getattr(ctx.source, "format_name", type(ctx.source).__name__), + "entries": [ + { + "key": getattr(e, "key", ""), + "source_text": getattr(e, "source_text", ""), + "target_text": getattr(e, "target_text", ""), + } + for e in translated + ], + } + merged_json = snapshot_dir / "merged_entries.json" + try: + merged_json.write_text( + json.dumps(payload, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + except OSError as exc: + logger.warning( + "MergeDataState: snapshot write %s failed: %s", merged_json, exc, + ) + return + + logger.info( + "MergeDataState: snapshot written to %s (translated=%d, remaining=%d)", + snapshot_dir, len(translated), len(untranslated), + ) + + +#: 【2026-10-09 方案 ② 新增】消费 "直接合入 full 表" 通道的 key。 +#: 由 :class:`LastMergeDataState` 填充;由 :class:`MergeDataState` 消费。 +_MERGE_ONLY_ENTRIES_KEY = "last_review.merge_only_entries" + + +def _consume_merge_only_entries(ctx: WorkflowContext) -> None: + """从 ``ctx.state_payload[_MERGE_ONLY_ENTRIES_KEY]`` 读昨日二审 approved + 条目,按 Rule 2b 精确路由到 ``ctx.entries``;读取后清空通道。 + + 这些条目的 ``target_text`` 已经填充(昨日二审通过的最终译文),下面 + ``split_translated`` 会把它们划入 ``translated`` 和今日二审 approved + 一起合入 full 表 —— 完全跳过 first_review / second_review。 + + **Rule 2b 精确版**: + * key 不冲突 → prepend 到 ctx.entries 头部; + * key 冲突 + source 相同 → **原地替换** ctx.entries 对应条目 + (保留昨日二审 approved 版本,它已过完整两轮审核,比今日的新版本 + 更前进); + * key 冲突 + source 不同 → WARN 并丢弃昨日版本。 + """ + from ...sources.base import Entry # noqa: WPS433 — 局部避免循环导入 + + raw_list = ctx.state_payload.get(_MERGE_ONLY_ENTRIES_KEY) or [] + if not raw_list: + return + + rolled: list = [] + for raw in raw_list: + if not isinstance(raw, dict): + continue + try: + rolled.append( + Entry( + key=str(raw.get("key", "")), + source_text=str(raw.get("source_text", "") or ""), + target_text=str(raw.get("target_text", "") or ""), + context=str(raw.get("context", "") or ""), + comment=str(raw.get("comment", "") or ""), + metadata=dict(raw.get("metadata") or {}), + ) + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "MergeDataState: skip malformed merge-only item: %s", exc, + ) + + # 清空通道,防止下次 run 重复合入。 + ctx.state_payload.pop(_MERGE_ONLY_ENTRIES_KEY, None) + + if not rolled: + return + + # Rule 2b 精确判定。 + today_by_key = {e.key: e for e in ctx.entries} + today_entries_mutable = list(ctx.entries) + today_index_by_key = {e.key: i for i, e in enumerate(today_entries_mutable)} + seen_in_rolled: set = set() + + prepend_entries: list = [] + replaced_in_today = 0 + dropped_diff_source = 0 + dropped_cross_channel = 0 + + for e in rolled: + if e.key in seen_in_rolled: + dropped_cross_channel += 1 + continue + seen_in_rolled.add(e.key) + + if e.key not in today_by_key: + prepend_entries.append(e) + continue + + today_version = today_by_key[e.key] + if today_version.source_text == e.source_text: + idx = today_index_by_key[e.key] + today_entries_mutable[idx] = e + today_by_key[e.key] = e + replaced_in_today += 1 + else: + logger.warning( + "MergeDataState: dropping yesterday merge-only entry key=%r " + "because today has the same key with a DIFFERENT source " + "(today's version wins).", + e.key, + ) + dropped_diff_source += 1 + + before = len(ctx.entries) + ctx.entries = prepend_entries + today_entries_mutable + logger.info( + "MergeDataState: injected merge-only entries: new=%d, " + "replaced_in_today=%d (same source), dropped_diff_source=%d, " + "dropped_cross_channel=%d. ctx.entries: %d → %d " + "— these skip first_review AND second_review, going straight into full-table merge.", + len(prepend_entries), replaced_in_today, dropped_diff_source, + dropped_cross_channel, before, len(ctx.entries), + ) + + +__all__ = ["MergeDataState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/pull_vcs_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/pull_vcs_state.py new file mode 100644 index 0000000000000000000000000000000000000000..1eda976fd670d5abc84de0129208aaefe969be4a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/pull_vcs_state.py @@ -0,0 +1,203 @@ +"""``pull_vcs`` 状态——从 VCS 拉取源文件工作副本。 + +实际拉取动作交给 :class:`~TiMi_HOK_Game_Translator.vcs.VcsClient`——默认 mock +后端不做任何事,真实后端(svn / git / perforce)由 +:attr:`Config.vcs.type` 选择。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + + +class PullVcsState(WorkflowStateBase): + """将本地工作副本同步到配置的版本。""" + + name = StateEnum.PULL_VCS.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + already_done = self._already_completed(ctx) + + target_revision = ctx.config.vcs.revision or "HEAD" + # local_path 以 ctx.vcs(由 factory 展开后的绝对路径)为准, + # 避免同时存在"全局 config.vcs vs profile.vcs vs {workspace} 占位符" + # 时三方不一致。 + local_path = getattr(ctx.vcs, "local_path", "") or ctx.config.vcs.local_path + + if already_done: + # 断点续跑:跳过真正的 svn update/checkout,但**仍然要重新 + # load entries**,否则下游 state(translate / review)会拿到 + # 空列表(``ctx.entries`` 不持久化)。``source.load()`` 是纯 + # 读操作,重复调用没有副作用也无需网络。 + logger.info("PullVcsState: already completed — reloading entries only.") + else: + logger.info( + "PullVcsState: syncing %s@%s → %s", + ctx.config.vcs.type, + target_revision, + local_path or "", + ) + try: + if local_path and not Path(local_path).exists(): + ctx.vcs.checkout() + else: + ctx.vcs.update(revision=target_revision) + except Exception as exc: # noqa: BLE001 + ctx.state_payload["pull_vcs.error"] = repr(exc) + raise + + source_cfg = _resolve_source_config(ctx) + source_path = resolve_source_path(ctx, source_cfg.path) + if not source_path: + logger.warning( + "PullVcsState: source.path is empty — no entries loaded.", + ) + ctx.entries = [] + else: + try: + ctx.entries = list(ctx.source.load(source_path)) + except Exception as exc: # noqa: BLE001 + # source 文件不存在 / 解析失败:**不能软吞**。下游 translate + # 会拿到 0 entries,审校阶段再被 Crowdin 拒单(HTTP 409 + # "no untranslated words"),导致误导性的报错链路。此处 + # 直接 raise,让 runner 把状态标为失败并把异常原样抛给用户。 + ctx.state_payload["pull_vcs.source_load_error"] = repr(exc) + ctx.state_payload["pull_vcs.source_path"] = source_path + raise + + ctx.state_payload["pull_vcs.entry_count"] = len(ctx.entries) + ctx.state_payload["pull_vcs.source_path"] = source_path + logger.info("PullVcsState: loaded %d entries.", len(ctx.entries)) + + # 【run 开始时的文件 hash 快照】——push_vcs 用来判断"相较于本 run 起 + # 点是否发生过变更"(而不是只看 dtxml_merge dump 前后,否则会把 + # last_merge_data 带入的昨日 approved 条目的 upsert 判成 no-op)。 + _record_pre_run_hashes(ctx, source_path) + + if not already_done: + self._mark_completed(ctx) + return None + +def _record_pre_run_hashes(ctx: WorkflowContext, incremental_path: str) -> None: # noqa: E302 + """把 ``incr`` + ``full`` 文件的 SHA-1 存到 ``ctx.state_payload``。 + + * ``incr`` 路径就是 ``pull_vcs.source_path``; + * ``full`` 路径优先取 profile 的 ``extra.full_table_path`` / + ``strategy_config.full_table_path``,否则从 incr 用 + :func:`infer_full_table_path` 推断。 + + 任何一个文件不存在就记 ``""``(空 hash)——push_vcs 侧会把空 hash + 等价于"本 run 之前这个文件不存在,任何新写入都算变更"。 + """ + import hashlib + + from ...utils.table_merger import infer_full_table_path # noqa: WPS433 + + def _sha1(p: str) -> str: + if not p: + return "" + try: + if not Path(p).exists(): + return "" + h = hashlib.sha1() + with open(p, "rb") as f: + for chunk in iter(lambda: f.read(65536), b""): + h.update(chunk) + return h.hexdigest() + except OSError as exc: + logger.warning("PullVcsState: hash %s failed: %s", p, exc) + return "" + + # incr hash + incr_hash = _sha1(incremental_path) + ctx.state_payload["push_vcs.pre_hash.incr"] = incr_hash + + # full 路径解析 + profile = ctx.language_profile + full_path = "" + if profile is not None: + for key in ("full_table_path",): + candidate = ( + profile.extra.get(key) + or profile.strategy_config.get(key) + ) + if candidate: + full_path = str(candidate) + break + if not full_path and incremental_path: + full_path = infer_full_table_path(incremental_path) + + ctx.state_payload["push_vcs.pre_hash.full_path"] = full_path + ctx.state_payload["push_vcs.pre_hash.full"] = _sha1(full_path) + + logger.info( + "PullVcsState: pre-run hashes recorded (incr=%s..., full=%s...; full_path=%s)", + (incr_hash or "")[:8], + (ctx.state_payload["push_vcs.pre_hash.full"] or "")[:8], + full_path or "", + ) + + +def _resolve_source_config(ctx: WorkflowContext): + """优先使用 profile 上的 source 配置,回退到全局 source。""" + profile = ctx.language_profile + if profile is not None and profile.source and profile.source.path: + return profile.source + return ctx.config.source + + +def resolve_source_path(ctx: WorkflowContext, path: str) -> str: + """将 ``path`` 解析为绝对文件路径。 + + 解析顺序(优先选用已经由 ``create_vcs_client`` 展开好的 + ``ctx.vcs.local_path`` 作为基准——它已经处理过 ``{workspace}`` 占位符 + 与绝对/相对路径逻辑,是最权威的 SVN 工作副本根路径): + + * ``path`` 本身为绝对路径时直接返回; + * 否则以 ``ctx.vcs.local_path`` 为基准拼接; + * 若 vcs client 没有 local_path(如 mock 后端),回退到 workspace 目录。 + """ + if not path: + return "" + p = Path(path) + if p.is_absolute(): + return str(p) + + # 首选:从已初始化的 VcsClient 读 local_path(factory 已展开占位符)。 + vcs_local = getattr(ctx.vcs, "local_path", "") or "" + if vcs_local: + return str((Path(vcs_local) / p).resolve()) + + # 回退 1:profile.vcs.local_path(相对路径按 workspace 展开)。 + profile = ctx.language_profile + profile_local = ( + profile.vcs.local_path if profile is not None and profile.vcs else "" + ) or "" + if profile_local: + profile_local = profile_local.replace("{workspace}", str(ctx.workspace)) + base = Path(profile_local) + if not base.is_absolute(): + base = ctx.workspace / base + return str((base / p).resolve()) + + # 回退 2:全局 config.vcs.local_path。 + global_local = ctx.config.vcs.local_path or "" + if global_local: + global_local = global_local.replace("{workspace}", str(ctx.workspace)) + base = Path(global_local) + if not base.is_absolute(): + base = Path.cwd() / base + return str((base / p).resolve()) + + # 回退 3:workspace。 + return str((ctx.workspace / p).resolve()) + + +__all__ = ["PullVcsState", "resolve_source_path"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_multi_vcs_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_multi_vcs_state.py new file mode 100644 index 0000000000000000000000000000000000000000..44604ab5dba596101a564a701bfa6eced7013e5c --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_multi_vcs_state.py @@ -0,0 +1,92 @@ +"""``push_multi_vcs`` 状态——发布到额外的目标路径。 + +将同一份翻译结果发布到多个 VCS 路径/分支。每个目标由 +:class:`~TiMi_HOK_Game_Translator.config.LanguageProfile` 上的 +:class:`~TiMi_HOK_Game_Translator.config.PublishTarget` 描述。 +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from .pull_vcs_state import resolve_source_path as _resolve + +logger = logging.getLogger(__name__) + + +class PushMultiVcsState(WorkflowStateBase): + """遍历 :attr:`LanguageProfile.multi_publish_targets` 逐个发布。 + + 每个目标的 ``source_path`` 作为 dump 目标。当 ``stages`` 非空时, + 仅当前 :attr:`Config.stage` 命中则执行。 + """ + + name = StateEnum.PUSH_MULTI_VCS.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("PushMultiVcsState: already completed — skipping.") + return None + + profile = ctx.language_profile + if profile is None or not profile.multi_publish_targets: + logger.info( + "PushMultiVcsState: no multi-publish targets configured — skipping.", + ) + self._mark_completed(ctx) + return None + + stage = ctx.config.stage + pushed = [] + for target in profile.multi_publish_targets: + if target.stages and stage not in target.stages: + logger.debug( + "PushMultiVcsState: target %r does not apply to stage %r", + target.name, stage, + ) + continue + if not target.source_path: + logger.warning( + "PushMultiVcsState: target %r has empty source_path — skipping.", + target.name, + ) + continue + + resolved = _resolve(ctx, target.source_path) + Path(resolved).parent.mkdir(parents=True, exist_ok=True) + try: + ctx.source.dump(ctx.entries, resolved) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + ctx.state_payload.setdefault("push_multi_vcs.errors", {}) + ctx.state_payload["push_multi_vcs.errors"][target.name] = repr(exc) + logger.warning( + "PushMultiVcsState: dump failed for target %r: %s", + target.name, exc, + ) + continue + + commit_msg = ctx.config.vcs.default_commit_message + try: + ctx.vcs.commit([resolved], message=commit_msg) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "PushMultiVcsState: commit failed for target %r: %s", + target.name, exc, + ) + continue + pushed.append(target.name) + + ctx.state_payload["push_multi_vcs.pushed"] = pushed + logger.info( + "PushMultiVcsState: published to %d target(s): %s", + len(pushed), pushed, + ) + self._mark_completed(ctx) + return None + + +__all__ = ["PushMultiVcsState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_vcs_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_vcs_state.py new file mode 100644 index 0000000000000000000000000000000000000000..5b7268b49292b833bc0c4f115c5c3cba53e64c7e --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/push_vcs_state.py @@ -0,0 +1,161 @@ +"""``push_vcs`` 状态——将合并后的译文提交回 VCS。""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +from ...commons import DEFAULT_VCS_COMMIT_MESSAGE +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from .pull_vcs_state import resolve_source_path as _resolve + +logger = logging.getLogger(__name__) + + +class PushVcsState(WorkflowStateBase): + """将条目写回源文件并提交至 VCS。 + + 为保证无变更不报错,此状态行为宽容;上游如需短路经可设置 + ``ctx.state_payload["push_vcs.skipped"] = True``。 + """ + + name = StateEnum.PUSH_VCS.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("PushVcsState: already completed — skipping.") + return None + if ctx.state_payload.get("push_vcs.skipped"): + reason = ctx.state_payload.get("push_vcs.skip_reason") or "upstream requested skip" + logger.info("PushVcsState: skipping — %s.", reason) + self._mark_completed(ctx) + return None + + source_cfg = _resolve_source_config(ctx) + incremental_path = _resolve(ctx, source_cfg.path) + if not incremental_path: + logger.warning("PushVcsState: source.path is empty — nothing to dump.") + self._mark_completed(ctx) + return None + + # 全量表路径:由 dtxml_merge 把合入后的绝对路径写进 state_payload, + # 本 state 要**和增量表一起**提交到 VCS——否则本轮合入全量表的译文 + # 只落在本地工作副本,SVN 侧永远拿不到(2026-10-09 实测事故现场)。 + # 若 dtxml_merge 本轮没跑(translated=0 → skip 分支),fallback 到 + # pull_vcs 落下来的 full_path(**绝不能**让 full_path 为空而漏判 + # last_merge_data 带入的昨日 approved 对 full 表的 upsert)。 + full_path = str( + ctx.state_payload.get("dtxml_merge.full_path") + or ctx.state_payload.get("push_vcs.pre_hash.full_path") + or "" + ) + + # 【基准 hash 来源】优先用 pull_vcs 阶段落下来的 ``pre_hash``——这是 + # "本次 run 刚开始、还没动过任何文件"时的真实快照;而不是本 state + # dump 前的瞬时值(否则会漏掉 dtxml_merge 对 full 表的 upsert, + # 以及 last_merge_data 对 full 表的 upsert,让 push_vcs 误判 + # "nothing changed" → 跳过 commit,SVN 侧永远拿不到当天译文)。 + # + # 若 state_payload 里取不到(兼容旧批次 / 不走 pull_vcs 的测试路径), + # 回退到"本 state dump 前的瞬时 hash"做兜底。 + pre_hash_inc = ctx.state_payload.get("push_vcs.pre_hash.incr") + if pre_hash_inc is None: + pre_hash_inc = _file_hash(incremental_path) + pre_hash_full = ctx.state_payload.get("push_vcs.pre_hash.full") + if pre_hash_full is None: + pre_hash_full = _file_hash(full_path) if full_path else None + + # 1) 写增量表(ctx.entries 已是"剔除 approved 之后的剩余条目")。 + Path(incremental_path).parent.mkdir(parents=True, exist_ok=True) + # 【P4 兼容钩子】写磁盘前通知 VCS 后端——svn/git/mock 为 no-op; + # perforce 会跑 `p4 edit`,取消本地文件的只读属性,否则下面的 + # ctx.source.dump() 会抛 PermissionError。 + _paths_to_prepare: list = [incremental_path] + if full_path: + _paths_to_prepare.append(full_path) + try: + ctx.vcs.prepare_for_write(_paths_to_prepare) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 不致命,commit 阶段仍会兜底。 + logger.warning( + "PushVcsState: vcs.prepare_for_write failed (continuing): %s", + exc, + ) + try: + ctx.source.dump(ctx.entries, incremental_path) + except Exception as exc: # noqa: BLE001 + ctx.state_payload["push_vcs.dump_error"] = repr(exc) + raise + + # 全量表的内容由 ``dtxml_merge`` 已经写入磁盘(它直接通过底层 + # ``merge_incremental_into_full`` 的 I/O 完成),本 state 无需再 + # dump;只需要对比哈希决定要不要加入 commit 列表。 + + post_hash_inc = _file_hash(incremental_path) + post_hash_full = _file_hash(full_path) if full_path else None + + changed_paths: list = [] + if pre_hash_inc != post_hash_inc: + changed_paths.append(incremental_path) + if full_path and pre_hash_full != post_hash_full: + changed_paths.append(full_path) + + if not changed_paths: + logger.info( + "PushVcsState: nothing changed (incremental=%s, full=%s) — " + "skipping commit to avoid empty/no-op push to VCS.", + incremental_path, full_path or "", + ) + ctx.state_payload["push_vcs.path"] = incremental_path + ctx.state_payload["push_vcs.unchanged"] = True + self._mark_completed(ctx) + return None + + commit_message = ( + ctx.state_payload.get("push_vcs.message") + or ctx.config.vcs.default_commit_message + or DEFAULT_VCS_COMMIT_MESSAGE + ) + try: + ctx.vcs.commit(changed_paths, message=str(commit_message)) + except Exception as exc: # noqa: BLE001 + ctx.state_payload["push_vcs.commit_error"] = repr(exc) + raise + + ctx.state_payload["push_vcs.path"] = incremental_path + ctx.state_payload["push_vcs.committed_paths"] = list(changed_paths) + logger.info( + "PushVcsState: committed %d file(s): %s", + len(changed_paths), changed_paths, + ) + + self._mark_completed(ctx) + return None + + +def _file_hash(path: str) -> Optional[str]: + """对 ``path`` 的内容计算 SHA-1;文件不存在/读失败/路径为空返回 ``None``。 + + 用途::class:`PushVcsState` 在 dump 前后各算一次,相同 → 跳过 commit。 + """ + import hashlib + + if not path: + return None + try: + with open(path, "rb") as fh: + return hashlib.sha1(fh.read()).hexdigest() + except OSError: + return None + + +def _resolve_source_config(ctx: WorkflowContext): + """优先使用 profile 上的 source 配置,回退到全局 source。""" + profile = ctx.language_profile + if profile is not None and profile.source and profile.source.path: + return profile.source + return ctx.config.source + + +__all__ = ["PushVcsState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/second_review_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/second_review_state.py new file mode 100644 index 0000000000000000000000000000000000000000..803f6d68f2b91dedef2434dbd6a31a1b086e5dc6 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/second_review_state.py @@ -0,0 +1,49 @@ +"""``second_review`` 状态——二次审校。""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import ReviewStage +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import run_review_stage + +logger = logging.getLogger(__name__) + + +class SecondReviewState(WorkflowStateBase): + """使用为 :class:`ReviewStage.SECOND` 配置的平台执行二次审校。 + + 若语种不需要二审,只需从 :attr:`LanguageProfile.workflow` 中去掉本状态; + 本状态在 stage 配置缺失时会开缓跳过,不会硬性报错。 + """ + + name = StateEnum.SECOND_REVIEW.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("SecondReviewState: already completed — skipping.") + return None + + profile = ctx.language_profile + if profile is not None: + review_cfg = profile.review(ReviewStage.SECOND.value) + if not review_cfg.platform or review_cfg.platform == "none": + logger.info( + "SecondReviewState: profile has no second-review platform — skipping.", + ) + self._mark_completed(ctx) + return None + + run_review_stage( + ctx, + review_stage=ReviewStage.SECOND.value, + resume_key_prefix="second_review", + ) + self._mark_completed(ctx) + return None + + +__all__ = ["SecondReviewState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/translate_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/translate_state.py new file mode 100644 index 0000000000000000000000000000000000000000..55055acfa76916ee97368a7fe00983f67a6dc6fa --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/translate_state.py @@ -0,0 +1,352 @@ +"""``translate`` 状态——运行当前语种的翻译策略。""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ...translation import get_translation_strategy +from ...utils import ( + collapse_by_source, + filter_against_pending, + load_pending_source_pairs, + save_incr_snapshot, +) +from .._tail_tasks import TailTaskStore +from ..state import WorkflowContext, WorkflowStateBase +from ._review_state_helpers import _resolve_lang # noqa: PLC2701 — 共享 helper + +logger = logging.getLogger(__name__) + + +#: state_payload 中记录"今日 incr 完整快照"路径的 key,供 review 阶段扩散时读。 +_SNAPSHOT_PATH_KEY = "translate.incr_snapshot_path" +#: state_payload 中记录"因 (key,source) 命中昨日 pending 而被屏蔽的 key 列表"。 +_SHADOWED_BY_PENDING_KEY = "translate.shadowed_by_pending_keys" +#: state_payload 中记录"因 key 已存在于全量表而被剔除"的 key 列表。 +#: ``merge_data`` 会消费它,从磁盘上的 incr 文件物理删除对应条目—— +#: 避免下次 run 的 pull_vcs 又把它们捞回来陷入"每天过滤一次"的脏循环。 +_SHADOWED_BY_FULL_TABLE_KEY = "translate.shadowed_by_full_table_keys" + + +class TranslateState(WorkflowStateBase): + """就地翻译 :attr:`WorkflowContext.entries` 中的每一条。 + + 在调用策略翻译前做**三项前置清洗**——对齐生产场景的数据一致性要求: + 滤掉 ``need_approve_summary_path`` 中 Origin 已存在的条目, + 并 ``drop_duplicates(subset=["Origin"])`` 按源语文本折叠: + + 0. 若已标完成则跳过(断点续跑,译文从 state_data 还原); + 1. **保存今日 incr 的完整快照**到 + ``workspace/batches//translate/incr_snapshot.xlsx``——含**所有** + entries(包括同 source 的兄弟行),供后续 review 阶段扩散时回捞; + 2. **按 (key, source) 对昨日 pending 做一致性过滤**: + * 完全一致 → 屏蔽今日版本(避免 Crowdin 侧出现同 (key,source) 双 task); + * 同 key 不同 source → 保留今日版本并 WARN(source 已更新,重译); + 3. **按 source_text 折叠**:同 source 多条只留第一条作代表走 LLM/审核, + 兄弟暂存在快照里,审完后由 ``_review_state_helpers`` 扩散回 ctx.entries; + 4. 为当前语种构造 :class:`BaseTranslationStrategy` 跑翻译; + 5. 把译文回写 ``ctx.entries``、持久化到 state_data; + 6. 标为已完成。 + """ + + name = StateEnum.TRANSLATE.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + # 断点续跑:跳过 LLM 调用,但从 state_data 恢复译文到内存 + # ``ctx.entries``。``ctx.entries`` 本身不持久化,因此必须回填 + # 下游 review / merge_data / push_vcs 才能拿到翻译结果。 + stored = ctx.state_data.get("translate.translations") or {} + if stored and ctx.entries: + hits = 0 + for entry in ctx.entries: + tgt = stored.get(entry.key, "") + if tgt and not entry.target_text: + entry.target_text = tgt + hits += 1 + logger.info( + "TranslateState: already completed — restored %d/%d translations from state.", + hits, len(ctx.entries), + ) + return None + # ``translate`` 被标为完成,但 state_data 里没有译文表。 + # 常见于:早期版本 state 文件遗留、或上次运行在 translate 之后 + # 的下游状态崩溃但 translate 的持久化段还没落盘。此时若直接 + # 跳过,下游会拿到 target_text 全空的 entries,Crowdin 会 + # 判定"所有串都已翻译"并返回 409 "no untranslated words"。 + # 更稳妖的做法是**降级为冷启动**:重跑 LLM。 + logger.warning( + "TranslateState: marked completed but translations cache is empty — " + "falling back to a full re-translation to avoid downstream data loss.", + ) + + # -------------------------------------------------------------- + # 1-3) 前置清洗:快照 + 过滤昨日 pending + 按 source 折叠。 + # -------------------------------------------------------------- + self._prepare_entries(ctx) + + # -------------------------------------------------------------- + # 4) 构造策略并翻译(只翻译代表,兄弟在快照里备着)。 + # -------------------------------------------------------------- + profile = ctx.language_profile + language_id = profile.id if profile else ctx.config.target_locale or "unknown" + target_locale = ( + (profile.target_locale if profile else "") + or ctx.config.target_locale + ) + source_locale = ( + (profile.source_locale if profile else "") + or ctx.config.source_locale + ) + strategy_config = dict(profile.strategy_config) if profile else {} + + strategy = get_translation_strategy( + language_id, + llm=ctx.llm, + strategy_config=strategy_config, + source_locale=source_locale, + target_locale=target_locale, + ) + + # sources.Entry 转为 translation.Entry,交给策略层翻译, + # 结果再写回工作流的条目列表。 + translation_entries = _to_translation_entries(ctx.entries) + result = strategy.process( + translation_entries, + source_locale=source_locale, + target_locale=target_locale, + ) + + _apply_translations(ctx.entries, result.translated) + + # 把译文表持久化到 state_data,供"断点续跑跳过时"回填 ctx.entries。 + # 只保存非空译文,避免干扰尚未翻译的条目。 + ctx.state_data["translate.translations"] = { + e.key: e.target_text for e in ctx.entries if e.target_text + } + + # 将统计与失败映射写入 state_data,便于断点续跑与面板取用。 + ctx.state_data["translate.stats"] = dict(result.stats) + ctx.state_data["translate.errors"] = dict(result.errors) + ctx.state_payload["translate.success"] = result.stats.get("success", 0) + ctx.state_payload["translate.failed"] = result.stats.get("failed", 0) + + logger.info( + "TranslateState: %d translated, %d failed (language=%s)", + result.stats.get("success", 0), + result.stats.get("failed", 0), + language_id, + ) + self._mark_completed(ctx) + return None + + # ------------------------------------------------------------------ + def _prepare_entries(self, ctx: WorkflowContext) -> None: + """三步前置清洗:快照 → 过滤 pending → 折叠同 source。 + + 在 LLM 调用之前执行,确保翻译量 = 唯一 source 代表数(和 Crowdin + 审员工作量对等)。 + """ + if not ctx.entries: + # 空列表直接返回:没有新增数据,review state 本来就会 skipped, + # 快照和 pending-filter 都没必要跑。 + logger.info("TranslateState: no entries from pull_vcs — skipping pre-cleanup.") + return + + workspace = Path(ctx.workspace) + batch_name = ctx.state_payload.get("review.batch_name") or ctx.state_data.get( + "translate.batch_name" + ) or self._fallback_batch_name(ctx) + # 把 batch_name 固化到 state_payload,review 阶段也会读同一个(它内部 + # 自己会 _resolve_batch_name,命中 state_payload 后不会再新建批次)。 + ctx.state_payload.setdefault("review.batch_name", batch_name) + + snapshot_dir = workspace / "batches" / batch_name / "translate" + snapshot_path = snapshot_dir / "incr_snapshot.xlsx" + + # Step 1:保存今日 incr 完整快照(含兄弟)。 + save_incr_snapshot(ctx.entries, snapshot_path) + ctx.state_payload[_SNAPSHOT_PATH_KEY] = str(snapshot_path) + + # Step 2:按 (key, source) 过滤昨日 pending。 + pending_pairs = load_pending_source_pairs( + TailTaskStore.path_for(workspace, _resolve_lang(ctx)), + stages=("first", "second"), + ) + if pending_pairs: + kept, dropped = filter_against_pending(ctx.entries, pending_pairs) + if dropped: + ctx.state_payload[_SHADOWED_BY_PENDING_KEY] = [e.key for e in dropped] + ctx.entries = kept + + # Step 2.5:按 key 过滤全量表——命中则剔除今日版本。 + # 【语义】全量表的 Key 唯一性原则:同一个 key 只应保留一条已审译文。 + # 今日 incr 里凡 key 已存在于 full 的,都视为"重复提交 / 回填历史 + # 条目"——直接跳过翻译+审核。被剔除的 key 记录到 state_payload, + # 由 merge_data 消费(从磁盘的 incr 文件物理删除),避免下次 run + # 的 pull_vcs 又把它们捞回来形成脏循环。 + self._filter_against_full_table(ctx) + + # Step 3:按 source_text 折叠(第一条作代表)。 + representatives, collapsed = collapse_by_source(ctx.entries) + if collapsed: + logger.info( + "TranslateState: collapsed %d sibling entries into representatives; " + "they will be broadcast back after review from %s.", + collapsed, snapshot_path.name, + ) + ctx.entries = representatives + + # ------------------------------------------------------------------ + def _filter_against_full_table(self, ctx: WorkflowContext) -> None: + """按 ``entry.key`` 和全量表做去重:命中则从 ctx.entries 剔除。 + + 被剔除的 keys 存到 :data:`_SHADOWED_BY_FULL_TABLE_KEY` 供 merge_data + 消费(从磁盘 incr 物理删除)。 + + **全量表路径优先级**: + 1. ``profile.extra.full_table_path`` + 2. ``profile.strategy_config.full_table_path`` + 3. 从 ``pull_vcs.source_path`` 用 :func:`infer_full_table_path` 推断 + + **边界**: + * ctx.entries 为空 → 直接返回; + * 全量表路径解析不到 / 文件不存在 → 返回空集合 → 本步为 no-op + (首日 bootstrap 场景兼容)。 + + **格式无关**:直接用 ``ctx.source`` 读全量表——支持 dtxml/json/ + xliff/xlsx/csv/yaml 等所有已注册格式。 + """ + if not ctx.entries: + return + + from ...utils.table_merger import ( # noqa: WPS433 + infer_full_table_path, + load_full_table_keys, + ) + + # 1) 解析 full_path + profile = ctx.language_profile + full_path = "" + if profile is not None: + for key in ("full_table_path",): + candidate = ( + profile.extra.get(key) + or profile.strategy_config.get(key) + ) + if candidate: + full_path = str(candidate) + break + if not full_path: + incr_path = str(ctx.state_payload.get("pull_vcs.source_path") or "") + if incr_path: + full_path = infer_full_table_path(incr_path) + + if not full_path: + logger.info( + "TranslateState: cannot resolve full_table_path — skip full-table dedup." + ) + return + + # 2) 读 full 表 key 集合——用 ctx.source(格式无关)。 + full_keys = load_full_table_keys(ctx.source, full_path) + if not full_keys: + logger.info( + "TranslateState: full table %s has 0 keys (or missing) — skip full-table dedup.", + full_path, + ) + return + + # 3) 过滤 ctx.entries + kept: list = [] + dropped_keys: list = [] + for entry in ctx.entries: + if entry.key in full_keys: + dropped_keys.append(entry.key) + else: + kept.append(entry) + + if dropped_keys: + ctx.state_payload[_SHADOWED_BY_FULL_TABLE_KEY] = dropped_keys + ctx.entries = kept + logger.info( + "TranslateState: filtered against full table: %d → %d " + "(dropped %d whose key already lives in %s). merge_data " + "will physically remove them from the incremental file.", + len(kept) + len(dropped_keys), len(kept), + len(dropped_keys), Path(full_path).name, + ) + else: + logger.info( + "TranslateState: full-table dedup checked %d entries against %d full keys; " + "no overlap.", + len(ctx.entries), len(full_keys), + ) + + # ------------------------------------------------------------------ + @staticmethod + def _fallback_batch_name(ctx: WorkflowContext) -> str: + """生成兜底的批次名(当 state_payload / state_data 里都没有时)。 + + 用 target_locale + 当前 datetime 戳记,和 _review_state_helpers + 里 ``build_batch_name`` 的格式一致(``_``)。 + """ + from ...platforms._batch import build_batch_name # noqa: WPS433 — 局部避免循环 + + profile = ctx.language_profile + target_locale = ( + (profile.target_locale if profile else "") + or ctx.config.target_locale + or "unknown" + ) + return build_batch_name(target_locale=target_locale) + + +def _to_translation_entries(source_entries): + """将 :class:`sources.Entry` 转为翻译层的 :class:`translation.Entry`。""" + from ...translation.base import Entry as TranslationEntry + + result = [] + for e in source_entries: + result.append( + TranslationEntry( + key=e.key, + source_text=e.source_text, + target_text=e.target_text, + context=e.context, + comment=e.comment, + en_terms=list(getattr(e, "en_terms", []) or []), + terms=list(getattr(e, "terms", []) or []), + metadata=dict(e.metadata) if e.metadata else {}, + ) + ) + return result + + +def _apply_translations(source_entries, translated_entries) -> None: + """将 translation.Entry 中的 target_text 回写到 sources.Entry。 + + 按 ``key`` 匹配,``key`` 在单个源文件内保证唯一。 + 同时把 ``metadata["english_side"]`` 两步翻译的英文中间结果一并带回, + 供 :class:`XlsxSource.dump` 写入 ``EnglishSide`` 列(排查痕迹)。 + """ + by_key = {e.key: e for e in translated_entries} + for entry in source_entries: + translated = by_key.get(entry.key) + if translated is None: + continue + if translated.target_text: + entry.target_text = translated.target_text + # 把英文中间结果搬回 sources.Entry 的 metadata,让 xlsx dump 时 + # EnglishSide 列能拿到值。缺省/空值不覆盖已有值。 + english_side = (translated.metadata or {}).get("english_side") if translated.metadata else None + if english_side: + if not getattr(entry, "metadata", None): + entry.metadata = {} + entry.metadata["english_side"] = english_side + + +__all__ = ["TranslateState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_grn_tm_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_grn_tm_state.py new file mode 100644 index 0000000000000000000000000000000000000000..fc7eb03b35997719821c37ec53e8592ef8346e32 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_grn_tm_state.py @@ -0,0 +1,46 @@ +"""``update_grn_tm`` 状态——向**二审平台**的默认 TM 库回灌历史已审译文。 + +与 :class:`~TiMi_HOK_Game_Translator.workflow.states.update_tm_state.UpdateTmState` +的唯一差别是 ``review_stage``: + + * ``update_tm`` → ``first_review`` 阶段的 TM(通常走 Phrase); + * ``update_grn_tm`` → ``second_review`` 阶段的 TM(通常走 Crowdin)。 + +两者**互不交叉**:一审平台的 TM 只写一审已审数据,二审平台的 TM 只写二审 +已审数据,避免轮次污染。 + +**运行时机**:在 ``second_review`` 状态**之前**执行。 +""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import ReviewStage, WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase +from .update_tm_state import _run_tm_upload + +logger = logging.getLogger(__name__) + + +class UpdateGrnTmState(WorkflowStateBase): + """向二审平台的默认 TM 库回灌历史已审译文(二审 = GRN)。""" + + name = StateEnum.UPDATE_GRN_TM.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("UpdateGrnTmState: already completed — skipping.") + return None + + _run_tm_upload( + ctx=ctx, + review_stage=ReviewStage.SECOND.value, + state_label="UpdateGrnTmState", + ) + self._mark_completed(ctx) + return None + + +__all__ = ["UpdateGrnTmState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_tm_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_tm_state.py new file mode 100644 index 0000000000000000000000000000000000000000..35d38f4a04d4d6e124ade17b47884dd3f019d110 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/update_tm_state.py @@ -0,0 +1,154 @@ +"""``update_tm`` 状态——向**一审平台**的默认 TM 库回灌历史已审译文。 + +**运行时机**:在 ``first_review`` 状态**之前**执行。流程: + +1. 根据 :attr:`LanguageProfile.reviews` 的 ``first`` 阶段配置构造一审平台 + adapter(Phrase / Crowdin / ...); +2. 扫描 ``/batches/_*/first_review/*_approved.xlsx`` + 汇总历史已审 ``(source, target)`` 对; +3. 产出 ``/tm/_first_tm.xlsx`` 两列 TM 文件; +4. 调 ``platform.upload_tm(file, target_locale=...)`` 完成"先清后传": + 先 ``clear_tm_segments`` 清空项目默认 TM,再 ``import`` 当前文件。 + +**失败处理**:全程 try/except —— TM 回灌失败只记告警 + 不阻塞主流程 +(审校员仍能在平台 UI 做审校,只是看不到 TM 参考而已)。 + +**可选扩展**:目标 adapter **未实现** ``upload_tm`` 时跳过并记告警日志; +这意味着自定义平台不需要支持 TM,只需实现 `` TranslationPlatform`` 抽象方法。 + +**跳过条件**: + * reviews.first.platform == "none" / 未配置 → 跳过; + * batches 下无任何历史已审文件 → 跳过(没数据可灌); + * platform adapter 没有 ``upload_tm`` 方法 → 跳过并告警。 +""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import PlatformType, ReviewStage, WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + + +class UpdateTmState(WorkflowStateBase): + """向一审平台的默认 TM 库回灌历史已审译文。""" + + name = StateEnum.UPDATE_TM.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("UpdateTmState: already completed — skipping.") + return None + + _run_tm_upload( + ctx=ctx, + review_stage=ReviewStage.FIRST.value, + state_label="UpdateTmState", + ) + self._mark_completed(ctx) + return None + + +def _run_tm_upload( + *, + ctx: WorkflowContext, + review_stage: str, + state_label: str, +) -> None: + """共享的 TM 回灌主流程,供一审/二审两个 state 复用。 + + 全程不抛异常——任何环节失败都转为 warning 日志,让主流程继续。 + """ + from pathlib import Path + from ...platforms.factory import build_review_tool + from ...utils.tm_file_builder import build_tm_file_for_stage + + profile = ctx.language_profile + if profile is None: + logger.info("%s: no language profile bound, skip.", state_label) + return + + review_cfg = profile.review(review_stage) + if (review_cfg.platform or PlatformType.NONE.value) == PlatformType.NONE.value: + logger.info( + "%s: reviews.%s.platform is 'none', skip TM upload.", + state_label, review_stage, + ) + return + + target_locale = profile.target_locale or ctx.config.target_locale + source_locale = profile.source_locale or ctx.config.source_locale or "zh-CN" + if not target_locale: + logger.warning("%s: target_locale is empty, skip.", state_label) + return + + workspace = Path(ctx.workspace) + + # 1) 聚合历史已审文件 → TM xlsx + tm_file = build_tm_file_for_stage( + workspace=workspace, + target_locale=target_locale, + source_locale=source_locale, + review_stage=review_stage, + ) + if tm_file is None: + logger.info( + "%s: no historical approved entries found for %s/%s, skip " + "(this is normal for first run).", + state_label, target_locale, review_stage, + ) + return + + # 2) 构造 adapter;复用 build_review_tool 工厂,自动走 Phrase / Crowdin 等 + try: + platform = build_review_tool( + profile, + review_stage, + global_platform=ctx.config.platform, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 + logger.warning( + "%s: failed to build review tool for stage=%s: %s", + state_label, review_stage, exc, + ) + return + + # 3) 平台没实现 TM 能力 → 跳过 + if not hasattr(platform, "upload_tm"): + logger.warning( + "%s: platform=%s does not implement upload_tm, skip " + "(TM pre-fill is optional).", + state_label, getattr(platform, "platform_name", "?"), + ) + return + + # 4) 上传。upload_tm 内部已 try/except + 返回 bool,这里只记结果日志。 + try: + ok = platform.upload_tm( + str(tm_file), + target_locale=target_locale, + ) + except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 — 双保险 + logger.warning( + "%s: upload_tm raised unexpectedly (continuing): %s", + state_label, exc, + ) + return + + if ok: + logger.info( + "%s: TM upload succeeded (platform=%s, file=%s).", + state_label, platform.platform_name, tm_file, + ) + else: + logger.warning( + "%s: TM upload returned False (platform=%s, file=%s); " + "pipeline continues.", + state_label, platform.platform_name, tm_file, + ) + + +__all__ = ["UpdateTmState", "_run_tm_upload"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/validate_data_state.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/validate_data_state.py new file mode 100644 index 0000000000000000000000000000000000000000..b49cd31854a360a9d9934a88e62d441577ebe81a --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states/validate_data_state.py @@ -0,0 +1,71 @@ +"""``validate_data`` 状态——发布前的最后校验。""" + +from __future__ import annotations + +import logging +from typing import Optional + +from ...commons import WorkflowState as StateEnum +from ..state import WorkflowContext, WorkflowStateBase + +logger = logging.getLogger(__name__) + + +class ValidateDataState(WorkflowStateBase): + """验证已翻译条目是否满足基本质量门禁。 + + 内置实现执行三项检查: + + * 每个条目的 ``key`` 不为空; + * 经 :class:`TranslateState` 处理的条目均应具备 ``target_text``( + 未命中仅汇总,不会抛异常); + * 对重复 key 报警。 + + 真实项目可能需要更丰富的检查(占位符一致、HTML 标签平衡、 + 术语合规性),可继承并覆写 :meth:`execute` 添加。 + """ + + name = StateEnum.VALIDATE_DATA.value + + def execute(self, ctx: WorkflowContext) -> Optional[str]: + if self._already_completed(ctx): + logger.info("ValidateDataState: already completed — skipping.") + return None + + missing_keys: list = [] + empty_target: list = [] + seen_keys: dict = {} + duplicates: list = [] + + for entry in ctx.entries: + if not entry.key: + missing_keys.append(entry.source_text[:40]) + continue + if entry.key in seen_keys: + duplicates.append(entry.key) + seen_keys[entry.key] = True + if not entry.target_text: + empty_target.append(entry.key) + + ctx.state_payload["validate_data.missing_keys"] = missing_keys + ctx.state_payload["validate_data.empty_target_keys"] = empty_target + ctx.state_payload["validate_data.duplicate_keys"] = duplicates + ctx.state_payload["validate_data.total"] = len(ctx.entries) + + if missing_keys or duplicates: + logger.warning( + "ValidateDataState: %d entries missing keys, %d duplicates.", + len(missing_keys), len(duplicates), + ) + if empty_target: + logger.info( + "ValidateDataState: %d entries still empty (untranslated).", + len(empty_target), + ) + logger.info("ValidateDataState: checked %d entries.", len(ctx.entries)) + + self._mark_completed(ctx) + return None + + +__all__ = ["ValidateDataState"] diff --git a/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states_manager.py b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..aea4b49cd5ce5863e5763178195289b253e98152 --- /dev/null +++ b/timi_hok_game_translator/TiMi_HOK_Game_Translator/src/TiMi_HOK_Game_Translator/workflow/states_manager.py @@ -0,0 +1,224 @@ +"""工作流状态完成记录器。 + +**不**驱动执行(驱动交给 :class:`~.runner.WorkflowRunner`),仅记录本次运行中 +已完成的状态,并落盘以支持进程重启后断点续跑。 + +文件结构:: + + { + "status": { "pull_vcs": true, "translate": false, ... }, + "metadata": { + "created_at": "2026-04-01T12:34:56.789012", + "updated_at": "2026-04-01T12:35:00.000000", + "version": "1.0" + } + } + +并发性:内部 ``RLock`` 保护变更方法,后台调度器可在运行时任意时刻 +调用 :meth:`get_progress`。 +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + + +class StatesManager: + """``state_name → bool`` 的持久化映射(是否已完成)。 + + 参数: + state_file_path: 存放状态的 JSON 文件路径(绝对或相对 workspace)。 + auto_save: ``True``(默认)时每次变更均立即写盘;为 ``False`` 时 + 需使用上下文管理器 API 批量写盘。 + """ + + _METADATA_VERSION = "1.0" + + def __init__( + self, + state_file_path: str | os.PathLike[str], + *, + auto_save: bool = True, + ) -> None: + self._path = Path(state_file_path) + self._auto_save = auto_save + self._lock = threading.RLock() + self._status: Dict[str, bool] = {} + self._metadata: Dict[str, Any] = {} + + # ------------------------------------------------------------------ + # 对外 API + # ------------------------------------------------------------------ + @property + def path(self) -> Path: + return self._path + + def initialize( + self, + initial_status: Dict[str, bool], + *, + force: bool = False, + ) -> None: + """以 ``initial_status`` 初始化状态。 + + 参数: + initial_status: ``state_name → False`` 映射,会被拷贝保存。 + force: ``True`` 时覆盖已存在的状态文件;默认 ``False`` + 则保留已有文件,以便断点续跑。 + """ + with self._lock: + if not force and self._path.exists(): + logger.info( + "StatesManager: resuming from existing state file %s", + self._path, + ) + self.load() + return + + self._status = dict(initial_status) + self._metadata = { + "created_at": _now_iso(), + "updated_at": _now_iso(), + "version": self._METADATA_VERSION, + } + self._save() + + def load(self) -> Dict[str, bool]: + """从磁盘重新加载状态;返回副本。""" + with self._lock: + if not self._path.exists(): + logger.debug("StatesManager: %s does not exist", self._path) + return {} + try: + data = json.loads(self._path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + logger.warning( + "StatesManager: failed to load %s: %s", self._path, exc, + ) + return {} + self._status = dict(data.get("status") or {}) + self._metadata = dict(data.get("metadata") or {}) + return dict(self._status) + + def save(self) -> None: + """强制写盘,忽略 :attr:`_auto_save` 设置。""" + with self._lock: + self._save() + + def update_status( + self, + state_name: str, + value: bool, + *, + save: Optional[bool] = None, + ) -> None: + """将 ``state_name`` 置为 ``value``,并选择是否写盘。""" + with self._lock: + previous = self._status.get(state_name) + self._status[state_name] = value + if previous != value: + logger.info( + "StatesManager: %s %s → %s", state_name, previous, value, + ) + if save if save is not None else self._auto_save: + self._save() + + def update_multiple( + self, + updates: Dict[str, bool], + *, + save: Optional[bool] = None, + ) -> None: + with self._lock: + for name, value in updates.items(): + self._status[name] = value + if save if save is not None else self._auto_save: + self._save() + + def mark_completed(self, state_name: str) -> None: + """:func:`update_status` 的语义封装:标完成。""" + self.update_status(state_name, True) + + def is_completed(self, state_name: str) -> bool: + with self._lock: + return self._status.get(state_name) is True + + def get_status(self, state_name: str) -> Optional[bool]: + with self._lock: + return self._status.get(state_name) + + def all_status(self) -> Dict[str, bool]: + with self._lock: + return dict(self._status) + + def reset(self, *, save: bool = True) -> None: + with self._lock: + for key in self._status: + self._status[key] = False + if save: + self._save() + + def get_progress(self) -> Dict[str, Any]: + """返回适合监控上报的进度快照。""" + with self._lock: + total = len(self._status) + completed = sum(1 for v in self._status.values() if v) + percent = round((completed / total * 100) if total else 0.0, 2) + return { + "total": total, + "completed": completed, + "remaining": total - completed, + "progress_percent": percent, + "updated_at": self._metadata.get("updated_at"), + } + + # ------------------------------------------------------------------ + # 上下文管理器 + # ------------------------------------------------------------------ + def __enter__(self) -> StatesManager: + return self + + def __exit__(self, exc_type, exc, tb) -> None: # noqa: D401 + if not self._auto_save: + self.save() + + # ------------------------------------------------------------------ + # 内部实现 + # ------------------------------------------------------------------ + def _save(self) -> None: + self._metadata["updated_at"] = _now_iso() + self._metadata.setdefault("created_at", self._metadata["updated_at"]) + self._metadata.setdefault("version", self._METADATA_VERSION) + payload = {"status": dict(self._status), "metadata": dict(self._metadata)} + self._path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = self._path.with_suffix(self._path.suffix + ".tmp") + try: + tmp_path.write_text( + json.dumps(payload, ensure_ascii=False, indent=2), + encoding="utf-8", + ) + os.replace(tmp_path, self._path) + except OSError as exc: + logger.warning( + "StatesManager: failed to write %s: %s", self._path, exc, + ) + if tmp_path.exists(): + try: # noqa: SIM105 + tmp_path.unlink() + except OSError: + pass + + +def _now_iso() -> str: + return datetime.now().isoformat() + + +__all__ = ["StatesManager"] diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/.gitattributes b/timi_hok_game_translator/UE_LQARestore_Plugin/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..de796edac19e930e17559d8a67d8c67ab19395d2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/.gitattributes @@ -0,0 +1,10 @@ +# auto generated by UGit +*.uasset filter=lfs diff=lfs merge=binary -text +*.umap filter=lfs diff=lfs merge=binary -text +*.png filter=lfs diff=lfs merge=binary -text + +# auto generated by UGit + + +# auto generated by UGit + diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/.gitignore b/timi_hok_game_translator/UE_LQARestore_Plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..825d381fe484064a05e8f07d7b534b6e3ce56e05 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/.gitignore @@ -0,0 +1,25 @@ +# Unreal Engine +Binaries/ +DerivedDataCache/ +Intermediate/ +Saved/ +Build/ +*.suo +*.sln +*.xcodeproj +*.xcworkspace + +# Visual Studio +.vs/ +*.user +*.opendb +*.db +*.ipch + +# Rider +.idea/ +*.sln.iml + +# Mac +.DS_Store +*.dSYM diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/.clang-format b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..1fdb4ac36da7be909631871d3f098f1fe955a1d3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/.clang-format @@ -0,0 +1,127 @@ +--- +Language: Cpp +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false +# BreakInheritanceList: AfterComma +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: true +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +FixNamespaceComments: true +ForEachMacros: + - for +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '.*\.generated\.h' + Priority: 100 + - Regex: '.*(PCH).*' + Priority: -1 + - Regex: '".*"' + Priority: 1 + - Regex: '^<.*\.(h)>' + Priority: 3 + - Regex: '^<.*>' + Priority: 4 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + CanonicalDelimiter: '' +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: true +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 4 +UseTab: Always +... diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Config/LQARestore.ini b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Config/LQARestore.ini new file mode 100644 index 0000000000000000000000000000000000000000..9c31e9013d1bdb71b92fd7f061fea6e976c5f984 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Config/LQARestore.ini @@ -0,0 +1,4 @@ +[HttpConfig] +Host=127.0.0.1:8080/api-pro +FileHost=127.0.0.1:8080 +Authorization=xxxxxxxxxx diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_en.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_en.json new file mode 100644 index 0000000000000000000000000000000000000000..e27f6a7348ea9d5388a907eb4afc8f3fe8326f5e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_en.json @@ -0,0 +1,127 @@ +{ + "ST_Gallery_Title": { + "TextKey": "ST_Gallery_Title", + "SourceStr": "LQA 验证画廊 (UE5)", + "translation": "LQA Verification Gallery (UE5)" + }, + "ST_Gallery_Title_UE4": { + "TextKey": "ST_Gallery_Title_UE4", + "SourceStr": "LQA 验证画廊 (UE4)", + "translation": "LQA Verification Gallery (UE4)" + }, + "ST_Gallery_Section_Text": { + "TextKey": "ST_Gallery_Section_Text", + "SourceStr": "一、文本类控件", + "translation": "1. Text Widgets" + }, + "ST_Gallery_Section_Input": { + "TextKey": "ST_Gallery_Section_Input", + "SourceStr": "二、交互/输入类控件", + "translation": "2. Interactive / Input Widgets" + }, + "ST_Gallery_Section_Present": { + "TextKey": "ST_Gallery_Section_Present", + "SourceStr": "三、展示类控件", + "translation": "3. Presentation Widgets" + }, + "ST_Gallery_Section_Layout": { + "TextKey": "ST_Gallery_Section_Layout", + "SourceStr": "四、布局容器", + "translation": "4. Layout Containers" + }, + "ST_Gallery_TextBlockSample": { + "TextKey": "ST_Gallery_TextBlockSample", + "SourceStr": "这是 TextBlock 示例", + "translation": "This is a TextBlock sample" + }, + "ST_Gallery_RichTextBlockSample": { + "TextKey": "ST_Gallery_RichTextBlockSample", + "SourceStr": "这是 RichTextBlock 富文本 示例", + "translation": "This is a RichTextBlock rich text sample" + }, + "ST_Gallery_MultiLineText": { + "TextKey": "ST_Gallery_MultiLineText", + "SourceStr": "MultiLineEditableText\n多行文本", + "translation": "MultiLineEditableText\nMulti-line text" + }, + "ST_Gallery_MultiLineTextBox": { + "TextKey": "ST_Gallery_MultiLineTextBox", + "SourceStr": "MultiLineEditableTextBox\n多行文本框", + "translation": "MultiLineEditableTextBox\nMulti-line text box" + }, + "ST_Gallery_Hint_EditableText": { + "TextKey": "ST_Gallery_Hint_EditableText", + "SourceStr": "EditableText 单行输入", + "translation": "EditableText single-line input" + }, + "ST_Gallery_Hint_EditableTextBox": { + "TextKey": "ST_Gallery_Hint_EditableTextBox", + "SourceStr": "EditableTextBox 单行输入框", + "translation": "EditableTextBox single-line input box" + }, + "ST_Gallery_BorderContent": { + "TextKey": "ST_Gallery_BorderContent", + "SourceStr": "Border 内容", + "translation": "Border Content" + }, + "ST_Gallery_OverlayStack": { + "TextKey": "ST_Gallery_OverlayStack", + "SourceStr": "Overlay 叠加", + "translation": "Overlay Stack" + }, + "ST_Gallery_ScaleBoxContent": { + "TextKey": "ST_Gallery_ScaleBoxContent", + "SourceStr": "ScaleBox 缩放内容", + "translation": "ScaleBox scaled content" + }, + "ST_Gallery_SafeZoneContent": { + "TextKey": "ST_Gallery_SafeZoneContent", + "SourceStr": "SafeZone 内容", + "translation": "SafeZone Content" + }, + "ST_Gallery_Section_Bug": { + "TextKey": "ST_Gallery_Section_Bug", + "SourceStr": "五、显示性质 BUG", + "translation": "5. Display Defects" + }, + "ST_Gallery_Bug_OverflowSingleLine": { + "TextKey": "ST_Gallery_Bug_OverflowSingleLine", + "SourceStr": "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠", + "translation": "This text does not wrap on purpose and overflows the stage boundary, verifying overflow detection" + }, + "ST_Gallery_Bug_OverflowMultiLine": { + "TextKey": "ST_Gallery_Bug_OverflowMultiLine", + "SourceStr": "换行后行数超出高度,越出舞台底部", + "translation": "Wrapped lines exceed the height" + }, + "ST_Gallery_Bug_FontSize": { + "TextKey": "ST_Gallery_Bug_FontSize", + "SourceStr": "字号 36 的文本", + "translation": "Font 36" + }, + "ST_Gallery_Bug_ButtonOverflow": { + "TextKey": "ST_Gallery_Bug_ButtonOverflow", + "SourceStr": "Confirm and Continue With All Changes", + "translation": "Confirm and Continue With All Changes" + }, + "ST_Gallery_Bug_LineHeight": { + "TextKey": "ST_Gallery_Bug_LineHeight", + "SourceStr": "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠", + "translation": "Line height is reduced to 30%, so adjacent lines overlap inside a single text node" + }, + "ST_Gallery_Bug_Invisible": { + "TextKey": "ST_Gallery_Bug_Invisible", + "SourceStr": "这段文本与底色同色,应完全不可见", + "translation": "This text uses the same color as the background and should be invisible" + }, + "ST_Gallery_Bug_TileViewOverflow": { + "TextKey": "ST_Gallery_Bug_TileViewOverflow", + "SourceStr": "OverflowingTileViewItemTextWithoutAnySpaces", + "translation": "OverflowingTileViewItemTextWithoutAnySpaces" + }, + "ST_Gallery_Bug_Truncate": { + "TextKey": "ST_Gallery_Bug_Truncate", + "SourceStr": "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别", + "translation": "This text is hard-clipped at the fixed width with no ellipsis, verifying truncation detection" + } +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ja.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ja.json new file mode 100644 index 0000000000000000000000000000000000000000..f2ff202652e67ec046378a1046c509ed637761b3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ja.json @@ -0,0 +1,127 @@ +{ + "ST_Gallery_Title": { + "TextKey": "ST_Gallery_Title", + "SourceStr": "LQA 验证画廊 (UE5)", + "translation": "LQA 検証ギャラリー (UE5)" + }, + "ST_Gallery_Title_UE4": { + "TextKey": "ST_Gallery_Title_UE4", + "SourceStr": "LQA 验证画廊 (UE4)", + "translation": "LQA 検証ギャラリー (UE4)" + }, + "ST_Gallery_Section_Text": { + "TextKey": "ST_Gallery_Section_Text", + "SourceStr": "一、文本类控件", + "translation": "1. テキストウィジェット" + }, + "ST_Gallery_Section_Input": { + "TextKey": "ST_Gallery_Section_Input", + "SourceStr": "二、交互/输入类控件", + "translation": "2. インタラクティブ/入力ウィジェット" + }, + "ST_Gallery_Section_Present": { + "TextKey": "ST_Gallery_Section_Present", + "SourceStr": "三、展示类控件", + "translation": "3. 表示ウィジェット" + }, + "ST_Gallery_Section_Layout": { + "TextKey": "ST_Gallery_Section_Layout", + "SourceStr": "四、布局容器", + "translation": "4. レイアウトコンテナ" + }, + "ST_Gallery_TextBlockSample": { + "TextKey": "ST_Gallery_TextBlockSample", + "SourceStr": "这是 TextBlock 示例", + "translation": "これは TextBlock のサンプルです" + }, + "ST_Gallery_RichTextBlockSample": { + "TextKey": "ST_Gallery_RichTextBlockSample", + "SourceStr": "这是 RichTextBlock 富文本 示例", + "translation": "これは RichTextBlock リッチテキスト のサンプルです" + }, + "ST_Gallery_MultiLineText": { + "TextKey": "ST_Gallery_MultiLineText", + "SourceStr": "MultiLineEditableText\n多行文本", + "translation": "MultiLineEditableText\n複数行テキスト" + }, + "ST_Gallery_MultiLineTextBox": { + "TextKey": "ST_Gallery_MultiLineTextBox", + "SourceStr": "MultiLineEditableTextBox\n多行文本框", + "translation": "MultiLineEditableTextBox\n複数行テキストボックス" + }, + "ST_Gallery_Hint_EditableText": { + "TextKey": "ST_Gallery_Hint_EditableText", + "SourceStr": "EditableText 单行输入", + "translation": "EditableText 単一行入力" + }, + "ST_Gallery_Hint_EditableTextBox": { + "TextKey": "ST_Gallery_Hint_EditableTextBox", + "SourceStr": "EditableTextBox 单行输入框", + "translation": "EditableTextBox 単一行入力ボックス" + }, + "ST_Gallery_BorderContent": { + "TextKey": "ST_Gallery_BorderContent", + "SourceStr": "Border 内容", + "translation": "Border コンテンツ" + }, + "ST_Gallery_OverlayStack": { + "TextKey": "ST_Gallery_OverlayStack", + "SourceStr": "Overlay 叠加", + "translation": "Overlay スタック" + }, + "ST_Gallery_ScaleBoxContent": { + "TextKey": "ST_Gallery_ScaleBoxContent", + "SourceStr": "ScaleBox 缩放内容", + "translation": "ScaleBox スケールコンテンツ" + }, + "ST_Gallery_SafeZoneContent": { + "TextKey": "ST_Gallery_SafeZoneContent", + "SourceStr": "SafeZone 内容", + "translation": "SafeZone コンテンツ" + }, + "ST_Gallery_Section_Bug": { + "TextKey": "ST_Gallery_Section_Bug", + "SourceStr": "五、显示性质 BUG", + "translation": "5. 表示上の不具合" + }, + "ST_Gallery_Bug_OverflowSingleLine": { + "TextKey": "ST_Gallery_Bug_OverflowSingleLine", + "SourceStr": "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠", + "translation": "このテキストは意図的に折り返さず、左側の固定領域からはみ出してステージの境界を超えます。テキストのオーバーフローと重なりの検出に使用します。" + }, + "ST_Gallery_Bug_OverflowMultiLine": { + "TextKey": "ST_Gallery_Bug_OverflowMultiLine", + "SourceStr": "换行后行数超出高度,越出舞台底部", + "translation": "折り返し後の行数が高さを超え、下部の参照行を覆います。" + }, + "ST_Gallery_Bug_FontSize": { + "TextKey": "ST_Gallery_Bug_FontSize", + "SourceStr": "字号 36 的文本", + "translation": "フォントサイズ 36 のテキスト" + }, + "ST_Gallery_Bug_ButtonOverflow": { + "TextKey": "ST_Gallery_Bug_ButtonOverflow", + "SourceStr": "Confirm and Continue With All Changes", + "translation": "Confirm and Continue With All Changes" + }, + "ST_Gallery_Bug_LineHeight": { + "TextKey": "ST_Gallery_Bug_LineHeight", + "SourceStr": "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠", + "translation": "行の高さが 30% に圧縮され、2 行のテキストが互いに重なります。単一テキストノード内部の重なりの検出に使用します。" + }, + "ST_Gallery_Bug_Invisible": { + "TextKey": "ST_Gallery_Bug_Invisible", + "SourceStr": "这段文本与底色同色,应完全不可见", + "translation": "このテキストは背景色と同じ色のため、完全に見えないはずです。" + }, + "ST_Gallery_Bug_TileViewOverflow": { + "TextKey": "ST_Gallery_Bug_TileViewOverflow", + "SourceStr": "OverflowingTileViewItemTextWithoutAnySpaces", + "translation": "OverflowingTileViewItemTextWithoutAnySpaces" + }, + "ST_Gallery_Bug_Truncate": { + "TextKey": "ST_Gallery_Bug_Truncate", + "SourceStr": "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别", + "translation": "このテキストは固定幅を超えるとハードクリップされ、末尾に省略記号は付きません。切り詰め検出に使用します。" + } +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ko.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ko.json new file mode 100644 index 0000000000000000000000000000000000000000..2287bb2dc3ecff1c0d5b68cd286bd3c9eed49c93 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/GameLocalizationExport_ko.json @@ -0,0 +1,127 @@ +{ + "ST_Gallery_Title": { + "TextKey": "ST_Gallery_Title", + "SourceStr": "LQA 验证画廊 (UE5)", + "translation": "LQA 검증 갤러리 (UE5)" + }, + "ST_Gallery_Title_UE4": { + "TextKey": "ST_Gallery_Title_UE4", + "SourceStr": "LQA 验证画廊 (UE4)", + "translation": "LQA 검증 갤러리 (UE4)" + }, + "ST_Gallery_Section_Text": { + "TextKey": "ST_Gallery_Section_Text", + "SourceStr": "一、文本类控件", + "translation": "1. 텍스트 위젯" + }, + "ST_Gallery_Section_Input": { + "TextKey": "ST_Gallery_Section_Input", + "SourceStr": "二、交互/输入类控件", + "translation": "2. 인터랙티브/입력 위젯" + }, + "ST_Gallery_Section_Present": { + "TextKey": "ST_Gallery_Section_Present", + "SourceStr": "三、展示类控件", + "translation": "3. 프레젠테이션 위젯" + }, + "ST_Gallery_Section_Layout": { + "TextKey": "ST_Gallery_Section_Layout", + "SourceStr": "四、布局容器", + "translation": "4. 레이아웃 컨테이너" + }, + "ST_Gallery_TextBlockSample": { + "TextKey": "ST_Gallery_TextBlockSample", + "SourceStr": "这是 TextBlock 示例", + "translation": "이것은 TextBlock 샘플입니다" + }, + "ST_Gallery_RichTextBlockSample": { + "TextKey": "ST_Gallery_RichTextBlockSample", + "SourceStr": "这是 RichTextBlock 富文本 示例", + "translation": "이것은 RichTextBlock 리치 텍스트 샘플입니다" + }, + "ST_Gallery_MultiLineText": { + "TextKey": "ST_Gallery_MultiLineText", + "SourceStr": "MultiLineEditableText\n多行文本", + "translation": "MultiLineEditableText\n여러 줄 텍스트" + }, + "ST_Gallery_MultiLineTextBox": { + "TextKey": "ST_Gallery_MultiLineTextBox", + "SourceStr": "MultiLineEditableTextBox\n多行文本框", + "translation": "MultiLineEditableTextBox\n여러 줄 텍스트 상자" + }, + "ST_Gallery_Hint_EditableText": { + "TextKey": "ST_Gallery_Hint_EditableText", + "SourceStr": "EditableText 单行输入", + "translation": "EditableText 한 줄 입력" + }, + "ST_Gallery_Hint_EditableTextBox": { + "TextKey": "ST_Gallery_Hint_EditableTextBox", + "SourceStr": "EditableTextBox 单行输入框", + "translation": "EditableTextBox 한 줄 입력 상자" + }, + "ST_Gallery_BorderContent": { + "TextKey": "ST_Gallery_BorderContent", + "SourceStr": "Border 内容", + "translation": "Border 콘텐츠" + }, + "ST_Gallery_OverlayStack": { + "TextKey": "ST_Gallery_OverlayStack", + "SourceStr": "Overlay 叠加", + "translation": "Overlay 스택" + }, + "ST_Gallery_ScaleBoxContent": { + "TextKey": "ST_Gallery_ScaleBoxContent", + "SourceStr": "ScaleBox 缩放内容", + "translation": "ScaleBox 크기 조정 콘텐츠" + }, + "ST_Gallery_SafeZoneContent": { + "TextKey": "ST_Gallery_SafeZoneContent", + "SourceStr": "SafeZone 内容", + "translation": "SafeZone 콘텐츠" + }, + "ST_Gallery_Section_Bug": { + "TextKey": "ST_Gallery_Section_Bug", + "SourceStr": "五、显示性质 BUG", + "translation": "5. 표시 관련 버그" + }, + "ST_Gallery_Bug_OverflowSingleLine": { + "TextKey": "ST_Gallery_Bug_OverflowSingleLine", + "SourceStr": "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠", + "translation": "이 텍스트는 의도적으로 줄바꿈하지 않아 왼쪽 고정 영역을 벗어나 스테이지 경계를 초과합니다. 텍스트 넘침과 겹침 감지에 사용됩니다." + }, + "ST_Gallery_Bug_OverflowMultiLine": { + "TextKey": "ST_Gallery_Bug_OverflowMultiLine", + "SourceStr": "换行后行数超出高度,越出舞台底部", + "translation": "줄바꿈 후 줄 수가 높이를 초과하여 하단 기준 줄을 덮습니다." + }, + "ST_Gallery_Bug_FontSize": { + "TextKey": "ST_Gallery_Bug_FontSize", + "SourceStr": "字号 36 的文本", + "translation": "글자 크기 36 텍스트" + }, + "ST_Gallery_Bug_ButtonOverflow": { + "TextKey": "ST_Gallery_Bug_ButtonOverflow", + "SourceStr": "Confirm and Continue With All Changes", + "translation": "Confirm and Continue With All Changes" + }, + "ST_Gallery_Bug_LineHeight": { + "TextKey": "ST_Gallery_Bug_LineHeight", + "SourceStr": "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠", + "translation": "줄 높이가 30%로 압축되어 두 줄의 텍스트가 서로 겹칩니다. 단일 텍스트 노드 내부의 겹침 감지에 사용됩니다." + }, + "ST_Gallery_Bug_Invisible": { + "TextKey": "ST_Gallery_Bug_Invisible", + "SourceStr": "这段文本与底色同色,应完全不可见", + "translation": "이 텍스트는 배경색과 같은 색이므로 완전히 보이지 않아야 합니다." + }, + "ST_Gallery_Bug_TileViewOverflow": { + "TextKey": "ST_Gallery_Bug_TileViewOverflow", + "SourceStr": "OverflowingTileViewItemTextWithoutAnySpaces", + "translation": "OverflowingTileViewItemTextWithoutAnySpaces" + }, + "ST_Gallery_Bug_Truncate": { + "TextKey": "ST_Gallery_Bug_Truncate", + "SourceStr": "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别", + "translation": "이 텍스트는 고정 너비를 초과하면 잘리고 끝에 줄임표가 없습니다. 잘림 감지에 사용됩니다." + } +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_en.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_en.json new file mode 100644 index 0000000000000000000000000000000000000000..31ebee7f1dad56e7172c7cc145838522687c934c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_en.json @@ -0,0 +1,143 @@ +{ + "LQA 验证画廊 (UE5)": "LQA Verification Gallery (UE5)", + "LQA 验证画廊 (UE4)": "LQA Verification Gallery (UE4)", + + "一、文本类控件": "1. Text Widgets", + "二、交互/输入类控件": "2. Interactive / Input Widgets", + "三、展示类控件": "3. Presentation Widgets", + "四、布局容器": "4. Layout Containers", + + "这是 TextBlock 示例": "This is a TextBlock sample", + "这是 RichTextBlock 富文本 示例": "This is a RichTextBlock rich text sample", + "MultiLineEditableText\n多行文本": "MultiLineEditableText\nMulti-line text", + "MultiLineEditableTextBox\n多行文本框": "MultiLineEditableTextBox\nMulti-line text box", + + "EditableText 单行输入": "EditableText single-line input", + "EditableTextBox 单行输入框": "EditableTextBox single-line input box", + + "Border 内容": "Border Content", + "Overlay 叠加": "Overlay Stack", + "ScaleBox 缩放内容": "ScaleBox scaled content", + "SafeZone 内容": "SafeZone Content", + + "TextBlock": "TextBlock", + "RichTextBlock": "RichTextBlock", + "EditableText": "EditableText", + "EditableTextBox": "EditableTextBox", + "MultiLineEditableText": "MultiLineEditableText", + "MultiLineEditableTextBox": "MultiLineEditableTextBox", + + "Button": "Button", + "CheckBox": "CheckBox", + "Slider": "Slider", + "ProgressBar": "ProgressBar", + "ComboBoxString": "ComboBoxString", + "SpinBox": "SpinBox", + + "Image": "Image", + "Throbber": "Throbber", + "CircularThrobber": "CircularThrobber", + "Spacer (40x20)": "Spacer (40x20)", + "Border": "Border", + "SizeBox (120x40)": "SizeBox (120x40)", + "ScaleBox": "ScaleBox", + "SafeZone": "SafeZone", + "WidgetSwitcher": "WidgetSwitcher", + + "HorizontalBox": "HorizontalBox", + "GridPanel": "GridPanel", + "UniformGridPanel": "UniformGridPanel", + "Overlay": "Overlay", + "WrapBox": "WrapBox", + + "[H0]": "[H0]", + "[H1]": "[H1]", + "[H2]": "[H2]", + "(0,0)": "(0,0)", + "(0,1)": "(0,1)", + "(1,0)": "(1,0)", + "(1,1)": "(1,1)", + + "U0": "U0", + "U1": "U1", + "U2": "U2", + "U3": "U3", + "Wrap0": "Wrap0", + "Wrap1": "Wrap1", + "Wrap2": "Wrap2", + "Wrap3": "Wrap3", + "Wrap4": "Wrap4", + "Wrap5": "Wrap5", + "Page 0": "Page 0", + + "Page 1": "Page 1", + + "CanvasPanel": "CanvasPanel", + "ScrollBox": "ScrollBox", + "VerticalBox": "VerticalBox", + "NamedSlot": "NamedSlot", + "ComboBoxKey": "ComboBoxKey", + "UserWidget": "UserWidget", + "InputKeySelector": "InputKeySelector", + "MenuAnchor": "MenuAnchor", + "ScrollBar": "ScrollBar", + "StackBox": "StackBox", + "InvalidationBox": "InvalidationBox", + "WindowTitleBarArea": "WindowTitleBarArea", + "PostBufferUpdate": "PostBufferUpdate", + "BackgroundBlur": "BackgroundBlur", + "RetainerBox": "RetainerBox", + "ExpandableArea": "ExpandableArea", + "ListView": "ListView", + "TileView": "TileView", + "TreeView": "TreeView", + "DynamicEntryBox": "DynamicEntryBox", + + "KeySelection": "KeySelection", + "NoKeySpecified": "NoKeySpecified", + "MenuAnchor Anchor": "MenuAnchor Anchor", + "InvalidationBox Content": "InvalidationBox Content", + "WindowTitleBarArea Content": "WindowTitleBarArea Content", + + "滚动到顶": "Scroll to Top", + "滚动到底": "Scroll to Bottom", + "切换背景": "Toggle Background", + + "DynamicEntryBoxText1": "DynamicEntryBoxText1", + "DynamicEntryBoxText2": "DynamicEntryBoxText2", + "DynamicEntryBoxText3": "DynamicEntryBoxText3", + + "ListViewText1": "ListViewText1", + "ListViewText2": "ListViewText2", + "ListViewText3": "ListViewText3", + "TileViewText1": "TileViewText1", + "TileViewText2": "TileViewText2", + "TreeViewText1": "TreeViewText1", + "TreeViewText2": "TreeViewText2", + "TreeViewText3": "TreeViewText3", + + "五、显示性质 BUG": "5. Display Defects", + "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠": "This text does not wrap on purpose and overflows the stage boundary, verifying overflow detection", + "换行后行数超出高度,越出舞台底部": "Wrapped lines exceed the height", + "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别": "This text is hard-clipped at the fixed width with no ellipsis, verifying truncation detection", + "字号 36 的文本": "Font 36", + "Confirm and Continue With All Changes": "Confirm and Continue With All Changes", + "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠": "Line height is reduced to 30%, so adjacent lines overlap inside a single text node", + "这段文本与底色同色,应完全不可见": "This text uses the same color as the background and should be invisible", + "OverflowingTileViewItemTextWithoutAnySpaces": "OverflowingTileViewItemTextWithoutAnySpaces", + + "[BUG-01] 单行超长溢出": "[BUG-01] Line overflow", + "[BUG-02] 换行纵向溢出": "[BUG-02] Wrapped overflow", + "[BUG-03] 字号过大溢出": "[BUG-03] Font overflow", + "[BUG-04] 按钮文本被截断": "[BUG-04] Button text clipped", + "[BUG-05] 行高压缩叠字": "[BUG-05] Line height overlap", + "[BUG-06] 文本同色不可见": "[BUG-06] Invisible text", + "[BUG-07] 文本被硬截断": "[BUG-07] Hard-clipped text", + "[BUG-08] TileView 容器重叠": "[BUG-08] TileView overlap", + "[BUG-09] TileView 条目截断": "[BUG-09] TileView text clipped", + "[BUG-10] 漏 Key 显示原始 Key": "[BUG-10] Missing text key", + "[BUG-11] 有 Key 但漏译": "[BUG-11] Missing translation", + "↑ 底部参照行": "↑ Bottom reference line", + "BugTile1": "BugTile1", + "BugTile2": "BugTile2" +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ja.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ja.json new file mode 100644 index 0000000000000000000000000000000000000000..560fb84abde7967f28d4e7c68f063603d6d9527e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ja.json @@ -0,0 +1,143 @@ +{ + "LQA 验证画廊 (UE5)": "LQA 検証ギャラリー (UE5)", + "LQA 验证画廊 (UE4)": "LQA 検証ギャラリー (UE4)", + + "一、文本类控件": "1. テキストウィジェット", + "二、交互/输入类控件": "2. インタラクティブ/入力ウィジェット", + "三、展示类控件": "3. 表示ウィジェット", + "四、布局容器": "4. レイアウトコンテナ", + + "这是 TextBlock 示例": "これは TextBlock のサンプルです", + "这是 RichTextBlock 富文本 示例": "これは RichTextBlock リッチテキスト のサンプルです", + "MultiLineEditableText\n多行文本": "MultiLineEditableText\n複数行テキスト", + "MultiLineEditableTextBox\n多行文本框": "MultiLineEditableTextBox\n複数行テキストボックス", + + "EditableText 单行输入": "EditableText 単一行入力", + "EditableTextBox 单行输入框": "EditableTextBox 単一行入力ボックス", + + "Border 内容": "Border コンテンツ", + "Overlay 叠加": "Overlay スタック", + "ScaleBox 缩放内容": "ScaleBox スケールコンテンツ", + "SafeZone 内容": "SafeZone コンテンツ", + + "TextBlock": "TextBlock", + "RichTextBlock": "RichTextBlock", + "EditableText": "EditableText", + "EditableTextBox": "EditableTextBox", + "MultiLineEditableText": "MultiLineEditableText", + "MultiLineEditableTextBox": "MultiLineEditableTextBox", + + "Button": "Button", + "CheckBox": "CheckBox", + "Slider": "Slider", + "ProgressBar": "ProgressBar", + "ComboBoxString": "ComboBoxString", + "SpinBox": "SpinBox", + + "Image": "Image", + "Throbber": "Throbber", + "CircularThrobber": "CircularThrobber", + "Spacer (40x20)": "Spacer (40x20)", + "Border": "Border", + "SizeBox (120x40)": "SizeBox (120x40)", + "ScaleBox": "ScaleBox", + "SafeZone": "SafeZone", + "WidgetSwitcher": "WidgetSwitcher", + + "HorizontalBox": "HorizontalBox", + "GridPanel": "GridPanel", + "UniformGridPanel": "UniformGridPanel", + "Overlay": "Overlay", + "WrapBox": "WrapBox", + + "[H0]": "[H0]", + "[H1]": "[H1]", + "[H2]": "[H2]", + "(0,0)": "(0,0)", + "(0,1)": "(0,1)", + "(1,0)": "(1,0)", + "(1,1)": "(1,1)", + + "U0": "U0", + "U1": "U1", + "U2": "U2", + "U3": "U3", + "Wrap0": "Wrap0", + "Wrap1": "Wrap1", + "Wrap2": "Wrap2", + "Wrap3": "Wrap3", + "Wrap4": "Wrap4", + "Wrap5": "Wrap5", + "Page 0": "Page 0", + + "Page 1": "Page 1", + + "CanvasPanel": "CanvasPanel", + "ScrollBox": "ScrollBox", + "VerticalBox": "VerticalBox", + "NamedSlot": "NamedSlot", + "ComboBoxKey": "ComboBoxKey", + "UserWidget": "UserWidget", + "InputKeySelector": "InputKeySelector", + "MenuAnchor": "MenuAnchor", + "ScrollBar": "ScrollBar", + "StackBox": "StackBox", + "InvalidationBox": "InvalidationBox", + "WindowTitleBarArea": "WindowTitleBarArea", + "PostBufferUpdate": "PostBufferUpdate", + "BackgroundBlur": "BackgroundBlur", + "RetainerBox": "RetainerBox", + "ExpandableArea": "ExpandableArea", + "ListView": "ListView", + "TileView": "TileView", + "TreeView": "TreeView", + "DynamicEntryBox": "DynamicEntryBox", + + "KeySelection": "KeySelection", + "NoKeySpecified": "NoKeySpecified", + "MenuAnchor Anchor": "MenuAnchor Anchor", + "InvalidationBox Content": "InvalidationBox Content", + "WindowTitleBarArea Content": "WindowTitleBarArea Content", + + "滚动到顶": "トップへスクロール", + "滚动到底": "ボトムへスクロール", + "切换背景": "背景を切り替え", + + "DynamicEntryBoxText1": "DynamicEntryBoxText1", + "DynamicEntryBoxText2": "DynamicEntryBoxText2", + "DynamicEntryBoxText3": "DynamicEntryBoxText3", + + "ListViewText1": "ListViewText1", + "ListViewText2": "ListViewText2", + "ListViewText3": "ListViewText3", + "TileViewText1": "TileViewText1", + "TileViewText2": "TileViewText2", + "TreeViewText1": "TreeViewText1", + "TreeViewText2": "TreeViewText2", + "TreeViewText3": "TreeViewText3", + + "五、显示性质 BUG": "5. 表示上の不具合", + "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠": "このテキストは意図的に折り返さず、左側の固定領域からはみ出してステージの境界を超えます。テキストのオーバーフローと重なりの検出に使用します。", + "换行后行数超出高度,越出舞台底部": "折り返し後の行数が高さを超え、下部の参照行を覆います。", + "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别": "このテキストは固定幅を超えるとハードクリップされ、末尾に省略記号は付きません。切り詰め検出に使用します。", + "字号 36 的文本": "フォントサイズ 36 のテキスト", + "Confirm and Continue With All Changes": "Confirm and Continue With All Changes", + "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠": "行の高さが 30% に圧縮され、2 行のテキストが互いに重なります。単一テキストノード内部の重なりの検出に使用します。", + "这段文本与底色同色,应完全不可见": "このテキストは背景色と同じ色のため、完全に見えないはずです。", + "OverflowingTileViewItemTextWithoutAnySpaces": "OverflowingTileViewItemTextWithoutAnySpaces", + + "[BUG-01] 单行超长溢出": "[BUG-01] 単一行の長いオーバーフロー", + "[BUG-02] 换行纵向溢出": "[BUG-02] 折り返しの縦方向オーバーフロー", + "[BUG-03] 字号过大溢出": "[BUG-03] フォントサイズ過大オーバーフロー", + "[BUG-04] 按钮文本被截断": "[BUG-04] ボタンテキストの切り詰め", + "[BUG-05] 行高压缩叠字": "[BUG-05] 行の高さ圧縮による文字重なり", + "[BUG-06] 文本同色不可见": "[BUG-06] テキスト同色で不可視", + "[BUG-07] 文本被硬截断": "[BUG-07] テキストのハードクリップ", + "[BUG-08] TileView 容器重叠": "[BUG-08] TileView コンテナの重なり", + "[BUG-09] TileView 条目截断": "[BUG-09] TileView 項目の切り詰め", + "[BUG-10] 漏 Key 显示原始 Key": "[BUG-10] キー漏れで元のキーを表示", + "[BUG-11] 有 Key 但漏译": "[BUG-11] キーありだが翻訳漏れ", + "↑ 底部参照行": "↑ 下部参照行", + "BugTile1": "BugTile1", + "BugTile2": "BugTile2" +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ko.json b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ko.json new file mode 100644 index 0000000000000000000000000000000000000000..779f7e54989dfa1e5de25f4d9c4855734826bb8c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQALocalization/Text_Translations_ko.json @@ -0,0 +1,143 @@ +{ + "LQA 验证画廊 (UE5)": "LQA 검증 갤러리 (UE5)", + "LQA 验证画廊 (UE4)": "LQA 검증 갤러리 (UE4)", + + "一、文本类控件": "1. 텍스트 위젯", + "二、交互/输入类控件": "2. 인터랙티브/입력 위젯", + "三、展示类控件": "3. 프레젠테이션 위젯", + "四、布局容器": "4. 레이아웃 컨테이너", + + "这是 TextBlock 示例": "이것은 TextBlock 샘플입니다", + "这是 RichTextBlock 富文本 示例": "이것은 RichTextBlock 리치 텍스트 샘플입니다", + "MultiLineEditableText\n多行文本": "MultiLineEditableText\n여러 줄 텍스트", + "MultiLineEditableTextBox\n多行文本框": "MultiLineEditableTextBox\n여러 줄 텍스트 상자", + + "EditableText 单行输入": "EditableText 한 줄 입력", + "EditableTextBox 单行输入框": "EditableTextBox 한 줄 입력 상자", + + "Border 内容": "Border 콘텐츠", + "Overlay 叠加": "Overlay 스택", + "ScaleBox 缩放内容": "ScaleBox 크기 조정 콘텐츠", + "SafeZone 内容": "SafeZone 콘텐츠", + + "TextBlock": "TextBlock", + "RichTextBlock": "RichTextBlock", + "EditableText": "EditableText", + "EditableTextBox": "EditableTextBox", + "MultiLineEditableText": "MultiLineEditableText", + "MultiLineEditableTextBox": "MultiLineEditableTextBox", + + "Button": "Button", + "CheckBox": "CheckBox", + "Slider": "Slider", + "ProgressBar": "ProgressBar", + "ComboBoxString": "ComboBoxString", + "SpinBox": "SpinBox", + + "Image": "Image", + "Throbber": "Throbber", + "CircularThrobber": "CircularThrobber", + "Spacer (40x20)": "Spacer (40x20)", + "Border": "Border", + "SizeBox (120x40)": "SizeBox (120x40)", + "ScaleBox": "ScaleBox", + "SafeZone": "SafeZone", + "WidgetSwitcher": "WidgetSwitcher", + + "HorizontalBox": "HorizontalBox", + "GridPanel": "GridPanel", + "UniformGridPanel": "UniformGridPanel", + "Overlay": "Overlay", + "WrapBox": "WrapBox", + + "[H0]": "[H0]", + "[H1]": "[H1]", + "[H2]": "[H2]", + "(0,0)": "(0,0)", + "(0,1)": "(0,1)", + "(1,0)": "(1,0)", + "(1,1)": "(1,1)", + + "U0": "U0", + "U1": "U1", + "U2": "U2", + "U3": "U3", + "Wrap0": "Wrap0", + "Wrap1": "Wrap1", + "Wrap2": "Wrap2", + "Wrap3": "Wrap3", + "Wrap4": "Wrap4", + "Wrap5": "Wrap5", + "Page 0": "Page 0", + + "Page 1": "Page 1", + + "CanvasPanel": "CanvasPanel", + "ScrollBox": "ScrollBox", + "VerticalBox": "VerticalBox", + "NamedSlot": "NamedSlot", + "ComboBoxKey": "ComboBoxKey", + "UserWidget": "UserWidget", + "InputKeySelector": "InputKeySelector", + "MenuAnchor": "MenuAnchor", + "ScrollBar": "ScrollBar", + "StackBox": "StackBox", + "InvalidationBox": "InvalidationBox", + "WindowTitleBarArea": "WindowTitleBarArea", + "PostBufferUpdate": "PostBufferUpdate", + "BackgroundBlur": "BackgroundBlur", + "RetainerBox": "RetainerBox", + "ExpandableArea": "ExpandableArea", + "ListView": "ListView", + "TileView": "TileView", + "TreeView": "TreeView", + "DynamicEntryBox": "DynamicEntryBox", + + "KeySelection": "KeySelection", + "NoKeySpecified": "NoKeySpecified", + "MenuAnchor Anchor": "MenuAnchor Anchor", + "InvalidationBox Content": "InvalidationBox Content", + "WindowTitleBarArea Content": "WindowTitleBarArea Content", + + "滚动到顶": "맨 위로 스크롤", + "滚动到底": "맨 아래로 스크롤", + "切换背景": "배경 전환", + + "DynamicEntryBoxText1": "DynamicEntryBoxText1", + "DynamicEntryBoxText2": "DynamicEntryBoxText2", + "DynamicEntryBoxText3": "DynamicEntryBoxText3", + + "ListViewText1": "ListViewText1", + "ListViewText2": "ListViewText2", + "ListViewText3": "ListViewText3", + "TileViewText1": "TileViewText1", + "TileViewText2": "TileViewText2", + "TreeViewText1": "TreeViewText1", + "TreeViewText2": "TreeViewText2", + "TreeViewText3": "TreeViewText3", + + "五、显示性质 BUG": "5. 표시 관련 버그", + "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠": "이 텍스트는 의도적으로 줄바꿈하지 않아 왼쪽 고정 영역을 벗어나 스테이지 경계를 초과합니다. 텍스트 넘침과 겹침 감지에 사용됩니다.", + "换行后行数超出高度,越出舞台底部": "줄바꿈 후 줄 수가 높이를 초과하여 하단 기준 줄을 덮습니다.", + "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别": "이 텍스트는 고정 너비를 초과하면 잘리고 끝에 줄임표가 없습니다. 잘림 감지에 사용됩니다.", + "字号 36 的文本": "글자 크기 36 텍스트", + "Confirm and Continue With All Changes": "Confirm and Continue With All Changes", + "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠": "줄 높이가 30%로 압축되어 두 줄의 텍스트가 서로 겹칩니다. 단일 텍스트 노드 내부의 겹침 감지에 사용됩니다.", + "这段文本与底色同色,应完全不可见": "이 텍스트는 배경색과 같은 색이므로 완전히 보이지 않아야 합니다.", + "OverflowingTileViewItemTextWithoutAnySpaces": "OverflowingTileViewItemTextWithoutAnySpaces", + + "[BUG-01] 单行超长溢出": "[BUG-01] 한 줄 넘침", + "[BUG-02] 换行纵向溢出": "[BUG-02] 줄바꿈 세로 넘침", + "[BUG-03] 字号过大溢出": "[BUG-03] 글자 크기 넘침", + "[BUG-04] 按钮文本被截断": "[BUG-04] 버튼 텍스트 잘림", + "[BUG-05] 行高压缩叠字": "[BUG-05] 줄 높이 압축 겹침", + "[BUG-06] 文本同色不可见": "[BUG-06] 텍스트 동일 색상으로 안 보임", + "[BUG-07] 文本被硬截断": "[BUG-07] 텍스트 하드 잘림", + "[BUG-08] TileView 容器重叠": "[BUG-08] TileView 컨테이너 겹침", + "[BUG-09] TileView 条目截断": "[BUG-09] TileView 항목 잘림", + "[BUG-10] 漏 Key 显示原始 Key": "[BUG-10] 키 누락으로 원래 키 표시", + "[BUG-11] 有 Key 但漏译": "[BUG-11] 키는 있지만 번역 누락", + "↑ 底部参照行": "↑ 하단 기준 줄", + "BugTile1": "BugTile1", + "BugTile2": "BugTile2" +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQARestore.uplugin b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQARestore.uplugin new file mode 100644 index 0000000000000000000000000000000000000000..d06d93e8657ac82efd4bc5ad8637ac1080d209b6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/LQARestore.uplugin @@ -0,0 +1,32 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "1.0.0", + "FriendlyName": "LQARestore", + "Description": "A plugin to restore the UI for Localization Quality Assurance (LQA).", + "Category": "Testing", + "CreatedBy": "Tencent", + "CanContainContent": true, + "IsBetaVersion": false, + "IsExperimentalVersion": false, + "Installed": false, + "SupportedTargetPlatforms": [ + "Win64" + ], + "Modules": [ + { + "Name": "LQARestore", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ + "Win64" + ] + } + ], + "Plugins": [ + { + "Name": "Paper2D", + "Enabled": true + } + ] +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Resources/Icon128.png b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Resources/Icon128.png new file mode 100644 index 0000000000000000000000000000000000000000..1231d4aad4d0d462fb7b178eb5b30aa61a10df0b Binary files /dev/null and b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Resources/Icon128.png differ diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/LQARestore.Build.cs b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/LQARestore.Build.cs new file mode 100644 index 0000000000000000000000000000000000000000..2be4e95014b861e5810af2a1c0e01a1e20f1bc31 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/LQARestore.Build.cs @@ -0,0 +1,60 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +// 引入 UnrealBuildTool 命名空间, 该工具 (UBT) 负责解析本构建脚本并生成编译配置 +using UnrealBuildTool; + +// LQARestore 模块的构建规则类, 必须继承自 ModuleRules +// 类名需要与模块名、以及 .Build.cs 文件名保持一致 +public class LQARestore : ModuleRules +{ + // 构造函数, UBT 会在解析模块时调用它 + // Target 参数描述了当前的编译目标信息 (平台、配置、类型等), 为只读规则 + public LQARestore(ReadOnlyTargetRules Target) : base(Target) + { + // 设置预编译头 (PCH) 的使用方式 + // UseExplicitOrSharedPCHs 表示使用显式或共享的 PCH, 是现代 UE 推荐的方式, 可提升编译速度 + PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; + + // 公有依赖模块: 这些模块会同时暴露给依赖本模块的其他模块 + // 即其他模块引用 LQARestore 时, 也能间接访问这些依赖的头文件 + PublicDependencyModuleNames.AddRange(new string[] + { + "Core", // UE 核心基础库 (容器、字符串、数学等), 几乎所有模块都需要 + "MediaAssets" // 媒体资源模块, 用于处理媒体播放器、媒体纹理等资源 + }); + + // 私有依赖模块: 仅本模块内部使用, 不会传递给依赖本模块的其他模块 + // 这样可以减少不必要的依赖传播, 加快编译并降低耦合 + PrivateDependencyModuleNames.AddRange(new string[] + { + "CoreUObject", // UObject 对象系统 (反射、GC、序列化等) + "Engine", // 引擎核心功能 (Actor、World、组件等) + "Slate", // Slate UI 框架 (界面控件) + "SlateCore", // Slate UI 核心组件 (底层绘制与基础类型) + "UMG", // 控件蓝图 (Unreal Motion Graphics, 基于 Slate 的可视化 UI) + "Settings", // 项目设置模块 (注册自定义配置页)) + "Json", // JSON 解析 (底层读写) + "JsonUtilities", // JSON 工具库 (结构体与 JSON 的互转等便捷功能) + "ImageWrapper", // 图像编解码 (PNG 解码, 用于还原运行时生成的纹理) + "RHI", // 渲染硬件接口 (Render Hardware Interface) + "RenderCore", // 渲染核心功能 + "ImageCore", // 图像核心类型 (FImage/FImageView, CompressImage 的输入) + "HTTP", // HTTP 网络请求模块 + "Paper2D", // 2D 渲染 (精灵 Sprite、Flipbook 等) + "InputCore", // 输入处理 (按键、轴映射等基础输入类型) + "zlib", // zlib 压缩库 (数据压缩/解压) + "Projects" // 项目/插件管理模块 (提供 IPluginManager 等接口) + }); + + // 仅当编译目标为编辑器 (Editor) 时才添加 UnrealEd 依赖 + // UnrealEd 包含大量编辑器专用功能, 若在打包的游戏运行时版本中引用会导致编译/链接错误 + if (Target.Type == TargetType.Editor) + { + PrivateDependencyModuleNames.Add("UnrealEd"); // 编辑器核心模块 + } + + // 公有预处理宏定义: 会暴露给依赖本模块的其他模块 + // 代码中可通过 #if WITH_LQA_RESTORE_TOOL_ENABLED 进行条件编译, 控制 LQA 还原工具功能的开关 + PublicDefinitions.Add("WITH_LQA_RESTORE_TOOL_ENABLED=1"); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/ConfigManager.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/ConfigManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc91eb1590660c2ee935d06c5158f62e0cd8ea1e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/ConfigManager.cpp @@ -0,0 +1,149 @@ +#include "Core/ConfigManager.h" + +#include "Misc/CommandLine.h" // 提供 FCommandLine::Get() 用于获取进程命令行 +#include "Misc/Paths.h" // 提供 FPaths 路径处理工具函数 + +// 定义 (实现) 在头文件中声明的日志分类, 整个模块中仅能定义一次 +DEFINE_LOG_CATEGORY(LogLQARestoreConfig); + +void UConfigManager::Initialize() +{ + // ---- 1. 初始化所有配置项的默认值 ---- + ProjectId = TEXT("0"); + JobId = TEXT("0"); + Language = TEXT("LAN_EU_EN"); + PoLanguage = TEXT("en"); + Regression = TEXT("0"); + CreateBug = TEXT("0"); + BugId.Empty(); + AISign = TEXT("1"); + DefaultNums = TEXT("1"); + MinID = TEXT("1"); + Modules.Empty(); + IsCover = TEXT("false"); + BaseDataId.Empty(); + BaseDataFilePath.Empty(); + bIsLocalMode = true; // 默认运行在本地模式 + RestoreDirection = ERestoreDirection::ChineseToForeign; // 默认: 中文 -> 外文 + + // ---- 2. 设置 PNG 保存目录 ---- + // 使用工程的 Saved 目录, 并转换为绝对路径, 避免相对路径带来的歧义 + PngSaveRootDir = FPaths::ConvertRelativePathToFull(FPaths::ProjectSavedDir()); + + // ---- 3. 初始化语言映射表 ---- + InitializeLanguageMap(); + + // ---- 4. 解析命令行参数 (会覆盖上面的默认值) ---- + ParseCommandLineParams(); + + // ---- 5. 输出当前配置到日志, 便于排查问题 ---- + UE_LOG(LogLQARestoreConfig, Log, TEXT("=== ConfigManager Initialized ===")); + UE_LOG(LogLQARestoreConfig, Log, TEXT("ProjectId: %s, JobId: %s"), *ProjectId, *JobId); + UE_LOG(LogLQARestoreConfig, Log, TEXT("Language: %s, PoLanguage: %s"), *Language, *PoLanguage); + UE_LOG(LogLQARestoreConfig, Log, TEXT("PngSaveRootDir: %s"), *PngSaveRootDir); + UE_LOG(LogLQARestoreConfig, Log, TEXT("Regression: %s, IsLocalMode: %s"), *Regression, + bIsLocalMode ? TEXT("true") : TEXT("false")); +} + +void UConfigManager::InitializeLanguageMap() +{ + // 预留 14 个槽位, 避免插入过程中的多次扩容 (哈希表 rehash) + LanguageMap.Reserve(14); + + // 建立 内部语言代码 -> PO 语言代码 的映射关系 + LanguageMap.Add(TEXT("LAN_EU_EN"), TEXT("en")); // 英语 + LanguageMap.Add(TEXT("LAN_EU_DE"), TEXT("de")); // 德语 + LanguageMap.Add(TEXT("LAN_FR_FR"), TEXT("fr")); // 法语 + LanguageMap.Add(TEXT("LAN_RU_RU"), TEXT("ru")); // 俄语 + LanguageMap.Add(TEXT("LAN_JP_JP"), TEXT("ja")); // 日语 + LanguageMap.Add(TEXT("LAN_KO_KO"), TEXT("ko")); // 韩语 + LanguageMap.Add(TEXT("LAN_CHT_CHT"), TEXT("zh-TW")); // 繁体中文 + LanguageMap.Add(TEXT("LAN_AR_AR"), TEXT("ar")); // 阿拉伯语 + LanguageMap.Add(TEXT("LAN_ES_LT"), TEXT("es")); // 西班牙语 + LanguageMap.Add(TEXT("LAN_PT_BR"), TEXT("pt-BR")); // 巴西葡萄牙语 + LanguageMap.Add(TEXT("LAN_TR_TR"), TEXT("tr")); // 土耳其语 + LanguageMap.Add(TEXT("LAN_TH_TH"), TEXT("th")); // 泰语 + LanguageMap.Add(TEXT("LAN_ID_ID"), TEXT("id")); // 印尼语 + LanguageMap.Add(TEXT("LAN_CHS_CHS"), TEXT("zh")); // 简体中文 +} + +void UConfigManager::ParseCommandLineParams() +{ + // 获取完整命令行字符串, 并以空格分割为若干参数 (最后一个参数 true 表示忽略空项) + const FString CommandLine = FCommandLine::Get(); + TArray Params; + CommandLine.ParseIntoArray(Params, TEXT(" "), true); + + // ---- 从命令行中解析出 "键=值" 形式的参数 ---- + for (const FString& Param : Params) + { + // 不含 "=" 的参数不是键值对, 跳过 + if (!Param.Contains(TEXT("="))) + { + continue; + } + + FString Key, Value; + // 以第一个 "=" 为界拆分为键和值 + if (Param.Split(TEXT("="), &Key, &Value)) + { + // 去除键名前导的 "-" (例如 -ProjectId=123 -> ProjectId) + Key.RemoveFromStart(TEXT("-")); + + CommandLineParams.Add(Key, Value); + UE_LOG(LogLQARestoreConfig, Verbose, TEXT("Parsed CommandLine: %s = %s"), *Key, *Value); + } + } + + // ---- 从已解析的参数中提取各配置项 (未提供的参数保留原默认值) ---- + ProjectId = GetCommandLineParam(TEXT("ProjectId"), ProjectId); + JobId = GetCommandLineParam(TEXT("JobId"), JobId); + Language = GetCommandLineParam(TEXT("Language"), Language); + PoLanguage = ConvertToPoLanguage(Language); // 根据语言代码换算 PO 语言代码 + Regression = GetCommandLineParam(TEXT("Regression"), Regression); + CreateBug = GetCommandLineParam(TEXT("CreateBug"), CreateBug); + BugId = GetCommandLineParam(TEXT("bugId"), BugId); + AISign = GetCommandLineParam(TEXT("AISign"), AISign); + DefaultNums = GetCommandLineParam(TEXT("DefaultNums"), DefaultNums); + MinID = GetCommandLineParam(TEXT("MinID"), MinID); + Modules = GetCommandLineParam(TEXT("Modules"), Modules); + IsCover = GetCommandLineParam(TEXT("IsCover"), IsCover); + BaseDataId = GetCommandLineParam(TEXT("BaseDataId"), BaseDataId); + BaseDataFilePath = GetCommandLineParam(TEXT("BaseDataFilePath"), BaseDataFilePath); + + // ---- 解析还原语言方向 ---- + // RestoreDirection=F2C 表示「外文 -> 中文」, 其余 (含缺省) 均为「中文 -> 外文」 + const FString DirStr = GetCommandLineParam(TEXT("RestoreDirection"), TEXT("C2F")); + RestoreDirection = DirStr.Equals(TEXT("F2C"), ESearchCase::IgnoreCase) + ? ERestoreDirection::ForeignToChinese + : ERestoreDirection::ChineseToForeign; + + // ---- 判定是否为本地模式 ---- + // 当 JobId 为 "0" (即未传入有效任务 ID) 时, 视为本地模式 + bIsLocalMode = (JobId == TEXT("0")); +} + +FString UConfigManager::GetCommandLineParam(const FString& Key, const FString& DefaultValue) const +{ + // 在缓存的命令行参数表中查找指定键 + if (const FString* FoundValue = CommandLineParams.Find(Key)) + { + return *FoundValue; + } + + // 未找到则返回调用方提供的默认值 + return DefaultValue; +} + +FString UConfigManager::ConvertToPoLanguage(const FString& InLanguage) const +{ + // 在语言映射表中查找对应的 PO 语言代码 + if (const FString* PoLang = LanguageMap.Find(InLanguage)) + { + return *PoLang; + } + + // 未匹配到时, 记录警告并回退到默认语言 "en" + UE_LOG(LogLQARestoreConfig, Warning, TEXT("Language '%s' not found in LanguageMap, defaulting to 'en'"), *InLanguage); + return TEXT("en"); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/FileManager.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/FileManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ed3560a59be6fb8c3bc1730139ca994f7e8d7e7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/FileManager.cpp @@ -0,0 +1,159 @@ +#include "Core/FileManager.h" + +#include "HAL/PlatformFileManager.h" // 平台文件系统抽象层, 用于创建目录树等操作 +#include "Misc/FileHelper.h" // 提供字符串与文件互相读写的便捷函数 +#include "Misc/Paths.h" // 路径处理工具 (拼接、判断存在性、取路径等) +#include "Serialization/JsonSerializer.h" // JSON 序列化/反序列化支持 + +// 定义 (实现) 在头文件中声明的日志分类, 使其在本翻译单元中真正生效 +DEFINE_LOG_CATEGORY(LogLQARestoreFile); + +// 递归查找目录下所有 JSON 文件 +void UFileManager::FindJsonFilesRecursive(const FString& Path, TArray& OutJsonFiles) +{ + // 将可能的相对路径转换为绝对路径, 便于日志输出和存在性校验 + const FString FullDirectoryPath = FPaths::ConvertRelativePathToFull(Path); + + // 目录不存在时直接报错返回, 避免后续无效操作 + if (!IFileManager::Get().DirectoryExists(*FullDirectoryPath)) + { + UE_LOG(LogLQARestoreFile, Error, TEXT("Directory not found: %s"), *FullDirectoryPath); + return; + } + + // 递归查找所有扩展名为 .json 的文件: + // 参数 Files=true 表示查找文件, Directories=false 表示不收集目录本身 + IFileManager::Get().FindFilesRecursive(OutJsonFiles, *Path, TEXT("*.json"), true, false); + + UE_LOG(LogLQARestoreFile, Log, TEXT("Found %d JSON files in: %s"), OutJsonFiles.Num(), *Path); +} + +// 根据传入路径 (文件或目录) 解析出待处理文件列表 +void UFileManager::GetFilePaths(const FString& DumpFilePath, TArray& OutFilePaths) +{ + // 情况一: 传入的是一个已存在的文件, 直接加入结果列表 + if (FPaths::FileExists(DumpFilePath)) + { + OutFilePaths.Add(DumpFilePath); + } + // 情况二: 传入的是一个目录, 递归收集其中的所有 JSON 文件 + else if (FPaths::DirectoryExists(DumpFilePath)) + { + IFileManager::Get().FindFilesRecursive(OutFilePaths, *DumpFilePath, TEXT("*.json"), true, false); + } + // 情况三: 路径既不是文件也不是目录, 记录警告 + else + { + UE_LOG(LogLQARestoreFile, Warning, TEXT("Path does not exist: %s"), *DumpFilePath); + } +} + +// 将 JSON 内容保存为 dump 文件 +FString UFileManager::SaveDumpDataToFile(const FString& DataId, const FString& JsonContent, const FString& SaveDir) +{ + // 依据 DataId 和目录生成完整的目标文件路径 + const FString OutputFilePath = GetDumpFilePath(DataId, SaveDir); + // 取出该文件所在的目录部分 + const FString OutputDir = FPaths::GetPath(OutputFilePath); + + // 写入前先确保目标目录存在 (必要时创建) + EnsureDirectoryExists(OutputDir); + + // 将 JSON 字符串写入文件, 成功则返回文件路径 + if (FFileHelper::SaveStringToFile(JsonContent, *OutputFilePath)) + { + UE_LOG(LogLQARestoreFile, Log, TEXT("Dump data saved: %s"), *OutputFilePath); + return OutputFilePath; + } + + // 写入失败时记录错误并返回空字符串 + UE_LOG(LogLQARestoreFile, Error, TEXT("Failed to save dump data: %s"), *OutputFilePath); + return FString(); +} + +// 加载并解析 JSON 文件 +TSharedPtr UFileManager::LoadJsonFromFile(const FString& FilePath) +{ + // 文件不存在, 提前返回空指针 + if (!FPaths::FileExists(FilePath)) + { + UE_LOG(LogLQARestoreFile, Warning, TEXT("JSON file not found: %s"), *FilePath); + return nullptr; + } + + // 将整个文件内容读入字符串; 读取失败则返回空指针 + FString JsonStr; + if (!FFileHelper::LoadFileToString(JsonStr, *FilePath)) + { + UE_LOG(LogLQARestoreFile, Error, TEXT("Failed to load JSON file: %s"), *FilePath); + return nullptr; + } + + // 创建 JSON 读取器, 并将字符串反序列化为 JSON 对象 + TSharedPtr JsonObject; + const TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonStr); + + // 反序列化失败或结果无效时, 返回空指针 + if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid()) + { + UE_LOG(LogLQARestoreFile, Error, TEXT("Failed to parse JSON file: %s"), *FilePath); + return nullptr; + } + + return JsonObject; +} + +// 判断指定 DataId 对应的 dump 文件是否存在 +bool UFileManager::DumpFileExists(const FString& DataId, const FString& SaveDir) const +{ + // 复用路径生成逻辑, 再判断文件是否存在 + const FString FilePath = GetDumpFilePath(DataId, SaveDir); + return FPaths::FileExists(FilePath); +} + +// 删除目录及其全部内容 +bool UFileManager::DeleteDirectory(const FString& DirectoryPath) +{ + // 目录本就不存在, 视为删除成功 + if (!FPaths::DirectoryExists(DirectoryPath)) + { + return true; + } + + // 删除目录: RequireExists=false (不强制要求存在), Tree=true (递归删除子目录与文件) + const bool bSuccess = IFileManager::Get().DeleteDirectory(*DirectoryPath, false, true); + if (!bSuccess) + { + UE_LOG(LogLQARestoreFile, Warning, TEXT("Failed to delete directory: %s"), *DirectoryPath); + } + + return bSuccess; +} + +// 确保目录存在, 不存在则创建 +bool UFileManager::EnsureDirectoryExists(const FString& DirectoryPath) +{ + // 目录已存在, 无需创建。 + if (FPaths::DirectoryExists(DirectoryPath)) + { + return true; + } + + // 创建完整的目录树 (会自动创建缺失的多级父目录) + const bool bSuccess = FPlatformFileManager::Get().GetPlatformFile().CreateDirectoryTree(*DirectoryPath); + if (!bSuccess) + { + UE_LOG(LogLQARestoreFile, Error, TEXT("Failed to create directory: %s"), *DirectoryPath); + } + + return bSuccess; +} + +// 生成 dump 文件的完整路径: {SaveDir}/LQAData/LQA_{DataId}.json +FString UFileManager::GetDumpFilePath(const FString& DataId, const FString& SaveDir) const +{ + // 先在基础目录下拼出专用子目录 LQAData + const FString LQADataDir = FPaths::Combine(SaveDir, TEXT("LQAData")); + // 再拼上以 DataId 命名的 JSON 文件名 + return FPaths::Combine(LQADataDir, FString::Printf(TEXT("LQA_%s.json"), *DataId)); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQAContainerWidget.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQAContainerWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f46b63f744d0c24c0a29c382cf035223e01e9964 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQAContainerWidget.cpp @@ -0,0 +1,5 @@ +// 包含对应的头文件声明 +// 该类目前没有任何需要实现的成员函数, 源文件存在的意义在于: +// 1. 保证该模块会为此类生成编译单元 (.obj), 以便链接反射数据; +// 2. 为后续可能添加的实现逻辑预留位置 +#include "Core/LQAContainerWidget.h" \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQARestoreManager.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQARestoreManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f227c0dd417104fb5646ac140bab925d422f6a64 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/LQARestoreManager.cpp @@ -0,0 +1,781 @@ +#include "Core/LQARestoreManager.h" + +#include "Core/ConfigManager.h" +#include "Core/FileManager.h" +#include "Core/RestoreWindowProxy.h" +#include "Core/RestoreWindowUtils.h" +#include "Core/RootObjWidget.h" +#include "Core/TaskManager.h" +#include "Framework/Application/SlateApplication.h" +#include "Engine/GameViewportClient.h" +#include "Engine/TextureRenderTarget2D.h" +#include "ImageUtils.h" +#include "Interfaces/IPluginManager.h" +#include "Misc/FileHelper.h" +#include "Misc/ScopeExit.h" +#include "Slate/WidgetRenderer.h" +#include "UObject/StrongObjectPtr.h" +#include "Utils/TranslationUtils/LoaderUtils.h" +#include "Widgets/SViewport.h" + +// 定义头文件中声明的日志分类 +DEFINE_LOG_CATEGORY(LogLQARestoreManager); + +// 子系统初始化: 重置状态 -> 创建并初始化管理器 -> 绑定委托 -> 延迟启动工作流 +void ULQARestoreManager::Initialize(FSubsystemCollectionBase& Collection) +{ + Super::Initialize(Collection); + UE_LOG(LogLQARestoreManager, Log, TEXT("LQARestoreManager initializing")); + + // 初始化内部状态变量 + NextWindowId = 0; + CurrentRestoreIndex = 0; + CurrentLocalFileIndex = 0; + CurrentRestoreRetryCount = 0; + bCanStartRestore = true; + + // 创建三大管理器实例 (以 this 为 Outer, 随本对象生命周期管理) + ConfigManager = NewObject(this); + TaskManager = NewObject(this); + FileManager = NewObject(this); + + // 初始化管理器: TaskManager 需要依赖 Config 与 File + ConfigManager->Initialize(); + TaskManager->Initialize(ConfigManager, FileManager); + + // 绑定网络相关委托, 将 TaskManager 的事件回调到本类对应处理函数 + TaskManager->OnJobDataReceived.AddUObject(this, &ULQARestoreManager::OnJobDataReceived); + TaskManager->OnDumpDataDownloaded.AddUObject(this, &ULQARestoreManager::OnDumpDataDownloaded); + TaskManager->OnRestoreResultUploaded.AddUObject(this, &ULQARestoreManager::OnRestoreResultUploaded); + + // 延迟 InitialStartDelay 秒后启动工作流 + // 使用 TWeakObjectPtr 弱引用, 避免定时器回调时对象已被销毁导致悬空访问 + TWeakObjectPtr WeakThis(this); + GetWorld()->GetTimerManager().SetTimer( + StartWorkTimer, + [WeakThis]() + { + if (WeakThis.IsValid()) + { + WeakThis->StartWork(); + } + }, + InitialStartDelay, false); // false 表示不循环, 仅触发一次 +} + +// 子系统反初始化: 销毁窗口、清理定时器, 确保无资源泄漏 +void ULQARestoreManager::Deinitialize() +{ + // 销毁所有活动窗口 + for (const TPair& Proxy : ActiveWindows) + { + Proxy.Value->DestroyWindow(); + } + ActiveWindows.Empty(); + + // 清理本对象注册的所有定时器 + if (GetWorld()) + { + GetWorld()->GetTimerManager().ClearAllTimersForObject(this); + } + + Super::Deinitialize(); + UE_LOG(LogLQARestoreManager, Log, TEXT("LQARestoreManager deinitialized")); +} + +// 工作流入口: 先加载翻译数据, 再根据模式分流到本地/平台工作流 +void ULQARestoreManager::StartWork() +{ + UE_LOG(LogLQARestoreManager, Log, TEXT("Starting restore workflow")); + + LoadTranslationData(); + + if (ConfigManager->IsLocalMode()) + { + HandleLocalWorkflow(); // 本地模式 + } + else + { + HandlePlatformWorkflow(true); // 平台模式 (首次请求) + } +} + +// 加载翻译数据: 根据配置的 PO 语言, 拼出两类本地化 JSON 文件路径并加载 +void ULQARestoreManager::LoadTranslationData() +{ + const FString& PoLanguage = ConfigManager->GetPoLanguage(); + + // 把配置里的还原方向下发给静态翻译工具 (影响 GetTranslateString 的中文守卫) + FLoaderUtils::SetRestoreDirection(ConfigManager->GetRestoreDirection()); + + // 本地化目录: <插件根目录>/LQALocalization + const TSharedPtr Plugin = IPluginManager::Get().FindPlugin(TEXT("LQARestore")); + const FString PluginBaseDir = + Plugin.IsValid() ? Plugin->GetBaseDir() : (FPaths::ProjectPluginsDir() / TEXT("LQARestore")); + const FString LocalizationDir = + FPaths::ConvertRelativePathToFull(PluginBaseDir / TEXT("LQALocalization")); + + // 游戏本地化导出文件 与 文本翻译文件 (文件名带语言后缀) + const FString GameLocFile = + FPaths::Combine(LocalizationDir, FString::Printf(TEXT("GameLocalizationExport_%s.json"), *PoLanguage)); + const FString TextTransFile = + FPaths::Combine(LocalizationDir, FString::Printf(TEXT("Text_Translations_%s.json"), *PoLanguage)); + + UE_LOG(LogLQARestoreManager, Log, TEXT("Loading translation files:")); + UE_LOG(LogLQARestoreManager, Log, TEXT(" - %s"), *GameLocFile); + UE_LOG(LogLQARestoreManager, Log, TEXT(" - %s"), *TextTransFile); + + // 交由加载工具解析并缓存翻译数据 + FLoaderUtils::LoadJsonFromFile(GameLocFile, TextTransFile, PoLanguage); +} + +// 对比模式准备: 仅当配置 IsCover == "true" 且基准数据有效时, +// 将基准数据插入待处理队列的最前面, 使其最先被还原并作为对比基准 +void ULQARestoreManager::SetupBaseDataIfNeeded() +{ + const FString& IsCover = ConfigManager->GetIsCover(); + if (IsCover != TEXT("true")) + { + return; // 未开启对比模式, 直接返回 + } + + const FString& BaseDataId = ConfigManager->GetBaseDataId(); + const FString& BaseDataFilePath = ConfigManager->GetBaseDataFilePath(); + + // 基准数据配置不完整则跳过 + if (BaseDataId.IsEmpty() || BaseDataFilePath.IsEmpty()) + { + return; + } + + UE_LOG(LogLQARestoreManager, Log, TEXT("Inserting base data ID: %s"), *BaseDataId); + // 插入到索引 0, 保证基准数据优先处理 + PendingDataIds.Insert(BaseDataId, 0); + PendingFilePaths.Insert(BaseDataFilePath, 0); +} + +// 启动平台模式的四个周期性定时器 (下载/还原/上传/拉任务, 均为循环定时器) +void ULQARestoreManager::SetupPlatformTimers() +{ + FTimerManager& TimerManager = GetWorld()->GetTimerManager(); + + TimerManager.SetTimer(DownloadTimer, this, &ULQARestoreManager::OnDownloadTick, DownloadInterval, true); + TimerManager.SetTimer(RestoreTimer, this, &ULQARestoreManager::OnRestoreTick, RestoreInterval, true); + TimerManager.SetTimer(UploadTimer, this, &ULQARestoreManager::OnUploadTick, UploadInterval, true); + TimerManager.SetTimer(JobDataTimer, this, &ULQARestoreManager::OnGetJobDataTick, JobDataInterval, true); +} + +// 平台工作流: 首次请求时准备基准数据并启动定时器, 然后向平台请求任务数据 +void ULQARestoreManager::HandlePlatformWorkflow(bool bIsFirstRequest) +{ + if (bIsFirstRequest) + { + SetupBaseDataIfNeeded(); + SetupPlatformTimers(); + } + + TaskManager->RequestJobData(bIsFirstRequest); +} + +// 本地工作流: 递归扫描本地 LQA 目录下的 JSON 文件, 并启动本地处理定时器 +void ULQARestoreManager::HandleLocalWorkflow() +{ + const FString BasePath = ConfigManager->GetPngSaveRootDir(); + const FString LocalDataPath = FPaths::Combine(BasePath, TEXT("LQA")); + + // 递归查找所有 JSON 文件, 结果存入 LocalJsonFiles + FileManager->FindJsonFilesRecursive(LocalDataPath, LocalJsonFiles); + CurrentLocalFileIndex = 0; + + UE_LOG(LogLQARestoreManager, Log, TEXT("Found %d local JSON files in: %s"), LocalJsonFiles.Num(), *LocalDataPath); + + // 启动循环定时器, 逐个处理本地文件 + GetWorld()->GetTimerManager().SetTimer( + LocalJobTimer, this, &ULQARestoreManager::OnLocalJobTick, LocalJobInterval, true); +} + +// 收到平台任务数据回调: 对新 ID 去重后加入待处理列表, 并加入下载队列 +void ULQARestoreManager::OnJobDataReceived(const TArray& InIdList, const TArray& InIdPathList) +{ + UE_LOG(LogLQARestoreManager, Log, TEXT("Received %d job data items"), InIdList.Num()); + + for (int32 i = 0; i < InIdList.Num(); ++i) + { + // 去重: 避免重复加入同一数据 ID + if (!PendingDataIds.Contains(InIdList[i])) + { + PendingDataIds.Add(InIdList[i]); + PendingFilePaths.Add(InIdPathList[i]); + TaskManager->EnqueueDownload(InIdList[i], InIdPathList[i]); // 加入下载队列 + } + } +} + +// dump 数据下载完成回调: 若该文件为基准数据且尚未加载, 则加载为对比基准 +void ULQARestoreManager::OnDumpDataDownloaded(const FString& DataId, const FString& FilePath) +{ + UE_LOG(LogLQARestoreManager, Log, TEXT("Dump data downloaded: %s"), *DataId); + + // 仅在基准数据尚未加载、且当前下载项正是基准数据时加载 + const FString& BaseDataId = ConfigManager->GetBaseDataId(); + if (!BaseComparisonData.IsValid() && DataId == BaseDataId) + { + BaseComparisonData = FileManager->LoadJsonFromFile(FilePath); + if (BaseComparisonData.IsValid()) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("Base comparison data loaded: %s"), *BaseDataId); + } + } +} + +// 还原结果上传完成回调: 目前仅记录日志 +void ULQARestoreManager::OnRestoreResultUploaded(const FString& DataId) +{ + UE_LOG(LogLQARestoreManager, Log, TEXT("Restore result uploaded: %s"), *DataId); +} + +// 拉取任务定时器回调: 本地模式跳过, 否则发起非首次的平台任务请求 +void ULQARestoreManager::OnGetJobDataTick() +{ + // 本地模式不需要拉取平台任务 + if (ConfigManager->IsLocalMode()) + { + return; + } + + HandlePlatformWorkflow(false); +} + +// 下载定时器回调: 本地模式跳过, 否则在可下载时处理下载队列 +void ULQARestoreManager::OnDownloadTick() +{ + // 本地模式跳过 + if (ConfigManager->IsLocalMode()) + { + return; + } + + if (TaskManager->CanDownload()) + { + TaskManager->ProcessDownloadQueue(); + } +} + +// 还原定时器回调: 本地模式跳过 (本地走 OnLocalJobTick): +// 平台模式下在允许还原且仍有待处理项时, 处理当前还原项 +void ULQARestoreManager::OnRestoreTick() +{ + // 本地模式使用 OnLocalJobTick, 这里跳过 + if (ConfigManager->IsLocalMode()) + { + return; + } + + // 没有待处理项, 直接返回 + if (PendingDataIds.Num() == 0) + { + return; + } + + // 当前有还原在进行 (!bCanStartRestore) 或 索引越界, 则不处理 + if (!bCanStartRestore || CurrentRestoreIndex >= PendingDataIds.Num()) + { + return; + } + + ProcessCurrentRestoreItem(); +} + +// 处理当前还原项: 检查 dump 文件是否已就绪 +// - 已就绪: 开始创建还原窗口 +// - 未就绪: 按最大次数重试等待下载, 超过上限则跳过该项 +void ULQARestoreManager::ProcessCurrentRestoreItem() +{ + bCanStartRestore = false; // 加锁, 防止并发还原 + + const FString& CurrentDataId = PendingDataIds[CurrentRestoreIndex]; + // 拼出 dump 文件路径: <根目录>/LQAData/LQA_.json + const FString DumpFilePath = FPaths::Combine( + ConfigManager->GetPngSaveRootDir(), TEXT("LQAData"), FString::Printf(TEXT("LQA_%s.json"), *CurrentDataId)); + + if (FPaths::FileExists(DumpFilePath)) + { + // 文件已就绪, 开始还原 + UE_LOG(LogLQARestoreManager, Log, TEXT("Restoring data ID: %s"), *CurrentDataId); + CurrentRestoreRetryCount = 0; // 重置重试计数 + MakeRestoredWindow(DumpFilePath, CurrentDataId); + } + else + { + // 文件尚未下载完成, 增加重试计数 + ++CurrentRestoreRetryCount; + + if (CurrentRestoreRetryCount < MaxRestoreRetryTimes) + { + // 未达重试上限, 继续等待 (下一次定时器再试, 不推进索引) + UE_LOG(LogLQARestoreManager, Log, TEXT("Waiting for file download: %s (Attempt: %d/%d)"), *CurrentDataId, + CurrentRestoreRetryCount, MaxRestoreRetryTimes); + bCanStartRestore = true; // 解锁以便下次重试 + } + else + { + // 达到重试上限, 跳过该项 + UE_LOG(LogLQARestoreManager, Warning, TEXT("File not found after %d attempts, skipping: %s"), + MaxRestoreRetryTimes, *DumpFilePath); + CurrentRestoreRetryCount = 0; // 重置重试计数 + bCanStartRestore = true; + ++CurrentRestoreIndex; // 推进到下一项 + } + } +} + +// 上传定时器回调: 本地模式跳过, 否则在可上传时处理上传队列 +void ULQARestoreManager::OnUploadTick() +{ + // 本地模式不上传 + if (ConfigManager->IsLocalMode()) + { + return; + } + + if (TaskManager->CanUpload()) + { + TaskManager->ProcessUploadQueue(); + } +} + +// 本地任务定时器回调: 逐个处理本地 JSON 文件, 全部处理完则停止定时器 +void ULQARestoreManager::OnLocalJobTick() +{ + // 没有可处理的文件, 停止定时器 + if (LocalJsonFiles.Num() == 0) + { + UE_LOG(LogLQARestoreManager, Warning, TEXT("No JSON files found for local processing")); + GetWorld()->GetTimerManager().ClearTimer(LocalJobTimer); + return; + } + + // 全部处理完, 停止定时器 + if (CurrentLocalFileIndex >= LocalJsonFiles.Num()) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("All local JSON files processed")); + GetWorld()->GetTimerManager().ClearTimer(LocalJobTimer); + return; + } + + // 取当前文件路径, 用文件名 (不含扩展名) 作为 DataId + const FString& JsonFilePath = LocalJsonFiles[CurrentLocalFileIndex]; + const FString DataId = FPaths::GetBaseFilename(JsonFilePath); + + UE_LOG(LogLQARestoreManager, Log, TEXT("Processing local file [%d/%d]: %s"), CurrentLocalFileIndex + 1, + LocalJsonFiles.Num(), *JsonFilePath); + + MakeRestoredWindow(JsonFilePath, DataId); + ++CurrentLocalFileIndex; // 推进到下一个本地文件 +} + +// 创建还原窗口: 新建窗口代理 -> 创建窗口 -> 延迟刷新文本后构建窗口 +bool ULQARestoreManager::MakeRestoredWindow(const FString& DumpFilePath, const FString& DataId) +{ + URestoreWindowProxy* WindowProxy = NewObject(this); + if (!WindowProxy) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to create RestoreWindowProxy")); + return false; + } + + // 分配唯一窗口 ID 并登记到活动窗口表 + ++NextWindowId; + WindowProxy->Initialize(NextWindowId, GetGameInstance()); + ActiveWindows.Emplace(NextWindowId, WindowProxy); + + // 记录本次 dump 的 session 目录, 以便资源按路径加载失败时, + // 能从同目录的 Textures/.png 兜底还原运行时生成的纹理 + WindowProxy->SetSnapshotDirectory(FPaths::GetPath(DumpFilePath)); + + // 先创建窗口 (加载布局) + FRestoreWindowUtils::CreateWindow(DumpFilePath, WindowProxy); + + // 延迟一段时间等待文本刷新后再构建窗口内容 + // 使用弱引用防止回调时对象已销毁 + TWeakObjectPtr WeakThis(this); + GetWorld()->GetTimerManager().SetTimer( + RefreshTextTimer, + [WeakThis, DumpFilePath, WindowProxy, DataId]() + { + if (!WeakThis.IsValid()) + { + return; + } + + // 判断当前项是否为基准数据: + // - 是基准数据: 构建时不使用对比数据 (nullptr) + // - 非基准数据: 使用已加载的 BaseComparisonData 做对比 + const bool bIsBaseData = (DataId == WeakThis->ConfigManager->GetBaseDataId()); + const TSharedPtr& ComparisonData = bIsBaseData ? nullptr : WeakThis->BaseComparisonData; + + // 构建窗口内容 + const bool bBuildSuccess = FRestoreWindowUtils::BuildWindow(DumpFilePath, WindowProxy, ComparisonData); + if (bBuildSuccess) + { + // 构建成功: 安排截图与上传 + WeakThis->ScheduleScreenshotAndUpload(WindowProxy, DataId); + } + else + { + // 构建失败: 记录错误,解锁并推进到下一项 + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to build window for: %s"), *DataId); + WeakThis->bCanStartRestore = true; + ++WeakThis->CurrentRestoreIndex; + } + }, + RefreshTextDelay, false); + + return true; +} + +// 设置截图模式; 仅影响之后排好的截图, 不会改动正在进行中的那次 +void ULQARestoreManager::SetScreenshotMode(ELQAScreenshotMode InMode) +{ + if (ScreenshotMode == InMode) + { + return; + } + + ScreenshotMode = InMode; + + UE_LOG(LogLQARestoreManager, Log, TEXT("Screenshot mode switched to: %s"), + InMode == ELQAScreenshotMode::WidgetOnly ? TEXT("WidgetOnly") : TEXT("Viewport")); +} + +ELQAScreenshotMode ULQARestoreManager::GetScreenshotMode() const +{ + return ScreenshotMode; +} + +// 安排截图与上传: 延迟等待渲染稳定后, 截图 -> 生成结果 JSON -> 清理窗口 -> 入上传队列 +void ULQARestoreManager::ScheduleScreenshotAndUpload(URestoreWindowProxy* WindowProxy, const FString& DataId) +{ + TWeakObjectPtr WeakThis(this); + + GetWorld()->GetTimerManager().SetTimer( + ScreenshotTimer, + [WeakThis, WindowProxy, DataId]() + { + if (!WeakThis.IsValid()) + { + return; + } + + // 结果输出目录: <根目录>/LQAResult/Restore__ + const FString& Language = WeakThis->ConfigManager->GetLanguage(); + const FString ResultDirName = FString::Printf(TEXT("Restore_%s_%s"), *DataId, *Language); + const FString ResultDirPath = + FPaths::Combine(WeakThis->ConfigManager->GetPngSaveRootDir(), TEXT("LQAResult"), ResultDirName); + + // 先删除旧目录再重建, 确保输出目录干净 + WeakThis->FileManager->DeleteDirectory(ResultDirPath); + WeakThis->FileManager->EnsureDirectoryExists(ResultDirPath); + + // 截图并保存为 screenshot.png, 取景范围由 ScreenshotMode 决定: + // WidgetOnly -> CaptureWidgetScreenshot: 只截根控件 (离屏渲染, 不带背景) + // Viewport -> CaptureViewportScreenshot: 截游戏视口 (背景 + 全部 UI) + const FString ScreenshotFilePath = FPaths::Combine(ResultDirPath, TEXT("screenshot.png")); + bool bScreenshotSuccess = false; + + switch (WeakThis->ScreenshotMode) + { + case ELQAScreenshotMode::WidgetOnly: + { + URootObjWidget* RootWidget = (WindowProxy != nullptr) ? WindowProxy->GetRootWidget() : nullptr; + + if (IsValid(RootWidget)) + { + bScreenshotSuccess = WeakThis->CaptureWidgetScreenshot(RootWidget, ScreenshotFilePath); + } + else + { + UE_LOG(LogLQARestoreManager, Error, TEXT("WidgetOnly screenshot needs a valid root widget: %s"), *DataId); + } + + break; + } + + case ELQAScreenshotMode::Viewport: + { + bScreenshotSuccess = WeakThis->CaptureViewportScreenshot(ScreenshotFilePath); + break; + } + + default: + UE_LOG(LogLQARestoreManager, Error, TEXT("Unsupported screenshot mode: %d"), + static_cast(WeakThis->ScreenshotMode)); + break; + } + + if (!bScreenshotSuccess) + { + UE_LOG(LogLQARestoreManager, Warning, TEXT("Failed to capture screenshot for: %s"), *DataId); + } + + // 生成校验/结果 JSON + UE_LOG(LogLQARestoreManager, Log, TEXT("Generating output for: %s"), *DataId); + FRestoreWindowUtils::GenerateCheckJson(WindowProxy, ResultDirPath); + + // 清理窗口并推进进度: 入上传队列 (本地模式下 OnUploadTick 会跳过实际上传) + WeakThis->ClearRestoreWindow(); + WeakThis->TaskManager->EnqueueUpload(DataId); + }, + ScreenshotDelay, false); +} + +// 清理还原窗口: 解锁 -> 记录已完成项 -> 推进索引 -> 销毁所有活动窗口 +void ULQARestoreManager::ClearRestoreWindow() +{ + bCanStartRestore = true; // 解锁, 允许开始下一项还原 + + // 将当前项记入已完成队列 + if (CurrentRestoreIndex < PendingDataIds.Num()) + { + CompletedDataIds.Enqueue(PendingDataIds[CurrentRestoreIndex]); + } + ++CurrentRestoreIndex; // 推进到下一项 + + // 销毁所有活动窗口 + for (const TPair& Proxy : ActiveWindows) + { + Proxy.Value->DestroyWindow(); + } + ActiveWindows.Empty(); + + UE_LOG(LogLQARestoreManager, Log, TEXT("Restore windows cleared, ready for next item")); +} + +// 截取指定 UMG 控件画面并保存为 PNG +// 流程: 计算控件尺寸 -> 创建渲染目标 -> 绘制控件 -> 读像素 -> 转 PNG -> 存盘 +bool ULQARestoreManager::CaptureWidgetScreenshot(UUserWidget* Widget, const FString& FilePath) +{ + // UMG 绘制及 GameThread_GetRenderTargetResource 应在游戏线程执行 + if (!IsInGameThread()) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("CaptureWidgetScreenshot must run on the game thread")); + return false; + } + + if (!IsValid(Widget)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Widget is invalid")); + return false; + } + + if (FilePath.IsEmpty()) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Screenshot file path is empty")); + return false; + } + + // 更新布局预计算 + Widget->ForceLayoutPrepass(); + + const FGeometry& CachedGeometry = Widget->GetCachedGeometry(); + const FVector2D LogicalSize = CachedGeometry.GetLocalSize(); + + const float DrawScale = CachedGeometry.GetAccumulatedLayoutTransform().GetScale(); + const float SafeScale = (DrawScale > KINDA_SMALL_NUMBER) ? DrawScale : 1.0f; + + // DrawSize 使用物理像素 (逻辑尺寸 * DPI 缩放), 与窗口的实际像素尺寸一致 + const FVector2D DrawSize = LogicalSize * SafeScale; + + if (!FMath::IsFinite(DrawSize.X) || !FMath::IsFinite(DrawSize.Y) || + DrawSize.X <= 0.0 || DrawSize.Y <= 0.0) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Invalid widget size: %fx%f"), DrawSize.X, DrawSize.Y); + return false; + } + + + const int32 Width = FMath::CeilToInt(DrawSize.X); + const int32 Height = FMath::CeilToInt(DrawSize.Y); + const int64 RequiredBytes = static_cast(Width) * Height * 4; + + if (Width <= 0 || Height <= 0 || RequiredBytes > MAX_int32) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Screenshot size is too large: %dx%d"), Width, Height); + return false; + } + + // 确保输出目录存在 + const FString OutputDirectory = FPaths::GetPath(FilePath); + + if (!OutputDirectory.IsEmpty() && !IFileManager::Get().DirectoryExists(*OutputDirectory)) + { + if (!IFileManager::Get().MakeDirectory(*OutputDirectory, true)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to create directory: %s"), *OutputDirectory); + return false; + } + } + + // 创建渲染目标 + TStrongObjectPtr RenderTarget( + FWidgetRenderer::CreateTargetFor(FVector2D(Width, Height), TF_Bilinear, /*bUseGammaCorrection=*/false)); + + if (!RenderTarget.IsValid()) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to create render target")); + return false; + } + + // 用作用域守卫保证任何退出路径都会释放 RT 的 GPU 资源 + ON_SCOPE_EXIT + { + if (RenderTarget.IsValid()) + { + RenderTarget->ReleaseResource(); + } + }; + + // 绘制控件及其子控件 + TUniquePtr WidgetRenderer = MakeUnique(false); + + WidgetRenderer->DrawWidget(RenderTarget.Get(), Widget->TakeWidget(), SafeScale, FVector2D(Width, Height), 0.0f); + + // 同步等待渲染完成, 之后再读取像素 + FlushRenderingCommands(); + + FTextureRenderTargetResource* RTResource = RenderTarget->GameThread_GetRenderTargetResource(); + + if (!RTResource) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to get render target resource")); + return false; + } + + TArray OutBMP; + + if (!RTResource->ReadPixels(OutBMP)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to read pixels from render target")); + return false; + } + + // 编码始终以渲染目标实际尺寸为准 + const int32 ImageWidth = RenderTarget->SizeX; + const int32 ImageHeight = RenderTarget->SizeY; + + const int64 ExpectedPixelCount = static_cast(ImageWidth) * ImageHeight; + + if (static_cast(OutBMP.Num()) != ExpectedPixelCount) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Pixel count mismatch: RT=%dx%d, Pixels=%d"), ImageWidth, ImageHeight, + OutBMP.Num()); + return false; + } + +#if ENGINE_MAJOR_VERSION >= 5 + // FImageView 直接指向 OutBMP 的像素, 不拷贝数据: FColor 数组即 BGRA8 + const FImageView ImageView(OutBMP.GetData(), ImageWidth, ImageHeight); + TArray64 CompressedData; + if (!FImageUtils::CompressImage(CompressedData, TEXT("png"), ImageView)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to compress image to PNG")); + return false; + } +#else + TArray CompressedData; + FImageUtils::CompressImageArray(ImageWidth, ImageHeight, OutBMP, CompressedData); +#endif + + if (CompressedData.Num() == 0) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("PNG compression returned empty data")); + return false; + } + + if (!FFileHelper::SaveArrayToFile(CompressedData, *FilePath)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to save screenshot to: %s"), *FilePath); + return false; + } + + UE_LOG(LogLQARestoreManager, Log, TEXT("Widget screenshot saved to: %s (Size: %dx%d)"), *FilePath, ImageWidth, + ImageHeight); + + return true; +} + +// 截取当前游戏视口画面 (含 UI) 并保存为 PNG +// 流程: 取视口控件 -> Slate 截图 -> 转 PNG -> 存盘 +bool ULQARestoreManager::CaptureViewportScreenshot(const FString& FilePath) +{ + UGameViewportClient* ViewportClient = GetWorld()->GetGameViewport(); + if (!ViewportClient) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to get GameViewportClient")); + return false; + } + + // 取游戏视口控件 + const TSharedPtr ViewportWidget = ViewportClient->GetGameViewportWidget(); + if (!ViewportWidget.IsValid() || !FSlateApplication::IsInitialized()) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to get game viewport widget")); + return false; + } + + // 确保输出目录存在, 否则 SaveArrayToFile 会直接失败 + const FString OutputDirectory = FPaths::GetPath(FilePath); + + if (!OutputDirectory.IsEmpty() && !IFileManager::Get().DirectoryExists(*OutputDirectory)) + { + if (!IFileManager::Get().MakeDirectory(*OutputDirectory, true)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to create directory: %s"), *OutputDirectory); + return false; + } + } + + TArray Bitmap; + FIntVector Size(0, 0, 0); + if (!FSlateApplication::Get().TakeScreenshot(ViewportWidget.ToSharedRef(), Bitmap, Size)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to take screenshot of game viewport")); + return false; + } + + const int64 ExpectedPixelCount = static_cast(Size.X) * Size.Y; + if (Size.X <= 0 || Size.Y <= 0 || static_cast(Bitmap.Num()) != ExpectedPixelCount) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Pixel count mismatch: ViewportWidget=%dx%d, Pixels=%d"), Size.X, Size.Y, + Bitmap.Num()); + return false; + } + +#if ENGINE_MAJOR_VERSION >= 5 + const FImageView ImageView(Bitmap.GetData(), Size.X, Size.Y); + TArray64 CompressedData; + if (!FImageUtils::CompressImage(CompressedData, TEXT("png"), ImageView)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to compress image to PNG")); + return false; + } +#else + TArray CompressedData; + FImageUtils::CompressImageArray(Size.X, Size.Y, Bitmap, CompressedData); +#endif + + if (CompressedData.Num() == 0) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("PNG compression returned empty data")); + return false; + } + + if (!FFileHelper::SaveArrayToFile(CompressedData, *FilePath)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to save screenshot to: %s"), *FilePath); + return false; + } + + UE_LOG(LogLQARestoreManager, Log, TEXT("Screenshot saved to: %s (Size: %dx%d)"), *FilePath, Size.X, Size.Y); + return true; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowProxy.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowProxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..486f47cf8cd211f69e53a794685f863bfe584ff2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowProxy.cpp @@ -0,0 +1,862 @@ +#include "Core/RestoreWindowProxy.h" + +#include "LQABase.h" +#include "Blueprint/SlateBlueprintLibrary.h" +#include "Components/Image.h" +#include "Components/NamedSlotInterface.h" +#include "Core/LQARestoreManager.h" +#include "Core/RestoreWindowUtils.h" +#include "Core/RootObjWidget.h" +#include "Engine/Engine.h" +#include "Framework/Application/SlateApplication.h" +#include "TimerManager.h" +#include "Types/ReflectionMetadata.h" +#include "Utils/GeometryUtils.h" +#include "Utils/TranslationUtils/LoaderUtils.h" +#include "WidgetSlots/Core/WidgetDefines.h" +#include "Widgets/SWidget.h" +#include "Widgets/SWindow.h" + +// ============================================================================ +// 匿名命名空间 —— 常量定义 (Anonymous Namespace - Constants) +// 这些常量仅在本编译单元内可见, 用于避免污染全局命名空间 +// ============================================================================ + +namespace +{ +// 控件初始化延迟时间 (单位: 秒) +constexpr float WidgetReadyDelayTime = 0.5f; + +// UserWidget 可见性校验的重叠比例阈值 (低于该值则忽略) +constexpr float OverlapRatioThreshold = 0.6f; + +// 控件类型名称常量 +namespace WidgetTypeNames +{ +constexpr const TCHAR* Undefined = TEXT("UNDEFINE"); // 未定义占位类型 +constexpr const TCHAR* FigmaScrollBox = TEXT("SFigmaScrollBox"); // Figma 滚动框 +constexpr const TCHAR* FigmaObjectWidget = TEXT("SFigmaObjectWidget"); // Figma 对象控件 +} + +// 无效文本键常量 (当节点缺少 TextKey 时使用) +constexpr const TCHAR* InvalidTextKey = TEXT(",INVALIDKEY"); + +// JSON 字段名常量集合 +namespace JsonFieldNames +{ +constexpr const TCHAR* WidgetTypeField = TEXT("WidgetType"); // 控件类型 +constexpr const TCHAR* WidgetNameField = TEXT("WidgetName"); // 控件名称 +constexpr const TCHAR* ChildNodesField = TEXT("ChildNodes"); // 子节点数组 +constexpr const TCHAR* SlotTypeField = TEXT("SlotType"); // 插槽类型 +constexpr const TCHAR* SlotField = TEXT("Slot"); // 插槽数据 +constexpr const TCHAR* SlotNameField = TEXT("SlotName"); // 命名插槽名 (如 Header/Body) +constexpr const TCHAR* CornersField = TEXT("corners"); // 四角坐标 (小写) +constexpr const TCHAR* ObjectDataField = TEXT("ObjectData"); // 对象数据 (大写) +constexpr const TCHAR* PageWidthField = TEXT("PageWidth"); // 页面宽度 +constexpr const TCHAR* PageHeightField = TEXT("PageHeight"); // 页面高度 +constexpr const TCHAR* LocalSizeField = TEXT("LocalSize"); // 本地尺寸 +constexpr const TCHAR* ParentCornersField = TEXT("ParentCorners"); // 父节点四角坐标 +constexpr const TCHAR* SourceStringField = TEXT("SourceString"); // 源字符串 (原文) +constexpr const TCHAR* TextKeyField = TEXT("TextKey"); // 文本键 +constexpr const TCHAR* TranslateStringField = TEXT("TranslateString"); // 翻译后字符串 +constexpr const TCHAR* HintTextField = TEXT("HintText"); // 提示文本 +constexpr const TCHAR* TextField = TEXT("Text"); // 文本 (大写) +constexpr const TCHAR* TextLowerField = TEXT("text"); // 文本 (小写) +constexpr const TCHAR* HintTextStrField = TEXT("hinttextStr"); // 提示文本字符串 +constexpr const TCHAR* HintTextSourceStrField = TEXT("HintTextSourceStr"); // 提示文本原文 +constexpr const TCHAR* HintTextKeyField = TEXT("HintTextKey"); // 提示文本键 +constexpr const TCHAR* TextStrField = TEXT("textStr"); // 文本字符串 +constexpr const TCHAR* UpperCornersField = TEXT("Corners"); // 四角坐标 (大写) +constexpr const TCHAR* LowerObjectDataField = TEXT("objectData"); // 对象数据 (小写) +constexpr const TCHAR* XField = TEXT("x"); // X 坐标字段 +constexpr const TCHAR* YField = TEXT("y"); // Y 坐标字段 +} +} + +// ============================================================================ +// 生命周期管理 (Lifecycle Management) +// ============================================================================ + +// 关闭编译器优化 (通常用于调试, 方便断点与变量查看) +LQA_DISABLE_OPTIMIZATION + +void URestoreWindowProxy::Initialize(int32 InWindowId, UGameInstance* InGameInstance) +{ + // 保存窗口 ID + WindowId = InWindowId; + // 创建主画布面板对象 + WindowPanel = NewObject(this); + // 缓存游戏实例引用 + CachedGameInstance = InGameInstance; + + // 纯 C++ 方式创建 LQA 还原根控件 (不依赖蓝图资源) + RootObj = CreateWidget(GetWorld(), URootObjWidget::StaticClass()); + if (!RootObj) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to create RootObjWidget")); + } + + // 设置延迟定时器: 延迟 WidgetReadyDelayTime 秒后回调 OnWidgetSystemReady + // 目的是等待控件系统完成初始化后再进行后续绘制 + if (CachedGameInstance) + { + CachedGameInstance->GetTimerManager().SetTimer(TimerHandle, + FTimerDelegate::CreateUObject(this, &URestoreWindowProxy::OnWidgetSystemReady), WidgetReadyDelayTime, + false); + } +} + +void URestoreWindowProxy::CreateWindow(const FVector2D& Size) +{ + // 将根控件添加到视口, 使用 WindowId 作为 ZOrder + if (RootObj) + { + RootObj->AddToViewport(WindowId); + } +} + +void URestoreWindowProxy::DestroyWindow() +{ + // 将根控件从父级移除并置空 + if (RootObj) + { + RootObj->RemoveFromParent(); + RootObj = nullptr; + } + + // 清空共享纹理缓存, 释放对象引用 + SharedTextureMap.Empty(); + WindowPanel = nullptr; + CachedGameInstance = nullptr; +} + +void URestoreWindowProxy::OnWidgetSystemReady() +{ + // 控件系统就绪后初始化根控件的缩放 + if (RootObj) + { + RootObj->InitScale(); + } + // 标记为可以绘制 + bIsReadyToDraw = true; +} + +// ============================================================================ +// 控件与面板管理 (Widget & Panel Management) +// ============================================================================ + +void URestoreWindowProxy::DetermineScrollContext(const FString& PanelType, + const TSharedPtr& PanelJsonObject, bool ParentScroll, + const TArray>& ParentScrollCorners, bool& OutIsScroll, + TArray>& OutScrollCorners) +{ + using namespace JsonFieldNames; + + // 若当前面板本身即为 Figma 滚动框, 则以自身的四角坐标作为滚动区域 + if (PanelType == WidgetTypeNames::FigmaScrollBox) + { + OutIsScroll = true; + OutScrollCorners = PanelJsonObject->GetArrayField(CornersField); + } + else + { + // 否则继承父节点的滚动状态与滚动区域 + OutIsScroll = ParentScroll; + OutScrollCorners = ParentScrollCorners; + } +} + +void URestoreWindowProxy::HandleUserWidget(UWidget* UserWidgetAsWidget, + const TSharedPtr& UserWidgetJsonObject, UPanelWidget* UserWidgetParentPanel, + const TArray>& ParentCorners, const FRestoreWidgetMeta& UserWidgetMetaData, + UUserWidget*& OutUserWidget, UPanelWidget*& OutUserWidgetParentPanel, + TSharedPtr& OutUserWidgetAdditionalData, FRestoreWidgetMeta& OutUserWidgetMetaData) +{ + using namespace JsonFieldNames; + + // 将传入控件转换为 UserWidget 类型 + OutUserWidget = Cast(UserWidgetAsWidget); + OutUserWidgetParentPanel = UserWidgetParentPanel; + + // 拷贝插槽布局相关数据 + CopyJsonField(UserWidgetJsonObject, OutUserWidgetAdditionalData, SlotField); + CopyJsonField(UserWidgetJsonObject, OutUserWidgetAdditionalData, SlotTypeField); + + // 从 ObjectData 中提取尺寸信息 + if (UserWidgetJsonObject->HasField(ObjectDataField)) + { + const TSharedPtr ObjectData = UserWidgetJsonObject->GetObjectField(ObjectDataField); + + // 设置页面尺寸 (优先取 ObjectData, 缺失时回退到 LocalSize) + if (ObjectData->HasField(PageWidthField)) + { + OutUserWidgetAdditionalData->SetNumberField(PageWidthField, ObjectData->GetNumberField(PageWidthField)); + OutUserWidgetAdditionalData->SetNumberField(PageHeightField, ObjectData->GetNumberField(PageHeightField)); + } + else if (UserWidgetJsonObject->HasField(LocalSizeField)) + { + const TSharedPtr LocalSize = UserWidgetJsonObject->GetObjectField(LocalSizeField); + OutUserWidgetAdditionalData->SetNumberField(PageWidthField, LocalSize->GetNumberField(XField)); + OutUserWidgetAdditionalData->SetNumberField(PageHeightField, LocalSize->GetNumberField(YField)); + } + } + + // 设置附加属性: 父节点四角坐标与控件元数据 + OutUserWidgetAdditionalData->SetArrayField(ParentCornersField, ParentCorners); + OutUserWidgetMetaData = UserWidgetMetaData; +} + +void URestoreWindowProxy::AddUserWidget(UUserWidget* ParentUserWidget, UPanelWidget* CurrentPanel, + UPanelWidget* ParentPanel, const TSharedPtr& UserWidgetAdditionalInfo, + const TSharedPtr& CurrentPanelAdditionalInfo, const FRestoreWidgetMeta& UserWidgetMetaData) +{ + using namespace JsonFieldNames; + + // 校验该 UserWidget 是否应被忽略 (基于与父容器的重叠比例) + const bool bShouldIgnore = ShouldIgnoreUserWidget(UserWidgetAdditionalInfo, CurrentPanelAdditionalInfo); + + // 提取 UserWidget 的尺寸 + FVector2D UserWidgetSize; + UserWidgetSize.X = UserWidgetAdditionalInfo->GetNumberField(PageWidthField); + UserWidgetSize.Y = UserWidgetAdditionalInfo->GetNumberField(PageHeightField); + + // 将 UserWidget 添加到根对象, 传入位置、尺寸、ZOrder 等信息 + RootObj->AddUserWidget(ParentUserWidget, CurrentPanel, ParentPanel, UserWidgetAdditionalInfo, FVector2D(0, 0), + UserWidgetMetaData.WidgetPosition, UserWidgetMetaData.WidgetSize, UserWidgetSize, UserWidgetMetaData.ZOrder, + RootObj->GetPositionScale(), bShouldIgnore); +} + +UPanelWidget* URestoreWindowProxy::AddPanel(UUserWidget* OwningUserWidget, UPanelWidget* OwningUserWidgetParentPanel, + const TSharedPtr& OwningUserWidgetAdditionalInfo, FRestoreWidgetMeta OwningUserWidgetMetaData, + UPanelWidget* ParentPanel, FString ParentPanelType, TArray> ParentCorners, bool ParentScroll, + TArray> ParentScrollCorners, const TSharedPtr& CurrentPanelJsonObject, + const FVector2D& WindowSize, FVector2D RootPos) +{ + using namespace JsonFieldNames; + + // 根对象无效则直接返回 + if (!RootObj) + { + return nullptr; + } + + // 获取 World 实例 (供子控件挂载与文本/图片检查使用) + UWorld* WorldInstance = GetWorldInstance(); + + // 解包 UNDEFINE 占位节点, 获取真正有效的面板 JSON + TSharedPtr PanelJsonObject = UnwrapUndefinedNode(CurrentPanelJsonObject); + if (!PanelJsonObject.IsValid()) + { + return nullptr; + } + + // 获取子节点数组, 若无子节点则返回 + const TArray>* ChildNodes; + if (!PanelJsonObject->TryGetArrayField(ChildNodesField, ChildNodes)) + { + return nullptr; + } + + // 读取当前面板的类型与名称 + FString MyPanelType = PanelJsonObject->GetStringField(WidgetTypeField); + const FString PanelWidgetName = PanelJsonObject->GetStringField(WidgetNameField); + + // 判定滚动上下文 (是否可滚动及滚动区域坐标) + bool bIsScroll = false; + TArray> ScrollCorners; + DetermineScrollContext(MyPanelType, PanelJsonObject, ParentScroll, ParentScrollCorners, bIsScroll, ScrollCorners); + + // 当前面板相关变量 + FRestoreWidgetMeta PanelMetaData; + UPanelWidget* MyPanel = nullptr; + TSharedPtr PanelSlotJsonObject = MakeShared(); + + // 嵌套 UserWidget 的输出变量 (当面板实际为 UserWidget 时, 由 HandleUserWidget 填充) + UUserWidget* OutOwningUserWidget = nullptr; + UPanelWidget* OutOwningUserWidgetParentPanel = nullptr; + TSharedPtr OutOwningUserWidgetAdditionalInfo = MakeShared(); + FRestoreWidgetMeta OutOwningUserWidgetMetaData; + + // 当前面板为 UserWidget 且其根控件是叶子 (而非面板容器) 时, 用于承载这些叶子的临时根容器 + UPanelWidget* LocalRootPanel = nullptr; + + // 处理 UNDEFINE 类型: 直接继承父节点的属性 + if (MyPanelType == WidgetTypeNames::Undefined) + { + MyPanelType = ParentPanelType; + MyPanel = ParentPanel; + bIsScroll = ParentScroll; + ScrollCorners = ParentScrollCorners; + } + else + { + UE_LOG(LogLQARestoreManager, Log, TEXT("URestoreWindowProxy AddPanel WidgetName: %s, PanelType: %s"), *PanelWidgetName, + *MyPanelType); + + // 通过工厂从 JSON 创建面板控件及其元数据 + PanelMetaData = FWidget2JsonFactory::WidgetFromJsonForPanel(PanelJsonObject, WindowSize, this); + UWidget* PanelWidget = PanelMetaData.WidgetIns; + if (!PanelWidget) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("URestoreWindowProxy WidgetFromJsonForPanel: %s"), *PanelWidgetName); + return nullptr; + } + + // 若存在插槽数据则进行拷贝 + CopyJsonField(PanelJsonObject, PanelSlotJsonObject, SlotField); + CopyJsonField(PanelJsonObject, PanelSlotJsonObject, SlotTypeField); + + // 尝试将控件转换为 PanelWidget (容器类型) + MyPanel = Cast(PanelWidget); + if (!MyPanel) + { + // 控件为 UserWidget (叶子类型, 而非容器) + // 填充嵌套 UserWidget 的输出变量, 供递归处理使用 + HandleUserWidget(PanelWidget, PanelJsonObject, ParentPanel, ParentCorners, PanelMetaData, + OutOwningUserWidget, OutOwningUserWidgetParentPanel, OutOwningUserWidgetAdditionalInfo, + OutOwningUserWidgetMetaData); + } + + // 命名插槽容器 (INamedSlotInterface, 如 UExpandableArea): 不是 UPanelWidget, + // 其内容需通过 SetContentForSlot 挂载。 + // 注意: UUserWidget 也实现 INamedSlotInterface, 但它已由 HandleUserWidget 识别 + // (OutOwningUserWidget 非空); 此处用 !MyPanel && !OutOwningUserWidget 排除 + // 普通面板与 UserWidget, 避免误伤。 + if (!MyPanel && !OutOwningUserWidget) + { + if (INamedSlotInterface* NamedSlotContainer = Cast(PanelWidget)) + { + // 先把容器本身挂载到父面板 + if (ParentPanel) + { + RootObj->AddWidgetInPanel(ParentPanel, RootPos, ParentPanelType, PanelWidget, + MakeShared(PanelSlotJsonObject), PanelMetaData.WidgetPosition, + PanelMetaData.WidgetSize, PanelMetaData.ZOrder, PanelMetaData.Property, WorldInstance); + } + + // 还原各命名插槽内容 (如 Header/Body) + RestoreNamedSlotChildren(NamedSlotContainer, *ChildNodes, WindowSize, WorldInstance); + + return nullptr; + } + } + + // 能容纳 UMG 子控件 + if (!MyPanel && !OutOwningUserWidget) + { + if (ParentPanel) + { + RootObj->AddWidgetInPanel(ParentPanel, RootPos, ParentPanelType, PanelWidget, + MakeShared(PanelSlotJsonObject), PanelMetaData.WidgetPosition, + PanelMetaData.WidgetSize, PanelMetaData.ZOrder, PanelMetaData.Property, WorldInstance); + } + return nullptr; + } + + // 仅当为顶层面板 (未嵌套于其他 UserWidget) 时, 才将面板加入根对象 + // OwningUserWidget == nullptr 表示这是独立面板, 而非某个父 UserWidget 的一部分 + if (!OwningUserWidget) + { + RootObj->AddPanel(ParentPanel, // 父面板 + ParentPanelType, // 父面板类型 + FVector2D(0, 0), // 父节点根位置 + MyPanel, // 当前面板 + MyPanelType, // 当前面板类型 + PanelMetaData.WidgetPosition, // 面板位置 + PanelMetaData.WidgetSize, // 面板尺寸 + OutOwningUserWidget, // UserWidget 实例 + PanelSlotJsonObject, // 面板插槽信息 + PanelMetaData.ZOrder, // ZOrder 层级 + RootObj->GetPositionScale()); // 位置缩放 + } + } + + // 是否需要计算滚动相关逻辑 (取决于父节点是否可滚动) + const bool bNeedCalScroll = ParentScroll; + + // 遍历并处理所有子节点 + for (const TSharedPtr& ChildNode : *ChildNodes) + { + TSharedPtr ChildJsonObject = ChildNode->AsObject(); + if (!ChildJsonObject.IsValid()) + { + continue; + } + + // 读取子控件的名称与类型 + FString ChildWidgetName, ChildWidgetType; + ChildJsonObject->TryGetStringField(WidgetNameField, ChildWidgetName); + ChildJsonObject->TryGetStringField(WidgetTypeField, ChildWidgetType); + + // 确定子控件的四角坐标 (UNDEFINE 类型继承父节点坐标) + TArray> ChildPanelCorners = ChildJsonObject->GetArrayField(CornersField); + if (ChildWidgetType == WidgetTypeNames::Undefined) + { + ChildPanelCorners = ParentCorners; + } + + // 针对 FigmaObjectWidget 校验其与滚动框的重叠; 若无重叠则跳过 + if (bNeedCalScroll && ChildWidgetType == WidgetTypeNames::FigmaObjectWidget) + { + if (!ValidateScrollBoxOverlap(ChildPanelCorners, ParentScrollCorners, ChildWidgetName)) + { + continue; + } + } + + // 若子节点仍含有子节点, 则递归处理 (即容器类控件) + if (HasChildNodes(ChildJsonObject)) + { + AddPanel(OutOwningUserWidget, OutOwningUserWidgetParentPanel, OutOwningUserWidgetAdditionalInfo, + OutOwningUserWidgetMetaData, MyPanel, MyPanelType, ChildPanelCorners, bIsScroll, ScrollCorners, + ChildJsonObject, WindowSize, PanelMetaData.WidgetPosition); + } + else // 处理叶子节点 (不含子节点的最终控件) + { + // 当前面板是 UserWidget (非面板容器) 时, 叶子节点应挂载到该 UserWidget 的根容器上。 + // 某些 UserWidget 的根控件直接是叶子 (如 TextBlock), 若直接跳过会导致整个条目内容丢失, + // 因此这里为其创建一个临时根容器承载这些叶子。 + if (OutOwningUserWidget) + { + if (!LocalRootPanel) + { + LocalRootPanel = NewObject(this); + } + + const FRestoreWidgetMeta ChildMetaData = + FWidget2JsonFactory::WidgetFromJson(ChildJsonObject, WindowSize, this); + if (!ChildMetaData.WidgetIns) + { + continue; + } + + // 处理叶子节点的文本字段与翻译 + ProcessLeafNodeTextData(ChildJsonObject); + + // 将叶子控件挂载到临时根容器 + AddChildToPanel( + LocalRootPanel, PanelMetaData.WidgetPosition, MyPanelType, ChildJsonObject, ChildMetaData, WorldInstance); + continue; + } + + // 从 JSON 创建控件元数据 + const FRestoreWidgetMeta ChildMetaData = FWidget2JsonFactory::WidgetFromJson(ChildJsonObject, WindowSize, this); + if (!ChildMetaData.WidgetIns) + { + continue; + } + + // 处理叶子节点的文本字段与翻译 + ProcessLeafNodeTextData(ChildJsonObject); + + // 将叶子控件添加到当前面板中 + AddChildToPanel(MyPanel, RootPos, MyPanelType, ChildJsonObject, ChildMetaData, WorldInstance); + } + } + + // 若存在拥有者 UserWidget, 则在处理完子节点后将其添加 + if (OwningUserWidget) + { + AddUserWidget(OwningUserWidget, MyPanel, OwningUserWidgetParentPanel, OwningUserWidgetAdditionalInfo, + PanelJsonObject, OwningUserWidgetMetaData); + } + else if (OutOwningUserWidget && LocalRootPanel) + { + // 当前面板自身是 UserWidget, 且其根控件是叶子 (而非面板容器) 时的兜底挂载: + // 把临时根容器设为该 UserWidget 的根控件并挂载到父面板, 避免条目内容丢失。 + AddUserWidget(OutOwningUserWidget, LocalRootPanel, OutOwningUserWidgetParentPanel, + OutOwningUserWidgetAdditionalInfo, PanelJsonObject, OutOwningUserWidgetMetaData); + } + + // 返回当前创建的面板 + return MyPanel; +} + +// ============================================================================ +// 视觉更新 (Visual Updates) +// ============================================================================ + +void URestoreWindowProxy::ProcessImageBackground(const FString& ImagePath) +{ + // 委托根对象处理背景图片更新 + if (RootObj) + { + RootObj->ProcessImageBackground(ImagePath); + } +} + +// ============================================================================ +// JSON 处理工具 (JSON Processing Utilities) +// ============================================================================ + +TSharedPtr URestoreWindowProxy::UnwrapUndefinedNode(TSharedPtr NodeJson) +{ + using namespace JsonFieldNames; + const FString WidgetType = NodeJson->GetStringField(WidgetTypeField); + + // 仅处理 UNDEFINE 类型节点 + if (WidgetType == WidgetTypeNames::Undefined) + { + const TArray> ChildNodesJson = NodeJson->GetArrayField(ChildNodesField); + if (ChildNodesJson.Num() == 1) + { + // 仅有一个子节点时, 继续向下解包 + TSharedPtr ChildNode = ChildNodesJson[0]->AsObject(); + // 若当前节点含插槽信息而子节点没有, 则将插槽信息下传给子节点 + if (NodeJson->HasField(SlotTypeField) && !ChildNode->HasField(SlotTypeField)) + { + CopyJsonField(NodeJson, ChildNode, SlotField); + CopyJsonField(NodeJson, ChildNode, SlotTypeField); + } + return UnwrapUndefinedNode(ChildNode); + } + else if (ChildNodesJson.Num() == 0) + { + // 无子节点, 视为无效 + return nullptr; + } + + // 多个子节点时无法继续解包, 返回当前节点 + return NodeJson; + } + // 非 UNDEFINE 节点直接返回 + return NodeJson; +} + +void URestoreWindowProxy::CopyJsonField( + const TSharedPtr& Source, TSharedPtr& Target, const FString& FieldName) +{ + // 源或目标无效则不处理 + if (!Source.IsValid() || !Target.IsValid()) + { + return; + } + + // 源存在该字段时, 将其值拷贝到目标 + if (Source->HasField(FieldName)) + { + const TSharedPtr FieldValue = Source->TryGetField(FieldName); + if (FieldValue.IsValid()) + { + Target->SetField(FieldName, FieldValue); + } + } +} + +bool URestoreWindowProxy::HasChildNodes(const TSharedPtr& JsonObject) const +{ + using namespace JsonFieldNames; + // 同时满足 “存在 ChildNodes 字段” 且 “数组非空” 才算有子节点 + return JsonObject->HasField(ChildNodesField) && JsonObject->GetArrayField(ChildNodesField).Num() > 0; +} + +UWorld* URestoreWindowProxy::GetWorldInstance() const +{ + if (!RootObj) + { + return nullptr; + } + + // 通过 Slate 反射元数据取得源对象的 World + const TSharedRef SlateWidget = RootObj->TakeWidget(); + const TSharedPtr MetaData = SlateWidget->GetMetaData(); + if (MetaData.IsValid()) + { + const TWeakObjectPtr SourceObject = MetaData->SourceObject; + return SourceObject->GetWorld(); + } + return nullptr; +} + +void URestoreWindowProxy::AddChildToPanel(UPanelWidget* Panel, const FVector2D& PanelPosition, const FString& PanelType, + const TSharedPtr& ChildJsonObject, const FRestoreWidgetMeta& ChildMeta, UWorld* WorldInstance) +{ + using namespace JsonFieldNames; + + // 拷贝插槽数据 + TSharedPtr SlotObject = MakeShared(); + CopyJsonField(ChildJsonObject, SlotObject, SlotField); + CopyJsonField(ChildJsonObject, SlotObject, SlotTypeField); + + // 将子控件挂载到面板 + RootObj->AddWidgetInPanel(Panel, PanelPosition, PanelType, ChildMeta.WidgetIns, + MakeShared(SlotObject), ChildMeta.WidgetPosition, ChildMeta.WidgetSize, ChildMeta.ZOrder, + ChildMeta.Property, WorldInstance); +} + +// ============================================================================ +// 命名插槽内容还原 (Named Slot Content Restoration) +// ============================================================================ + +void URestoreWindowProxy::RestoreNamedSlotChildren(INamedSlotInterface* NamedSlotContainer, + const TArray>& ChildNodes, const FVector2D& WindowSize, UWorld* WorldInstance) +{ + using namespace JsonFieldNames; + + if (!NamedSlotContainer) + { + return; + } + + // 遍历各命名插槽子节点 (如 Header/Body) + for (const TSharedPtr& ChildNode : ChildNodes) + { + const TSharedPtr ChildJsonObject = ChildNode->AsObject(); + if (!ChildJsonObject.IsValid()) + { + continue; + } + + // 读取命名插槽名 (采集侧写入的 SlotName 字段) + FString SlotName; + ChildJsonObject->TryGetStringField(SlotNameField, SlotName); + if (SlotName.IsEmpty()) + { + continue; + } + + // 递归还原该命名插槽内容子树, 并通过 SetContentForSlot 挂载 + const FRestoreWidgetMeta ContentMeta = RestoreNamedSlotContent(ChildJsonObject, WindowSize, WorldInstance); + if (ContentMeta.WidgetIns) + { + NamedSlotContainer->SetContentForSlot(FName(*SlotName), ContentMeta.WidgetIns); + } + } +} + +FRestoreWidgetMeta URestoreWindowProxy::RestoreNamedSlotContent( + const TSharedPtr& JsonObject, const FVector2D& WindowSize, UWorld* WorldInstance) +{ + using namespace JsonFieldNames; + + FRestoreWidgetMeta Meta; + if (!JsonObject.IsValid()) + { + return Meta; + } + + // 容器节点: 还原面板并递归挂载其子节点 + if (HasChildNodes(JsonObject)) + { + Meta = FWidget2JsonFactory::WidgetFromJsonForPanel(JsonObject, WindowSize, this); + if (!Meta.WidgetIns) + { + return Meta; + } + + if (UPanelWidget* Panel = Cast(Meta.WidgetIns)) + { + const FString PanelType = JsonObject->GetStringField(WidgetTypeField); + const TArray>& ChildNodes = JsonObject->GetArrayField(ChildNodesField); + + for (const TSharedPtr& ChildNode : ChildNodes) + { + const TSharedPtr ChildJsonObject = ChildNode->AsObject(); + if (!ChildJsonObject.IsValid()) + { + continue; + } + + // 递归还原子节点 + const FRestoreWidgetMeta ChildMeta = + RestoreNamedSlotContent(ChildJsonObject, WindowSize, WorldInstance); + if (!ChildMeta.WidgetIns) + { + continue; + } + + // 将子控件挂载到当前面板 + AddChildToPanel(Panel, Meta.WidgetPosition, PanelType, ChildJsonObject, ChildMeta, WorldInstance); + } + } + } + else + { + // 叶子节点: 还原控件并处理文本翻译 + Meta = FWidget2JsonFactory::WidgetFromJson(JsonObject, WindowSize, this); + if (Meta.WidgetIns) + { + // ProcessLeafNodeTextData 会就地修改 JSON, 因此使用可变副本 + TSharedPtr MutableJson = JsonObject; + ProcessLeafNodeTextData(MutableJson); + } + } + + return Meta; +} + +// ============================================================================ +// 文本与翻译处理 (Text & Translation Processing) +// ============================================================================ + +void URestoreWindowProxy::ProcessLeafNodeTextData(TSharedPtr& LeafNodeJsonObject) +{ + using namespace JsonFieldNames; + + // 处理文本翻译: 同时存在原文与文本键时, 获取翻译结果并写回 + if (LeafNodeJsonObject->HasField(SourceStringField) && LeafNodeJsonObject->HasField(TextKeyField)) + { + const FString NewText = FLoaderUtils::GetTranslateString( + LeafNodeJsonObject->GetStringField(TextKeyField), LeafNodeJsonObject->GetStringField(SourceStringField)); + LeafNodeJsonObject->SetStringField(TranslateStringField, NewText); + } + + // 获取或准备 TextKey 值 (缺失时使用无效键常量) + FString TextKeyValue; + if (!LeafNodeJsonObject->TryGetStringField(TextKeyField, TextKeyValue)) + { + TextKeyValue = InvalidTextKey; + } + + // 处理 objectData, 提取 HintText 与 Text 字段 + const TSharedPtr ObjectDataObject = LeafNodeJsonObject->GetObjectField(LowerObjectDataField); + if (ObjectDataObject.IsValid()) + { + // 从 objectData 中提取提示文本 (HintText) + if (ObjectDataObject->HasField(HintTextField)) + { + const FString HintText = ObjectDataObject->GetStringField(HintTextField); + // 仅当叶子节点尚无提示文本字段时才写入, 避免覆盖已有数据 + if (!LeafNodeJsonObject->HasField(HintTextStrField)) + { + LeafNodeJsonObject->SetStringField(HintTextStrField, HintText); + LeafNodeJsonObject->SetStringField(HintTextSourceStrField, HintText); + LeafNodeJsonObject->SetStringField(HintTextKeyField, TextKeyValue); + } + } + + // 从 objectData 中提取正文文本 (Text) + if (ObjectDataObject->HasField(TextField)) + { + const FString Text = ObjectDataObject->GetStringField(TextLowerField); + // 仅当叶子节点尚无文本字段时才写入 + if (!LeafNodeJsonObject->HasField(TextStrField)) + { + LeafNodeJsonObject->SetStringField(TextStrField, Text); + LeafNodeJsonObject->SetStringField(SourceStringField, Text); + LeafNodeJsonObject->SetStringField(TextKeyField, TextKeyValue); + } + } + } +} + +// ============================================================================ +// 校验工具 (Validation Utilities) +// ============================================================================ + +bool URestoreWindowProxy::ValidateScrollBoxOverlap(const TArray>& ChildWidgetCorners, + const TArray>& ScrollBoxCorners, const FString& ChildWidgetName) const +{ + // 将 JSON 坐标数组转换为 FVector2D 点集 + TArray ScrollBoxPoints; + TArray ChildWidgetPoints; + + FGeometryUtils::JsonArrayToVector2DArray(ScrollBoxCorners, ScrollBoxPoints); + FGeometryUtils::JsonArrayToVector2DArray(ChildWidgetCorners, ChildWidgetPoints); + + // 判断子控件多边形与滚动框多边形是否重叠 + const bool bOverlap = FGeometryUtils::DoPolygonsOverlap(ChildWidgetPoints, ScrollBoxPoints); + +#if !UE_BUILD_SHIPPING + // 非发行版本下, 若无重叠则打印调试信息便于排查 + if (!bOverlap) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("No intersection, %s"), *ChildWidgetName); + FGeometryUtils::PrintJsonArrayPoints(ScrollBoxCorners, TEXT("ParentScrollCorners")); + FGeometryUtils::PrintJsonArrayPoints(ChildWidgetCorners, TEXT("ChildPanelCorners")); + } +#endif + + return bOverlap; +} + +bool URestoreWindowProxy::ShouldIgnoreUserWidget( + const TSharedPtr& UserWidgetPanelJsonObject, const TSharedPtr& PanelJsonObject) const +{ + using namespace JsonFieldNames; + + // 若不存在父节点四角坐标, 则无法判断, 默认不忽略 + if (!UserWidgetPanelJsonObject->HasField(ParentCornersField)) + { + return false; + } + + // 从 JSON 中读取父容器与 UserWidget 的四角坐标 + const TArray> ParentContainerCornersJson = + UserWidgetPanelJsonObject->GetArrayField(ParentCornersField); + const TArray> UserWidgetCornersJson = PanelJsonObject->GetArrayField(UpperCornersField); + + // 将 JSON 坐标解析为 FVector2D 数组 + TArray ParentContainerCorners, UserWidgetCorners; + if (!FGeometryUtils::ParseCornersFromJsonArray(ParentContainerCornersJson, ParentContainerCorners) || + !FGeometryUtils::ParseCornersFromJsonArray(UserWidgetCornersJson, UserWidgetCorners)) + { + return false; + } + + // 计算两者的包围盒及其重叠比例 + const FBox2D ParentContainerBox = FGeometryUtils::GetBoundingBox(ParentContainerCorners); + const FBox2D UserWidgetBox = FGeometryUtils::GetBoundingBox(UserWidgetCorners); + const float OverlapRatio = FGeometryUtils::GetOverlapRatio(ParentContainerBox, UserWidgetBox); + + // 重叠比例低于阈值则忽略该 UserWidget + return OverlapRatio < OverlapRatioThreshold; +} + +// ============================================================================ +// 校验与导出 (Validation & Export) +// ============================================================================ + +void URestoreWindowProxy::GenerateCheckCorners(FString CheckInfoFilePath, TArray CheckParentWidgets) +{ + if (RootObj) + { + // 通过 Slate 反射元数据获取 World 实例 + TSharedRef SlateWidget = RootObj->TakeWidget(); + const TSharedPtr MetaData = SlateWidget->GetMetaData(); + UWorld* WorldInstance; + + // 文本与图片的校验信息列表 + TArray> CheckTextList; + TArray> CheckImageList; + + if (MetaData.IsValid()) + { + TWeakObjectPtr SourceObject = MetaData->SourceObject; + WorldInstance = SourceObject->GetWorld(); + // 收集指定父控件下的文本与图片校验信息 + CheckTextList = RootObj->GetTextCheckInfo(WorldInstance, CheckParentWidgets); + CheckImageList = RootObj->GetImageCheckInfo(WorldInstance, CheckParentWidgets); + } + else + { + WorldInstance = nullptr; + UE_LOG(LogLQARestoreManager, Error, TEXT("[LQA] Get Invalid World!")); + } + + // 组装 JSON 对象, 包含 image 与 text 两个数组字段 + TSharedPtr JsonObject = MakeShareable(new FJsonObject()); + + JsonObject->SetArrayField(TEXT("image"), CheckImageList); + JsonObject->SetArrayField(TEXT("text"), CheckTextList); + + // 将 JSON 对象序列化为字符串 + FString JsonString; + TSharedRef> Writer = TJsonWriterFactory<>::Create(&JsonString); + FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer); + + // 转换为 UTF-8 编码并写入目标文件 + FTCHARToUTF8 Converter(*JsonString); + const char* UTF8Data = Converter.Get(); + int32 DataSize = Converter.Length(); + IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile(); + TUniquePtr FileHandle(PlatformFile.OpenWrite(*CheckInfoFilePath)); + if (FileHandle) + { + FileHandle->Write((const uint8*) UTF8Data, DataSize); + } + } +} + +// 恢复编译器优化 +LQA_ENABLE_OPTIMIZATION \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6866edce96d9ed4edc5315f6e8eb436fbc07c17 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RestoreWindowUtils.cpp @@ -0,0 +1,560 @@ +#include "Core/RestoreWindowUtils.h" + +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/Image.h" +#include "Core/RestoreWindowProxy.h" +#include "Core/LQARestoreManager.h" +#include "CoreMinimal.h" +#include "Engine/Engine.h" +#include "Engine/Texture2D.h" +#include "Engine/Texture2DDynamic.h" +#include "IImageWrapper.h" +#include "IImageWrapperModule.h" +#include "ImageUtils.h" +#include "Json.h" +#include "JsonObjectConverter.h" +#include "Kismet/KismetRenderingLibrary.h" +#include "Materials/MaterialInstanceConstant.h" +#include "Materials/MaterialInstanceDynamic.h" +#include "Materials/MaterialInterface.h" +#include "Math/Color.h" +#include "Modules/ModuleManager.h" +#include "Slate/WidgetRenderer.h" +#include "Utils/JsonUtils.h" +#include "Utils/SlateBrushUtils.h" +#include "Utils/TextureUtils.h" +#include "Utils/TranslationUtils/LoaderUtils.h" +#if WITH_EDITOR +#include "Factories/TextureFactory.h" +#endif +#include "WidgetSlots/Core/RestoreWidget2JsonFactory.h" +#include "WidgetSlots/Core/WidgetDefines.h" +#include "WidgetTree/LQAWidgetNode.h" + +// ============================================================================ +// 匿名命名空间 —— 常量定义 +// 使用匿名命名空间使常量仅在本翻译单元 (本 .cpp) 内可见, 避免符号污染 +// ============================================================================ + +namespace +{ +// 顶层父控件检测所用的 Layer (层级) 阈值 +// 层级值小于该阈值的控件才会被视为 “顶层” 候选 +constexpr int32 TopParentLayerThreshold = 10000; +} + +// ============================================================================ +// 静态成员初始化 +// ============================================================================ + +// 还原窗口销毁委托的定义 +FOnRestoreWindowDestroyed FRestoreWindowUtils::OnRestoreWindowDestroyed; +// 校验用父控件列表的定义 +TArray FRestoreWindowUtils::AllCheckParentWidgets; + +// 纯文本控件类型集合: 包含各类文本块、可编辑文本框等, 不含图片 +const TArray FRestoreWindowUtils::PureTextWidgetTypes = {LQAWidgetNames::LQA_TextBlock, + LQAWidgetNames::LQA_RichTextBlock, LQAWidgetNames::LQA_EditableText, LQAWidgetNames::LQA_EditableTextBox, + LQAWidgetNames::LQA_MultilineEditableText, LQAWidgetNames::LQA_MultilineEditableTextBox, + LQAWidgetNames::LQA_LEDRichTextBlock}; + +// 文本与图片控件类型集合: 在纯文本类型基础上额外包含 Image 图片控件 +const TArray FRestoreWindowUtils::TextAndImageWidgetTypes = {LQAWidgetNames::LQA_TextBlock, + LQAWidgetNames::LQA_RichTextBlock, LQAWidgetNames::LQA_EditableText, LQAWidgetNames::LQA_EditableTextBox, + LQAWidgetNames::LQA_MultilineEditableText, LQAWidgetNames::LQA_MultilineEditableTextBox, + LQAWidgetNames::LQA_LEDRichTextBlock, LQAWidgetNames::LQA_Image}; + +// ============================================================================ +// 窗口创建与构建 +// ============================================================================ + +bool FRestoreWindowUtils::CreateWindow(const FString& DumpFilePath, URestoreWindowProxy* WindowProxy) +{ + // 校验 dump 文件是否存在, 不存在则记录错误并返回失败 + if (!FPaths::FileExists(DumpFilePath)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Target Dump File Not Found! Path: %s"), *DumpFilePath); + return false; + } + + // 将 dump 文件内容整体读取为字符串 + FString JsonStr; + FFileHelper::LoadFileToString(JsonStr, *DumpFilePath); + + // 创建 JSON 对象并进行反序列化 + TSharedPtr RootObj = MakeShareable(new FJsonObject()); + const TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonStr); + if (!FJsonSerializer::Deserialize(JsonReader, RootObj)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Dump File Failed! Path: %s"), *DumpFilePath); + return false; + } + + // 从 JSON 中解析出窗口尺寸 + FVector2D WindowSize; + if (!DeserializeWindowSize(RootObj, WindowSize)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Window Size Failed! Path: %s"), *DumpFilePath); + return false; + } + + // 使用解析得到的尺寸创建窗口 + WindowProxy->CreateWindow(WindowSize); + return true; +} + +bool FRestoreWindowUtils::BuildWindow( + const FString& DumpFilePath, URestoreWindowProxy* WindowProxy, TSharedPtr BaseUIDataObj) +{ + // 校验 dump 文件是否存在 + if (!FPaths::FileExists(DumpFilePath)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Target Dump File Not Found! Path: %s"), *DumpFilePath); + return false; + } + + // 读取 dump 文件内容 + FString JsonStr; + if (!FFileHelper::LoadFileToString(JsonStr, *DumpFilePath)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to load dump file! Path: %s"), *DumpFilePath); + return false; + } + + TSharedPtr RootObj; // 最终用于构建 UI 的根 JSON 对象 + FString ObjectParentWidget = TEXT(""); // 需要重点校验的父控件名称 + FVector2D WindowSize; // 窗口尺寸 + // 判断是否传入了有效的基础 UI 数据 + const bool bHasBaseData = BaseUIDataObj.IsValid() && BaseUIDataObj->Values.Num() > 0; + + // 模式一: 将 dump 中的组件配置合并到基础 UI 数据中 + if (bHasBaseData) + { + // 解析 dump 文件以获取组件配置 + TSharedPtr DumpObj = MakeShareable(new FJsonObject()); + TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonStr); + if (!FJsonSerializer::Deserialize(JsonReader, DumpObj)) + { + UE_LOG( + LogTemp, Error, TEXT("Failed to deserialize dump file for component config! Path: %s"), *DumpFilePath); + return false; + } + + // 提前校验窗口尺寸 (快速失败, 避免后续无谓处理) + if (!DeserializeWindowSize(DumpObj, WindowSize)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Window Size Failed! Path: %s"), *DumpFilePath); + return false; + } + + // 提取组件配置字段 componentConfig + const TSharedPtr ComponentConfig = DumpObj->TryGetField(TEXT("componentConfig")); + if (!ComponentConfig.IsValid() || ComponentConfig->Type != EJson::Object) + { + // 未找到组件配置时, 退化为直接加载模式 + UE_LOG(LogLQARestoreManager, Warning, TEXT("Component config not found, fallback to direct load")); + } + else + { + // 从组件配置中读取匹配与替换所需的字段 + const TSharedPtr ConfigObj = ComponentConfig->AsObject(); + const FString ParentWidget = ConfigObj->GetStringField(TEXT("parentWidget")); // 目标父控件 + const FString WidgetName = ConfigObj->GetStringField(TEXT("widgetName")); // 目标控件 + const FString ReplaceText = ConfigObj->GetStringField(TEXT("replaceText")); // 替换文本 + const FString ReplaceKey = ConfigObj->GetStringField(TEXT("replaceKey")); // 替换文本 Key + + UE_LOG(LogLQARestoreManager, Display, TEXT("Component Config - Parent: %s, Widget: %s, Text: %s"), *ParentWidget, + *WidgetName, *ReplaceText); + + // 将替换应用到基础 UI 数据的 uitree 数组中 + const TArray>* UITrees; + if (BaseUIDataObj->TryGetArrayField(TEXT("uitree"), UITrees)) + { + for (const TSharedPtr& TreeValue : *UITrees) + { + if (TreeValue.IsValid() && TreeValue->Type == EJson::Object) + { + // 在该树中递归查找并替换, 成功后记录父控件并跳出循环 + if (ReplaceBaseData(TreeValue->AsObject(), ParentWidget, WidgetName, ReplaceText, ReplaceKey)) + { + ObjectParentWidget = ParentWidget; + break; + } + } + } + } + } + // 以基础 UI 数据作为最终构建数据源 + RootObj = BaseUIDataObj; + } + // 模式二: 直接从 dump 文件加载数据 + else + { + RootObj = MakeShareable(new FJsonObject()); + TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonStr); + if (!FJsonSerializer::Deserialize(JsonReader, RootObj)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Dump File Failed! Path: %s"), *DumpFilePath); + return false; + } + + // 提前校验窗口尺寸 (快速失败) + if (!DeserializeWindowSize(RootObj, WindowSize)) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Window Size Failed! Path: %s"), *DumpFilePath); + return false; + } + } + + // 使用解析得到的窗口尺寸正式构建 UI + UE_LOG(LogLQARestoreManager, Display, TEXT("Deserialize Success! Size: %.0fx%.0f, Path: %s"), WindowSize.X, WindowSize.Y, + *DumpFilePath); + DeserializeData(RootObj, WindowProxy, WindowSize, WindowProxy, ObjectParentWidget); + return true; +} + +bool FRestoreWindowUtils::DeserializeWindowSize(const TSharedPtr& RootObj, FVector2D& OutSize) +{ + TSharedPtr MetaData; + + // 兼容两种元数据字段命名: 优先 gameData, 其次 meta + if (RootObj->HasField(TEXT("gameData"))) + { + MetaData = RootObj->GetObjectField(TEXT("gameData")); + } + else if (RootObj->HasField(TEXT("meta"))) + { + MetaData = RootObj->GetObjectField(TEXT("meta")); + } + else + { + // 两种字段都不存在, 视为失败 + UE_LOG(LogLQARestoreManager, Error, TEXT("Find Meta Data Failed!")); + return false; + } + + // 从元数据中读取 sizeX / sizeY 作为窗口宽高 + if (MetaData->HasField(TEXT("sizeX")) && MetaData->HasField(TEXT("sizeY"))) + { + OutSize.X = MetaData->GetNumberField(TEXT("sizeX")); + OutSize.Y = MetaData->GetNumberField(TEXT("sizeY")); + return true; + } + + UE_LOG(LogLQARestoreManager, Error, TEXT("Deserialize Window Size Failed!")); + return false; +} + +bool FRestoreWindowUtils::ReplaceBaseData(const TSharedPtr& Node, const FString& MatchParentWidget, + const FString& MatchWidgetName, const FString& ReplaceText, const FString& ReplaceKey) +{ + // 节点无效直接返回, 防止空指针访问 + if (!Node.IsValid()) + { + return false; + } + + // 读取当前节点的父控件名与控件名, 用于匹配判断 + const FString ParentWidget = Node->GetStringField(TEXT("ParentWidget")); + const FString WidgetName = Node->GetStringField(TEXT("WidgetName")); + + // 当前节点与目标控件匹配, 执行文本替换 + if (ParentWidget == MatchParentWidget && WidgetName == MatchWidgetName) + { + // 替换节点上的文本相关字段 + Node->SetStringField(TEXT("TextKey"), ReplaceKey); + Node->SetStringField(TEXT("SourceString"), ReplaceText); + Node->SetStringField(TEXT("textStr"), ReplaceText); + + // 若存在 ObjectData 子对象, 也需替换其中的文本字段 + if (Node->HasField(TEXT("ObjectData"))) + { + TSharedPtr ObjectData = Node->GetObjectField(TEXT("ObjectData")); + if (ObjectData.IsValid()) + { + // 兼容多种命名方式的文本字段, 找到第一个即替换并退出 + static const TArray TextFieldNames = { + TEXT("Text"), TEXT("text"), TEXT("HintText"), TEXT("hintText")}; + + for (const FString& FieldName : TextFieldNames) + { + if (ObjectData->HasField(FieldName)) + { + ObjectData->SetStringField(FieldName, ReplaceText); + break; + } + } + } + } + return true; + } + + // 当前节点不匹配, 则递归搜索其子节点 ChildNodes + const TArray>* ChildNodes; + if (Node->TryGetArrayField(TEXT("ChildNodes"), ChildNodes)) + { + for (const TSharedPtr& ChildValue : *ChildNodes) + { + if (ChildValue.IsValid() && ChildValue->Type == EJson::Object) + { + // 任一子节点替换成功即可向上返回 true + if (ReplaceBaseData( + ChildValue->AsObject(), MatchParentWidget, MatchWidgetName, ReplaceText, ReplaceKey)) + { + return true; + } + } + } + } + + // 整棵子树均未匹配 + return false; +} + +// ============================================================================ +// 控件类型检测 +// ============================================================================ + +bool FRestoreWindowUtils::ContainsWidgetType(const TSharedPtr& JsonObject, const TArray& TypeList) +{ + // 节点无效直接返回 + if (!JsonObject.IsValid()) + { + return false; + } + + // 检查当前节点的 WidgetType 是否在给定类型列表中 + FString WidgetType; + if (JsonObject->TryGetStringField(TEXT("WidgetType"), WidgetType)) + { + if (TypeList.Contains(FName(*WidgetType))) + { + return true; + } + } + + // 递归检查所有子节点 + const TArray>* ChildNodes; + if (JsonObject->TryGetArrayField(TEXT("ChildNodes"), ChildNodes)) + { + for (const TSharedPtr& ChildValue : *ChildNodes) + { + if (ChildValue.IsValid() && ChildValue->Type == EJson::Object) + { + if (ContainsWidgetType(ChildValue->AsObject(), TypeList)) + { + return true; + } + } + } + } + + return false; +} + +bool FRestoreWindowUtils::ContainsDisplayableWidget(const TSharedPtr& JsonObject) +{ + // 复用通用检测, 判断是否包含文本或图片控件 + return ContainsWidgetType(JsonObject, TextAndImageWidgetTypes); +} + +bool FRestoreWindowUtils::ContainsOnlyTextWidget(const TSharedPtr& JsonObject) +{ + // 复用通用检测, 判断是否包含纯文本控件 + return ContainsWidgetType(JsonObject, PureTextWidgetTypes); +} + +// ============================================================================ +// 校验与导出 +// ============================================================================ + +void FRestoreWindowUtils::GenerateCheckJson(URestoreWindowProxy* WindowProxy, const FString& ResultDirPath) +{ + // 窗口代理为空时无法生成, 记录错误并返回 + if (!WindowProxy) + { + UE_LOG(LogLQARestoreManager, Error, TEXT("GenerateCheckJson: WindowProxy is null")); + return; + } + + // 组合输出文件路径并生成校验角点信息 + FString CheckInfoFilePath = FPaths::Combine(ResultDirPath, TEXT("check_info.json")); + WindowProxy->GenerateCheckCorners(CheckInfoFilePath, AllCheckParentWidgets); +} + +// ============================================================================ +// 私有辅助函数 +// ============================================================================ + +void FRestoreWindowUtils::DeserializeData(const TSharedPtr& RootObj, URestoreWindowProxy* WindowProxy, + const FVector2D& InWindowSize, URestoreWindowProxy* RestoreWindowProxy, const FString& ObjectParentWidget) +{ + // 取出 UI 树数组, 每个元素代表一棵控件树 + const TArray> UITrees = RootObj->GetArrayField(TEXT("uitree")); + + // 过滤与处理 UI 树节点 + TArray> ValidUITrees; // 有效的 UI 树集合 + FString TopParentWidget; // 检测到的顶层父控件 + + ValidUITrees.Reserve(UITrees.Num()); // 预分配内存, 减少动态扩容开销 + + for (const TSharedPtr& JsonValue : UITrees) + { + const TSharedPtr TreeObject = JsonValue->AsObject(); + // if (!TreeObject.IsValid() || !ContainsDisplayableWidget(TreeObject)) + // 仅校验对象有效性 (此处暂不过滤 “可显示控件”, 保留原注释逻辑) + if (!TreeObject.IsValid()) + { + continue; + } + + // 必须包含 ObjectData 字段, 否则跳过 + if (!TreeObject->HasField(TEXT("ObjectData"))) + { + continue; + } + + TSharedPtr ObjectData = TreeObject->GetObjectField(TEXT("ObjectData")); + + // 将 Layer (层级) 值限制在 int32 合法范围内, 防止溢出 + const double LayerValueDouble = ObjectData->GetNumberField(TEXT("Layer")); + const int32 LayerValue = + (LayerValueDouble > static_cast(INT32_MAX)) ? INT32_MAX : static_cast(LayerValueDouble); + + // 将修正后的层级值写回 JSON + ObjectData->SetNumberField(TEXT("Layer"), LayerValue); + + UE_LOG(LogLQARestoreManager, Log, TEXT("Widget: %s, PanelLayer: %s, Layer: %d"), + *TreeObject->GetStringField(TEXT("WidgetName")), *ObjectData->GetStringField(TEXT("PanelLayer")), + LayerValue); + + // 该树有效, 加入待处理列表 + ValidUITrees.Add(JsonValue); + + // 记录顶层父控件: 仅当为纯文本控件且层级小于阈值时才更新 + if (ContainsOnlyTextWidget(TreeObject) && LayerValue < TopParentLayerThreshold) + { + TopParentWidget = TreeObject->GetStringField(TEXT("ParentWidget")); + } + } + + // 设置校验用父控件列表, 先清空旧数据 + AllCheckParentWidgets.Empty(); + + if (!ObjectParentWidget.IsEmpty()) + { + // 覆盖优先: 使用外部指定的父控件 + AllCheckParentWidgets.Add(ObjectParentWidget); + } + else if (!TopParentWidget.IsEmpty()) + { + // 默认情况: 使用自动检测到的顶层父控件 + AllCheckParentWidgets.Add(TopParentWidget); + } + + UE_LOG(LogLQARestoreManager, Log, TEXT("ValidUITrees: %d, CheckParentWidgets: %d"), ValidUITrees.Num(), + AllCheckParentWidgets.Num()); + + // 无有效 UI 树则提前退出 + if (ValidUITrees.Num() == 0) + { + return; + } + + // 若存在背景图数据则进行处理 + FString BackgroundImagePath; + if (RootObj->HasField(TEXT("bg_data"))) + { + const FString BgData = RootObj->GetStringField(TEXT("bg_data")); + UE_LOG(LogLQARestoreManager, Log, TEXT("Found bg_data field, length: %d"), BgData.Len()); + + // 将十六进制背景数据解码并保存为图片文件 + BackgroundImagePath = ProcessBackgroundImage(BgData); + if (!BackgroundImagePath.IsEmpty()) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("Background image saved to: %s"), *BackgroundImagePath); + // 将背景图设置到窗口 + WindowProxy->ProcessImageBackground(*BackgroundImagePath); + } + else + { + UE_LOG(LogLQARestoreManager, Warning, TEXT("Failed to process background image")); + } + } + else + { + UE_LOG(LogLQARestoreManager, Log, TEXT("No bg_data field found in JSON")); + } + + // 逐棵有效 UI 树构建 UI 面板 + static const TArray> EmptyArray; // 复用的空数组, 避免重复构造 + for (const TSharedPtr& JsonValue : ValidUITrees) + { + const TSharedPtr TreeObject = JsonValue->AsObject(); + FRestoreWidgetMeta MetaData; + + // 添加面板: 传入窗口尺寸与各类构建参数, 由窗口代理完成具体控件创建 + WindowProxy->AddPanel(nullptr, nullptr, nullptr, MetaData, nullptr, TEXT(""), EmptyArray, false, EmptyArray, + TreeObject, InWindowSize, FVector2D::ZeroVector); + } + + // 清理临时背景图文件, 避免残留 + if (!BackgroundImagePath.IsEmpty() && FPaths::FileExists(BackgroundImagePath)) + { + IFileManager::Get().Delete(*BackgroundImagePath); + } +} + +FString FRestoreWindowUtils::ProcessBackgroundImage(const FString& HexData) +{ + UE_LOG(LogLQARestoreManager, Log, TEXT("ProcessBackgroundImage called, HexData length: %d"), HexData.Len()); + + // 将十六进制字符串转换为字节数组 + TArray Bytes; + const int32 Length = HexData.Len(); + Bytes.Reserve(Length / 2); // 每两个十六进制字符对应一个字节 + + for (int32 i = 0; i < Length; i += 2) + { + if (i + 1 < Length) + { + // 高位字符 * 16 + 低位字符, 合成一个字节 + const uint8 Byte = FParse::HexDigit(HexData[i]) * 16 + FParse::HexDigit(HexData[i + 1]); + Bytes.Add(Byte); + } + } + + // 未解析出任何字节, 视为失败 + if (Bytes.Num() == 0) + { + UE_LOG(LogLQARestoreManager, Warning, TEXT("No bytes converted from hex data")); + return TEXT(""); + } + + UE_LOG(LogLQARestoreManager, Log, TEXT("Converted %d bytes from hex data"), Bytes.Num()); + + // 使用时间戳生成唯一文件名, 避免重名覆盖 + const FString Timestamp = FDateTime::Now().ToString(TEXT("%Y%m%d_%H%M%S")); + const FString SaveDir = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("LQABg")); + + // 目录不存在时创建 (递归创建) + if (!IFileManager::Get().DirectoryExists(*SaveDir)) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("Creating directory: %s"), *SaveDir); + IFileManager::Get().MakeDirectory(*SaveDir, true); + } + + const FString FileName = FString::Printf(TEXT("%s_BG.png"), *Timestamp); + const FString FilePath = FPaths::Combine(SaveDir, FileName); + + // 将字节数组写入文件 + if (FFileHelper::SaveArrayToFile(Bytes, *FilePath)) + { + UE_LOG(LogLQARestoreManager, Log, TEXT("Background image saved successfully: %s"), *FilePath); + return FilePath; + } + + UE_LOG(LogLQARestoreManager, Error, TEXT("Failed to save background image to: %s"), *FilePath); + return TEXT(""); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RootObjWidget.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RootObjWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cde050d695bb50d196d726bce3340e8df285110 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/RootObjWidget.cpp @@ -0,0 +1,1046 @@ +#include "Core/RootObjWidget.h" + +// ---- Slate / UMG 控件及插槽相关头文件 ---- +#include "Blueprint/SlateBlueprintLibrary.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Button.h" +#include "Components/ButtonSlot.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/CheckBox.h" +#include "Components/GridPanel.h" +#include "Components/GridSlot.h" +#include "Components/HorizontalBox.h" +#include "Components/HorizontalBoxSlot.h" +#include "Components/Image.h" +#include "Components/RichTextBlock.h" +#include "Components/SafeZone.h" +#include "Components/SafeZoneSlot.h" +#include "Components/ScaleBox.h" +#include "Components/ScaleBoxSlot.h" +#include "Components/ScrollBox.h" +#include "Components/ScrollBoxSlot.h" +#include "Components/SizeBox.h" +#include "Components/SizeBoxSlot.h" +#include "Components/TextBlock.h" +#include "Components/UniformGridPanel.h" +#include "Components/UniformGridSlot.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Components/Widget.h" +#include "Components/WrapBox.h" +#include "Components/WrapBoxSlot.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +// ---- 纹理、字体、图片编解码等支持 ---- +#include "Engine/Texture2D.h" +#include "Fonts/FontMeasure.h" +#include "Framework/Application/SlateApplication.h" +#include "IImageWrapper.h" +#include "IImageWrapperModule.h" +#include "JsonObjectConverter.h" +#include "Materials/MaterialInstanceConstant.h" +#include "PaperSprite.h" +#include "Types/ReflectionMetadata.h" +// ---- 本插件内部工具类 ---- +#include "Utils/ImageRenderUtils.h" +#include "Utils/TranslationUtils/ValidatorUtils.h" +#include "WidgetSlots/Core/Slot2JsonFactory.h" +#include "WidgetSlots/Core/RestoreWidget2JsonFactory.h" +#include "WidgetSlots/Core/WidgetDefines.h" +#include "Widgets/Input/SButton.h" +#include "Widgets/SViewport.h" +#include "Widgets/SWidget.h" + +// 定义头文件中声明的日志分类 +DEFINE_LOG_CATEGORY(LogLQARestoreRootObj); + +//============================================================================== +// 区块: 辅助函数 +//============================================================================== + +namespace LQAConstants +{ +// 视口与缩放基准常量: 以 2560 宽度作为参考分辨率 +constexpr float ReferenceViewportWidth = 2560.0f; + +// LQA 校验阈值: 行高占比最小值 (低于此值视为行高异常) +constexpr float MinLineHeightPercentage = 0.7f; +} + +/** + * 保证浮点值有效 (非 NaN、非无穷大), 否则返回 0 + */ +float SafeFloat(float value) +{ + if (FMath::IsNaN(value) || !FMath::IsFinite(value)) + { + return 0.0f; + } + return value; +} + +/** + * 以四个角点的中心为基准, 对角点进行缩放 + * 用于根据 Alpha 通道分析结果裁剪控件的实际可见边界 + */ +void ScaleCornerPoints(FVector2D& LeftBottomPos, FVector2D& LeftUpperPos, FVector2D& RightUpperPos, + FVector2D& RightBottomPos, float ScaleX, float ScaleY) +{ + // 计算四个角点的中心点 + float CenterX = (LeftBottomPos.X + LeftUpperPos.X + RightUpperPos.X + RightBottomPos.X) / 4.0f; + float CenterY = (LeftBottomPos.Y + LeftUpperPos.Y + RightUpperPos.Y + RightBottomPos.Y) / 4.0f; + FVector2D Center(CenterX, CenterY); + + // 定义缩放操作: 以中心点为原点进行缩放 + TFunction ScalePoint = [&](FVector2D& Point) + { + Point.X = (Point.X - Center.X) * ScaleX + Center.X; + Point.Y = (Point.Y - Center.Y) * ScaleY + Center.Y; + }; + + // 直接就地修改四个角点 + ScalePoint(LeftBottomPos); + ScalePoint(LeftUpperPos); + ScalePoint(RightUpperPos); + ScalePoint(RightBottomPos); +} + +//============================================================================== +// 区块: 媒体与资源管理 +//============================================================================== + +// 加载 PNG 并设置为全屏背景 (详见头文件说明) +void URootObjWidget::ProcessImageBackground(const FString& ImagePath) +{ + // 重置忽略列表 (每次重设背景视为新的一轮布局) + IgnoreUniqueIds.Empty(); + + // 主画布或控件树无效时无法继续 + if (!MainCanvas || !WidgetTree) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("MainCanvas or WidgetTree is null")); + return; + } + + // 读取整个文件到字节数组 + TArray FileData; + if (!FFileHelper::LoadFileToArray(FileData, *ImagePath)) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("Failed to load file: %s"), *ImagePath); + return; + } + + // 加载 ImageWrapper 模块并创建 PNG 解码器 + IImageWrapperModule& ImageWrapperModule = + FModuleManager::LoadModuleChecked(FName("ImageWrapper")); + TSharedPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG); + + // 将压缩数据交给解码器; 失败则返回 + if (!ImageWrapper.IsValid() || !ImageWrapper->SetCompressed(FileData.GetData(), FileData.Num())) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("Failed to parse PNG data")); + return; + } + + // 解码出 RGBA (每通道 8 位) 的原始像素数据 + TArray RawData; + if (!ImageWrapper->GetRaw(ERGBFormat::RGBA, 8, RawData)) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("Failed to get raw image data")); + return; + } + + // 创建一张瞬态纹理 (运行时生成, 不保存到磁盘) + UTexture2D* Texture = UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_R8G8B8A8); + + // UE 5.0+ 中 PlatformData 已私有化, 必须通过 GetPlatformData() 访问; UE4 下保留直接字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + if (!Texture || !Texture->GetPlatformData()) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("Failed to create texture")); + return; + } + + // 锁定首个 Mip 的内存, 将原始像素拷贝进去, 再解锁 + void* TextureData = Texture->GetPlatformData()->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FMemory::Memcpy(TextureData, RawData.GetData(), RawData.Num()); + Texture->GetPlatformData()->Mips[0].BulkData.Unlock(); +#else + if (!Texture || !Texture->PlatformData) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("Failed to create texture")); + return; + } + + void* TextureData = Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FMemory::Memcpy(TextureData, RawData.GetData(), RawData.Num()); + Texture->PlatformData->Mips[0].BulkData.Unlock(); +#endif + + // 将 CPU 端数据提交到 GPU, 使纹理生效 + Texture->UpdateResource(); + + // 创建一个 UImage 控件, 并把刚才的纹理作为笔刷资源 + UImage* BGImage = WidgetTree->ConstructWidget(UImage::StaticClass(), TEXT("BGImage")); + FSlateBrush Brush; + Brush.SetResourceObject(Texture); + BGImage->SetBrush(Brush); + + // 添加到主画布, 并设置锚点为全屏拉伸 (左上 0,0 到右下 1,1 偏移全 0) + MainCanvas->AddChild(BGImage); + if (UCanvasPanelSlot* CanvasSlot = Cast(BGImage->Slot)) + { + CanvasSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 1.f)); + CanvasSlot->SetOffsets(FMargin(0.f, 0.f, 0.f, 0.f)); + } +} + +//============================================================================== +// 区块: 控件层级管理 +//============================================================================== + +// 递归收集某控件及其所有子控件的唯一 ID +void CollectWidgetUniqueIDs(UWidget* Widget, TArray& OutUniqueIDs) +{ + if (!Widget) + return; + + // 记录当前控件 ID + OutUniqueIDs.Add(Widget->GetUniqueID()); + + // 如果是面板控件, 递归处理所有子控件 + if (UPanelWidget* Panel = Cast(Widget)) + { + for (int32 i = 0; i < Panel->GetChildrenCount(); ++i) + { + CollectWidgetUniqueIDs(Panel->GetChildAt(i), OutUniqueIDs); + } + } +} + +namespace +{ +// 当无法确定插槽尺寸时使用的默认回退尺寸 (基于常见的 1440p 分辨率) +const FVector2D FallbackSlotSize(2560.0f, 1440.0f); +} + +// 将 UserWidget 添加到控件层级并配置插槽 (详见头文件说明) +void URootObjWidget::AddUserWidget(UUserWidget* UserWidgetInstance, UWidget* UserWidgetRootCanvas, + UPanelWidget* ParentPanel, TSharedPtr AdditionalInfo, FVector2D ParentRootPosition, + FVector2D AbsolutePosition, FVector2D SlotSize, FVector2D DesiredSize, int32 ZOrder, int32 InPositionScale, + bool bShouldIgnore) +{ + // 校验必要参数:UserWidget 实例不可为空 + if (!UserWidgetInstance) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("[AddUserWidget] UserWidgetInstance is null")); + return; + } + // 校验必要参数:UserWidget 根画布不可为空 + if (!UserWidgetRootCanvas) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("[AddUserWidget] UserWidgetRootCanvas is null")); + return; + } + + // 父面板为空时回退到主画布 + if (!ParentPanel) + { + ParentPanel = MainCanvas; + } + + // 设置 UserWidget 的根控件 + UserWidgetInstance->WidgetTree->RootWidget = UserWidgetRootCanvas; + + // 将 UserWidget 挂载到父面板 + ParentPanel->AddChild(UserWidgetInstance); + + // 配置插槽布局 (优先 JSON, 失败则默认画布定位) + ConfigureUserWidgetSlot(UserWidgetInstance, AdditionalInfo, ParentPanel, ParentRootPosition, AbsolutePosition, + SlotSize, ZOrder, InPositionScale); + + // 如需忽略, 将该 UserWidget 整个层级加入 LQA 忽略列表 + if (bShouldIgnore) + { + CollectIgnoredWidgets(UserWidgetInstance); + } +} + +// 配置 UserWidget 插槽: 优先使用 JSON 配置, 失败则回退默认画布定位 +void URootObjWidget::ConfigureUserWidgetSlot(UUserWidget* UserWidgetInstance, + const TSharedPtr& AdditionalInfo, UPanelWidget* ParentPanel, const FVector2D& ParentRootPosition, + const FVector2D& AbsolutePosition, const FVector2D& SlotSize, int32 ZOrder, int32 InPositionScale) +{ + UPanelSlot* PanelSlot = UserWidgetInstance->Slot; + if (!PanelSlot) + { + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("[ConfigureUserWidgetSlot] PanelSlot is null")); + return; + } + + // 尝试从 JSON 应用插槽配置 + bool bSlotConfigured = false; + if (AdditionalInfo.IsValid()) + { + bSlotConfigured = FSlot2JsonFactory::SlotFromJson(AdditionalInfo, PanelSlot); + } + + // JSON 配置失败时, 回退为默认画布定位 + if (!bSlotConfigured) + { + ApplyDefaultCanvasSlot(PanelSlot, ParentPanel, ParentRootPosition, AbsolutePosition, SlotSize, ZOrder, + InPositionScale); // 使用调用方传入的缩放参数 + + if (UOverlaySlot* OverlaySlot = Cast(PanelSlot)) + { + OverlaySlot->SetHorizontalAlignment(HAlign_Fill); + OverlaySlot->SetVerticalAlignment(VAlign_Fill); + } + } +} + +// 应用默认画布插槽: 将绝对位置转换为父画布的本地坐标并设置偏移 +void URootObjWidget::ApplyDefaultCanvasSlot(UPanelSlot* PanelSlot, UPanelWidget* ParentPanel, + const FVector2D& ParentRootPosition, const FVector2D& AbsolutePosition, const FVector2D& SlotSize, int32 ZOrder, + int32 InPositionScale) +{ + // 仅支持画布面板插槽 + UCanvasPanelSlot* CanvasPanelSlot = Cast(PanelSlot); + if (!CanvasPanelSlot) + { + return; + } + + // 获取父画布的缓存几何信息 (用于坐标换算) + const FGeometry CanvasGeometry = ParentPanel->GetCachedGeometry(); + + // 计算相对位置: 绝对位置减去父控件根位置 + const FVector2D RelativePosition = AbsolutePosition - ParentRootPosition; + // 转换为父画布的本地坐标 + const FVector2D LocalPosition = + CanvasGeometry.AbsoluteToLocal(RelativePosition + CanvasGeometry.LocalToAbsolute(FVector2D::ZeroVector)); + + // 应用插槽配置: 锚点固定左上角, 设置偏移 (位置乘以缩放系数) 与尺寸、层级 + CanvasPanelSlot->SetAnchors(FAnchors(0.0f, 0.0f, 0.0f, 0.0f)); + CanvasPanelSlot->SetOffsets( + FMargin(LocalPosition.X * InPositionScale, LocalPosition.Y * InPositionScale, SlotSize.X, SlotSize.Y)); + CanvasPanelSlot->SetZOrder(ZOrder); +} + +// 收集 UserWidget 层级内所有控件 ID 到忽略列表 +void URootObjWidget::CollectIgnoredWidgets(UUserWidget* UserWidgetInstance) +{ + UWidget* RootWidget = UserWidgetInstance->GetRootWidget(); + if (!RootWidget) + { + return; + } + + // 递归收集后追加到总忽略列表 + TArray WidgetUniqueIDs; + CollectWidgetUniqueIDs(RootWidget, WidgetUniqueIDs); + + IgnoreUniqueIds.Append(WidgetUniqueIDs); +} + +// 将面板添加到另一面板并配置插槽 (JSON 优先, 失败回退默认画布定位) +void URootObjWidget::AddPanel(UPanelWidget* ParentPanel, FString ParentPanelType, FVector2D ParentRootPosition, + UPanelWidget* Panel, FString PanelType, FVector2D PanelPosition, FVector2D PanelSize, + UUserWidget* UserWidgetInstance, TSharedPtr PanelSlotInfo, int32 ZOrder, int32 InPositionScale) +{ + // 若为 UserWidget 则跳过 (由 AddUserWidget 单独处理) + if (UserWidgetInstance) + { + UE_LOG(LogLQARestoreRootObj, Log, TEXT("this is UserWidgetInstance, ignore!")); + return; + } + + if (!Panel) + { + return; + } + + // 父面板为空时使用主画布 + if (!ParentPanel) + { + ParentPanel = MainCanvas; + } + + // 添加到父面板并取得插槽 + ParentPanel->AddChild(Panel); + UPanelSlot* PanelSlot = Panel->Slot; + + // 尝试从 JSON 配置插槽 + bool bSlotConfigured = false; + if (PanelSlotInfo.IsValid()) + { + bSlotConfigured = FSlot2JsonFactory::SlotFromJson(PanelSlotInfo, PanelSlot); + } + + // JSON 配置失败则回退默认画布定位 (注意此处使用成员变量 PositionScale) + if (!bSlotConfigured) + { + ApplyDefaultCanvasSlot( + PanelSlot, ParentPanel, ParentRootPosition, PanelPosition, PanelSize, ZOrder, this->PositionScale); + } +} + +// 将子控件添加到面板, 并在 needOCR 时注册到 LQA 检查列表 +void URootObjWidget::AddWidgetInPanel(UPanelWidget* Panel, FVector2D PanelPosition, FString PanelType, UWidget* Child, + TSharedPtr ChildSlotInfo, FVector2D ChildPosition, FVector2D ChildSize, int32 ChildZOrder, + TSharedPtr ChildProperty, UWorld* WorldInstance) +{ + if (!Child) + { + return; + } + + // 根据子控件属性判断是否需要注册到 LQA 检查 + if (ChildProperty.IsValid()) + { + const bool bIsImage = ChildProperty->GetBoolField(TEXT("isImage")); + const bool bIsText = ChildProperty->GetBoolField(TEXT("isText")); + const bool bNeedOCR = ChildProperty->GetBoolField(TEXT("needOCR")); + + // 仅当需要 OCR 时才登记 + if (bNeedOCR) + { + if (bIsImage) + { + // 图片控件: 加入图片检查列表及对应属性 + CheckImageWidgets.Add(Child); + ImageProperty.Add(ChildProperty); + } + else if (bIsText) + { + // 文本控件: 加入文本检查列表及对应属性 + CheckTextWidgets.Add(Child); + TextProperty.Add(ChildProperty); + } + } + } + + // 添加到面板并取得插槽 + Panel->AddChild(Child); + UPanelSlot* PanelSlot = Child->Slot; + + // 尝试从 JSON 应用插槽配置 + bool bSlotConfigured = false; + if (ChildSlotInfo.IsValid()) + { + TSharedPtr SlotJsonObject = ChildSlotInfo->AsObject(); + if (SlotJsonObject.IsValid()) + { + bSlotConfigured = FSlot2JsonFactory::SlotFromJson(SlotJsonObject, PanelSlot); + } + } + + // JSON 配置失败则回退默认画布定位 + if (!bSlotConfigured) + { + ApplyDefaultCanvasSlot( + PanelSlot, Panel, PanelPosition, ChildPosition, ChildSize, ChildZOrder, this->PositionScale); + } +} + +// 初始化缩放系数 (当前实现保持为 1, 原始缩放逻辑已注释保留) +void URootObjWidget::InitScale() +{ + // 当前禁用: 原逻辑通过计算反向缩放来归一化画布渲染 + // 若重新启用, 会根据画布几何缩放来设置 PositionScale + + // 默认缩放为 1 (即不缩放) + PositionScale = 1; + + /* 原始实现 (已注释): + if (FSlateApplication::Get().GetGameViewport()) + { + FVector2D Scale{MainCanvas->GetCachedGeometry().Scale}; + UE_LOG(LogLQARestore, Warning, TEXT("Get Scale: %f"), Scale.X); + Scale.X = 1 / Scale.X; + Scale.Y = 1 / Scale.Y; + MainCanvas->SetRenderScale(Scale); // 设置为归一化缩放 + MainCanvas->SetRenderTransformPivot(FVector2D::ZeroVector); + + // 可在此根据计算结果设置 PositionScale + // PositionScale = static_cast(Scale.X); + } + */ +} + +// 控件重建: 纯 C++ 创建主画布作为根控件 +TSharedRef URootObjWidget::RebuildWidget() +{ + // 纯 C++ 创建根画布, 不依赖任何蓝图资产; 且仅创建一次 + if (WidgetTree && !MainCanvas) + { + MainCanvas = WidgetTree->ConstructWidget( + UCanvasPanel::StaticClass(), TEXT("MainCanvas")); + WidgetTree->RootWidget = MainCanvas; + } + return Super::RebuildWidget(); +} + +/** + * 校验文本内容的常见 LQA 问题 + * - 错误码 9: 行高过小 (< 0.7) + * - 错误码 8: 译文与原文之间 HTML 标签或 Hash 标签 (#标记) 不匹配 + */ +void URootObjWidget::CheckTextBugs(TSharedPtr TextInfo) +{ + // 使用 TSet 去重, 避免重复加入相同错误码 + TSet Bugs; + + // 检查行高占比: 有效且小于阈值则记为错误码 9 + const float LineHeightPercentage = TextInfo->GetNumberField(TEXT("lineHeightPercentage")); + if (LineHeightPercentage > 0.0f && LineHeightPercentage < LQAConstants::MinLineHeightPercentage) + { + Bugs.Add(TEXT("9")); + } + + // 取出译文与原文字符串 + const FString TextStr = TextInfo->GetStringField(TEXT("textStr")); + const FString SourceStr = TextInfo->GetStringField(TEXT("SourceString")); + + // 若译文包含 '<', 比较译文与原文的 HTML 标签集合是否一致 + if (TextStr.Contains(TEXT("<"))) + { + TArray Tags1, Tags2; + const bool bIsEqual = FValidatorUtils::AreHtmlTagSetsEqual(TextStr, SourceStr, Tags1, Tags2); + if (!bIsEqual) + { + Bugs.Add(TEXT("8")); + } + } + + // 若译文含 '#' 但不是 "##Notrans" 标记, 比较 Hash 标签集合是否一致 + if (!TextStr.Contains(TEXT("##Notrans")) && TextStr.Contains(TEXT("#"))) + { + TArray Tags1, Tags2; + const bool bIsEqual = FValidatorUtils::AreHashTagSetsEqual(TextStr, SourceStr, Tags1, Tags2); + if (!bIsEqual) + { + Bugs.Add(TEXT("8")); + } + } + + // 将错误码集合写回 JSON 的 "preprocessing_err" 字段 + TArray> BugJsonArray; + for (const FString& Bug : Bugs) + { + BugJsonArray.Add(MakeShared(Bug)); + } + TextInfo->SetArrayField(TEXT("preprocessing_err"), BugJsonArray); +} + +/** + * 收集所有已注册文本控件的 LQA 信息 + * 若提供了 CheckParentWidgets,则按父控件名前缀过滤 + * 返回包含角点、缺陷、显示信息的 JSON 对象数组 + */ +TArray> URootObjWidget::GetTextCheckInfo( + UWorld* WorldInstance, TArray CheckParentWidgets) +{ + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("GenerateTextCheckInfo:%d"), CheckTextWidgets.Num()); + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("TextProperty:%d"), TextProperty.Num()); + + TArray> TextInfos; + // 预留容量, 减少动态扩容开销 + TextInfos.Reserve(CheckTextWidgets.Num()); + + // 取过滤用的顶层父控件名 (取列表首项), 非空时启用过滤 + const FString TopParentWidgetName = (CheckParentWidgets.Num() > 0) ? CheckParentWidgets[0] : TEXT(""); + const bool bFilterByParent = !TopParentWidgetName.IsEmpty(); + + for (int32 Index = 0; Index < CheckTextWidgets.Num(); ++Index) + { + // 弱引用取原始指针, 可能已被 GC 回收 + UWidget* Widget = CheckTextWidgets[Index].Get(); + if (!Widget) + { + continue; + } + + // 取对应的文本属性 JSON + const TSharedPtr& TextInfo = TextProperty[Index]; + if (!TextInfo.IsValid()) + { + continue; + } + + // 跳过空文本 + if (TextInfo->GetStringField(TEXT("textStr")).IsEmpty()) + { + continue; + } + + // 跳过忽略列表中的控件 + if (IgnoreUniqueIds.Contains(Widget->GetUniqueID())) + { + continue; + } + + // 按父控件名前缀过滤 + if (bFilterByParent) + { + const FString ParentWidgetName = TextInfo->GetStringField(TEXT("ParentWidget")); + if (!ParentWidgetName.StartsWith(TopParentWidgetName)) + { + continue; + } + } + + // 计算并更新角点坐标 (文本模式, 带对齐信息) + TextInfo->SetArrayField( + TEXT("corners"), GetCorners(Widget, WorldInstance, true, TextInfo->GetStringField(TEXT("justification")), + TextInfo->GetStringField(TEXT("verticalJustification")))); + + // 执行文本缺陷校验 + CheckTextBugs(TextInfo); + + TextInfos.Add(MakeShared(TextInfo)); + } + + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("TextInfos: %d"), TextInfos.Num()); + return TextInfos; +} + +/** + * 收集所有已注册图片控件的 LQA 信息 + * 会过滤不可见控件及超出视口范围的控件 + * 返回包含角点坐标的 JSON 对象数组 + */ +TArray> URootObjWidget::GetImageCheckInfo( + UWorld* WorldInstance, TArray CheckParentWidgets) +{ + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("GenerateImageCheckInfo: %d"), CheckImageWidgets.Num()); + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("ImageProperty: %d"), ImageProperty.Num()); + + TArray> ImageInfos; + ImageInfos.Reserve(CheckImageWidgets.Num()); + + // 过滤用父控件名及开关 + const FString TopParentWidgetName = (CheckParentWidgets.Num() > 0) ? CheckParentWidgets[0] : TEXT(""); + const bool bFilterByParent = !TopParentWidgetName.IsEmpty(); + + for (int32 Index = 0; Index < CheckImageWidgets.Num(); ++Index) + { + // 跳过已回收或不可见的控件 + UWidget* Widget = CheckImageWidgets[Index].Get(); + if (!Widget || !Widget->IsVisible()) + { + continue; + } + + const TSharedPtr& ImageInfo = ImageProperty[Index]; + if (!ImageInfo.IsValid()) + { + continue; + } + + // 跳过忽略列表中的控件 + if (IgnoreUniqueIds.Contains(Widget->GetUniqueID())) + { + continue; + } + + // 按父控件名前缀过滤 + if (bFilterByParent) + { + const FString ParentWidgetName = ImageInfo->GetStringField(TEXT("ParentWidget")); + if (!ParentWidgetName.StartsWith(TopParentWidgetName)) + { + continue; + } + } + + // 根据控件类型进一步判断可见性 + bool bVisible = false; + if (UImage* Image = Cast(Widget)) + { + // 图片: 根据笔刷、可见性、渲染透明度、缩放综合判断 +#if ENGINE_MAJOR_VERSION >= 5 + bVisible = FImageRenderUtils::IsBrushVisible( + Image->GetBrush(), Image->GetVisibility(), Image->GetRenderOpacity(), Image->GetRenderTransform().Scale); +#else + bVisible = FImageRenderUtils::IsBrushVisible( + Image->Brush, Image->GetVisibility(), Image->GetRenderOpacity(), Image->RenderTransform.Scale); +#endif + } + else if (Cast(Widget)) + { + // 按钮: 始终视为可见 + bVisible = true; + } + else + { + // 不支持的控件类型, 跳过 + continue; + } + + if (!bVisible) + { + continue; + } + + // 计算角点坐标 (图片模式); 为空说明被过滤掉 (无背景/超视口等) + TArray> Corners = GetCorners(Widget, WorldInstance, false); + if (Corners.Num() == 0) + { + continue; + } + + // 写入角点、添加索引, 并初始化错误列表为空 + ImageInfo->SetArrayField(TEXT("corners"), Corners); + ImageInfo->SetNumberField(TEXT("addIndex"), Index); + ImageInfo->SetArrayField(TEXT("preprocessing_err"), TArray>()); + + ImageInfos.Add(MakeShared(ImageInfo)); + } + + UE_LOG(LogLQARestoreRootObj, Warning, TEXT("ImageInfos: %d"), ImageInfos.Num()); + return ImageInfos; +} + +// 将二维坐标转换为含 x/y 字段的 JSON 对象 +TSharedPtr URootObjWidget::ConvertPos2Json(const FVector2D& InPos) +{ + TSharedPtr PosValue = MakeShared(); + PosValue->SetNumberField(TEXT("x"), InPos.X); + PosValue->SetNumberField(TEXT("y"), InPos.Y); + return PosValue; +} + +//============================================================================== +// 区块: 角点计算 - 辅助函数 +//============================================================================== + +// 计算文本控件的四个角点 (按期望尺寸 + 对齐偏移, Y 轴翻转) +bool URootObjWidget::CalculateTextCorners(UWidget* Widget, const FVector2D& PixelPos, const FVector2D& ViewportSize, + const FString& Justification, const FString& VerticalJustification, FVector2D& OutLeftBottom, + FVector2D& OutLeftUpper, FVector2D& OutRightUpper, FVector2D& OutRightBottom) +{ + // 取控件几何、容器绝对尺寸, 以及按参考分辨率换算的缩放 + const FGeometry& CanvasGeometry = Widget->GetCachedGeometry(); + const FVector2D AbsoluteSize = USlateBlueprintLibrary::GetAbsoluteSize(CanvasGeometry); + const float Scale = ViewportSize.X / LQAConstants::ReferenceViewportWidth; + // 使用期望尺寸 (实际渲染文本大小) 乘以缩放 + const FVector2D DesiredSize = Widget->GetDesiredSize() * Scale; + + // 根据水平对齐计算水平偏移 + float HorizontalOffset = 0.0f; + const FString LowerJustification = Justification.ToLower(); + if (LowerJustification == TEXT("center")) + { + HorizontalOffset = (AbsoluteSize.X - DesiredSize.X) / 2.0f; // 居中 + } + else if (LowerJustification == TEXT("right")) + { + HorizontalOffset = AbsoluteSize.X - DesiredSize.X; // 右对齐 + } + + // 根据垂直对齐计算垂直偏移 + float VerticalOffset = 0.0f; + const FString LowerVerticalJustification = VerticalJustification.ToLower(); + if (LowerVerticalJustification == TEXT("center")) + { + VerticalOffset = (AbsoluteSize.Y - DesiredSize.Y) / 2.0f; // 垂直居中 + } + else if (LowerVerticalJustification == TEXT("bottom")) + { + VerticalOffset = AbsoluteSize.Y - DesiredSize.Y; // 底部对齐 + } + + // 计算四个角点坐标 (Y 轴翻转: 屏幕坐标与视口坐标 Y 方向相反) + OutLeftUpper.X = PixelPos.X + HorizontalOffset; + OutLeftUpper.Y = ViewportSize.Y - (PixelPos.Y + VerticalOffset); + + OutLeftBottom.X = PixelPos.X + HorizontalOffset; + OutLeftBottom.Y = ViewportSize.Y - (PixelPos.Y + VerticalOffset + DesiredSize.Y); + + OutRightUpper.X = OutLeftUpper.X + DesiredSize.X; + OutRightUpper.Y = ViewportSize.Y - (PixelPos.Y + VerticalOffset); + + OutRightBottom.X = OutLeftUpper.X + DesiredSize.X; + OutRightBottom.Y = ViewportSize.Y - (PixelPos.Y + VerticalOffset + DesiredSize.Y); + + return true; +} + +// 针对 Texture2D, 根据源图 Alpha 边界缩放角点 (裁剪透明边) +void URootObjWidget::ApplyTextureAlphaScaling( + UTexture2D* Texture, FVector2D& LeftBottom, FVector2D& LeftUpper, FVector2D& RightUpper, FVector2D& RightBottom) +{ + if (!Texture) + { + return; + } + +#if WITH_EDITOR + // 从源数据由外向内扫描得到非透明像素的包围盒 + const FIntRect AlphaBounds = FImageRenderUtils::GetAlphaBoundsFromSource_OuterToInner(Texture, 0); + const int32 OrigWidth = Texture->Source.GetSizeX(); + const int32 OrigHeight = Texture->Source.GetSizeY(); + + // 用可见边界与原始尺寸的比例作为缩放系数 + if (OrigWidth > 0 && OrigHeight > 0) + { + const float ScaleX = AlphaBounds.Width() / static_cast(OrigWidth); + const float ScaleY = AlphaBounds.Height() / static_cast(OrigHeight); + ScaleCornerPoints(LeftBottom, LeftUpper, RightUpper, RightBottom, ScaleX, ScaleY); + } +#else + // 打包 (非编辑器) 构建下无法读取纹理源数据, 不做 Alpha 裁剪缩放, 保持原角点 + UE_LOG(LogLQARestoreRootObj, Warning, + TEXT("ApplyTextureAlphaScaling 依赖编辑器源数据(Source), 打包版本跳过 Alpha 缩放")); +#endif +} + +// 针对 PaperSprite, 根据其在源纹理中的区域计算 Alpha 边界并缩放角点 +void URootObjWidget::ApplySpriteAlphaScaling( + UPaperSprite* Sprite, FVector2D& LeftBottom, FVector2D& LeftUpper, FVector2D& RightUpper, FVector2D& RightBottom) +{ + if (!Sprite) + { + return; + } + +#if WITH_EDITOR + // 取精灵的源纹理 + UTexture2D* SpriteTexture = Sprite->GetSourceTexture(); + if (!SpriteTexture) + { + return; + } + + // 取精灵在源纹理中的 UV 起点与尺寸 (浮点) + const FVector2D SpriteUV_Float = Sprite->GetSourceUV(); + const FVector2D SpriteSize_Float = Sprite->GetSourceSize(); + + // 转为整型像素坐标 + const FIntPoint SourceUV(FMath::FloorToInt(SpriteUV_Float.X), FMath::FloorToInt(SpriteUV_Float.Y)); + const FIntPoint SourceDimension(FMath::FloorToInt(SpriteSize_Float.X), FMath::FloorToInt(SpriteSize_Float.Y)); + + // 在指定子区域内计算 Alpha 边界 + const FIntRect AlphaBounds = + FImageRenderUtils::GetAlphaBoundsFromSource_OuterToInner(SpriteTexture, 0, SourceUV, SourceDimension); + + // 用可见边界与精灵尺寸的比例缩放角点 + if (SourceDimension.X > 0 && SourceDimension.Y > 0) + { + const float ScaleX = AlphaBounds.Width() / static_cast(SourceDimension.X); + const float ScaleY = AlphaBounds.Height() / static_cast(SourceDimension.Y); + ScaleCornerPoints(LeftBottom, LeftUpper, RightUpper, RightBottom, ScaleX, ScaleY); + } +#else + // 打包 (非编辑器) 构建下 UPaperSprite 源纹理接口不可用, 跳过 Alpha 缩放 + UE_LOG(LogLQARestoreRootObj, Warning, + TEXT("ApplySpriteAlphaScaling 依赖编辑器 PaperSprite 源数据, 打包版本跳过 Alpha 缩放")); +#endif +} + +// 计算图片控件的四个角点 (含有效性校验、坐标换算、Alpha 裁剪与视口判断) +bool URootObjWidget::CalculateImageCorners(UWidget* Widget, UWorld* WorldInstance, const FVector2D& ViewportSize, + FVector2D& OutLeftBottom, FVector2D& OutLeftUpper, FVector2D& OutRightUpper, FVector2D& OutRightBottom) +{ + const FGeometry& CanvasGeometry = Widget->GetCachedGeometry(); + const FVector2D AbsoluteSize = USlateBlueprintLibrary::GetAbsoluteSize(CanvasGeometry); + const float Scale = ViewportSize.X / LQAConstants::ReferenceViewportWidth; + const FVector2D DesiredSize = Widget->GetDesiredSize() * Scale; + + // 尺寸近似为 0 时视为无效, 直接返回 + if (FMath::IsNearlyZero(FMath::Min(AbsoluteSize.X, DesiredSize.X)) || + FMath::IsNearlyZero(FMath::Min(AbsoluteSize.Y, DesiredSize.Y))) + { + return false; + } + + // 控件无可见背景时跳过 + if (FImageRenderUtils::IsWidgetNoBackground(Widget)) + { + return false; + } + + // 取控件几何与本地尺寸, 构造本地坐标系下的四个角 + const FGeometry Geometry = Widget->GetCachedGeometry(); + const FVector2D LocalSize = Geometry.GetLocalSize(); + + const FVector2D BottomLeft(0, LocalSize.Y); + const FVector2D TopLeft(0, 0); + const FVector2D TopRight(LocalSize.X, 0); + const FVector2D BottomRight(LocalSize.X, LocalSize.Y); + + // 将本地坐标转换为视口坐标 + FVector2D ViewportPos; + USlateBlueprintLibrary::LocalToViewport(WorldInstance, Geometry, BottomLeft, OutLeftBottom, ViewportPos); + USlateBlueprintLibrary::LocalToViewport(WorldInstance, Geometry, TopLeft, OutLeftUpper, ViewportPos); + USlateBlueprintLibrary::LocalToViewport(WorldInstance, Geometry, TopRight, OutRightUpper, ViewportPos); + USlateBlueprintLibrary::LocalToViewport(WorldInstance, Geometry, BottomRight, OutRightBottom, ViewportPos); + + // Y 轴翻转 + OutLeftBottom.Y = ViewportSize.Y - OutLeftBottom.Y; + OutLeftUpper.Y = ViewportSize.Y - OutLeftUpper.Y; + OutRightUpper.Y = ViewportSize.Y - OutRightUpper.Y; + OutRightBottom.Y = ViewportSize.Y - OutRightBottom.Y; + + // 取控件的笔刷 (图片直接取笔刷: 按钮按当前状态取对应样式) + const FSlateBrush* ImageBrush = nullptr; + + if (UImage* MyImage = Cast(Widget)) + { +#if ENGINE_MAJOR_VERSION >= 5 + ImageBrush = &MyImage->GetBrush(); +#else + ImageBrush = &MyImage->Brush; +#endif + } + else if (UButton* MyButton = Cast(Widget)) + { +#if ENGINE_MAJOR_VERSION >= 5 + const FButtonStyle& ButtonStyle = MyButton->GetStyle(); +#else + const FButtonStyle& ButtonStyle = MyButton->WidgetStyle; +#endif + // 取底层 Slate 按钮以读取按下/悬停状态 + TSharedPtr SlateWidget = MyButton->GetCachedWidget(); + TSharedPtr SButtonWidget = StaticCastSharedPtr(SlateWidget); + + if (SButtonWidget.IsValid()) + { + const bool bPressed = SButtonWidget->IsPressed(); + const bool bHovered = SButtonWidget->IsHovered(); + + // 根据状态选择对应笔刷: 按下 > 悬停 > 普通 + if (bPressed) + { + ImageBrush = &ButtonStyle.Pressed; + } + else if (bHovered) + { + ImageBrush = &ButtonStyle.Hovered; + } + else + { + ImageBrush = &ButtonStyle.Normal; + } + } + } + + if (ImageBrush) + { + // 根据资源类型应用 Alpha 裁剪缩放 + if (UTexture2D* Texture = Cast(ImageBrush->GetResourceObject())) + { + ApplyTextureAlphaScaling(Texture, OutLeftBottom, OutLeftUpper, OutRightUpper, OutRightBottom); + } + else if (UPaperSprite* Sprite = Cast(ImageBrush->GetResourceObject())) + { + ApplySpriteAlphaScaling(Sprite, OutLeftBottom, OutLeftUpper, OutRightUpper, OutRightBottom); + } + else if (Cast(ImageBrush->GetResourceObject())) + { + // 材质实例暂不支持, 跳过 + return false; + } + + // 任一角点超出视口即判定为不可用 + const bool bIsAnyPointOutOfViewport = FImageRenderUtils::IsPointOutOfViewport(OutLeftBottom, ViewportSize) || + FImageRenderUtils::IsPointOutOfViewport(OutLeftUpper, ViewportSize) || + FImageRenderUtils::IsPointOutOfViewport(OutRightUpper, ViewportSize) || + FImageRenderUtils::IsPointOutOfViewport(OutRightBottom, ViewportSize); + + if (bIsAnyPointOutOfViewport) + { + return false; + } + } + + return true; +} + +// 将四个角点按 [左下, 左上, 右上, 右下] 顺序转换为 JSON 数组 +TArray> URootObjWidget::CornersToJsonArray( + const FVector2D& LeftBottom, const FVector2D& LeftUpper, const FVector2D& RightUpper, const FVector2D& RightBottom) +{ + TArray> CornerPosList; + CornerPosList.Reserve(4); + + CornerPosList.Emplace(MakeShared(ConvertPos2Json(LeftBottom))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(LeftUpper))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(RightUpper))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(RightBottom))); + + return CornerPosList; +} + +//============================================================================== +// 区块: 角点计算 - 主函数 +//============================================================================== + +/** + * 计算控件在屏幕空间中的四个角点坐标 + * + * 文本控件: + * - 使用 DesiredSize (实际渲染文本尺寸) 而非 AbsoluteSize (容器尺寸) + * - 应用文本对齐偏移 (水平 Justification 与垂直 VerticalJustification) + * - 返回基于实际文本边界的角点 + * + * 图片控件: + * - 分析纹理 Alpha 通道以裁剪透明边缘 + * - 支持 Texture2D 与 PaperSprite 资源 + * - 根据可见像素边界缩放角点 + * - 过滤无背景或超出视口的控件 + * + * 坐标系: Y 轴翻转 (ViewportSize.Y - PixelPos.Y) + * + * @return 4 个 JSON 角点坐标: [左下, 左上, 右上, 右下] + */ +TArray> URootObjWidget::GetCorners( + UWidget* Widget, UWorld* WorldInstance, bool bIsText, FString Justification, FString VerticalJustification) +{ + // World 无效直接报错返回 + if (!WorldInstance) + { + UE_LOG(LogLQARestoreRootObj, Error, TEXT("[LQA] Get Invalid World!")); + return TArray>(); + } + + // 获取视口尺寸 + FVector2D ViewportSize = FVector2D::ZeroVector; + if (const UGameViewportClient* ViewportClient = WorldInstance->GetGameViewport()) + { + ViewportClient->GetViewportSize(ViewportSize); + } + + // 根据控件类型分别计算角点 + FVector2D LeftBottomPos, LeftUpperPos, RightUpperPos, RightBottomPos; + bool bSuccess = false; + + if (bIsText) + { + // 文本: 先取控件左上角在视口中的像素位置 + const FGeometry& CanvasGeometry = Widget->GetCachedGeometry(); + FVector2D PixelPos, ViewportPos; + USlateBlueprintLibrary::LocalToViewport( + WorldInstance, CanvasGeometry, FVector2D::ZeroVector, PixelPos, ViewportPos); + + bSuccess = CalculateTextCorners(Widget, PixelPos, ViewportSize, Justification, VerticalJustification, + LeftBottomPos, LeftUpperPos, RightUpperPos, RightBottomPos); + } + else + { + // 图片: 直接计算 + bSuccess = CalculateImageCorners( + Widget, WorldInstance, ViewportSize, LeftBottomPos, LeftUpperPos, RightUpperPos, RightBottomPos); + } + + // 计算失败返回空数组 + if (!bSuccess) + { + return TArray>(); + } + + // 转换为 JSON 数组返回 + return CornersToJsonArray(LeftBottomPos, LeftUpperPos, RightUpperPos, RightBottomPos); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/TaskManager.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/TaskManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83c5019f2628baf052a306ac54be49044b627173 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Core/TaskManager.cpp @@ -0,0 +1,526 @@ +#include "Core/TaskManager.h" + +#include "Core/ConfigManager.h" +#include "Core/FileManager.h" +#include "Serialization/JsonSerializer.h" // JSON 序列化/反序列化 +#include "Utils/HttpUtils/HttpRequestHelper.h" // 封装的 HTTP 请求辅助类 +#include "zlib.h" // gzip 解压所需的 zlib 库 + +// 定义头文件中声明的日志分类 (每个分类在整个工程中仅能定义一次) +DEFINE_LOG_CATEGORY(LogLQARestoreTask); + +// 匿名命名空间: 仅在本编译单元内可见的常量, 避免污染全局命名空间 +namespace +{ +constexpr int32 InitialDecompressionBufferSize = 1024 * 1024; // 解压缓冲区初始大小: 1MB +constexpr int32 DecompressionGrowthFactor = 2; // 缓冲区不足时的扩容倍数 +} + +void UTaskManager::Initialize(UConfigManager* InConfigManager, UFileManager* InFileManager) +{ + // 保存依赖引用并将所有运行时状态重置为初始值 + ConfigManager = InConfigManager; + FileManager = InFileManager; + bIsDownloading = false; + bIsUploading = false; + DownloadRetryCount = 0; + UploadRetryCount = 0; + UE_LOG(LogLQARestoreTask, Log, TEXT("TaskManager Initialized")); +} + +void UTaskManager::RequestJobData(bool bIsFirstRequest) +{ + // 前置校验: 配置管理器必须有效 + if (!ConfigManager) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("ConfigManager is null")); + return; + } + + // JobId 为 "0" 表示无有效任务, 直接跳过请求 + const FString& JobId = ConfigManager->GetJobId(); + if (JobId == TEXT("0")) + { + UE_LOG(LogLQARestoreTask, Warning, TEXT("JobId is 0, skipping job data request")); + return; + } + + // 发起获取任务数据的 HTTP 请求, 所有查询参数均来自配置管理器 + FHttpRequestHelper::GetJobData(JobId, ConfigManager->GetRegression(), ConfigManager->GetLanguage(), + ConfigManager->GetDefaultNums(), ConfigManager->GetMinID(), ConfigManager->GetModules()); + + // 使用弱指针捕获 this, 防止在异步回调触发时对象已被销毁而产生悬空访问 + TWeakObjectPtr WeakThis(this); + FHttpRequestHelper::OnRequestSuccess.BindLambda( + [WeakThis](FHttpResponsePtr ResponsePtr) + { + // 回调执行前再次确认对象仍然有效 + if (WeakThis.IsValid()) + { + WeakThis->OnJobDataSuccess(ResponsePtr); + } + }); +} + +void UTaskManager::OnJobDataSuccess(FHttpResponsePtr Response) +{ + // 响应有效性校验 + if (!Response.IsValid()) + { + UE_LOG(LogLQARestoreTask, Warning, TEXT("Job data response is invalid")); + return; + } + + const int32 ResponseCode = Response->GetResponseCode(); + const FString ResponseData = Response->GetContentAsString(); + + // 非 2xx: 直接暴露状态码与响应体前 500 字符 (便于识别 HTML 错误页 / 鉴权失败等) + if (ResponseCode < 200 || ResponseCode >= 300) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("Job data HTTP error: %d, Body: %s"), ResponseCode, + *ResponseData.Left(500)); + return; + } + + // 将响应体内容解析为 JSON 对象 + TSharedPtr JsonObject; + const TSharedRef> JsonReader = TJsonReaderFactory<>::Create(ResponseData); + + if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid()) + { + // 解析失败时打印响应码与响应体预览 (如误把前端 HTML 当成 JSON 即可一眼看出) + UE_LOG(LogLQARestoreTask, Error, TEXT("Failed to parse job data response. Code: %d, Preview: %s"), + ResponseCode, *ResponseData.Left(500)); + return; + } + + // 取出外层的 "data" 对象字段 + const TSharedPtr* DataObject; + if (!JsonObject->TryGetObjectField(TEXT("data"), DataObject) || !DataObject->IsValid()) + { + UE_LOG(LogLQARestoreTask, Warning, TEXT("No data field in job data response")); + return; + } + + // 取出 "data.datas" 数组字段, 其中每个元素是一条任务记录 + const TArray>* DataList; + if (!(*DataObject)->TryGetArrayField(TEXT("datas"), DataList)) + { + return; + } + + // 预分配容器大小, 减少动态扩容开销 + TArray IdList; + TArray IdPathList; + IdList.Reserve(DataList->Num()); + IdPathList.Reserve(DataList->Num()); + + // 遍历每条任务记录, 提取 id 与 file_path 字段 + for (const TSharedPtr& Value : *DataList) + { + const TSharedPtr& DataItem = Value->AsObject(); + if (DataItem.IsValid()) + { + IdList.Add(DataItem->GetStringField(TEXT("id"))); + IdPathList.Add(DataItem->GetStringField(TEXT("file_path"))); + } + } + + // 广播任务数据, 通知外部监听者进行后续处理 (如入队下载) + UE_LOG(LogLQARestoreTask, Log, TEXT("Received %d job data items"), IdList.Num()); + OnJobDataReceived.Broadcast(IdList, IdPathList); +} + +void UTaskManager::EnqueueDownload(const FString& DataId, const FString& FilePath) +{ + // 将 作为一个二元组加入下载队列 + PendingDownloads.Enqueue(MakeTuple(DataId, FilePath)); +} + +void UTaskManager::ProcessDownloadQueue() +{ + // 若正在下载或依赖未就绪, 则不启动新的下载 (保证串行执行) + if (bIsDownloading || !FileManager || !ConfigManager) + { + return; + } + + // 从队列取出下一个待下载项: 队列为空则直接返回 + TPair DownloadItem; + if (!PendingDownloads.Dequeue(DownloadItem)) + { + return; + } + + // 使用 MoveTemp 避免字符串拷贝, 记录当前活动下载任务信息 + ActiveDownloadDataId = MoveTemp(DownloadItem.Key); + ActiveDownloadFilePath = MoveTemp(DownloadItem.Value); + + // 若本地已存在对应 dump 文件, 则跳过下载并直接视为成功 (FilePath 传空表示复用已有文件) + if (FileManager->DumpFileExists(ActiveDownloadDataId, ConfigManager->GetPngSaveRootDir())) + { + UE_LOG(LogLQARestoreTask, Log, TEXT("Dump file already exists: %s"), *ActiveDownloadDataId); + OnDumpDataDownloaded.Broadcast(ActiveDownloadDataId, FString()); + return; + } + + // 置下载标志位, 加锁防止并发下载 + bIsDownloading = true; + UE_LOG(LogLQARestoreTask, Log, TEXT("Downloading dump data: %s"), *ActiveDownloadDataId); + + // 发起下载请求 + FHttpRequestHelper::GetDumpData(ActiveDownloadDataId, ActiveDownloadFilePath); + + // 绑定成功/失败回调 (弱指针保护, 防止悬空访问) + TWeakObjectPtr WeakThis(this); + FHttpRequestHelper::OnRequestSuccessForDump.BindLambda( + [WeakThis](FHttpResponsePtr ResponsePtr) + { + if (WeakThis.IsValid()) + { + WeakThis->OnDownloadSuccess(ResponsePtr); + } + }); + + FHttpRequestHelper::OnRequestFailForDump.BindLambda( + [WeakThis]() + { + if (WeakThis.IsValid()) + { + WeakThis->OnDownloadFail(); + } + }); +} + +void UTaskManager::OnDownloadSuccess(FHttpResponsePtr Response) +{ + // 响应无效, 转入失败处理 (可能触发重试) + if (!Response.IsValid()) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("Response is invalid: %s"), *ActiveDownloadDataId); + OnDownloadFail(); + return; + } + + // 校验 HTTP 状态码是否为 2xx 成功区间 + const int32 ResponseCode = Response->GetResponseCode(); + UE_LOG(LogLQARestoreTask, Log, TEXT("Download response code: %d, DataId: %s"), ResponseCode, *ActiveDownloadDataId); + + if (ResponseCode < 200 || ResponseCode >= 300) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("HTTP error response: %d, Content: %s"), ResponseCode, + *Response->GetContentAsString()); + OnDownloadFail(); + return; + } + + // 获取响应二进制内容 + const TArray& CompressedData = Response->GetContent(); + UE_LOG(LogLQARestoreTask, Log, TEXT("Downloaded data size: %d bytes"), CompressedData.Num()); + + // 空数据视为失败 + if (CompressedData.Num() == 0) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("Download data is empty: %s"), *ActiveDownloadDataId); + OnDownloadFail(); + return; + } + + // 通过文件头魔数 (0x1f 0x8b) 判断数据是否为 gzip 压缩格式 + if (CompressedData.Num() >= 2) + { + const bool bIsGzip = (CompressedData[0] == 0x1f && CompressedData[1] == 0x8b); + UE_LOG(LogLQARestoreTask, Log, TEXT("Data format check - IsGzip: %s, First bytes: %02X %02X"), + bIsGzip ? TEXT("Yes") : TEXT("No"), CompressedData[0], CompressedData[1]); + + if (!bIsGzip) + { + // 非 gzip: 按未压缩的原始 JSON 文本处理 + FString JsonString(UTF8_TO_TCHAR(CompressedData.GetData())); + UE_LOG(LogLQARestoreTask, Warning, TEXT("Data is not gzip compressed, treating as raw JSON")); + + // 校验 JSON 合法性 + TSharedPtr JsonObject; + const TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonString); + if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid()) + { + // 打印前 200 字符便于定位非法数据 + UE_LOG(LogLQARestoreTask, Error, TEXT("Invalid JSON data (raw): %s, Preview: %s"), *ActiveDownloadDataId, + *JsonString.Left(200)); + OnDownloadFail(); + return; + } + + // 保存到本地文件 + const FString SavedPath = + FileManager->SaveDumpDataToFile(ActiveDownloadDataId, JsonString, ConfigManager->GetPngSaveRootDir()); + if (SavedPath.IsEmpty()) + { + OnDownloadFail(); + return; + } + + // 下载成功: 重置重试计数、释放下载锁并广播结果 + UE_LOG(LogLQARestoreTask, Log, TEXT("Download success (raw JSON): %s"), *ActiveDownloadDataId); + DownloadRetryCount = 0; + bIsDownloading = false; + OnDumpDataDownloaded.Broadcast(ActiveDownloadDataId, SavedPath); + return; + } + } + + // gzip 数据: 执行解压 + TArray DecompressedData; + if (!DecompressGzipData(CompressedData, DecompressedData)) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("Failed to decompress gzip data: %s"), *ActiveDownloadDataId); + OnDownloadFail(); + return; + } + + // 将解压后的字节转为字符串, 并截断到最后一个 '}' 为止 + // (防止解压缓冲区尾部残留的未初始化/填充字节导致 JSON 解析失败) + FString JsonString(UTF8_TO_TCHAR(DecompressedData.GetData())); + int32 LastBraceIndex; + if (JsonString.FindLastChar(TCHAR('}'), LastBraceIndex)) + { + JsonString.LeftInline(LastBraceIndex + 1); + } + + // 校验 JSON 合法性 + TSharedPtr JsonObject; + const TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonString); + if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid()) + { + UE_LOG(LogLQARestoreTask, Error, TEXT("Invalid JSON data: %s"), *ActiveDownloadDataId); + OnDownloadFail(); + return; + } + + // 保存到本地文件 + const FString SavedPath = + FileManager->SaveDumpDataToFile(ActiveDownloadDataId, JsonString, ConfigManager->GetPngSaveRootDir()); + if (SavedPath.IsEmpty()) + { + OnDownloadFail(); + return; + } + + // 下载成功: 重置重试计数、释放下载锁并广播结果 + UE_LOG(LogLQARestoreTask, Log, TEXT("Download success: %s"), *ActiveDownloadDataId); + DownloadRetryCount = 0; + bIsDownloading = false; + OnDumpDataDownloaded.Broadcast(ActiveDownloadDataId, SavedPath); +} + +void UTaskManager::OnDownloadFail() +{ + // 累加重试计数 + ++DownloadRetryCount; + UE_LOG(LogLQARestoreTask, Error, TEXT("Download failed: %s (Retry: %d/%d)"), *ActiveDownloadDataId, DownloadRetryCount, + MaxRetryTimes); + + if (DownloadRetryCount < MaxRetryTimes) + { + // 未达最大重试次数: 将任务重新入队, 等待下一轮调度 + PendingDownloads.Enqueue(MakeTuple(ActiveDownloadDataId, ActiveDownloadFilePath)); + } + else + { + // 达到最大重试次数: 重置计数并广播最终失败 + DownloadRetryCount = 0; + OnDumpDataFailed.Broadcast(ActiveDownloadDataId); + } + + // 释放下载锁, 允许处理队列中的下一个任务 + bIsDownloading = false; +} + +bool UTaskManager::DecompressGzipData(const TArray& CompressedData, TArray& OutDecompressedData) +{ + // 初始化 zlib 解压流结构体并清零 + z_stream strm; + FMemory::Memset(&strm, 0, sizeof(strm)); + strm.zalloc = Z_NULL; // 使用 zlib 默认内存分配器 + strm.zfree = Z_NULL; + strm.opaque = Z_NULL; + + // inflateInit2 的窗口位参数: 16 + MAX_WBITS 表示启用 gzip 头解析 + if (inflateInit2(&strm, 16 + MAX_WBITS) != Z_OK) + { + return false; + } + + // 设置输入缓冲区指针与长度 (const_cast 去掉常量性以符合 zlib C 接口要求) + strm.avail_in = CompressedData.Num(); + strm.next_in = const_cast(CompressedData.GetData()); + + // 预分配输出缓冲区, 取 输入大小 与 1MB 中较大者, 减少后续扩容次数 + const int32 EstimatedSize = FMath::Max(CompressedData.Num(), InitialDecompressionBufferSize); + OutDecompressedData.Reserve(EstimatedSize); + OutDecompressedData.AddUninitialized(EstimatedSize); + + int32 Result; + do + { + // 根据已输出字节数更新输出游标与剩余可写空间 + strm.avail_out = OutDecompressedData.Num() - strm.total_out; + strm.next_out = OutDecompressedData.GetData() + strm.total_out; + + // 执行解压 + Result = inflate(&strm, Z_NO_FLUSH); + + // 解压完成 + if (Result == Z_STREAM_END) + { + break; + } + + // 出错: 清理流、清空输出并返回失败 + if (Result != Z_OK) + { + inflateEnd(&strm); + OutDecompressedData.Empty(); + return false; + } + + // 输出缓冲区已满但数据未解压完: 按增长因子扩容后继续 + if (strm.avail_out == 0) + { + const int32 NewSize = OutDecompressedData.Num() * DecompressionGrowthFactor; + OutDecompressedData.AddUninitialized(NewSize - OutDecompressedData.Num()); + } + } while (true); + + // 释放解压流资源, 并将输出数组裁剪为实际解压出的字节数 + inflateEnd(&strm); + OutDecompressedData.SetNum(strm.total_out); + return true; +} + +void UTaskManager::EnqueueUpload(const FString& DataId) +{ + // 将 DataId 加入上传队列 + PendingUploads.Enqueue(DataId); +} + +void UTaskManager::GetRestoreResultPaths(const FString& DataId, FString& OutPngDir, FString& OutJsonDir) const +{ + // 结果目录命名规则: Restore__<语言> + const FString DirName = FString::Printf(TEXT("Restore_%s_%s"), *DataId, *ConfigManager->GetLanguage()); + // 完整路径: /LQAResult/ + OutPngDir = FPaths::Combine(ConfigManager->GetPngSaveRootDir(), TEXT("LQAResult"), DirName); + // 当前实现 PNG 与 JSON 文件位于同一目录 + OutJsonDir = OutPngDir; +} + +void UTaskManager::ProcessUploadQueue() +{ + // 若正在上传或依赖未就绪, 则不启动新的上传 (保证串行执行) + if (bIsUploading || !FileManager || !ConfigManager) + { + return; + } + + // 从队列取出下一个待上传的 DataId;队列为空则返回 + if (!PendingUploads.Dequeue(ActiveUploadDataId)) + { + return; + } + + // 置上传标志位, 加锁防止并发上传 + bIsUploading = true; + UE_LOG(LogLQARestoreTask, Log, TEXT("Uploading restore result: %s"), *ActiveUploadDataId); + + // 计算该数据对应的结果目录 + FString PngDirectoryPath, JsonDirectoryPath; + GetRestoreResultPaths(ActiveUploadDataId, PngDirectoryPath, JsonDirectoryPath); + + // 结果目录不存在, 视为上传失败 + if (!FPaths::DirectoryExists(PngDirectoryPath)) + { + UE_LOG(LogLQARestoreTask, Warning, TEXT("Result directory not found: %s"), *PngDirectoryPath); + OnUploadFail(); + return; + } + + // 分别查找目录下的 PNG 与 JSON 文件 + TArray PngFiles; + TArray JsonFiles; + IFileManager& FileManagerRef = IFileManager::Get(); + FileManagerRef.FindFiles(PngFiles, *PngDirectoryPath, TEXT("png")); + FileManagerRef.FindFiles(JsonFiles, *JsonDirectoryPath, TEXT("json")); + + // PNG 或 JSON 缺失则无法上传 + if (PngFiles.Num() == 0 || JsonFiles.Num() == 0) + { + UE_LOG(LogLQARestoreTask, Warning, TEXT("No PNG or JSON files found for upload: %s"), *ActiveUploadDataId); + OnUploadFail(); + return; + } + + // 取第一个 PNG 和第一个 JSON 文件作为本次上传内容 + const FString PngFilePath = FPaths::Combine(PngDirectoryPath, PngFiles[0]); + const FString CheckInfoFilePath = FPaths::Combine(JsonDirectoryPath, JsonFiles[0]); + + // 发送还原结果请求, 参数均来自配置管理器 + FHttpRequestHelper::SendRestoreResult(ConfigManager->GetProjectId(), ConfigManager->GetJobId(), ActiveUploadDataId, + CheckInfoFilePath, {PngFilePath}, ConfigManager->GetLanguage(), ConfigManager->GetRegression(), + ConfigManager->GetCreateBug(), ConfigManager->GetBugId(), ConfigManager->GetAISign()); + + // 弱指针捕获, 并按值捕获目录路径供回调中清理使用 + TWeakObjectPtr WeakThis(this); + FHttpRequestHelper::OnRequestSuccessForSendResult.BindLambda( + [WeakThis, PngDirectoryPath, JsonDirectoryPath](FHttpResponsePtr ResponsePtr) + { + if (!WeakThis.IsValid() || !ResponsePtr.IsValid()) + { + return; + } + + // 上传成功后删除本地结果目录以释放磁盘空间 + WeakThis->FileManager->DeleteDirectory(PngDirectoryPath); + WeakThis->FileManager->DeleteDirectory(JsonDirectoryPath); + WeakThis->OnUploadSuccess(ResponsePtr); + }); + + FHttpRequestHelper::OnRequestFailForSendResult.BindLambda( + [WeakThis]() + { + if (WeakThis.IsValid()) + { + WeakThis->OnUploadFail(); + } + }); +} + +void UTaskManager::OnUploadSuccess(FHttpResponsePtr Response) +{ + // 上传成功: 重置重试计数、释放上传锁并广播结果 + UE_LOG(LogLQARestoreTask, Log, TEXT("Upload success: %s"), *ActiveUploadDataId); + UploadRetryCount = 0; + bIsUploading = false; + OnRestoreResultUploaded.Broadcast(ActiveUploadDataId); +} + +void UTaskManager::OnUploadFail() +{ + // 累加重试计数 + ++UploadRetryCount; + UE_LOG(LogLQARestoreTask, Error, TEXT("Upload failed: %s (Retry: %d/%d)"), *ActiveUploadDataId, UploadRetryCount, + MaxRetryTimes); + + if (UploadRetryCount < MaxRetryTimes) + { + // 未达最大重试次数: 重新入队等待重试 + PendingUploads.Enqueue(ActiveUploadDataId); + } + else + { + // 达到最大重试次数: 重置计数并放弃 (注意: 此处未广播失败事件) + UploadRetryCount = 0; + } + + // 释放上传锁, 允许处理队列中的下一个任务 + bIsUploading = false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQABase.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQABase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca964396652af8e3dbb5005805e8e436508d9887 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQABase.cpp @@ -0,0 +1,13 @@ +// 引入对应的头文件, 获取 LogLQARestore 日志分类的声明 +#include "LQABase.h" + +/** + * 定义 (实例化) 在 LQABase.h 中声明的 LogLQARestore 日志分类 + * + * DECLARE_LOG_CATEGORY_EXTERN 只是 “声明”, 而 DEFINE_LOG_CATEGORY 才真正 + * “定义” 该日志分类对应的全局对象, 两者必须成对出现: + * - 声明放在头文件中 (供多个源文件共享引用); + * - 定义放在某一个 .cpp 文件中 (且整个模块中只能定义一次), + * 否则会导致链接期 “重复定义” 或 “未定义符号” 的错误 + */ +DEFINE_LOG_CATEGORY(LogLQARestore) \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQARestore.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQARestore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b816524bdb24d832ec3ca601bab9a53dc3a61bb0 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/LQARestore.cpp @@ -0,0 +1,37 @@ +// 包含本模块对应的头文件 +#include "LQARestore.h" + +// 包含 HTTP 请求配置工具类, 用于初始化插件的网络请求相关配置 +#include "Utils/HttpUtils/HttpRequestConfig.h" + +// 定义本地化文本的命名空间, 供 LOCTEXT 等本地化宏使用 +// 使用后需在文件末尾用 #undef 取消定义, 避免影响其他文件 +#define LOCTEXT_NAMESPACE "FLQARestoreModule" + +/** + * 模块启动入口 + * 引擎在加载本插件模块时自动调用, 用于执行初始化逻辑 + */ +void FLQARestoreModule::StartupModule() +{ + // 从配置文件初始化 HTTP 请求配置 (如服务器地址、超时时间、请求头等) + HttpRequestConfig::Initialize(); +} + +/** + * 模块关闭入口 + * 引擎在卸载本插件模块 (或引擎退出) 时调用, 用于执行清理逻辑 + */ +void FLQARestoreModule::ShutdownModule() +{ + // 该函数可能在关闭阶段被调用, 用于清理本模块占用的资源 + // 当前无需额外清理操作, 故留空 +} + +// 取消本地化文本命名空间的定义, 与前面的 #define 配对使用 +#undef LOCTEXT_NAMESPACE + +// 向引擎注册并实现本模块 +// 第一个参数为模块类名, 第二个参数为模块名 (需与 .uplugin / .Build.cs 中的模块名一致) +// 该宏会生成模块的工厂函数, 使引擎能够正确创建并加载 FLQARestoreModule 实例 +IMPLEMENT_MODULE(FLQARestoreModule, LQARestore) \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/DataConverterUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/DataConverterUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf8634799c49a0904b0482b8a880610db1a3f79c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/DataConverterUtils.cpp @@ -0,0 +1,43 @@ +#include "Utils/DataConverterUtils.h" + +// 将十六进制字符串转换为二进制字节数组 +bool FDataConverterUtils::GetBinaryDataFromString(const FString& InData, TArray& OutData) +{ + // 先清空输出数组, 避免残留上一次调用的数据 + OutData.Empty(); + + // 获取输入字符串长度, 作为缓冲区的预分配大小 + const uint32 Size = InData.Len(); + + // 创建临时缓冲区并预分配空间 (SetNumUninitialized 不初始化内存, 性能更高) + TArray Buffer; + Buffer.SetNumUninitialized(Size); + + // 调用引擎自带的 ToHexBlob 将十六进制字符串解析为字节写入 Buffer + // 解析成功返回 true, 失败 (格式非法等) 返回 false + if (FString::ToHexBlob(InData, Buffer.GetData(), Size)) + { + // 使用 MoveTemp 进行移动语义赋值, 避免数组内存的额外拷贝 + OutData = MoveTemp(Buffer); + return true; + } + + // 解析失败, 返回 false, OutData 保持为空 + return false; +} + +// 将二进制字节数组转换为十六进制字符串 +void FDataConverterUtils::TransBinaryDataToString(const TArray& InData, FString& OutStr) +{ + // 先清空输出字符串, 避免残留上一次调用的数据 + OutStr.Empty(); + + // 预分配容量: 每个字节对应两个十六进制字符, 提前 Reserve 可减少动态扩容次数 + OutStr.Reserve(InData.Num() * 2); + + // 逐字节遍历, 将每个字节格式化为两位大写十六进制 (不足两位前面补 0) 并追加到结果字符串 + for (const uint8 Byte : InData) + { + OutStr += FString::Printf(TEXT("%02X"), Byte); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/GeometryUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/GeometryUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f87122575569da5739cfd690284e9aebf50547db --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/GeometryUtils.cpp @@ -0,0 +1,297 @@ +#include "Utils/GeometryUtils.h" + +#include "LQABase.h" + +// 将 JSON 数组转换为二维点 (FVector2D) 数组 +bool FGeometryUtils::JsonArrayToVector2DArray( + const TArray>& JsonArray, TArray& OutPoints, int32 ExpectedCount) +{ + // 先清空输出数组, 避免残留旧数据 + OutPoints.Empty(); + + // 若已知期望的点数量, 提前预留内存以减少动态扩容带来的开销 + if (ExpectedCount > 0) + { + OutPoints.Reserve(ExpectedCount); + } + + // 遍历 JSON 数组中的每一个元素 + for (const TSharedPtr& JsonValue : JsonArray) + { + // 跳过空的 JSON 值 + if (!JsonValue.IsValid()) + { + continue; + } + + // 将 JSON 值转换为 JSON 对象 (期望形如 { "x": ..., "y": ... }) + const TSharedPtr PointObj = JsonValue->AsObject(); + if (!PointObj.IsValid()) + { + continue; + } + + // 尝试读取 x、y 两个数值字段, 二者都存在时才算一个有效点 + double X = 0, Y = 0; + if (PointObj->TryGetNumberField(TEXT("x"), X) && PointObj->TryGetNumberField(TEXT("y"), Y)) + { + // double 转为 float 存入二维向量数组 + OutPoints.Add(FVector2D(static_cast(X), static_cast(Y))); + } + } + + // ExpectedCount < 0 表示不校验数量, 直接视为成功; + // 否则需要实际解析出的点数与期望数量一致才算成功 + return ExpectedCount < 0 || OutPoints.Num() == ExpectedCount; +} + +// 根据一组角点计算轴对齐包围盒 (AABB) +FBox2D FGeometryUtils::GetBoundingBox(const TArray& Corners) +{ + // 没有角点时返回一个默认 (空) 的包围盒 + if (Corners.Num() == 0) + { + return FBox2D(); + } + + // 以第一个角点初始化最小 / 最大坐标 + FVector2D Min = Corners[0]; + FVector2D Max = Corners[0]; + + // 遍历剩余角点, 逐步更新包围盒的边界 + for (int32 i = 1; i < Corners.Num(); ++i) + { + Min.X = FMath::Min(Min.X, Corners[i].X); + Min.Y = FMath::Min(Min.Y, Corners[i].Y); + Max.X = FMath::Max(Max.X, Corners[i].X); + Max.Y = FMath::Max(Max.Y, Corners[i].Y); + } + + // 由最小点和最大点构造包围盒 + return FBox2D(Min, Max); +} + +// 计算两个包围盒的重叠比例 (相对于 BoxB 的面积) +float FGeometryUtils::GetOverlapRatio(const FBox2D& BoxA, const FBox2D& BoxB) +{ + // 计算重叠区域的左下角 (取两个盒子较大的最小值) + FVector2D OverlapMin(FMath::Max(BoxA.Min.X, BoxB.Min.X), FMath::Max(BoxA.Min.Y, BoxB.Min.Y)); + // 计算重叠区域的右上角 (取两个盒子较小的最大值) + FVector2D OverlapMax(FMath::Min(BoxA.Max.X, BoxB.Max.X), FMath::Min(BoxA.Max.Y, BoxB.Max.Y)); + + // 重叠区域的宽和高 + float OverlapWidth = OverlapMax.X - OverlapMin.X; + float OverlapHeight = OverlapMax.Y - OverlapMin.Y; + + // 宽或高小于等于 0, 说明两个盒子没有实际重叠 + if (OverlapWidth <= 0 || OverlapHeight <= 0) + { + return 0.f; + } + + // 重叠面积 + float OverlapArea = OverlapWidth * OverlapHeight; + // BoxB 的总面积 (作为比例基准) + float AreaB = (BoxB.Max.X - BoxB.Min.X) * (BoxB.Max.Y - BoxB.Min.Y); + + // 基准面积无效时直接返回 0, 避免除零 + if (AreaB <= 0) + { + return 0.f; + } + + // 返回重叠面积占 BoxB 面积的比例 + return OverlapArea / AreaB; +} + +// 射线投射算法: 判断点是否在多边形内部 +bool FGeometryUtils::IsPointInPolygon(const FVector2D& Point, const TArray& Polygon) +{ + // 记录射线与多边形边的交点个数 + int32 Intersections = 0; + const int32 N = Polygon.Num(); + + // 依次遍历多边形的每一条边 (P1 -> P2) + for (int32 i = 0; i < N; ++i) + { + const FVector2D& P1 = Polygon[i]; + // 使用取模保证最后一条边能连回起点, 形成闭合多边形 + const FVector2D& P2 = Polygon[(i + 1) % N]; + + // 从测试点向右发出一条水平射线: + // 1) (P1.Y > Point.Y) != (P2.Y > Point.Y) 判断该边是否跨越测试点所在的水平线; + // 2) 后半部分计算该边与水平线交点的 X 坐标, 若在测试点右侧则记一次相交 + if (((P1.Y > Point.Y) != (P2.Y > Point.Y)) && + (Point.X < (P2.X - P1.X) * (Point.Y - P1.Y) / (P2.Y - P1.Y) + P1.X)) + { + Intersections++; + } + } + + // 交点个数为奇数时, 点在多边形内部 (奇偶规则) + return (Intersections % 2) == 1; +} + +// 判断两条线段 (P1P2) 与 (Q1Q2) 是否相交 +bool FGeometryUtils::DoLinesIntersect( + const FVector2D& P1, const FVector2D& P2, const FVector2D& Q1, const FVector2D& Q2) +{ + // Orientation: 计算三点 (A, B, C) 的方向 (叉积符号) + // 返回 0 -> 三点共线 + // 返回 1 -> 顺时针方向 + // 返回 2 -> 逆时针方向 + TFunction Orientation = + [](const FVector2D& A, const FVector2D& B, const FVector2D& C) + { + float Val = (B.Y - A.Y) * (C.X - B.X) - (B.X - A.X) * (C.Y - B.Y); + if (Val == 0) + { + return 0; + } + return (Val > 0) ? 1 : 2; + }; + + // OnSegment: 在已知三点共线的前提下, 判断点 B 是否落在线段 AC 上 + TFunction OnSegment = + [](const FVector2D& A, const FVector2D& B, const FVector2D& C) + { + return B.X <= FMath::Max(A.X, C.X) && B.X >= FMath::Min(A.X, C.X) && B.Y <= FMath::Max(A.Y, C.Y) && + B.Y >= FMath::Min(A.Y, C.Y); + }; + + // 分别计算四组三点的方向关系 + int O1 = Orientation(P1, P2, Q1); + int O2 = Orientation(P1, P2, Q2); + int O3 = Orientation(Q1, Q2, P1); + int O4 = Orientation(Q1, Q2, P2); + + // 一般情况: Q1、Q2 位于 P1P2 的两侧, 且 P1、P2 位于 Q1Q2 的两侧, 则相交 + if (O1 != O2 && O3 != O4) + { + return true; + } + + // 特殊情况 (共线且落在线段上): 处理端点重合或点在边上的边界情形 + if (O1 == 0 && OnSegment(P1, Q1, P2)) + { + return true; + } + if (O2 == 0 && OnSegment(P1, Q2, P2)) + { + return true; + } + if (O3 == 0 && OnSegment(Q1, P1, Q2)) + { + return true; + } + if (O4 == 0 && OnSegment(Q1, P2, Q2)) + { + return true; + } + + // 以上条件都不满足, 则两线段不相交 + return false; +} + +// 判断两个多边形的边是否存在相交 +bool FGeometryUtils::DoPolygonsEdgesIntersect(const TArray& A, const TArray& B) +{ + const int32 NA = A.Num(); + const int32 NB = B.Num(); + + // 遍历多边形 A 的每一条边 + for (int32 i = 0; i < NA; ++i) + { + const FVector2D& A_P1 = A[i]; + const FVector2D& A_P2 = A[(i + 1) % NA]; // 取模保证边闭合 + + // 遍历多边形 B 的每一条边 + for (int32 j = 0; j < NB; ++j) + { + const FVector2D& B_P1 = B[j]; + const FVector2D& B_P2 = B[(j + 1) % NB]; // 取模保证边闭合 + + // 只要有任意一对边相交, 即可判定两多边形的边相交 + if (DoLinesIntersect(A_P1, A_P2, B_P1, B_P2)) + { + return true; + } + } + } + + return false; +} + +// 判断两个多边形是否重叠 +bool FGeometryUtils::DoPolygonsOverlap(const TArray& A, const TArray& B) +{ + // 情况一: A 的任意顶点在 B 内部 (如 A 完全被 B 包含) + for (const FVector2D& PointA : A) + { + if (IsPointInPolygon(PointA, B)) + { + return true; + } + } + + // 情况二: B 的任意顶点在 A 内部 (如 B 完全被 A 包含) + for (const FVector2D& PointB : B) + { + if (IsPointInPolygon(PointB, A)) + { + return true; + } + } + + // 情况三: 两多边形的边相交 (部分重叠 / 相互穿插) + if (DoPolygonsEdgesIntersect(A, B)) + { + return true; + } + + // 三种情况都不满足则不重叠 + return false; +} + +#if !UE_BUILD_SHIPPING +// 调试用: 将 JSON 数组中的点逐个打印到日志 +void FGeometryUtils::PrintJsonArrayPoints(const TArray>& JsonArray, const FString& ArrayName) +{ + // 打印数组名称作为日志开头 + UE_LOG(LogLQARestore, Log, TEXT("Print array %s:"), *ArrayName); + + // 遍历数组中的每个元素 + for (int32 i = 0; i < JsonArray.Num(); ++i) + { + const TSharedPtr& JsonValue = JsonArray[i]; + + // 元素为空: 打印警告并跳过 + if (!JsonValue.IsValid()) + { + UE_LOG(LogLQARestore, Warning, TEXT(" Index %d JsonValue is invalid"), i); + continue; + } + + // 尝试转换为 JSON 对象 + const TSharedPtr PointObj = JsonValue->AsObject(); + if (PointObj.IsValid()) + { + double X = 0, Y = 0; + // 同时读取到 x、y 字段才打印坐标, 否则提示字段缺失 + if (PointObj->TryGetNumberField(TEXT("x"), X) && PointObj->TryGetNumberField(TEXT("y"), Y)) + { + UE_LOG(LogLQARestore, Log, TEXT(" Point[%d] : x = %.3f, y = %.3f"), i, X, Y); + } + else + { + UE_LOG(LogLQARestore, Warning, TEXT(" Point[%d] missing x or y field"), i); + } + } + else + { + // 元素不是 JSON 对象 + UE_LOG(LogLQARestore, Warning, TEXT(" Point[%d] is not a Json object"), i); + } + } +} +#endif \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestConfig.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestConfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19c34b5efe910099d168d809925d9cccfb2caa16 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestConfig.cpp @@ -0,0 +1,104 @@ +#include "Utils/HttpUtils/HttpRequestConfig.h" + +#include "Misc/ConfigCacheIni.h" // 提供 GConfig, 用于读取 .ini 配置文件 +#include "Interfaces/IPluginManager.h" // 提供 IPluginManager, 用于定位插件目录 + +// 为头文件中声明的日志分类提供唯一定义 (整个模块只能定义一次) +DEFINE_LOG_CATEGORY(LogLQARestoreHttp); + +namespace HttpRequestConfig +{ +// 全局配置变量的实际定义与初始值 (默认空字符串, 加载成功后被覆盖) +FString Host = TEXT(""); +FString FileHost = TEXT(""); +FString Authorization = TEXT(""); + +/** + * 从插件的 Config/LQARestore.ini 读取 HTTP 配置并写入全局变量 + * 流程: + * 1. 定位 LQARestore 插件; + * 2. 拼接并校验配置文件绝对路径; + * 3. 通过 GConfig 读取 [HttpConfig] 节下的 Host / Authorization + * 任意步骤失败都会记录日志并安全返回, 不会抛出异常 + */ +void Initialize() +{ + // 通过插件管理器查找名为 "LQARestore" 的插件实例 + const TSharedPtr Plugin = IPluginManager::Get().FindPlugin(TEXT("LQARestore")); + if (!Plugin.IsValid()) + { + // 未找到插件 (例如插件未启用或名称不匹配), 无法继续加载配置 + UE_LOG(LogLQARestoreHttp, Error, TEXT("Plugin 'LQARestore' not found")); + return; + } + + // 以插件根目录为基准拼接配置文件路径, 并转换为绝对路径以保证可靠性 + const FString ConfigFile = FPaths::ConvertRelativePathToFull(Plugin->GetBaseDir() / TEXT("Config/LQARestore.ini")); + + UE_LOG(LogLQARestoreHttp, Log, TEXT("Attempting to load config from: %s"), *ConfigFile); + + // 文件不存在时仅警告并返回, 使用默认 (空) 配置 + if (!FPaths::FileExists(ConfigFile)) + { + UE_LOG(LogLQARestoreHttp, Warning, TEXT("Config file not found: %s"), *ConfigFile); + return; + } + + UE_LOG(LogLQARestoreHttp, Log, TEXT("Config file found, loading...")); + + // 配置项所在的节 (section) 名称, 对应 .ini 中的 [HttpConfig] + const FString ConfigSection = TEXT("HttpConfig"); + + // GConfig 是引擎全局配置缓存, 正常运行期一般有效, 这里仍做空指针防护 + if (GConfig) + { + FString ConfigHost; + FString ConfigAuth; + + // 读取 Host: 成功时自动补全 "http://" 前缀后写入全局 Host + if (GConfig->GetString(*ConfigSection, TEXT("Host"), ConfigHost, ConfigFile)) + { + Host = TEXT("http://") + ConfigHost; + UE_LOG(LogLQARestoreHttp, Log, TEXT("Loaded Host: %s"), *Host); + } + else + { + // 缺少 Host 配置项, 保持默认空值 + UE_LOG(LogLQARestoreHttp, Warning, TEXT("Host not found in config")); + } + + // 读取 FileHost (下载基址): 成功时补全 "http://" 前缀; 缺省时回退到 Host + FString ConfigFileHost; + if (GConfig->GetString(*ConfigSection, TEXT("FileHost"), ConfigFileHost, ConfigFile) && + !ConfigFileHost.IsEmpty()) + { + FileHost = TEXT("http://") + ConfigFileHost; + UE_LOG(LogLQARestoreHttp, Log, TEXT("Loaded FileHost: %s"), *FileHost); + } + else + { + // 未配置 FileHost 时, 回退使用 Host (保持旧行为的兼容) + FileHost = Host; + UE_LOG(LogLQARestoreHttp, Warning, TEXT("FileHost not found, fallback to Host: %s"), *FileHost); + } + + // 读取 Authorization: 成功时写入全局 Authorization + if (GConfig->GetString(*ConfigSection, TEXT("Authorization"), ConfigAuth, ConfigFile)) + { + Authorization = ConfigAuth; + // 出于安全考虑只打印长度, 不打印令牌内容本身, 避免泄露敏感信息 + UE_LOG(LogLQARestoreHttp, Log, TEXT("Loaded Authorization (length: %d)"), Authorization.Len()); + } + else + { + // 缺少 Authorization 配置项, 保持默认空值 + UE_LOG(LogLQARestoreHttp, Warning, TEXT("Authorization not found in config")); + } + } + else + { + // GConfig 不可用 (极少见, 通常是过早调用导致), 记录错误 + UE_LOG(LogLQARestoreHttp, Error, TEXT("GConfig is null")); + } +} +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestHelper.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29e177f4c899d0b5f8b522c83af662b8c554b39a --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/HttpUtils/HttpRequestHelper.cpp @@ -0,0 +1,239 @@ +#include "Utils/HttpUtils/HttpRequestHelper.h" + +#include "LQABase.h" +#include "Misc/FileHelper.h" // FFileHelper: 文件读取为字节数组 +#include "Misc/Paths.h" // FPaths: 文件路径与存在性判断 + +// 关闭编译器优化 (通常用于调试, 便于单步跟踪 HTTP 组包逻辑) +LQA_DISABLE_OPTIMIZATION + +// ===== 静态委托成员定义 (在头文件中声明, 此处分配存储空间) ===== +FOnRequestSuccess FHttpRequestHelper::OnRequestSuccess; +FOnRequestSuccess FHttpRequestHelper::OnRequestSuccessForDump; +FOnRequestSuccess FHttpRequestHelper::OnRequestSuccessForSendResult; +FOnRequestFail FHttpRequestHelper::OnRequestFailForDump; +FOnRequestFail FHttpRequestHelper::OnRequestFailForSendResult; + +// 创建并初始化一个 HTTP 请求对象 +TSharedRef FHttpRequestHelper::CreateRequest(const FString& URL, const FString& Verb) +{ + // 通过 HTTP 模块单例创建请求实例 + TSharedRef Request = FHttpModule::Get().CreateRequest(); + Request->SetURL(URL); // 设置目标地址 + Request->SetVerb(Verb); // 设置请求方法 (GET/POST 等) + // 记录请求日志, 便于排查 + UE_LOG(LogLQARestoreHttp, Log, TEXT("%s: %s"), *Verb, *URL); + return Request; +} + +// 统一的响应处理: 成功则触发成功委托, 否则记录警告并触发失败委托 +void FHttpRequestHelper::HandleResponse( + FHttpResponsePtr Response, bool bSuccess, FOnRequestSuccess& SuccessDelegate, FOnRequestFail& FailDelegate) +{ + // 连接成功且响应有效 + if (bSuccess && Response.IsValid()) + { + if (SuccessDelegate.IsBound()) // 仅在委托已绑定时执行, 避免空调用 + { + SuccessDelegate.Execute(Response); + } + } + else + { + // 请求失败 (网络错误或响应无效) + UE_LOG(LogLQARestoreHttp, Warning, TEXT("Request failed")); + if (FailDelegate.IsBound()) + { + FailDelegate.Execute(); + } + } +} + +// 发送 dump 文件数据到服务器 +void FHttpRequestHelper::SendDumpFile(const FString& JsonData, const FString& ProjectId) +{ + // 拼接接口地址: {Host}/data/project/{ProjectId}/create + const FString URL = HttpRequestConfig::Host + TEXT("/data/project/") + ProjectId + TEXT("/create"); + TSharedRef Request = CreateRequest(URL, TEXT("POST")); + // 以表单编码方式提交 + Request->SetHeader(TEXT("Content-Type"), TEXT("application/x-www-form-urlencoded")); + Request->SetContentAsString(JsonData); // 设置请求体为 JSON 字符串 + // 绑定完成回调并发起异步请求 + Request->OnProcessRequestComplete().BindStatic(&FHttpRequestHelper::OnRequestResponseFinished); + Request->ProcessRequest(); +} + +// 获取项目信息 +void FHttpRequestHelper::GetProjectInfo(const FString& ProjectId) +{ + // 拼接接口地址, format=SDK 表示以 SDK 格式返回 + const FString URL = HttpRequestConfig::Host + TEXT("/project/project_info/") + ProjectId + TEXT("?format=SDK"); + TSharedRef Request = CreateRequest(URL, TEXT("GET")); + Request->OnProcessRequestComplete().BindStatic(&FHttpRequestHelper::OnRequestResponseFinished); + Request->ProcessRequest(); +} + +// 获取任务数据 (带查询参数拼接) +void FHttpRequestHelper::GetJobData(const FString& JobId, const FString& IsRegression, const FString& Language, + const FString& Count, const FString& MinId, const FString& Modules) +{ + // 组织查询参数键值对 + TMap Params = {{TEXT("job_id"), JobId}, {TEXT("regression"), IsRegression}, + {TEXT("language"), Language}, {TEXT("count"), Count}, {TEXT("minID"), MinId}}; + + // 模块参数非空时, 将下划线分隔转换为逗号分隔后加入参数 + if (!Modules.IsEmpty()) + { + Params.Add(TEXT("module_ids"), Modules.Replace(TEXT("_"), TEXT(","), ESearchCase::IgnoreCase)); + } + + // 遍历参数并进行 URL 编码, 拼接为 query string (以 & 连接) + FString QueryString; + for (const TPair& Pair : Params) + { + if (!QueryString.IsEmpty()) + QueryString += TEXT("&"); + QueryString += FString::Printf( + TEXT("%s=%s"), *FGenericPlatformHttp::UrlEncode(*Pair.Key), *FGenericPlatformHttp::UrlEncode(*Pair.Value)); + } + + // 拼接最终 URL + const FString URL = HttpRequestConfig::Host + TEXT("/api/job/datas?") + QueryString; + TSharedRef Request = CreateRequest(URL, TEXT("GET")); + // 设置鉴权头 + Request->SetHeader(TEXT("LQA-Authorization"), HttpRequestConfig::Authorization); + Request->OnProcessRequestComplete().BindStatic(&FHttpRequestHelper::OnGetJobDataRequestResponseFinished); + Request->ProcessRequest(); +} + +// 发送还原结果 (使用 multipart/form-data 同时提交表单字段与文件) +void FHttpRequestHelper::SendRestoreResult(const FString& ProjectId, const FString& JobId, const FString& DataId, + const FString& CheckInfoFilePath, const TArray& PngFilePaths, const FString& Language, + const FString& Regression, const FString& CreateBug, const FString& BugId, const FString& AISign) +{ + const FString URL = HttpRequestConfig::Host + TEXT("/api/image/entity"); + TSharedRef Request = CreateRequest(URL, TEXT("POST")); + Request->SetHeader(TEXT("LQA-Authorization"), HttpRequestConfig::Authorization); + + // 生成 multipart 分隔符 (使用 GUID 保证唯一性) + const FString Boundary = TEXT("--") + FGuid::NewGuid().ToString(); + Request->SetHeader(TEXT("Content-Type"), TEXT("multipart/form-data; boundary=") + Boundary); + + // 请求体内容以字节数组形式手动拼装 + TArray Content; + const FString BoundaryPrefix = FString::Printf(TEXT("--%s\r\n"), *Boundary); // 每个分段的起始分隔行 + + // 普通表单字段集合 (注意: rect_locations 为文件路径, 稍后作为文件内容读取) + TMap FormData = {{TEXT("project_id"), ProjectId}, {TEXT("job_id"), JobId}, + {TEXT("data_id"), DataId}, {TEXT("language"), Language}, {TEXT("rect_locations"), CheckInfoFilePath}, + {TEXT("regression"), Regression}, {TEXT("ai_sign"), AISign}, {TEXT("create_bug_tapd"), CreateBug}}; + + // 逐个写入表单字段 + for (const TPair& Pair : FormData) + { + // 写入分隔符 + Content.Append(reinterpret_cast(TCHAR_TO_UTF8(*BoundaryPrefix)), BoundaryPrefix.Len()); + // 写入该字段的 Content-Disposition 头 + Content.Append(reinterpret_cast(TCHAR_TO_UTF8( + *FString::Printf(TEXT("Content-Disposition: form-data; name=\"%s\"\r\n\r\n"), *Pair.Key))), + FString::Printf(TEXT("Content-Disposition: form-data; name=\"%s\"\r\n\r\n"), *Pair.Key).Len()); + + if (Pair.Key == TEXT("rect_locations")) + { + // rect_locations 特殊处理: 将其值当作文件路径, 读取文件内容写入请求体 + TArray FileData; + if (FFileHelper::LoadFileToArray(FileData, *Pair.Value)) + { + Content.Append(FileData); + } + } + else + { + // 普通字段: 直接写入字符串值 (UTF-8) + Content.Append(reinterpret_cast(TCHAR_TO_UTF8(*Pair.Value)), Pair.Value.Len()); + } + // 字段结束换行 + Content.Append(reinterpret_cast("\r\n"), 2); + } + + // 逐个写入 PNG 图片文件 + for (const FString& FilePath : PngFilePaths) + { + if (FPaths::FileExists(FilePath)) // 仅处理存在的文件 + { + // 文件名规则: {JobId}-{DataId}-{Language}.png + const FString FileName = FString::Printf(TEXT("%s-%s-%s.png"), *JobId, *DataId, *Language); + // 文件分段头, 字段名统一为 "files", 二进制流类型 + const FString FileHeader = + FString::Printf(TEXT("Content-Disposition: form-data; name=\"files\"; filename=\"%s\"\r\nContent-Type: " + "application/octet-stream\r\n\r\n"), + *FileName); + + TArray FileData; + if (FFileHelper::LoadFileToArray(FileData, *FilePath)) // 读取图片字节 + { + Content.Append(reinterpret_cast(TCHAR_TO_UTF8(*BoundaryPrefix)), BoundaryPrefix.Len()); + Content.Append(reinterpret_cast(TCHAR_TO_UTF8(*FileHeader)), FileHeader.Len()); + Content.Append(FileData); // 图片数据主体 + Content.Append(reinterpret_cast("\r\n"), 2); // 分段结束换行 + } + } + } + + // 写入 multipart 结束分隔符 (--boundary--) + Content.Append(reinterpret_cast(TCHAR_TO_UTF8(*FString::Printf(TEXT("--%s--\r\n"), *Boundary))), + FString::Printf(TEXT("--%s--\r\n"), *Boundary).Len()); + + // 设置请求体并发起请求 + Request->SetContent(Content); + Request->OnProcessRequestComplete().BindStatic(&FHttpRequestHelper::OnRequestResponseFinished); + Request->ProcessRequest(); +} + +// 下载 dump 数据 +void FHttpRequestHelper::GetDumpData(const FString& DataId, const FString& FilePath) +{ + // 下载基址使用独立的 FileHost (file_path 为域名根下绝对路径, 不含 API 网关前缀); + // FileHost 为空时回退到 Host, 不再对端口做 :8080->:80 的硬替换 + const FString DownloadHost = + HttpRequestConfig::FileHost.IsEmpty() ? HttpRequestConfig::Host : HttpRequestConfig::FileHost; + + const FString URL = DownloadHost + FilePath; + TSharedRef Request = CreateRequest(URL, TEXT("GET")); + Request->SetHeader(TEXT("Content-Type"), TEXT("application/json")); + + // 若下载同样需要鉴权, 带上鉴权头 (media 为公开资源时服务端会忽略该头, 不影响) + Request->SetHeader(TEXT("LQA-Authorization"), HttpRequestConfig::Authorization); + + // 构造用户数据, 携带 DataId 以便回调时识别对应数据 + TSharedPtr RequestData = MakeShared(); + RequestData->DataId = DataId; + + // 绑定携带用户数据的回调并发起请求 + Request->OnProcessRequestComplete().BindStatic(&FHttpRequestHelper::OnGetDataRequestResponseFinished, RequestData); + Request->ProcessRequest(); +} + +// 任务数据请求完成回调 -> 分发到通用成功 / dump 失败委托 +void FHttpRequestHelper::OnGetJobDataRequestResponseFinished( + FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully) +{ + HandleResponse(Response, bConnectedSuccessfully, OnRequestSuccess, OnRequestFailForDump); +} + +// 通用请求完成回调 -> 分发到发送结果成功 / 失败委托 +void FHttpRequestHelper::OnRequestResponseFinished( + FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully) +{ + HandleResponse(Response, bConnectedSuccessfully, OnRequestSuccessForSendResult, OnRequestFailForSendResult); +} + +// dump 数据下载完成回调 -> 分发到 dump 成功 / 失败委托 +void FHttpRequestHelper::OnGetDataRequestResponseFinished(FHttpRequestPtr Request, FHttpResponsePtr Response, + bool bConnectedSuccessfully, TSharedPtr UserData) +{ + HandleResponse(Response, bConnectedSuccessfully, OnRequestSuccessForDump, OnRequestFailForDump); +} + +// 恢复编译器优化 +LQA_ENABLE_OPTIMIZATION \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/ImageRenderUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/ImageRenderUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..973345d9c92f49cc146a9349235064f591edb1e4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/ImageRenderUtils.cpp @@ -0,0 +1,416 @@ +#include "Utils/ImageRenderUtils.h" + +#include "LQABase.h" // 提供 LogLQARestore 日志分类 + +#include "Components/Button.h" // UButton 控件 +#include "Components/Image.h" // UImage 控件 + +//============================================================================== +// 画刷与控件可见性 (Brush & Widget Visibility) +//============================================================================== + +// 综合判断一个 Slate 画刷是否会真正渲染出可见内容 +// 任意一项检查不通过即认为 “不可见”, 提前返回 false +bool FImageRenderUtils::IsBrushVisible( + const FSlateBrush& Brush, ESlateVisibility Visibility, float RenderOpacity, FVector2D RenderScale) +{ + // 1. 可见性状态: Collapsed (折叠, 不占布局) 或 Hidden (隐藏, 占布局) 都不渲染 + if (Visibility == ESlateVisibility::Collapsed || Visibility == ESlateVisibility::Hidden) + { + return false; + } + + // 2. 渲染不透明度: 小于等于 0 表示完全透明, 不可见 + if (RenderOpacity <= 0.0f) + { + return false; + } + + // 3. 渲染缩放: 任一轴缩放为 0 则被压缩成一条线/一点, 不可见 + if (RenderScale.X == 0.0f || RenderScale.Y == 0.0f) + { + return false; + } + + // 4. 绘制类型: NoDrawType 表示不绘制任何内容 + if (Brush.DrawAs == ESlateBrushDrawType::NoDrawType) + { + return false; + } + + // 5. 图像尺寸: 宽或高小于等于 0 则没有可绘制面积 + FVector2D ImageSize = Brush.GetImageSize(); + if (ImageSize.X <= 0.0f || ImageSize.Y <= 0.0f) + { + return false; + } + + // 6. 着色颜色的 Alpha: 小于等于 0 表示整体被着色为完全透明 + FLinearColor Tint = Brush.TintColor.GetSpecifiedColor(); + if (Tint.A <= 0.0f) + { + return false; + } + + // 7. 资源对象: 若没有绑定资源 (如纹理/材质) + if (Brush.GetResourceObject() == nullptr) + { + // 当绘制类型既不是 Box (九宫格盒子) 也不是 Border (边框) 时, + // 没有资源意味着没有可绘制内容; 而 Box/Border 可仅靠纯色绘制, 故放行 + if (Brush.DrawAs != ESlateBrushDrawType::Box && Brush.DrawAs != ESlateBrushDrawType::Border) + { + return false; + } + } + + // 所有检查均通过, 判定为可见 + return true; +} + +// 判断画刷是否没有可绘制背景: 绘制类型为 NoDrawType 或无资源对象 +bool FImageRenderUtils::IsBrushNoBackground(const FSlateBrush& Brush) +{ + return Brush.DrawAs == ESlateBrushDrawType::NoDrawType || Brush.GetResourceObject() == nullptr; +} + +// 判断控件在所有状态下是否都没有背景, 目前仅支持 UButton 和 UImage +bool FImageRenderUtils::IsWidgetNoBackground(UWidget* Widget) +{ + // 空指针保护 + if (!Widget) + { + return false; + } + + // —— 按钮控件 —— + if (UButton* Button = Cast(Widget)) + { + // UE 5.1+ 中直接访问 UButton::WidgetStyle 已废弃, 必须改用 GetStyle(); UE4 下仍可直接访问字段 +#if ENGINE_MAJOR_VERSION >= 5 + const FButtonStyle& Style = Button->GetStyle(); +#else + const FButtonStyle& Style = Button->WidgetStyle; +#endif + + // 只有当按钮的四种状态 (常态/悬停/按下/禁用) 画刷全部无背景时, 才认为该按钮无背景 + return IsBrushNoBackground(Style.Normal) && IsBrushNoBackground(Style.Hovered) && + IsBrushNoBackground(Style.Pressed) && IsBrushNoBackground(Style.Disabled); + } + // —— 图像控件 —— + else if (UImage* Image = Cast(Widget)) + { + // 检查 Image 的画刷是否无背景 (同样做引擎版本兼容处理) +#if ENGINE_MAJOR_VERSION >= 5 + return IsBrushNoBackground(Image->GetBrush()); +#else + return IsBrushNoBackground(Image->Brush); +#endif + } + + // 其它类型控件暂不处理, 默认返回 false (视为有背景) + return false; +} + +//============================================================================== +// 纹理 Alpha 通道分析 (Texture Alpha Analysis) +//============================================================================== + +// 遍历纹理每个像素, 计算 Alpha 大于阈值的可见像素所构成的包围矩形 +// 基于 PlatformData (运行时平台数据) 读取像素颜色 +FIntRect FImageRenderUtils::GetVisiblePixelRect(UTexture2D* Texture, uint8 AlphaThreshold) +{ + // UE 5.0+ 中 PlatformData 已私有化, 必须通过 GetPlatformData() 访问; UE4 下保留直接字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + // 校验纹理有效性及是否存在 Mip 数据 + if (!Texture || !Texture->GetPlatformData() || Texture->GetPlatformData()->Mips.Num() == 0) + { + return FIntRect(); + } + + // 取第 0 级 Mip (最高分辨率) + FTexture2DMipMap& Mip = Texture->GetPlatformData()->Mips[0]; +#else + if (!Texture || !Texture->PlatformData || Texture->PlatformData->Mips.Num() == 0) + { + return FIntRect(); + } + + FTexture2DMipMap& Mip = Texture->PlatformData->Mips[0]; +#endif + int32 Width = Mip.SizeX; + int32 Height = Mip.SizeY; + + // 以只读方式锁定批量数据, 获取像素内存指针 + void* Data = Mip.BulkData.Lock(LOCK_READ_ONLY); + if (!Data) + { + // 锁定失败也要解锁, 避免数据保持锁定状态 + Mip.BulkData.Unlock(); + return FIntRect(); + } + + // 将原始数据按 FColor (BGRA/RGBA 每像素 4 字节) 解释 + FColor* Colors = static_cast(Data); + + // 初始化边界: Min 取最大值、Max 取最小值, 便于后续收敛 + int32 MinX = Width, MinY = Height, MaxX = 0, MaxY = 0; + bool bFound = false; // 是否找到至少一个可见像素 + + // 逐行逐列扫描所有像素 + for (int32 Y = 0; Y < Height; ++Y) + { + for (int32 X = 0; X < Width; ++X) + { + FColor& Pixel = Colors[Y * Width + X]; + if (Pixel.A > AlphaThreshold) // Alpha 超过阈值视为可见 + { + bFound = true; + // 不断更新包围矩形的四个边界 + MinX = FMath::Min(MinX, X); + MinY = FMath::Min(MinY, Y); + MaxX = FMath::Max(MaxX, X); + MaxY = FMath::Max(MaxY, Y); + } + } + } + + // 解锁批量数据 + Mip.BulkData.Unlock(); + + if (!bFound) + { + // 整张纹理完全透明, 返回空矩形 + return FIntRect(0, 0, 0, 0); + } + + // 注意: MaxX、MaxY 是 “包含” 的像素索引, 而 FIntRect 右下角为开区间, 故需 +1 + return FIntRect(MinX, MinY, MaxX + 1, MaxY + 1); +} + +// 检查纹理指定区域内是否存在透明像素, 基于 Source (源) 数据以保证 Alpha 精确 +bool FImageRenderUtils::HasTransparencyFromSource( + UTexture2D* Texture, uint8 AlphaThreshold, FIntPoint RegionUV, FIntPoint RegionSize) +{ +#if WITH_EDITOR + // 纹理及其源数据有效性校验 + if (!Texture || !Texture->Source.IsValid()) + { + UE_LOG(LogLQARestore, Warning, TEXT("Texture is invalid or has no Source data")); + return false; + } + + int32 Width = Texture->Source.GetSizeX(); + int32 Height = Texture->Source.GetSizeY(); + + // 若未指定区域尺寸, 则默认检测整张纹理 + if (RegionSize.X == 0 || RegionSize.Y == 0) + { + RegionUV = FIntPoint(0, 0); + RegionSize = FIntPoint(Width, Height); + } + + // 校验检测区域是否越界 + if (RegionUV.X < 0 || RegionUV.Y < 0 || RegionUV.X + RegionSize.X > Width || RegionUV.Y + RegionSize.Y > Height) + { + UE_LOG(LogLQARestore, Warning, TEXT("Detection region exceeds texture bounds")); + return false; + } + + // 读取第 0 级 Mip 的原始字节数据 (每像素 4 字节: R,G,B,A) + TArray> RawData; + if (!Texture->Source.GetMipData(RawData, 0)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to get Mip data")); + return false; + } + + // 遍历区域内每个像素, 取其 Alpha 分量 (偏移 +3) + for (int32 Y = RegionUV.Y; Y < RegionUV.Y + RegionSize.Y; ++Y) + { + for (int32 X = RegionUV.X; X < RegionUV.X + RegionSize.X; ++X) + { + uint8 Alpha = RawData[(Y * Width + X) * 4 + 3]; + if (Alpha <= AlphaThreshold) // 一旦发现透明像素立即返回 + { + return true; + } + } + } + + // 区域内未发现透明像素 + return false; +#else + // 打包 (非编辑器) 构建下无法访问 UTexture2D::Source, 功能降级 + UE_LOG(LogLQARestore, Warning, + TEXT("HasTransparencyFromSource 依赖编辑器源数据(Source), 打包版本不可用")); + return false; +#endif +} + +// 由外向内扫描四条边, 求出不透明像素的包围盒, 基于 Source 源数据分析 +FIntRect FImageRenderUtils::GetAlphaBoundsFromSource_OuterToInner( + UTexture2D* Texture, uint8 AlphaThreshold, FIntPoint RegionUV, FIntPoint RegionSize) +{ + // 默认返回空矩形 + FIntRect Result(0, 0, 0, 0); + +#if WITH_EDITOR + // 纹理及其源数据有效性校验 + if (!Texture || !Texture->Source.IsValid()) + { + UE_LOG(LogLQARestore, Warning, TEXT("Texture is invalid or has no Source data")); + return Result; + } + + int32 Width = Texture->Source.GetSizeX(); + int32 Height = Texture->Source.GetSizeY(); + + // 未指定区域尺寸则默认为整张纹理 + if (RegionSize.X == 0 || RegionSize.Y == 0) + { + RegionUV = FIntPoint(0, 0); + RegionSize = FIntPoint(Width, Height); + } + + // 区域越界校验 + if (RegionUV.X < 0 || RegionUV.Y < 0 || RegionUV.X + RegionSize.X > Width || RegionUV.Y + RegionSize.Y > Height) + { + UE_LOG(LogLQARestore, Warning, TEXT("Detection region exceeds texture bounds")); + return Result; + } + + // 读取第 0 级 Mip 原始字节数据 + TArray> RawData; + if (!Texture->Source.GetMipData(RawData, 0)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to get Mip data")); + return Result; + } + + // 四个边界初始为 -1, 表示尚未找到 + int32 Left = -1; + int32 Right = -1; + int32 Top = -1; + int32 Bottom = -1; + + // —— 从左向右扫描, 找到第一列含不透明像素的位置, 即为左边界 —— + for (int32 X = RegionUV.X; X < RegionUV.X + RegionSize.X; ++X) + { + bool bFound = false; + for (int32 Y = RegionUV.Y; Y < RegionUV.Y + RegionSize.Y; ++Y) + { + uint8 Alpha = RawData[(Y * Width + X) * 4 + 3]; + if (Alpha > AlphaThreshold) + { + Left = X; + bFound = true; + break; // 本列已找到不透明像素, 无需继续 + } + } + if (bFound) + { + break; // 已确定左边界, 结束外层循环 + } + } + + // —— 从右向左扫描, 找到右边界 —— + for (int32 X = RegionUV.X + RegionSize.X - 1; X >= RegionUV.X; --X) + { + bool bFound = false; + for (int32 Y = RegionUV.Y; Y < RegionUV.Y + RegionSize.Y; ++Y) + { + uint8 Alpha = RawData[(Y * Width + X) * 4 + 3]; + if (Alpha > AlphaThreshold) + { + Right = X; + bFound = true; + break; + } + } + if (bFound) + { + break; + } + } + + // —— 从上向下扫描, 找到上边界 —— + // 此处 X 范围已利用上面求得的 Left/Right 做收窄优化, 减少无效扫描 + for (int32 Y = RegionUV.Y; Y < RegionUV.Y + RegionSize.Y; ++Y) + { + bool bFound = false; + for (int32 X = (Left != -1 ? Left : RegionUV.X); X <= (Right != -1 ? Right : RegionUV.X + RegionSize.X - 1); + ++X) + { + uint8 Alpha = RawData[(Y * Width + X) * 4 + 3]; + if (Alpha > AlphaThreshold) + { + Top = Y; + bFound = true; + break; + } + } + if (bFound) + { + break; + } + } + + // —— 从下向上扫描, 找到下边界 —— + for (int32 Y = RegionUV.Y + RegionSize.Y - 1; Y >= RegionUV.Y; --Y) + { + bool bFound = false; + for (int32 X = (Left != -1 ? Left : RegionUV.X); X <= (Right != -1 ? Right : RegionUV.X + RegionSize.X - 1); + ++X) + { + uint8 Alpha = RawData[(Y * Width + X) * 4 + 3]; + if (Alpha > AlphaThreshold) + { + Bottom = Y; + bFound = true; + break; + } + } + if (bFound) + { + break; + } + } + + // 若某方向始终未找到不透明像素, 则退回使用该方向的区域默认边界 + if (Left == -1) + { + Left = RegionUV.X; + } + if (Right == -1) + { + Right = RegionUV.X + RegionSize.X - 1; + } + if (Top == -1) + { + Top = RegionUV.Y; + } + if (Bottom == -1) + { + Bottom = RegionUV.Y + RegionSize.Y - 1; + } + + // 返回包围矩形, 由于 FIntRect 右下角为开区间, Right、Bottom 需 +1 + return FIntRect(Left, Top, Right + 1, Bottom + 1); +#else + // 打包 (非编辑器) 构建下无法访问 UTexture2D::Source, 返回空矩形 + UE_LOG(LogLQARestore, Warning, + TEXT("GetAlphaBoundsFromSource_OuterToInner 依赖编辑器源数据(Source), 打包版本不可用")); + return Result; +#endif +} + +// 判断某点是否超出视口范围 (坐标为负或超过视口宽高) +bool FImageRenderUtils::IsPointOutOfViewport(const FVector2D& Point, const FVector2D& ViewportSize) +{ + // 任一坐标小于 0, 或超过视口对应的宽/高, 即视为超出 + if (Point.X < 0.f || Point.Y < 0.f || Point.X > ViewportSize.X || Point.Y > ViewportSize.Y) + { + return true; // 超出范围 + } + return false; // 在范围内 +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/JsonUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/JsonUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f8f3547e961e82bc40202819a74cb8810f9ee88 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/JsonUtils.cpp @@ -0,0 +1,436 @@ +#include "Utils/JsonUtils.h" + +#include "LQABase.h" // 提供日志分类 LogLQARestore 的声明 + +#include "Json.h" +#include "JsonObjectConverter.h" // 提供 FJsonObjectConverter, 可借助反射做属性与 JSON 的互转 + +//====================================================================== +// 序列化: 各基础类型 -> JSON +//====================================================================== + +// 将 FVector2D 序列化为 { "x": X, "y": Y } 的 JSON 子对象, 并挂到 RootObj 的 EntryName 字段下 +bool FJsonUtils::SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const FVector2D& InVector) +{ + if (RootObj.IsValid()) // 校验根对象有效, 避免对空指针操作 + { + // 新建一个子 JSON 对象用于存放 x / y 两个分量 + const TSharedPtr VectorObj = MakeShareable(new FJsonObject); + VectorObj->SetNumberField(TEXT("x"), InVector.X); + VectorObj->SetNumberField(TEXT("y"), InVector.Y); + + // 将子对象作为 EntryName 字段挂到根对象上 + RootObj->SetObjectField(EntryName, VectorObj); + return true; + } + return false; // 根对象无效, 序列化失败 +} + +// 将布尔值写入 EntryName 字段 +bool FJsonUtils::SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const bool InBool) +{ + if (RootObj.IsValid()) + { + RootObj->SetBoolField(EntryName, InBool); + return true; + } + return false; +} + +// 将 int32 写入 EntryName 字段 (JSON 中以数值类型存储) +bool FJsonUtils::SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const int32 InNum) +{ + if (RootObj.IsValid()) + { + RootObj->SetNumberField(EntryName, InNum); + return true; + } + return false; +} + +// 将 float 写入 EntryName 字段 +bool FJsonUtils::SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const float InNum) +{ + if (RootObj.IsValid()) + { + RootObj->SetNumberField(EntryName, InNum); + return true; + } + return false; +} + +// 将 double 写入 EntryName 字段 +bool FJsonUtils::SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const double InNum) +{ + if (RootObj.IsValid()) + { + RootObj->SetNumberField(EntryName, InNum); + return true; + } + return false; +} + +// 将字符串写入 EntryName 字段 +bool FJsonUtils::SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const FString& InStr) +{ + if (RootObj.IsValid()) + { + RootObj->SetStringField(EntryName, InStr); + return true; + } + return false; +} + +//====================================================================== +// 反序列化: JSON -> 各基础类型 +//====================================================================== + +// 从 JSON 读取 Vector2D; 字段缺失、子对象无效时返回零向量; 缺少某个分量时该分量保持默认值 0 +FVector2D FJsonUtils::DeserializeFromJson_Vector2D(const TSharedPtr& RootObj, const FString& EntryName) +{ + if (RootObj->HasField(EntryName)) // 先判断字段是否存在 + { + const TSharedPtr VectorObj = RootObj->GetObjectField(EntryName); + if (VectorObj.IsValid()) + { + FVector2D DefaultVector = FVector2D::ZeroVector; + if (VectorObj->HasField(TEXT("x"))) + { + DefaultVector.X = VectorObj->GetNumberField(TEXT("x")); + } + if (VectorObj->HasField(TEXT("y"))) + { + DefaultVector.Y = VectorObj->GetNumberField(TEXT("y")); + } + + return DefaultVector; + } + } + return FVector2D::ZeroVector; // 未找到有效数据, 返回零向量 +} + +// 从 JSON 读取布尔值, 字段缺失返回 false +bool FJsonUtils::DeserializeFromJson_Bool(const TSharedPtr& RootObj, const FString& EntryName) +{ + if (RootObj->HasField(EntryName)) + { + return RootObj->GetBoolField(EntryName); + } + return false; +} + +//====================================================================== +// 通用对象序列化: UObject -> JSON (基于反射) +//====================================================================== + +bool FJsonUtils::SerializeObject2Json(const UObject* Object, TSharedPtr& OutJsonObject) +{ + // 入参校验: 对象与输出 JSON 对象都必须有效 + if (!Object || !OutJsonObject.IsValid()) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to get Object")); + return false; + } + + // 二次校验输出对象 (冗余保护) + if (!OutJsonObject.IsValid()) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to OutJsonObject")); + return false; + } + + UClass* Class = Object->GetClass(); // 获取对象的反射类信息 + + // 使用属性迭代器遍历该类的所有 UProperty + for (TFieldIterator PropIt(Class); PropIt; ++PropIt) + { + FProperty* Property = *PropIt; + FString PropertyName = Property->GetName(); + // 获取该属性在对象实例中的内存地址 + const void* Value = Property->ContainerPtrToValuePtr(Object); + + UE_LOG(LogLQARestore, Log, TEXT("111111:%s"), *PropertyName); // 调试日志: 输出当前属性名 + if (!Value) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to get value for property: %s"), *Property->GetName()); + continue; + } + // 跳过名为 Slots 的属性 (业务上单独处理, 不参与通用序列化) + if (PropertyName == TEXT("Slots")) + { + continue; + } + + // 跳过不应被序列化的属性: 实例化引用、瞬态、编辑器专用、已废弃、显式跳过序列化等 + if (Property->HasAnyPropertyFlags(CPF_InstancedReference | CPF_Transient | CPF_DuplicateTransient | + CPF_EditorOnly | CPF_Deprecated | CPF_SkipSerialization | + CPF_NonPIEDuplicateTransient)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Skipping Instanced property: %s"), *Property->GetName()); + continue; + } + + // 跳过各类对象指针属性 (强引用 / 弱引用 / 软引用), 避免序列化指针地址 + if (Property->IsA() || Property->IsA() || + Property->IsA()) + { + UE_LOG(LogLQARestore, Warning, TEXT("Skipping pointer property: %s"), *Property->GetName()); + continue; + } + + // 借助 UE 的转换器把属性值转为 JSON 值, 并写入输出对象 + TSharedPtr JsonValue = FJsonObjectConverter::UPropertyToJsonValue(Property, Value, 0, 0, nullptr); + if (JsonValue.IsValid()) + { + OutJsonObject->SetField(PropertyName, JsonValue); + } + } + + // 只要写入了任意字段即视为成功 + if (OutJsonObject->Values.Num()) + return true; + + return false; +} + +// 从 JSON 读取 int32, 字段缺失返回 0 +int32 FJsonUtils::DeserializeFromJson_Int32(const TSharedPtr& RootObj, const FString& EntryName) +{ + if (RootObj->HasField(EntryName)) + { + return RootObj->GetNumberField(EntryName); + } + return 0; +} + +// 从 JSON 读取 float, 字段缺失返回 0.0f +float FJsonUtils::DeserializeFromJson_Float(const TSharedPtr& RootObj, const FString& EntryName) +{ + if (RootObj->HasField(EntryName)) + { + return RootObj->GetNumberField(EntryName); + } + return 0.0f; +} + +// 从 JSON 读取字符串, 字段缺失返回空串 +FString FJsonUtils::DeserializeFromJson_FString(const TSharedPtr& RootObj, const FString& EntryName) +{ + if (RootObj->HasField(EntryName)) + { + return RootObj->GetStringField(EntryName); + } + return TEXT(""); +} + +//====================================================================== +// 字段名大小写对齐: 让采集端写出的 camelCase 字段能被还原端的反射查找命中 +//====================================================================== + +namespace +{ + // 为嵌套 USTRUCT 补上反射期望的字段名别名, 使两种写法都能命中同一个 JSON 值 + void AddReflectionFieldAliasesRecursive( + const TSharedPtr& JsonObject, const UStruct* StructDefinition) + { + if (!JsonObject.IsValid() || !StructDefinition) + { + return; + } + + for (TFieldIterator It(StructDefinition); It; ++It) + { + const FProperty* Property = *It; + const FString ExpectedName = StructDefinition->GetAuthoredNameForField(Property); + + // 优先采用反射名称对应的字段 + TSharedPtr JsonValue = JsonObject->TryGetField(ExpectedName); + + if (!JsonValue.IsValid()) + { + // 复用导出端所用的同一套变换生成候选名, 保证与写出端完全对称 + const FString ExportedName = FJsonObjectConverter::StandardizeCase(ExpectedName); + if (ExportedName != ExpectedName) + { + JsonValue = JsonObject->TryGetField(ExportedName); + if (JsonValue.IsValid()) + { + JsonObject->SetField(ExpectedName, JsonValue); + } + } + } + + if (!JsonValue.IsValid()) + { + continue; + } + + const FStructProperty* StructProperty = CastField(Property); + if (!StructProperty || JsonValue->Type != EJson::Object) + { + continue; + } + + AddReflectionFieldAliasesRecursive(JsonValue->AsObject(), StructProperty->Struct); + } + } +} + +void FJsonUtils::StandardizeCaseForImport(const TSharedPtr& JsonObject, const UStruct* StructDefinition) +{ + AddReflectionFieldAliasesRecursive(JsonObject, StructDefinition); +} + +//====================================================================== +// 通用对象反序列化: JSON -> UStruct / UObject (基于反射) +//====================================================================== + +bool FJsonUtils::DeserializeFromJson_Object( + const TSharedRef& JsonObject, UStruct* StructDefinition, void* StructPtr) +{ + // 先把字段名大小写对齐到目标的反射属性名, 否则 camelCase 的嵌套字段会被静默跳过 + FJsonUtils::StandardizeCaseForImport(JsonObject, StructDefinition); + + // 遍历目标类型的全部反射属性 + for (TFieldIterator It(StructDefinition); It; ++It) + { + FProperty* Property = *It; + FString PropertyName = Property->GetName(); + + // 检查 JSON 中是否存在同名字段 + if (!JsonObject->HasField(PropertyName)) + { + continue; // 不存在对应字段则跳过该属性 + } + + // 取出该字段对应的 JSON 值 + TSharedPtr JsonValue = JsonObject->TryGetField(PropertyName); + if (!JsonValue.IsValid()) + { + continue; + } + + // 定位属性在目标实例中的内存地址 + void* ValuePtr = Property->ContainerPtrToValuePtr(StructPtr); + UE_LOG(LogLQARestore, Warning, TEXT("property:%s"), *PropertyName); + // 将 JSON 值写入该属性, 失败则整体反序列化终止 + if (!JsonValueToProperty(JsonValue, Property, ValuePtr)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to convert JSON field %s to property"), *PropertyName); + return false; + } + } + + return true; +} + +// 将单个 JSON 值按属性的实际类型写入内存, 支持数值 / 布尔 / 字符串 / 数组 / 结构体 / 枚举, 并对数组与结构体做递归处理 +bool FJsonUtils::JsonValueToProperty(const TSharedPtr& JsonValue, FProperty* Property, void* ValuePtr) +{ + // —— 整数属性 —— + if (FIntProperty* IntProp = CastField(Property)) + { + if (JsonValue->Type == EJson::Number) // JSON 必须是数值类型 + { + int32 IntValue = static_cast(JsonValue->AsNumber()); + IntProp->SetPropertyValue(ValuePtr, IntValue); + return true; + } + } + // —— 浮点属性 —— + else if (FFloatProperty* FloatProp = CastField(Property)) + { + if (JsonValue->Type == EJson::Number) + { + float FloatValue = static_cast(JsonValue->AsNumber()); + FloatProp->SetPropertyValue(ValuePtr, FloatValue); + return true; + } + } + // —— 布尔属性 —— + else if (FBoolProperty* BoolProp = CastField(Property)) + { + if (JsonValue->Type == EJson::Boolean) + { + bool bBoolValue = JsonValue->AsBool(); + BoolProp->SetPropertyValue(ValuePtr, bBoolValue); + return true; + } + } + // —— 字符串属性 —— + else if (FStrProperty* StrProp = CastField(Property)) + { + if (JsonValue->Type == EJson::String) + { + FString StrValue = JsonValue->AsString(); + StrProp->SetPropertyValue(ValuePtr, StrValue); + return true; + } + } + // —— 数组属性 —— 逐元素递归转换 + else if (FArrayProperty* ArrayProp = CastField(Property)) + { + if (JsonValue->Type == EJson::Array) + { + const TArray>& JsonArray = JsonValue->AsArray(); + // FScriptArrayHelper 用于在反射层面安全地操作 TArray 内存 + FScriptArrayHelper Helper(ArrayProp, ValuePtr); + Helper.Resize(JsonArray.Num()); // 按 JSON 数组长度调整容器大小 + + for (int32 i = 0; i < JsonArray.Num(); ++i) + { + void* ElemPtr = Helper.GetRawPtr(i); // 取第 i 个元素的地址 + // ArrayProp->Inner 为元素类型, 递归转换每个元素 + if (!JsonValueToProperty(JsonArray[i], ArrayProp->Inner, ElemPtr)) + { + return false; + } + } + return true; + } + } + // —— 结构体属性 —— 递归调用对象反序列化 + else if (FStructProperty* StructProp = CastField(Property)) + { + if (JsonValue->Type == EJson::Object) + { + TSharedPtr SubObject = JsonValue->AsObject(); + if (!DeserializeFromJson_Object(SubObject.ToSharedRef(), StructProp->Struct, ValuePtr)) + { + return false; + } + return true; + } + } + // —— 枚举属性 —— 支持按名称字符串或底层整数两种写法 + else if (FEnumProperty* EnumProp = CastField(Property)) + { + if (JsonValue->Type == EJson::String) // 以枚举名字符串表示 + { + FString EnumName = JsonValue->AsString(); + UEnum* Enum = EnumProp->GetEnum(); + int64 EnumValue = Enum->GetValueByNameString(EnumName); + if (EnumValue == INDEX_NONE) // 名称无法匹配到任何枚举项 + { + return false; + } + void* EnumValuePtr = EnumProp->ContainerPtrToValuePtr(ValuePtr); + // 通过底层整型属性写入枚举的实际数值 + EnumProp->GetUnderlyingProperty()->SetIntPropertyValue(EnumValuePtr, EnumValue); + return true; + } + else if (JsonValue->Type == EJson::Number) // 直接以底层整数表示 + { + int64 EnumValue = static_cast(JsonValue->AsNumber()); + void* EnumValuePtr = EnumProp->ContainerPtrToValuePtr(ValuePtr); + EnumProp->GetUnderlyingProperty()->SetIntPropertyValue(EnumValuePtr, EnumValue); + return true; + } + } + + // 其余类型暂不支持 + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/SlateBrushUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/SlateBrushUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..517724de70b881364f6d66649c230fc195636407 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/SlateBrushUtils.cpp @@ -0,0 +1,286 @@ +#include "Utils/SlateBrushUtils.h" + +#include "LQABase.h" + +#include "Serialization/JsonReader.h" +#include "Serialization/JsonSerializer.h" + +// 根据 JSON 对象创建 FSlateBrush: 逐个字段尝试解析, 解析成功才覆盖对应属性, 失败则保留默认值 +FSlateBrush FSlateBrushUtils::CreateSlateBrushFromJson( + const TSharedPtr& JsonObject, UObject* ResourceObject) +{ + // 创建一个使用默认值初始化的画刷 + FSlateBrush Brush; + + // 若传入了资源对象 (纹理/材质等),则设置到画刷上 + if (ResourceObject) + { + Brush.SetResourceObject(ResourceObject); + } + + // 解析图片尺寸 ImageSize([X, Y] 数组) + FVector2D ImageSize; + if (ParseVector2D(JsonObject, TEXT("ImageSize"), ImageSize)) + { + Brush.ImageSize = ImageSize; + } + + // 解析边距 Margin (Left/Top/Right/Bottom 子对象) + FMargin Margin; + if (ParseMargin(JsonObject, TEXT("Margin"), Margin)) + { + Brush.Margin = Margin; + } + + // 解析着色颜色 TintColor + FSlateColor TintColor; + if (ParseSlateColor(JsonObject, TEXT("TintColor"), TintColor)) + { + Brush.TintColor = TintColor; + } + + // 解析 UV 区域 UVRegion (定义采样纹理的子区域) + const TSharedPtr* UVRegionObj; + if (JsonObject->TryGetObjectField(TEXT("UVRegion"), UVRegionObj)) + { + // UVRegion 需要同时包含 MinX/MinY/MaxX/MaxY 四个数值字段 + double MinX = 0.0, MinY = 0.0, MaxX = 0.0, MaxY = 0.0; + if ((*UVRegionObj)->TryGetNumberField(TEXT("MinX"), MinX) && + (*UVRegionObj)->TryGetNumberField(TEXT("MinY"), MinY) && + (*UVRegionObj)->TryGetNumberField(TEXT("MaxX"), MaxX) && + (*UVRegionObj)->TryGetNumberField(TEXT("MaxY"), MaxY)) + { + // 用最小点和最大点构造一个 FBox2D 作为 UV 区域 + Brush.SetUVRegion(FBox2D(FVector2D(static_cast(MinX), static_cast(MinY)), + FVector2D(static_cast(MaxX), static_cast(MaxY)))); + } + } + + // 解析绘制方式 DrawAs (如 Box / Border / Image 等) + ESlateBrushDrawType::Type DrawAs; + if (ParseEnum(JsonObject, TEXT("DrawAs"), DrawAs)) + { + Brush.DrawAs = DrawAs; + } + + // 解析平铺方式 Tiling (水平/垂直/双向平铺) + ESlateBrushTileType::Type Tiling; + if (ParseEnum(JsonObject, TEXT("Tiling"), Tiling)) + { + Brush.Tiling = Tiling; + } + + // 解析镜像方式 Mirroring (水平/垂直/双向镜像) + ESlateBrushMirrorType::Type Mirroring; + if (ParseEnum(JsonObject, TEXT("Mirroring"), Mirroring)) + { + Brush.Mirroring = Mirroring; + } + + // 解析图片类型 ImageType (如 FullColor / Linear 等) + ESlateBrushImageType::Type ImageType; + if (ParseEnum(JsonObject, TEXT("ImageType"), ImageType)) + { + Brush.ImageType = ImageType; + } + + // 记录日志, 表示画刷已从 JSON 成功创建 + UE_LOG(LogLQARestore, Log, TEXT("Created SlateBrush from JSON")); + return Brush; +} + +// 解析二维向量: 期望 JSON 字段是一个长度为 2 的数组 [X, Y] +bool FSlateBrushUtils::ParseVector2D( + const TSharedPtr& JsonObject, const FString& FieldName, FVector2D& OutVector) +{ + const TArray>* ArrayPtr; + // 字段必须存在、是数组且长度恰好为 2 + if (JsonObject->TryGetArrayField(FieldName, ArrayPtr) && ArrayPtr->Num() == 2) + { + double X = 0, Y = 0; + // 两个元素都必须能转换为数值 + if ((*ArrayPtr)[0]->TryGetNumber(X) && (*ArrayPtr)[1]->TryGetNumber(Y)) + { + OutVector = FVector2D(static_cast(X), static_cast(Y)); + return true; + } + } + return false; +} + +// 解析边距: 期望 JSON 字段是一个包含 Left/Top/Right/Bottom 的子对象 +bool FSlateBrushUtils::ParseMargin( + const TSharedPtr& JsonObject, const FString& FieldName, FMargin& OutMargin) +{ + const TSharedPtr* MarginObj; + if (JsonObject->TryGetObjectField(FieldName, MarginObj)) + { + double Left = 0, Top = 0, Right = 0, Bottom = 0; + // 四个方向的数值都必须存在才算解析成功 + if ((*MarginObj)->TryGetNumberField(TEXT("Left"), Left) && (*MarginObj)->TryGetNumberField(TEXT("Top"), Top) && + (*MarginObj)->TryGetNumberField(TEXT("Right"), Right) && + (*MarginObj)->TryGetNumberField(TEXT("Bottom"), Bottom)) + { + OutMargin = FMargin(static_cast(Left), static_cast(Top), static_cast(Right), + static_cast(Bottom)); + return true; + } + } + return false; +} + +// 解析线性颜色: 期望 JSON 字段是包含 R/G/B 的子对象, A (透明度) 可选, 缺省为 1.0 (不透明) +bool FSlateBrushUtils::ParseLinearColor( + const TSharedPtr& JsonObject, const FString& FieldName, FLinearColor& OutColor) +{ + const TSharedPtr* ColorObj; + if (JsonObject->TryGetObjectField(FieldName, ColorObj)) + { + double R = 0, G = 0, B = 0, A = 1.0; + // R/G/B 为必填项 + if ((*ColorObj)->TryGetNumberField(TEXT("R"), R) && (*ColorObj)->TryGetNumberField(TEXT("G"), G) && + (*ColorObj)->TryGetNumberField(TEXT("B"), B)) + { + // A 为可选项: 若存在则覆盖默认值 1.0, 不存在时忽略返回值保持默认 + (*ColorObj)->TryGetNumberField(TEXT("A"), A); + OutColor = FLinearColor( + static_cast(R), static_cast(G), static_cast(B), static_cast(A)); + return true; + } + } + return false; +} + +// 解析 Slate 颜色: 先按线性颜色解析, 再包装为 FSlateColor +bool FSlateBrushUtils::ParseSlateColor( + const TSharedPtr& JsonObject, const FString& FieldName, FSlateColor& OutColor) +{ + FLinearColor LinearColor; + if (ParseLinearColor(JsonObject, FieldName, LinearColor)) + { + OutColor = FSlateColor(LinearColor); + return true; + } + return false; +} + +// 解析枚举: JSON 中以字符串存储枚举名, 这里根据不同枚举类型做字符串到枚举值的映射 +// 使用 if constexpr 在编译期按 EnumType 选择对应的分支, 避免运行时开销与无效比较 +template +bool FSlateBrushUtils::ParseEnum(const TSharedPtr& JsonObject, const FString& FieldName, EnumType& OutEnum) +{ + FString EnumStr; + // 先尝试把字段读取为字符串 + if (JsonObject->TryGetStringField(FieldName, EnumStr)) + { + // 空字符串视为无效, 解析失败 + if (EnumStr.Len() == 0) + return false; + + // 画刷绘制方式枚举 + if constexpr (std::is_same::value) + { + // "NoDrawType" 与 "None" 都映射为不绘制 + if (EnumStr == "NoDrawType" || EnumStr == "None") + { + OutEnum = ESlateBrushDrawType::NoDrawType; + return true; + } + else if (EnumStr == "Box") // 九宫格盒子绘制 + { + OutEnum = ESlateBrushDrawType::Box; + return true; + } + else if (EnumStr == "Border") // 边框绘制 + { + OutEnum = ESlateBrushDrawType::Border; + return true; + } + else if (EnumStr == "Image") // 普通图片绘制 + { + OutEnum = ESlateBrushDrawType::Image; + return true; + } + } + // 画刷平铺方式枚举 + else if constexpr (std::is_same::value) + { + if (EnumStr == "NoTile") // 不平铺 + { + OutEnum = ESlateBrushTileType::NoTile; + return true; + } + else if (EnumStr == "Horizontal") // 水平平铺 + { + OutEnum = ESlateBrushTileType::Horizontal; + return true; + } + else if (EnumStr == "Vertical") // 垂直平铺 + { + OutEnum = ESlateBrushTileType::Vertical; + return true; + } + else if (EnumStr == "Both") // 水平和垂直都平铺 + { + OutEnum = ESlateBrushTileType::Both; + return true; + } + } + // 画刷镜像方式枚举 + else if constexpr (std::is_same::value) + { + if (EnumStr == "NoMirror") // 不镜像 + { + OutEnum = ESlateBrushMirrorType::NoMirror; + return true; + } + else if (EnumStr == "Horizontal") // 水平镜像 + { + OutEnum = ESlateBrushMirrorType::Horizontal; + return true; + } + else if (EnumStr == "Vertical") // 垂直镜像 + { + OutEnum = ESlateBrushMirrorType::Vertical; + return true; + } + else if (EnumStr == "Both") // 水平和垂直都镜像 + { + OutEnum = ESlateBrushMirrorType::Both; + return true; + } + } + // 画刷图片类型枚举 + else if constexpr (std::is_same::value) + { + if (EnumStr == "NoImage") // 无图片 + { + OutEnum = ESlateBrushImageType::NoImage; + return true; + } + else if (EnumStr == "FullColor") // 全彩图片 + { + OutEnum = ESlateBrushImageType::FullColor; + return true; + } + else if (EnumStr == "Linear") // 线性颜色空间图片 + { + OutEnum = ESlateBrushImageType::Linear; + return true; + } + } + } + // 字段不存在、不是字符串或字符串未匹配到任何枚举值时返回 false + return false; +} + +// 显式模板实例化: 由于 ParseEnum 的定义位于 .cpp 中, +// 需要为用到的每种枚举类型显式实例化, 以避免其他翻译单元调用时产生链接错误 +template bool FSlateBrushUtils::ParseEnum( + const TSharedPtr&, const FString&, ESlateBrushDrawType::Type&); +template bool FSlateBrushUtils::ParseEnum( + const TSharedPtr&, const FString&, ESlateBrushTileType::Type&); +template bool FSlateBrushUtils::ParseEnum( + const TSharedPtr&, const FString&, ESlateBrushMirrorType::Type&); +template bool FSlateBrushUtils::ParseEnum( + const TSharedPtr&, const FString&, ESlateBrushImageType::Type&); \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TextureUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TextureUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7648a9afe2c3a63a041abce1e68d38ad0bd89b8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TextureUtils.cpp @@ -0,0 +1,683 @@ +#include "Utils/TextureUtils.h" + +#include "LQABase.h" // 日志分类 LogLQARestore 等基础定义 + +#include "Components/Image.h" // UImage 图片控件 +#include "Core/RestoreWindowProxy.h" // URestoreWindowProxy, 含纹理缓存 SharedTextureMap +#include "IImageWrapper.h" // IImageWrapper, PNG 解码 +#include "IImageWrapperModule.h" // IImageWrapperModule, 获取 PNG 解码器 +#include "ImageUtils.h" // FImageUtils, 用于 PNG 压缩 +#include "Materials/MaterialInstanceDynamic.h" // UMaterialInstanceDynamic (动态材质实例) +#include "Materials/MaterialInterface.h" // UMaterialInterface (材质接口基类) +#include "Misc/FileHelper.h" // FFileHelper (读取导出的 PNG) +#include "Modules/ModuleManager.h" // FModuleManager (获取 ImageWrapper 模块) +#include "Utils/JsonUtils.h" // 自定义 JSON 反序列化工具 +#include "Utils/SlateBrushUtils.h" // 自定义 Slate 画刷构建工具 + +// 初始化静态成员变量 (材质画刷缓存) +TMap FTextureUtils::MaterialBrushCache; + +// 辅助函数: 将 JSON 对象转换为线性颜色 (FLinearColor) +static bool JsonObjectToLinearColor(const TSharedPtr& JsonColor, FLinearColor& OutColor) +{ + // JSON 对象无效直接返回失败 + if (!JsonColor.IsValid()) + return false; + + double R = 0.0, G = 0.0, B = 0.0, A = 0.0; + // 依次尝试读取 R/G/B/A 四个颜色通道字段, 全部成功才构造颜色 + if (JsonColor->TryGetNumberField(TEXT("R"), R) && JsonColor->TryGetNumberField(TEXT("G"), G) && + JsonColor->TryGetNumberField(TEXT("B"), B) && JsonColor->TryGetNumberField(TEXT("A"), A)) + { + // JSON 中数值为 double, 需显式转换为 float + OutColor = + FLinearColor(static_cast(R), static_cast(G), static_cast(B), static_cast(A)); + return true; + } + return false; +} + +// 辅助函数: 根据资源路径加载纹理 (UTexture) +static UTexture* LoadTextureFromPath(const FString& Path) +{ + // 路径为空直接返回空指针 + if (Path.IsEmpty()) + return nullptr; + // 同步加载纹理对象并转换为 UTexture 类型 + return Cast(StaticLoadObject(UTexture::StaticClass(), nullptr, *Path)); +} + +// 辅助函数: 从 JSON 中读取并应用材质参数 (标量/向量/纹理) +static void ApplyMaterialParametersFromJson(UMaterialInstance* MI, const TSharedPtr& JsonObject) +{ + // 材质实例或 JSON 对象无效时记录错误并返回 + if (!MI || !JsonObject.IsValid()) + { + UE_LOG(LogLQARestore, Error, TEXT("Invalid material instance or JSON object")); + return; + } + + // 只有动态材质实例 (MID) 才支持运行时设置参数 + UMaterialInstanceDynamic* MID = Cast(MI); + if (!MID) + { + UE_LOG(LogLQARestore, Warning, TEXT("Material instance is not dynamic, cannot set parameters")); + return; + } + + // —— 处理标量参数 (ScalarParameters) —— + const TSharedPtr* ScalarParamsObj = nullptr; + if (JsonObject->TryGetObjectField(TEXT("ScalarParameters"), ScalarParamsObj)) + { + // 遍历每一个标量参数键值对 + for (const TPair>& Pair : (*ScalarParamsObj)->Values) + { + const FString& ParamName = Pair.Key; + double Value = 0.0; + // 成功读取数值后设置到材质 + if (Pair.Value->TryGetNumber(Value)) + { + MID->SetScalarParameterValue(FName(*ParamName), static_cast(Value)); + } + } + } + + // —— 处理向量参数 (VectorParameters, 通常为颜色) —— + const TSharedPtr* VectorParamsObj = nullptr; + if (JsonObject->TryGetObjectField(TEXT("VectorParameters"), VectorParamsObj)) + { + for (const TPair>& Pair : (*VectorParamsObj)->Values) + { + const FString& ParamName = Pair.Key; + const TSharedPtr* ColorObj = nullptr; + // 向量参数本身是一个 JSON 对象 (含 RGBA) + if (Pair.Value->TryGetObject(ColorObj)) + { + FLinearColor Color; + // 转换为线性颜色后设置到材质 + if (JsonObjectToLinearColor(*ColorObj, Color)) + { + MID->SetVectorParameterValue(FName(*ParamName), Color); + } + } + } + } + + // —— 处理纹理参数 (TextureParameters) —— + const TSharedPtr* TextureParamsObj = nullptr; + if (JsonObject->TryGetObjectField(TEXT("TextureParameters"), TextureParamsObj)) + { + for (const TPair>& Pair : (*TextureParamsObj)->Values) + { + const FString& ParamName = Pair.Key; + FString TexturePath; + // 纹理参数的值是纹理资源路径字符串 + if (Pair.Value->TryGetString(TexturePath)) + { + UTexture* Tex = LoadTextureFromPath(TexturePath); + if (Tex) + { + MID->SetTextureParameterValue(FName(*ParamName), Tex); + } + else + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to load texture: %s"), *TexturePath); + } + } + } + } +} + +// 根据 JSON 对象更新图片控件画刷: 支持动态材质、Texture2D、PaperSprite、常量材质实例 +void FTextureUtils::UpdateImageBrushFromJsonObj( + UImage* InImage, const TSharedPtr& InTextureDataRoot, URestoreWindowProxy* RestoreWindowProxy) +{ + // 图片控件为空直接返回 + if (!InImage) + { + return; + } + + // 获取当前画刷: UE5 与 UE4 的接口不同, 这里做版本兼容处理 +#if ENGINE_MAJOR_VERSION >= 5 + FSlateBrush CurrentBrush = InImage->GetBrush(); +#else + FSlateBrush CurrentBrush = InImage->Brush; +#endif + // 从 JSON 中读取资源对象字符串 (格式: "Type'Path'") + FString ResourceString = InTextureDataRoot->GetStringField(TEXT("resourceObject")); + + // 取出当前画刷已绑定的资源对象 + UObject* Resource = CurrentBrush.GetResourceObject(); + + // 若资源已经加载且有效, 则无需重复加载直接返回 + // UE 5.0+ 已移除 UObject::IsPendingKill(), 统一使用全局 ::IsValid() (UE4 下也可用) + if (IsValid(Resource) && !Resource->HasAnyFlags(RF_NeedLoad)) + { + UE_LOG(LogLQARestore, Log, TEXT("Resource already loaded and valid")); + return; + } + + // 解析资源字符串, 拆分出类型与路径 + FString Type, Path; + UE_LOG(LogLQARestore, Warning, TEXT("ResourceString: %s"), *ResourceString); + if (!ParseResourceString(ResourceString, Type, Path)) + { + UE_LOG(LogLQARestore, Warning, TEXT("ParseResourceString failed for %s"), *ResourceString); + return; + } + + // 归一化类型名: dump 端可能写出全限定名 (如 "/Script/Engine.Texture2D"), + // 转为短名后下面的各项类型判定才能命中 + Type = NormalizeAssetType(Type); + + // —— 分支一: 动态材质实例 (MaterialInstanceDynamic) —— + if (Type == TEXT("MaterialInstanceDynamic")) + { + // 读取基础材质路径并加载 + FString BaseMaterialPath = InTextureDataRoot->GetStringField(TEXT("MaterialPath")); + UMaterialInterface* BaseMaterial = LoadObject(nullptr, *BaseMaterialPath); + if (!BaseMaterial) + { + UE_LOG(LogLQARestore, Error, TEXT("BaseMaterial not found")); + return; + } + + // 基于基础材质创建动态材质实例 (以 InImage 作为 Outer) + UMaterialInstanceDynamic* MID = UMaterialInstanceDynamic::Create(BaseMaterial, InImage); + if (!MID) + { + UE_LOG(LogLQARestore, Error, TEXT("Failed to create MID")); + return; + } + // 应用 JSON 中的材质参数, 再把动态材质挂到既有画刷上 + ApplyMaterialParametersFromJson(MID, InTextureDataRoot); + InImage->SetBrushResourceObject(MID); + return; + } + // —— 分支二: 其它资源类型 (Texture2D / PaperSprite / MaterialInstanceConstant) —— + else + { + // 按类型加载资源对象 + UObject* ResourceObject = LoadResourceByType(Type, Path); + if (!ResourceObject) + { + // 按路径加载失败: 运行时生成的纹理 (如 /Engine/Transient.Texture2D_x) 并不存在于磁盘上, + // 此时退回到 dump session 目录内的导出结果, 用 nameMD5 定位那份 PNG 并重建成运行时纹理 + FString NameMD5; + InTextureDataRoot->TryGetStringField(TEXT("nameMD5"), NameMD5); + + FString SnapshotDirectory; + if (RestoreWindowProxy) + { + SnapshotDirectory = RestoreWindowProxy->GetSnapshotDirectory(); + } + + if (UTexture2D* FallbackTexture = + LoadRuntimeTextureFromSnapshot(RestoreWindowProxy, SnapshotDirectory, NameMD5)) + { + InImage->SetBrushResourceObject(FallbackTexture); + UE_LOG(LogLQARestore, Log, TEXT("Applied exported PNG fallback for %s (nameMD5=%s)"), + *ResourceString, *NameMD5); + return; + } + + UE_LOG(LogLQARestore, Warning, TEXT("LoadResourceByType failed for %s %s"), *Type, *Path); + return; + } + + // 2D 纹理 + if (Type == TEXT("Texture2D")) + { + UTexture2D* Texture = Cast(ResourceObject); + if (Texture) + { + InImage->SetBrushResourceObject(Texture); + return; + } + } + // 2D 精灵 + else if (Type == TEXT("PaperSprite")) + { + UPaperSprite* Sprite = Cast(ResourceObject); + if (Sprite) + { + InImage->SetBrushResourceObject(Sprite); + return; + } + } + // 常量材质实例 + else if (Type == TEXT("MaterialInstanceConstant")) + { + UMaterialInstanceConstant* MatInst = Cast(ResourceObject); + if (MatInst) + { + InImage->SetBrushResourceObject(MatInst); + return; + } + } + // 不支持的类型或类型转换失败 + else + { + UE_LOG(LogLQARestore, Warning, TEXT("Unsupported resource type or failed to cast: %s"), *Type); + } + } +} + +// 根据资源字符串构建画刷 (输出到 OutBrush), 不直接设置到控件 +bool FTextureUtils::SetBrushFromResourceString( + UImage* InImage, FSlateBrush& OutBrush, const FString& ResourceString, const TSharedPtr& JsonObject) +{ + FString Type, Path; + + // 解析资源字符串 + UE_LOG(LogLQARestore, Warning, TEXT("ResourceString: %s"), *ResourceString); + if (!ParseResourceString(ResourceString, Type, Path)) + { + UE_LOG(LogLQARestore, Warning, TEXT("ParseResourceString failed for %s"), *ResourceString); + return false; + } + + // —— 材质类型 (动态/常量): 统一创建动态材质实例并应用参数 —— + if (Type == TEXT("MaterialInstanceDynamic") || Type == TEXT("MaterialInstanceConstant")) + { + FString BaseMaterialPath = JsonObject->GetStringField(TEXT("MaterialPath")); + UMaterialInterface* BaseMaterial = LoadObject(nullptr, *BaseMaterialPath); + if (!BaseMaterial) + { + UE_LOG(LogLQARestore, Error, TEXT("BaseMaterial not found")); + return false; + } + + UMaterialInstanceDynamic* MID = UMaterialInstanceDynamic::Create(BaseMaterial, InImage); + if (!MID) + { + UE_LOG(LogLQARestore, Error, TEXT("Failed to create MID")); + return false; + } + + // 应用材质参数, 并填充输出画刷 + ApplyMaterialParametersFromJson(MID, JsonObject); + OutBrush.SetResourceObject(MID); + OutBrush.ImageSize = FVector2D(1920.0f, 1080.0f); // 材质默认使用 1920x1080 的尺寸 + OutBrush.DrawAs = ESlateBrushDrawType::Image; // 以图片方式绘制 + return true; + } + // —— 其它资源类型 —— + else + { + UObject* ResourceObject = LoadResourceByType(Type, Path); + if (!ResourceObject) + { + UE_LOG(LogLQARestore, Warning, TEXT("LoadResourceByType failed for %s %s"), *Type, *Path); + return false; + } + + // 2D 纹理: 画刷尺寸取纹理实际宽高 + if (Type == TEXT("Texture2D")) + { + UTexture2D* Texture = Cast(ResourceObject); + if (Texture) + { + OutBrush.SetResourceObject(Texture); + OutBrush.ImageSize = FVector2D(Texture->GetSizeX(), Texture->GetSizeY()); + OutBrush.DrawAs = ESlateBrushDrawType::Image; + return true; + } + } + // 2D 精灵: 画刷尺寸取精灵源尺寸 + else if (Type == TEXT("PaperSprite")) + { + UPaperSprite* Sprite = Cast(ResourceObject); + if (Sprite) + { + OutBrush.SetResourceObject(Sprite); +#if WITH_EDITOR + OutBrush.ImageSize = FVector2D(Sprite->GetSourceSize().X, Sprite->GetSourceSize().Y); +#else + // 打包 (非编辑器) 构建下无法获取精灵源尺寸, 画刷尺寸置零 (由上层按需处理) + OutBrush.ImageSize = FVector2D::ZeroVector; + UE_LOG(LogLQARestore, Warning, + TEXT("PaperSprite 源尺寸(GetSourceSize)为编辑器专属, 打包版本置零")); +#endif + OutBrush.DrawAs = ESlateBrushDrawType::Image; + return true; + } + } + } + + // 走到这里说明类型不支持或转换失败 + UE_LOG(LogLQARestore, Warning, TEXT("Unsupported resource type or failed to cast: %s"), *Type); + return false; +} + +// 解析资源字符串: "Type'Path'" -> Type + Path +bool FTextureUtils::ParseResourceString(const FString& ResourceString, FString& OutType, FString& OutPath) +{ + // 查找第一个单引号的位置, 用于分隔类型和路径 + int32 QuoteIndex = ResourceString.Find(TEXT("'")); + if (QuoteIndex == INDEX_NONE) + return false; + + // 单引号之前为类型 + OutType = ResourceString.Left(QuoteIndex); + // 单引号之后为路径 + OutPath = ResourceString.Mid(QuoteIndex + 1); + // 去除路径末尾的右单引号 + if (OutPath.EndsWith(TEXT("'"))) + { + OutPath.LeftChopInline(1); + } + return true; +} + +// 根据类型和路径同步加载对应的资源对象 +UObject* FTextureUtils::LoadResourceByType(const FString& Type, const FString& Path) +{ + // dump 端可能写出全限定类型名 (如 "/Script/Engine.Texture2D"), + // 必须先归一化为短名再判定, 否则所有分支都会落空 + const FString CanonicalType = NormalizeAssetType(Type); + + if (CanonicalType == TEXT("Texture2D")) + { + return Cast(StaticLoadObject(UTexture2D::StaticClass(), nullptr, *Path)); + } + else if (CanonicalType == TEXT("PaperSprite")) + { + return Cast(StaticLoadObject(UPaperSprite::StaticClass(), nullptr, *Path)); + } + else if (CanonicalType == TEXT("MaterialInstanceConstant")) + { + return Cast( + StaticLoadObject(UMaterialInstanceConstant::StaticClass(), nullptr, *Path)); + } + + // 未知类型返回空指针 + return nullptr; +} + +// 归一化资源类型名: "/Script/Engine.Texture2D" -> "Texture2D" +FString FTextureUtils::NormalizeAssetType(const FString& InType) +{ + // 全限定名形如 "/Script/Engine.Texture2D", 取最后一个 '/' 之后的部分 + int32 SlashIndex = INDEX_NONE; + if (InType.FindLastChar(TEXT('/'), SlashIndex) && SlashIndex < InType.Len() - 1) + { + return InType.RightChop(SlashIndex + 1); + } + return InType; +} + +// 从 dump session 目录的 Textures/.png 兜底还原运行时生成的纹理 +UTexture2D* FTextureUtils::LoadRuntimeTextureFromSnapshot( + URestoreWindowProxy* RestoreWindowProxy, const FString& SnapshotDirectory, const FString& NameMD5) +{ + if (SnapshotDirectory.IsEmpty() || NameMD5.IsEmpty()) + { + return nullptr; + } + + // dump 端约定: 导出的运行时纹理位于 /Textures/.png + const FString PngFilePath = FPaths::Combine(SnapshotDirectory, TEXT("Textures"), NameMD5 + TEXT(".png")); + + // 优先命中窗口内的纹理缓存, 避免重复解码同一张 PNG + if (RestoreWindowProxy) + { + if (UTexture2D* const* CachedTexture = RestoreWindowProxy->SharedTextureMap.Find(PngFilePath)) + { + return *CachedTexture; + } + } + + if (!FPaths::FileExists(PngFilePath)) + { + UE_LOG(LogLQARestore, Warning, TEXT("No exported PNG fallback at %s"), *PngFilePath); + return nullptr; + } + + TArray FileData; + if (!FFileHelper::LoadFileToArray(FileData, *PngFilePath)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to read PNG file: %s"), *PngFilePath); + return nullptr; + } + + // 解码 PNG + IImageWrapperModule& ImageWrapperModule = + FModuleManager::LoadModuleChecked(FName("ImageWrapper")); + const TSharedPtr ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG); + if (!ImageWrapper.IsValid() || !ImageWrapper->SetCompressed(FileData.GetData(), FileData.Num())) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to parse PNG data: %s"), *PngFilePath); + return nullptr; + } + + TArray RawData; + if (!ImageWrapper->GetRaw(ERGBFormat::RGBA, 8, RawData)) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to get raw image data: %s"), *PngFilePath); + return nullptr; + } + + // 用解码出的像素填充一张运行时纹理 + UTexture2D* Texture = + UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_R8G8B8A8); + if (!Texture) + { + UE_LOG(LogLQARestore, Warning, TEXT("Failed to create transient texture for %s"), *PngFilePath); + return nullptr; + } + +// UE 5.0+ 中 PlatformData 已私有化, 必须通过 GetPlatformData() 访问; UE4 下保留直接字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + if (!Texture->GetPlatformData() || Texture->GetPlatformData()->Mips.Num() == 0) + { + UE_LOG(LogLQARestore, Warning, TEXT("Transient texture has no platform data: %s"), *PngFilePath); + return nullptr; + } + void* TextureData = Texture->GetPlatformData()->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FMemory::Memcpy(TextureData, RawData.GetData(), RawData.Num()); + Texture->GetPlatformData()->Mips[0].BulkData.Unlock(); +#else + if (!Texture->PlatformData || Texture->PlatformData->Mips.Num() == 0) + { + UE_LOG(LogLQARestore, Warning, TEXT("Transient texture has no platform data: %s"), *PngFilePath); + return nullptr; + } + void* TextureData = Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FMemory::Memcpy(TextureData, RawData.GetData(), RawData.Num()); + Texture->PlatformData->Mips[0].BulkData.Unlock(); +#endif + + // 将 CPU 端数据提交到 GPU, 使纹理生效 + Texture->UpdateResource(); + + UE_LOG(LogLQARestore, Log, TEXT("Restored runtime texture %dx%d from %s"), ImageWrapper->GetWidth(), + ImageWrapper->GetHeight(), *PngFilePath); + + // 入缓存: SharedTextureMap 是 UPROPERTY, 可确保该纹理不被 GC 回收 + if (RestoreWindowProxy) + { + RestoreWindowProxy->SharedTextureMap.Add(PngFilePath, Texture); + } + + return Texture; +} + +// 从 JSON 对象中加载纹理 (支持 Texture2D 与 PaperSprite 两种类型) +UTexture2D* FTextureUtils::GetTextureFromJsonObj( + const TSharedPtr& InTextureDataRoot, URestoreWindowProxy* RestoreWindowProxy) +{ + FString Type; + // 读取 "type" 字段判断资源类型 + if (InTextureDataRoot->TryGetStringField(TEXT("type"), Type)) + { + // —— 类型一: Texture2D —— + if (Type.Equals(TEXT("Texture2D"))) + { + FString TextureName; + + // 读取纹理名称 (通常格式为 "Texture2D /Game/.../Name") + if (InTextureDataRoot->TryGetStringField(TEXT("name"), TextureName)) + { + FString PathName; + int32 SpaceIndex; + // 以空格分隔, 空格之后的部分为真实资源路径 + if (TextureName.FindChar(TEXT(' '), SpaceIndex)) + { + PathName = TextureName.Mid(SpaceIndex + 1); + UE_LOG(LogLQARestore, Log, TEXT("PathName space: %s"), *PathName); + } + + // 优先从纹理缓存中查找, 命中则直接返回, 避免重复加载 + if (RestoreWindowProxy->SharedTextureMap.Find(TextureName)) + { + return RestoreWindowProxy->SharedTextureMap[TextureName]; + } + + // 缓存未命中, 动态加载纹理 + if (TextureName.StartsWith("Texture2D")) + { + UTexture2D* NewTexture = + Cast(StaticLoadObject(UTexture2D::StaticClass(), nullptr, *PathName)); + if (NewTexture) + { + // 加载成功后写入缓存 + RestoreWindowProxy->SharedTextureMap.Emplace(TextureName, NewTexture); + UE_LOG(LogLQARestore, Log, TEXT("Loaded Texture2D successfully: %s"), *TextureName); + return NewTexture; + } + UE_LOG(LogLQARestore, Error, TEXT("Failed to load Texture2D: %s"), *PathName); + } + else if (TextureName.StartsWith("TextureRenderTarget2D")) + { + // 渲染目标纹理暂未实现处理逻辑 + UE_LOG(LogLQARestore, Warning, TEXT("TextureRenderTarget2D not supported: %s"), *TextureName); + } + else + { + UE_LOG(LogLQARestore, Error, TEXT("Unknown texture type: %s"), *TextureName); + } + } + else + { + UE_LOG(LogLQARestore, Error, TEXT("[GetTextureFromJsonObj] Failed to get name field")); + } + return nullptr; + } + + // —— 类型二: PaperSprite (返回其源纹理) —— + if (Type.Equals(TEXT("PaperSprite"))) + { + FString TextureName; + if (InTextureDataRoot->TryGetStringField(TEXT("name"), TextureName)) + { + // 精灵名称字段 "spritename" + const FString SpriteName = InTextureDataRoot->GetStringField(TEXT("spritename")); + FString PathName; + int32 SpaceIndex; + // 以空格分隔取出精灵资源路径 + if (SpriteName.FindChar(TEXT(' '), SpaceIndex)) + { + PathName = SpriteName.Mid(SpaceIndex + 1); + UE_LOG(LogLQARestore, Log, TEXT("PathName space: %s"), *PathName); + } + + // 加载精灵资源 + UPaperSprite* MySprite = + Cast(StaticLoadObject(UPaperSprite::StaticClass(), nullptr, *PathName)); + if (MySprite) + { +#if WITH_EDITOR + // 取出精灵的源纹理并写入缓存 + UTexture2D* Texture = MySprite->GetSourceTexture(); + RestoreWindowProxy->SharedTextureMap.Emplace(SpriteName, Texture); + UE_LOG(LogLQARestore, Log, TEXT("Loaded PaperSprite successfully: %s"), *SpriteName); + return Texture; +#else + // 打包 (非编辑器) 构建下 GetSourceTexture 不可用 + UE_LOG(LogLQARestore, Warning, + TEXT("PaperSprite 源纹理(GetSourceTexture)为编辑器专属, 打包版本不可用: %s"), *SpriteName); + return nullptr; +#endif + } + UE_LOG(LogLQARestore, Error, TEXT("Failed to load PaperSprite: %s"), *PathName); + } + else + { + UE_LOG(LogLQARestore, Error, TEXT("[GetTextureFromJsonObj] Failed to find texture named")); + } + return nullptr; + } + } + // 未能读取到 type 字段 + UE_LOG(LogLQARestore, Error, TEXT("[GetTextureFromJsonObj] Failed to deserialize type")); + return nullptr; +} + +// 读取 Texture2D 的像素数据并压缩为 PNG 二进制 +bool FTextureUtils::GetTexture2DData(UTexture2D* Texture2D, TArray& OutData) +{ + // 备份原始压缩设置与 sRGB 设置, 读取完成后恢复 + TextureCompressionSettings OldCompressionSettings = Texture2D->CompressionSettings; + const bool OldSRGB = Texture2D->SRGB; + // 为了拿到未经处理的原始像素, 临时关闭压缩与 sRGB + Texture2D->CompressionSettings = TextureCompressionSettings::TC_VectorDisplacementmap; + Texture2D->SRGB = false; + Texture2D->UpdateResource(); // 使设置生效, 重新构建纹理资源 + + // 计算像素总数与缓冲区字节大小 + size_t PixelCount = Texture2D->GetSizeX() * Texture2D->GetSizeY(); + size_t BufferSize = PixelCount * sizeof(FColor); + + // 分配颜色数组用于接收像素数据 + TArray Colors; + Colors.SetNum(PixelCount); + + // 获取第 0 级 Mip 数据 + // UE 5.0+ 中 PlatformData 已私有化, 必须通过 GetPlatformData() 访问; UE4 下保留直接字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + FTexture2DMipMap& Texture_Mip = Texture2D->GetPlatformData()->Mips[0]; +#else + FTexture2DMipMap& Texture_Mip = Texture2D->PlatformData->Mips[0]; +#endif + // 锁定 BulkData 以读写方式访问底层像素内存 + void* Texture_Data = Texture_Mip.BulkData.Lock(LOCK_READ_WRITE); + + // 将像素数据拷贝到颜色数组, 随后解锁 + FMemory::Memcpy(Colors.GetData(), Texture_Data, BufferSize); + Texture_Mip.BulkData.Unlock(); + + // 恢复原始压缩与 sRGB 设置 + Texture2D->CompressionSettings = OldCompressionSettings; + Texture2D->SRGB = OldSRGB; + Texture2D->UpdateResource(); + + // 将颜色数组压缩为 PNG 二进制 + // UE 5.5+ 中 CompressImageArray 已废弃, 改用 PNGCompressImageArray (要求 TArray64&) +#if ENGINE_MAJOR_VERSION >= 5 + TArray64 PngData; + FImageUtils::PNGCompressImageArray(Texture2D->GetSizeX(), Texture2D->GetSizeY(), Colors, PngData); + // 将 64 位数组内容拷贝到输出的 32 位数组 + OutData.Reset(PngData.Num()); + OutData.Append(PngData.GetData(), PngData.Num()); +#else + FImageUtils::CompressImageArray(Texture2D->GetSizeX(), Texture2D->GetSizeY(), Colors, OutData); +#endif + + return true; +} + +// 从 JSON 对象中解析纹理元数据 (索引、UV、尺寸) +FLQATextureMeta FTextureUtils::GetTextureMeta(const TSharedPtr& TextureDataObj) +{ + FLQATextureMeta MetaData; + // 读取索引字段, 注意这里减 1 (通常是把 1-based 索引转换为 0-based) + MetaData.TextureIndex = FJsonUtils::DeserializeFromJson_Int32(TextureDataObj, TEXT("Index")) - 1; + // 读取 UV 坐标 + MetaData.TextureUV = FJsonUtils::DeserializeFromJson_Vector2D(TextureDataObj, TEXT("UV")); + // 读取纹理尺寸 + MetaData.TextureSize = FJsonUtils::DeserializeFromJson_Vector2D(TextureDataObj, TEXT("Size")); + + return MetaData; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/LoaderUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/LoaderUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1f23ba4fddd80d51de1f04134a76f50fda0468b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/LoaderUtils.cpp @@ -0,0 +1,134 @@ +#include "Utils/TranslationUtils/LoaderUtils.h" + +#include "LQABase.h" + +#include "Utils/TranslationUtils/ValidatorUtils.h" + +// 关闭编译器优化 (通常用于调试, 便于断点与单步跟踪该文件内的代码) +LQA_DISABLE_OPTIMIZATION + +// 静态成员变量定义: 全局的翻译映射表 +// AllKeyText:翻译键 -> 翻译文本 +TMap FLoaderUtils::AllKeyText; +// AllTextKey:源文本 -> 翻译文本 +TMap FLoaderUtils::AllTextKey; + +// 还原方向默认值: 中文 -> 外文 +ERestoreDirection FLoaderUtils::RestoreDirection = ERestoreDirection::ChineseToForeign; + +/** + * 从两个 JSON 文件分别加载翻译数据到 AllKeyText 和 AllTextKey 两张映射表中 + */ +bool FLoaderUtils::LoadJsonFromFile(const FString& FilePath, const FString& FilePathForText, const FString& Language) +{ + // ===== 第一部分: 加载「键-翻译」JSON 文件, 填充 AllKeyText ===== + FString JsonString; + // 将文件完整内容读取到字符串中 + if (FFileHelper::LoadFileToString(JsonString, *FilePath)) + { + // 创建 JSON 读取器与承载解析结果的 JSON 对象 + TSharedRef> JsonReader = TJsonReaderFactory<>::Create(JsonString); + TSharedPtr JsonContent; + + // 反序列化: 将 JSON 字符串解析为 FJsonObject + if (FJsonSerializer::Deserialize(JsonReader, JsonContent)) + { + UE_LOG(LogLQARestore, Log, TEXT("LoadFileToString: %s"), *FilePath); + // 遍历 JSON 顶层的每一个键值对 + for (const TPair>& Pair : JsonContent->Values) + { + TSharedPtr JsonValue = Pair.Value; + // 每个值本身是一个 JSON 对象, 从中取出其子对象 + TSharedPtr Content = JsonValue->AsObject(); + // 读取对象中的 "translation" 字段作为翻译文本 + FString ObjectText = Content->GetStringField(TranslationFieldName); + // 以「外层键」为 Key、「translation 字段值」为 Value 存入映射表 + AllKeyText.Add(Pair.Key, ObjectText); + } + } + } + + // ===== 第二部分: 加载「文本-翻译」JSON 文件, 填充 AllTextKey ===== + FString TextJsonString; + if (FFileHelper::LoadFileToString(TextJsonString, *FilePathForText)) + { + TSharedRef> TextJsonReader = TJsonReaderFactory<>::Create(TextJsonString); + TSharedPtr TextJsonContent; + + if (FJsonSerializer::Deserialize(TextJsonReader, TextJsonContent)) + { + UE_LOG(LogLQARestore, Log, TEXT("LoadFileToString: %s"), *FilePathForText); + // 遍历顶层键值对 + for (const TPair>& Pair : TextJsonContent->Values) + { + TSharedPtr JsonValue = Pair.Value; + // 这里的值是纯字符串类型, 直接取出 + if (JsonValue->Type == EJson::String) + { + FString Value = JsonValue->AsString(); + // 以「源文本」为 Key、「翻译文本」为 Value 存入映射表 + AllTextKey.Add(Pair.Key, Value); + } + } + } + else + { + // 解析失败则记录错误并直接返回 false + UE_LOG(LogLQARestore, Error, TEXT("Failed to parse JSON file: %s"), *FilePathForText); + return false; + } + } + + // 只有当两张映射表都成功加载到数据时, 才认为加载成功 + return AllKeyText.Num() > 0 && AllTextKey.Num() > 0; +} + +/** + * 根据键与内容查询翻译结果, 按优先级依次尝试多种匹配策略 + */ +FString FLoaderUtils::GetTranslateString(const FString& QueryKey, const FString& QueryContent) +{ + // 0. 中文守卫: 仅在「外文 -> 中文」方向启用 + // 此方向下, 原文含中文说明已是译文, 原样返回; + // 「中文 -> 外文」方向下, 中文是待翻译原文, 不能短路, 必须继续查字典 + if (RestoreDirection == ERestoreDirection::ForeignToChinese + && FValidatorUtils::ContainsChinese(QueryContent)) + { + return QueryContent; + } + + // 1. 检查内容是否仅由数字、标点和空白组成; 若是, 则无需翻译, 返回原内容 (两种方向都适用) + bool bOnlyNumbersAndPunctuation = true; + for (const TCHAR& Char : QueryContent) + { + // 只要出现一个非数字、非标点、非空白的字符, 就说明含有需翻译的文本 + if (!FChar::IsDigit(Char) && !FChar::IsPunct(Char) && !FChar::IsWhitespace(Char)) + { + bOnlyNumbersAndPunctuation = false; + break; + } + } + // 仅当「全是数字/标点」且内容非空时才直接返回原内容 + if (bOnlyNumbersAndPunctuation && !QueryContent.IsEmpty()) + { + return QueryContent; + } + + // 2. 优先通过「键」在 AllKeyText 中查找匹配的翻译 + if (const FString* FoundValue = AllKeyText.Find(QueryKey)) + { + return *FoundValue; + } + + // 3. 再通过「内容」在 AllTextKey 中查找匹配的翻译 + if (const FString* FoundValue = AllTextKey.Find(QueryContent)) + { + return *FoundValue; + } + + // 4. 以上均未命中, 返回「未匹配」标记 + return UnmatchedMarker; +} + +// 恢复编译器优化 (与文件顶部的 LQA_DISABLE_OPTIMIZATION 成对使用) +LQA_ENABLE_OPTIMIZATION \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/ValidatorUtils.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/ValidatorUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ce0e58630c418d439fbc7237c21a2d8a13b57f3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/Utils/TranslationUtils/ValidatorUtils.cpp @@ -0,0 +1,141 @@ +#include "Utils/TranslationUtils/ValidatorUtils.h" + +// 引入虚幻引擎国际化模块下的正则表达式支持 (FRegexPattern / FRegexMatcher) +#include "Internationalization/Regex.h" + +// 检测字符串中是否包含中文字符 +bool FValidatorUtils::ContainsChinese(const FString& Text) +{ + // 逐个遍历字符串中的每个字符 + for (const TCHAR& Char : Text) + { + // 判断字符是否落在「CJK 统一表意文字」基本区间 (U+4E00 ~ U+9FFF) + // 该区间覆盖了绝大多数常用汉字 + if (Char >= 0x4E00 && Char <= 0x9FFF) + { + // 一旦发现中文字符即可提前返回, 无需继续遍历 + return true; + } + } + // 遍历结束仍未发现中文字符, 返回 false + return false; +} + +// 检测字符串中是否包含英文字母 +bool FValidatorUtils::ContainsEn(const FString& Text) +{ + // 使用索引遍历字符串中的每个字符 + for (int32 i = 0; i < Text.Len(); ++i) + { + TCHAR Char = Text[i]; + // 判断字符是否为大写字母 (A-Z) 或小写字母 (a-z) + if ((Char >= 'A' && Char <= 'Z') || (Char >= 'a' && Char <= 'z')) + { + // 发现英文字母即提前返回 + return true; + } + } + // 未发现任何英文字母, 返回 false + return false; +} + +// 从输入字符串中提取 HTML 开标签、闭标签以及所有标签 +void FValidatorUtils::ExtractHtmlTags( + const FString& Input, TArray& OutOpenTags, TArray& OutCloseTags, TArray& OutAllTags) +{ + // 先清空输出数组, 防止外部传入的数组携带脏数据 + OutOpenTags.Reset(); + OutCloseTags.Reset(); + OutAllTags.Reset(); + + // 匹配开标签的正则表达式: + // - (?!/) : 负向先行断言, 排除以 '/' 开头的闭标签; + // - [^>...]+ : 匹配标签内容, 并排除 '>' 以及若干 Unicode 区间 + // (中文、日文假名、韩文、泰文等), 避免把普通文本误判为标签 + FString OpenTagPatternStr = TEXT(R"(<(?!/)[^>\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF\\u0E00-\\u0E7F]+>)"); + FRegexPattern OpenTagPattern(OpenTagPatternStr); + FRegexMatcher OpenTagMatcher(OpenTagPattern, Input); + + // 循环查找所有匹配到的开标签 + while (OpenTagMatcher.FindNext()) + { + // 获取整个匹配结果 (捕获组 0), 并统一转为小写以便后续比较 + FString Match = OpenTagMatcher.GetCaptureGroup(0).ToLower(); + OutOpenTags.Add(Match); + } + + // 匹配闭标签 "" 的正则表达式: + // - (^|[^<]) : 要求 "" 前面是字符串开头或非 '<' 字符 (捕获组 1); + // - () : 实际要匹配的闭标签本身 (捕获组 2); + // - (?!>) : 负向先行断言, 确保其后不紧跟 '>' + FString CloseTagPatternStr = TEXT(R"((^|[^<])()(?!>))"); + FRegexPattern CloseTagPattern(CloseTagPatternStr); + FRegexMatcher CloseTagMatcher(CloseTagPattern, Input); + + // 循环查找所有匹配到的闭标签 + while (CloseTagMatcher.FindNext()) + { + // 取捕获组 2, 即 "" 本身 (捕获组 1 仅用于定位前缀, 不需要) + FString Match = CloseTagMatcher.GetCaptureGroup(2); + OutCloseTags.Add(Match); + } + + // 对开标签与闭标签数组进行排序, 使标签集合的比较与顺序无关 + OutOpenTags.Sort(); + OutCloseTags.Sort(); +} + +// 比较两个字符串的 HTML 标签集合是否一致 +bool FValidatorUtils::AreHtmlTagSetsEqual( + const FString& S1, const FString& S2, TArray& OutTags1, TArray& OutTags2) +{ + // 分别用于存放两个字符串提取出的开标签与闭标签 + TArray Open1, Close1; + TArray Open2, Close2; + + // 分别从 S1、S2 中提取 HTML 标签 + ExtractHtmlTags(S1, Open1, Close1, OutTags1); + ExtractHtmlTags(S2, Open2, Close2, OutTags2); + + // 由于提取时已排序, 可直接用 == 比较开标签集合与闭标签集合 + bool bOpenEqual = Open1 == Open2; + bool bCloseEqual = Close1 == Close2; + + // 只有开标签与闭标签集合都相等时, 才认为两者标签结构一致 + return bOpenEqual && bCloseEqual; +} + +// 从输入字符串中提取形如 #tag# 的哈希标签 +void FValidatorUtils::ExtractHashTags(const FString& Input, TArray& OutHashTags) +{ + // 清空输出数组, 避免脏数据 + OutHashTags.Reset(); + + // 匹配哈希标签的正则表达式: 以 '#' 开头和结尾, + // 中间由字母、数字、下划线或中文字符组成 (#...#) + FRegexPattern HashTagPattern(TEXT(R"(#[A-Za-z0-9_\\u4e00-\\u9fa5]+#)")); + FRegexMatcher Matcher(HashTagPattern, Input); + + // 循环查找所有匹配到的哈希标签 + while (Matcher.FindNext()) + { + // 获取整个匹配结果 (捕获组 0), 并统一转为小写便于后续比较 + FString Match = Matcher.GetCaptureGroup(0).ToLower(); + OutHashTags.Add(Match); + } + + // 排序, 使集合比较与顺序无关 + OutHashTags.Sort(); +} + +// 比较两个字符串的哈希标签集合是否一致 +bool FValidatorUtils::AreHashTagSetsEqual( + const FString& S1, const FString& S2, TArray& OutTags1, TArray& OutTags2) +{ + // 分别从 S1、S2 中提取哈希标签 (提取函数内部已排序) + ExtractHashTags(S1, OutTags1); + ExtractHashTags(S2, OutTags2); + + // 直接比较两个已排序的哈希标签集合是否完全相等 + return OutTags1 == OutTags2; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/RestoreWidget2JsonFactory.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/RestoreWidget2JsonFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b457b09fb2222b4e11f1a5af9e596b91c19c2de --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/RestoreWidget2JsonFactory.cpp @@ -0,0 +1,637 @@ +#include "WidgetSlots/Core/RestoreWidget2JsonFactory.h" + +// 各类文本控件头文件, 用于 GetText 中的类型转换 +#include "Components/EditableText.h" +#include "Components/EditableTextBox.h" +#include "Components/MultiLineEditableText.h" +#include "Components/MultiLineEditableTextBox.h" +#include "Components/RichTextBlock.h" +#include "Components/TextBlock.h" +// Widget 与 JSON 互转的接口定义 +#include "WidgetSlots/Core/Widget2JsonInterface.h" +// 各种具体控件类型对应的 Widget2Json 实现 (文本、图片、按钮、各类面板容器等) +#include "WidgetSlots/Widgets/LQA_BackgroundBlur2Json.h" +#include "WidgetSlots/Widgets/LQA_Border2Json.h" +#include "WidgetSlots/Widgets/LQA_Button2Json.h" +#include "WidgetSlots/Widgets/LQA_CanvasPanel2Json.h" +#include "WidgetSlots/Widgets/LQA_CheckBox2Json.h" +#include "WidgetSlots/Widgets/LQA_CircularThrobber2Json.h" +#include "WidgetSlots/Widgets/LQA_ComboBox2Json.h" +#include "WidgetSlots/Widgets/LQA_EditableTextBlock2Json.h" +#include "WidgetSlots/Widgets/LQA_EditableTextBox2Json.h" +#include "WidgetSlots/Widgets/LQA_GridPanel2Json.h" +#include "WidgetSlots/Widgets/LQA_HorizontalBox2Json.h" +#include "WidgetSlots/Widgets/LQA_Image2Json.h" +#include "WidgetSlots/Widgets/LQA_InputKeySelector2Json.h" +#include "WidgetSlots/Widgets/LQA_MenuAnchor2Json.h" +#include "WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.h" +#include "WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.h" +#include "WidgetSlots/Widgets/LQA_Overlay2Json.h" +#include "WidgetSlots/Widgets/LQA_ProgressBar2Json.h" +#include "WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.h" +#include "WidgetSlots/Widgets/LQA_RetainerBox2Json.h" +#include "WidgetSlots/Widgets/LQA_RichTextBlock2Json.h" +#include "WidgetSlots/Widgets/LQA_SafeZone2Json.h" +#include "WidgetSlots/Widgets/LQA_ScaleBox2Json.h" +#include "WidgetSlots/Widgets/LQA_ScrollBar2Json.h" +#include "WidgetSlots/Widgets/LQA_ScrollBox2Json.h" +#include "WidgetSlots/Widgets/LQA_SizeBox2Json.h" +#include "WidgetSlots/Widgets/LQA_Slider2Json.h" +#include "WidgetSlots/Widgets/LQA_Spacer2Json.h" +#include "WidgetSlots/Widgets/LQA_SpinBox2Json.h" +#include "WidgetSlots/Widgets/LQA_TextBlock2Json.h" +#include "WidgetSlots/Widgets/LQA_TextScroller2Json.h" +#include "WidgetSlots/Widgets/LQA_ListView2Json.h" +#include "WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.h" +#include "WidgetSlots/Widgets/LQA_Throbber2Json.h" +#include "WidgetSlots/Widgets/LQA_UniformGridPanel2Json.h" +#include "WidgetSlots/Widgets/LQA_UserWidget2Json.h" +#include "WidgetSlots/Widgets/LQA_VerticalBox2Json.h" +#include "WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.h" +#include "WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.h" +#include "WidgetSlots/Widgets/LQA_WrapBox2Json.h" +#include "WidgetSlots/Widgets/LQA_ExpandableArea2Json.h" +#include "WidgetSlots/Widgets/LQA_StackBox2Json.h" +#include "WidgetSlots/Widgets/LQA_InvalidationBox2Json.h" +#include "WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.h" +#include "WidgetTree/LQAWidgetNode.h" // LQAWidgetNames 控件类型名称常量 +#include "Utils/JsonUtils.h" // JSON 反序列化辅助工具 + +// 根据 JSON 中的 WidgetType 字段, 创建对应类型的 Widget2Json 接口实现 +TSharedPtr FWidget2JsonFactory::MakeWidgetData(const TSharedPtr InWidgetData) +{ + // 缺少 WidgetType 字段则无法判断类型, 直接返回空 + if (!InWidgetData->HasField(TEXT("WidgetType"))) + { + return nullptr; + } + + // 读取控件类型名称 + const FName WidgetType = FName(*InWidgetData->GetStringField(TEXT("WidgetType"))); + + // Slate 根类型复用场景需优先判定: + if (InWidgetData->HasField(TEXT("WidgetClass"))) + { + const FName WidgetClass = FName(*InWidgetData->GetStringField(TEXT("WidgetClass"))); + if (WidgetClass == LQAWidgetClassNames::LQA_DynamicEntryBox) + { + return MakeShareable(new FLQA_DynamicEntryBox2Json()); + } + } + + // 依次匹配控件类型, 创建对应的转换器实例 + // —— 文本类控件 —— + if (WidgetType == LQAWidgetNames::LQA_TextBlock) + { + return MakeShareable(new FLQA_TextBlock2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_RichTextBlock) + { + return MakeShareable(new FLQA_RichTextBlock2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_EditableText) + { + return MakeShareable(new FLQA_EditableTextBlock2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_MultilineEditableText) + { + return MakeShareable(new FLQA_MultilineEditableTextBlock2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_EditableTextBox) + { + return MakeShareable(new FLQA_EditableTextBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_MultilineEditableTextBox) + { + return MakeShareable(new FLQA_MultilineEditableTextBox()); + } + // —— 图片 / 按钮 —— + if (WidgetType == LQAWidgetNames::LQA_Image) + { + return MakeShareable(new FLQA_Image2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Button) + { + return MakeShareable(new FLQA_Button2Json()); + } + // —— 各类面板 / 容器控件 —— + if (WidgetType == LQAWidgetNames::LQA_Canvas) + { + return MakeShareable(new FLQA_CanvasPanel2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_GridPanel) + { + return MakeShareable(new FLQA_GridPanel2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ScrollBox) + { + return MakeShareable(new FLQA_ScrollBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_VerticalBox) + { + return MakeShareable(new FLQA_VerticalBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_HorizontalBox) + { + return MakeShareable(new FLQA_HorizontalBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_UniformGridPanel) + { + return MakeShareable(new FLQA_UniformGridPanel2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ScaleBox) + { + return MakeShareable(new FLQA_ScaleBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_SafeZone) + { + return MakeShareable(new FLQA_SafeZone2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_WrapBox) + { + return MakeShareable(new FLQA_WrapBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_UserWidget) + { + return MakeShareable(new FLQA_UserWidget2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_BackgroundBlur) + { + return MakeShareable(new FLQA_BackgroundBlur2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_CheckBox) + { + return MakeShareable(new FLQA_CheckBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_SizeBox) + { + return MakeShareable(new FLQA_SizeBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Border) + { + return MakeShareable(new FLQA_Border2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Overlay) + { + return MakeShareable(new FLQA_Overlay2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ComboBox) + { + return MakeShareable(new FLQA_ComboBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_RetainerBox) + { + return MakeShareable(new FLQA_RetainerBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_WidgetSwitcher) + { + return MakeShareable(new FLQA_WidgetSwitcher2Json()); + } + + if (WidgetType == LQAWidgetNames::LQA_ProgressBar) + { + return MakeShareable(new FLQA_ProgressBar2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Slider) + { + return MakeShareable(new FLQA_Slider2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_SpinBox) + { + return MakeShareable(new FLQA_SpinBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Throbber) + { + return MakeShareable(new FLQA_Throbber2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_CircularThrobber) + { + return MakeShareable(new FLQA_CircularThrobber2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_Spacer) + { + return MakeShareable(new FLQA_Spacer2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ScrollBar) + { + return MakeShareable(new FLQA_ScrollBar2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_InputKeySelector) + { + return MakeShareable(new FLQA_InputKeySelector2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_MenuAnchor) + { + return MakeShareable(new FLQA_MenuAnchor2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_PostBufferUpdate) + { + return MakeShareable(new FLQA_PostBufferUpdate2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ListView) + { + return MakeShareable(new FLQA_ListView2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_TileView) + { + return MakeShareable(new FLQA_TileView2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_TreeView) + { + return MakeShareable(new FLQA_TreeView2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_StackBox) + { + return MakeShareable(new FLQA_StackBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_WindowTitleBarArea) + { + return MakeShareable(new FLQA_WindowTitleBarArea2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_InvalidationBox) + { + return MakeShareable(new FLQA_InvalidationBox2Json()); + } + if (WidgetType == LQAWidgetNames::LQA_ExpandableArea) + { + return MakeShareable(new FLQA_ExpandableArea2Json()); + } + + // 未匹配到任何已注册类型: 输出警告, 提示在此函数中补充对应 handler, 该节点将被跳过 + UE_LOG(LogLQARestoreWidget2Json, Warning, TEXT("Unsupported WidgetType '%s', node will be skipped. " + "Register its handler in FWidget2JsonFactory::MakeWidgetData."),*WidgetType.ToString()); + + return nullptr; +} + +// 移除 JSON 对象中所有的委托 (Delegate) 字段, 这些字段无法被还原 +void FWidget2JsonFactory::RemoveDelegateFields(const TSharedPtr& InJsonObj) +{ + // 无效对象直接返回 + if (!InJsonObj.IsValid()) + { + return; + } + + // 先收集需要移除的键, 避免在遍历容器时直接修改导致迭代器失效 + TArray RemovedEntry; + RemovedEntry.Reserve(8); // 预分配, 按典型委托数量预留空间, 减少扩容开销 + + // 遍历所有字段, 收集键名中包含 "Delegate" 的字段 + for (const TPair>& Pair : InJsonObj->Values) + { + if (Pair.Key.Contains(TEXT("Delegate"))) + { + RemovedEntry.Emplace(Pair.Key); + } + } + + // 统一移除收集到的委托字段 + for (const FString& Key : RemovedEntry) + { + InJsonObj->RemoveField(Key); + } +} + +// 移除 ObjectData 中的 Slots 字段, 防止还原时与父容器的插槽处理产生冲突 +void FWidget2JsonFactory::RemoveSlotsFromObjectData(const TSharedPtr& InJsonObj) +{ + // 无效对象直接返回 + if (!InJsonObj.IsValid()) + { + return; + } + + // 尝试取出 ObjectData 子对象, 并确认其有效 + const TSharedPtr* ObjectDataJsonObjPtr = nullptr; + if (InJsonObj->TryGetObjectField(TEXT("ObjectData"), ObjectDataJsonObjPtr) && ObjectDataJsonObjPtr && + ObjectDataJsonObjPtr->IsValid()) + { + TSharedPtr ObjectDataJsonObj = *ObjectDataJsonObjPtr; + // 若存在 Slots 字段则移除 + if (ObjectDataJsonObj->HasField(TEXT("Slots"))) + { + ObjectDataJsonObj->RemoveField(TEXT("Slots")); + } + } +} + +// 清理 JSON 对象: 移除无法还原的委托字段与插槽字段 +void FWidget2JsonFactory::CleanJsonObject(const TSharedPtr& InJsonObj) +{ + RemoveDelegateFields(InJsonObj); // 移除委托字段 + RemoveSlotsFromObjectData(InJsonObj); // 移除 ObjectData 中的 Slots +} + +// 从 JSON 还原控件, 并填充完整元数据 (位置、尺寸、层级、附加属性) +FRestoreWidgetMeta FWidget2JsonFactory::WidgetFromJson( + const TSharedPtr& InJsonObj, const FVector2D& InWindowSize, URestoreWindowProxy* RestoreWindowProxy) +{ + FRestoreWidgetMeta MetaData; + + // 先清理 JSON, 移除无法还原的字段 + CleanJsonObject(InJsonObj); + + // 根据控件类型创建对应的转换器接口 + const TSharedPtr Interface = MakeWidgetData(InJsonObj); + if (Interface.IsValid()) + { + // 通过接口把 JSON 反序列化为真正的控件实例 + MetaData.WidgetIns = Interface->FromJson(InJsonObj, RestoreWindowProxy); + // 解析控件位置 + MetaData.WidgetPosition = GetWidgetPos(InJsonObj, InWindowSize); + + // 构建附加属性 JSON 对象, 先设置默认标记: + // needOCR 是否需要 OCR 识别、isImage 是否为图片、isText 是否为文本 + TSharedPtr JsonObject = MakeShareable(new FJsonObject()); + JsonObject->SetBoolField(TEXT("needOCR"), false); + JsonObject->SetBoolField(TEXT("isImage"), false); + JsonObject->SetBoolField(TEXT("isText"), false); + + // 记录父控件名称、源字符串、控件名称等基础信息 + JsonObject->SetStringField( + TEXT("ParentWidget"), FJsonUtils::DeserializeFromJson_FString(InJsonObj, TEXT("ParentWidget"))); + JsonObject->SetStringField( + TEXT("SourceString"), FJsonUtils::DeserializeFromJson_FString(InJsonObj, TEXT("SourceString"))); + JsonObject->SetStringField( + TEXT("WidgetName"), FJsonUtils::DeserializeFromJson_FString(InJsonObj, TEXT("WidgetName"))); + + // 获取控件的具体类型, 用于分支处理 + ELQAWidgetType myType = Interface->GetType(); + + if (myType == ELQAWidgetType::LQA_Image || myType == ELQAWidgetType::LQA_Button) + { + // 图片 / 按钮: 使用绝对尺寸转换, 确保尺寸正确 + MetaData.WidgetSize = GetWidgetSize(InJsonObj, InWindowSize, true); + // 非文本控件, 文本相关字段置空 + JsonObject->SetStringField(TEXT("textStr"), TEXT("")); + JsonObject->SetStringField(TEXT("TextKey"), TEXT("")); + JsonObject->SetStringField(TEXT("justification"), TEXT("")); + JsonObject->SetStringField(TEXT("verticalJustification"), TEXT("")); + + // 默认图片需要 OCR 识别 + JsonObject->SetBoolField(TEXT("needOCR"), true); + // 若贴图数据里带有材质路径 (MaterialPath), 说明是材质图片, 不需要 OCR + if (InJsonObj->HasField(TEXT("TextureData"))) + { + TSharedPtr TextureObject = InJsonObj->GetObjectField(TEXT("TextureData")); + if (TextureObject->HasField(TEXT("MaterialPath"))) + { + JsonObject->SetBoolField(TEXT("needOCR"), false); + } + } + + // 标记为图片 + JsonObject->SetBoolField(TEXT("isImage"), true); + } + else if (myType == ELQAWidgetType::LQA_CheckBox || myType == ELQAWidgetType::LQA_ComboBoxStringText || + myType == ELQAWidgetType::LQA_RetainerBox || myType == ELQAWidgetType::LQA_WidgetSwitcher || + myType == ELQAWidgetType::LQA_ListView || myType == ELQAWidgetType::LQA_TileView || + myType == ELQAWidgetType::LQA_TreeView) + { + // 复选框 / 下拉框 / RetainerBox / WidgetSwitcher / 列表类: 使用绝对尺寸, 文本相关字段置空 + MetaData.WidgetSize = GetWidgetSize(InJsonObj, InWindowSize, true); + JsonObject->SetStringField(TEXT("textStr"), TEXT("")); + JsonObject->SetStringField(TEXT("TextKey"), TEXT("")); + JsonObject->SetStringField(TEXT("justification"), TEXT("")); + JsonObject->SetStringField(TEXT("verticalJustification"), TEXT("")); + } + else if (myType == ELQAWidgetType::LQA_TextBlock || myType == ELQAWidgetType::LQA_RichText || + myType == ELQAWidgetType::LQA_EditableText || myType == ELQAWidgetType::LQA_MultilineEditableText || + myType == ELQAWidgetType::LQA_EditableTextBox || + myType == ELQAWidgetType::LQA_MultilineEditableTextBox) + { + // 各类文本控件: 使用相对尺寸 (LocalSize) + MetaData.WidgetSize = GetWidgetSize(InJsonObj, InWindowSize, false); + // 从控件实例中提取当前文本内容 + FString textStr = GetText(MetaData.WidgetIns); + JsonObject->SetStringField(TEXT("textStr"), textStr); + // 文本的多语言 Key + JsonObject->SetStringField( + TEXT("TextKey"), FJsonUtils::DeserializeFromJson_FString(InJsonObj, TEXT("TextKey"))); + // 从 ObjectData 中读取对齐信息 + const TSharedPtr* ObjectData; + if (InJsonObj->TryGetObjectField(TEXT("ObjectData"), ObjectData)) + { + // 水平对齐方式 + JsonObject->SetStringField( + TEXT("justification"), FJsonUtils::DeserializeFromJson_FString(*ObjectData, TEXT("justification"))); + // 垂直对齐方式; 若 verticalJustification 为空, 则回退读取 TextAlignVertical 字段 + FString verticalJustification = + FJsonUtils::DeserializeFromJson_FString(*ObjectData, TEXT("verticalJustification")); + if (verticalJustification == TEXT("")) + { + verticalJustification = + FJsonUtils::DeserializeFromJson_FString(*ObjectData, TEXT("TextAlignVertical")); + } + JsonObject->SetStringField(TEXT("verticalJustification"), verticalJustification); + // 行高百分比 + JsonObject->SetNumberField(TEXT("lineHeightPercentage"), + FJsonUtils::DeserializeFromJson_Float(*ObjectData, TEXT("lineHeightPercentage"))); + } + // 文本控件需要 OCR 识别, 并标记为文本 + JsonObject->SetBoolField(TEXT("needOCR"), true); + JsonObject->SetBoolField(TEXT("isText"), true); + MetaData.Property = JsonObject; + } + + // 保存附加属性与渲染层级 (LayerId) + MetaData.Property = JsonObject; + MetaData.ZOrder = FJsonUtils::DeserializeFromJson_Int32(InJsonObj, TEXT("LayerId")); + } + + return MetaData; +} + +// 从 JSON 还原面板 (容器) 控件, 仅填充基础元数据 +FRestoreWidgetMeta FWidget2JsonFactory::WidgetFromJsonForPanel( + const TSharedPtr& InJsonObj, const FVector2D& InWindowSize, URestoreWindowProxy* RestoreWindowProxy) +{ + // 先清理 JSON, 移除无法还原的字段 + CleanJsonObject(InJsonObj); + + // 创建面板控件实例 + const TSharedPtr Interface = MakeWidgetData(InJsonObj); + FRestoreWidgetMeta MetaData; + if (Interface.IsValid()) + { + // 反序列化出面板控件实例 + MetaData.WidgetIns = Interface->FromJson(InJsonObj, RestoreWindowProxy); + // 解析位置与尺寸 (面板使用相对尺寸) + MetaData.WidgetPosition = GetWidgetPos(InJsonObj, InWindowSize); + MetaData.WidgetSize = GetWidgetSize(InJsonObj, InWindowSize, false); + // 面板不需要附加属性 + MetaData.Property = nullptr; + // 默认层级取 LayerId + MetaData.ZOrder = FJsonUtils::DeserializeFromJson_Int32(InJsonObj, TEXT("LayerId")); + // 若 ObjectData 中存在 Layer 字段, 则优先使用它作为层级 + if (InJsonObj->HasField(TEXT("ObjectData"))) + { + TSharedPtr ObjectData = InJsonObj->GetObjectField(TEXT("ObjectData")); + if (ObjectData->HasField(TEXT("Layer"))) + { + MetaData.ZOrder = FJsonUtils::DeserializeFromJson_Int32(ObjectData, TEXT("Layer")); + } + } + // 输出面板位置与尺寸日志, 便于调试 + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("Panel Widget Pos: %f, %f"), MetaData.WidgetPosition.X, + MetaData.WidgetPosition.Y); + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("Panel Widget Size: %f, %f"), MetaData.WidgetSize.X, MetaData.WidgetSize.Y); + } + + return MetaData; +} + +// 从各种文本类控件中提取文本内容; 非文本控件返回空字符串 +FString FWidget2JsonFactory::GetText(UWidget* UI) +{ + // 依次尝试将控件转换为各类文本控件类型, 成功则返回其文本 + if (UTextBlock* TextBlock = Cast(UI)) + { + return TextBlock->GetText().ToString(); + } + if (URichTextBlock* RichTextBlock = Cast(UI)) + { + return RichTextBlock->GetText().ToString(); + } + if (UEditableText* EditableText = Cast(UI)) + { + return EditableText->GetText().ToString(); + } + if (UEditableTextBox* EditableTextBox = Cast(UI)) + { + return EditableTextBox->GetText().ToString(); + } + if (UMultiLineEditableText* MultiLineEditableText = Cast(UI)) + { + return MultiLineEditableText->GetText().ToString(); + } + if (UMultiLineEditableTextBox* MultiLineEditableTextBox = Cast(UI)) + { + return MultiLineEditableTextBox->GetText().ToString(); + } + + // 非文本控件, 返回空字符串 + return TEXT(""); +} + +// 从 JSON 根对象中解析窗口尺寸 (读取 meta.sizeX / meta.sizeY) +bool FWidget2JsonFactory::DeserializeWindowSize(const TSharedPtr& RootObj, FVector2D& OutSize) +{ + // 根对象需包含 meta 字段 + if (RootObj->HasField(TEXT("meta"))) + { + const TSharedPtr MetaData = RootObj->GetObjectField(TEXT("meta")); + // meta 中需同时包含 sizeX 与 sizeY + if (MetaData->HasField(TEXT("sizeX")) && MetaData->HasField(TEXT("sizeY"))) + { + OutSize.X = MetaData->GetNumberField(TEXT("sizeX")); + OutSize.Y = MetaData->GetNumberField(TEXT("sizeY")); + return true; + } + // 缺少尺寸字段 + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Deserialize Window Size Failed!")); + return false; + } + + // 缺少 meta 字段 + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Find Meta Data Failed!")); + return false; +} + +// 从 JSON 获取控件位置, 并进行坐标系转换 +FVector2D FWidget2JsonFactory::GetWidgetPos(const TSharedPtr InWidgetData, const FVector2D& InWindowSize) +{ + // 优先从 corners (四角坐标) 数组中获取位置 + TArray> SizePoint = InWidgetData->GetArrayField(TEXT("corners")); + if (SizePoint.Num() == 4) + { + // 使用第 2 个角点 (corner[1]) 作为左上角位置 + return DeserializePoint(SizePoint[1]->AsObject(), InWindowSize); + } + + // 若没有 corners, 则回退使用 ViewportPos 字段 + if (InWidgetData->HasField(TEXT("ViewportPos"))) + { + TSharedPtr ViewportPosObj = InWidgetData->GetObjectField(TEXT("ViewportPos")); + FVector2D Point = FVector2D::ZeroVector; + if (ViewportPosObj->HasField(TEXT("x"))) + { + Point.X = ViewportPosObj->GetNumberField(TEXT("x")); + } + + if (ViewportPosObj->HasField(TEXT("y"))) + { + Point.Y = ViewportPosObj->GetNumberField(TEXT("y")); + } + return Point; + } + + // 两者都没有, 返回零向量 + return FVector2D::ZeroVector; +} + +// 从 JSON 获取控件尺寸 +FVector2D FWidget2JsonFactory::GetWidgetSize( + const TSharedPtr InWidgetData, const FVector2D& InWindowSize, bool bUseAbsoluteSize) +{ + // 图片 / 按钮等: 根据四角坐标计算绝对尺寸 + if (bUseAbsoluteSize) + { + if (InWidgetData->HasField(TEXT("corners"))) + { + TArray> SizePoint = InWidgetData->GetArrayField(TEXT("corners")); + if (SizePoint.Num() == 4) + { + // 由左上角 (corner[1]) 与右下角 (corner[3]) 坐标差值计算尺寸 + const FVector2D LeftUpper = DeserializePoint(SizePoint[1]->AsObject(), InWindowSize); + const FVector2D RightBottom = DeserializePoint(SizePoint[3]->AsObject(), InWindowSize); + return RightBottom - LeftUpper; + } + } + return FVector2D::ZeroVector; + } + + // 文本等控件: 使用 LocalSize (相对尺寸) + if (InWidgetData->HasField(TEXT("LocalSize"))) + { + const TSharedPtr LocalSizeObj = InWidgetData->GetObjectField(TEXT("LocalSize")); + FVector2D Point = FVector2D::ZeroVector; + if (LocalSizeObj->HasField(TEXT("x"))) + { + Point.X = LocalSizeObj->GetNumberField(TEXT("x")); + } + + if (LocalSizeObj->HasField(TEXT("y"))) + { + Point.Y = LocalSizeObj->GetNumberField(TEXT("y")); + } + return Point; + } + + return FVector2D::ZeroVector; +} + +// 从 JSON 解析一个二维坐标点, 并将坐标系从左下角原点转换为左上角原点 +FVector2D FWidget2JsonFactory::DeserializePoint(const TSharedPtr InPosData, const FVector2D& InWindowSize) +{ + FVector2D Point = FVector2D::ZeroVector; + if (InPosData->HasField(TEXT("x"))) + { + Point.X = InPosData->GetNumberField(TEXT("x")); + } + + if (InPosData->HasField(TEXT("y"))) + { + Point.Y = InPosData->GetNumberField(TEXT("y")); + } + + // 非零点才需要转换坐标系 + if (!Point.IsZero()) + { + // 原始坐标以窗口左下角为原点, 这里转换回以左上角为原点 (Y 轴翻转) + Point.Y = InWindowSize.Y - Point.Y; + } + + return Point; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonFactory.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..736198dc031efbff8327cba14e80fbc05a07208b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonFactory.cpp @@ -0,0 +1,134 @@ +#include "WidgetSlots/Core/Slot2JsonFactory.h" + +// 接口基类头文件 +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +// 各类具体槽类型对应的 Slot2Json 实现头文件 +#include "WidgetSlots/Slots/LQA_BorderSlot2Json.h" // Border (边框) 槽 +#include "WidgetSlots/Slots/LQA_ButtonSlot2Json.h" // Button (按钮) 槽 +#include "WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.h" // CanvasPanel (画布面板) 槽 +#include "WidgetSlots/Slots/LQA_GridSlot2Json.h" // Grid (网格) 槽 +#include "WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.h" // HorizontalBox (水平布局) 槽 +#include "WidgetSlots/Slots/LQA_OverlaySlot2Json.h" // Overlay (叠加) 槽 +#include "WidgetSlots/Slots/LQA_SafeZoneSlot2Json.h" // SafeZone (安全区) 槽 +#include "WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.h" // ScaleBox (缩放盒) 槽 +#include "WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.h" // ScrollBox (滚动盒) 槽 +#include "WidgetSlots/Slots/LQA_SizeBoxSlot2Json.h" // SizeBox (尺寸盒) 槽 +#include "WidgetSlots/Slots/LQA_UniformGridSlot2Json.h" // UniformGrid (均匀网格) 槽 +#include "WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.h" // VerticalBox (垂直布局) 槽 +#include "WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.h" // WidgetSwitcher (控件切换器) 槽 +#include "WidgetSlots/Slots/LQA_StackBoxSlot2Json.h" // StackBox (堆叠盒) 槽 +#include "WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.h" // WindowTitleBarArea (窗口标题栏区域) 槽 +#include "WidgetSlots/Slots/LQA_WrapBoxSlot2Json.h" // WrapBox (自动换行盒) 槽 + +// 控件树节点定义 +#include "WidgetTree/LQAWidgetNode.h" + +// 根据 JSON 中的槽类型 (SlotType) 创建对应的 Slot2Json 接口实例 +TSharedPtr FSlot2JsonFactory::MakeSlotData(const TSharedPtr JsonData) +{ + // 校验: JSON 必须同时包含 "SlotType" (槽类型) 和 "Slot" (槽数据) 两个字段, 否则无法处理 + if (!JsonData->HasField(TEXT("SlotType")) || !JsonData->HasField(TEXT("Slot"))) + { + return nullptr; + } + + // 读取槽类型字符串 + FString SlotType = JsonData->GetStringField(TEXT("SlotType")); + + // UE 的类名通常以 "U" 为前缀 (如 UCanvasPanelSlot), 这里去掉首字母 "U", + // 以便与下方不带前缀的类型名 (如 "CanvasPanelSlot") 进行匹配 + if (SlotType.StartsWith(TEXT("U"))) + { + SlotType = SlotType.RightChop(1); + } + + // 转换为 FName, 便于高效比较 + const FName SlotTypeName = FName(*SlotType); + + // 依次匹配各已知槽类型, 命中后创建对应的 Slot2Json 实现并以共享指针返回 + + if (SlotTypeName == FName(TEXT("BorderSlot"))) + { + return MakeShareable(new FLQA_BorderSlot2Json()); + } + if (SlotTypeName == FName(TEXT("ButtonSlot"))) + { + return MakeShareable(new FLQA_ButtonSlot2Json()); + } + if (SlotTypeName == FName(TEXT("CanvasPanelSlot"))) + { + return MakeShareable(new FLQA_CanvasPanelSlot2Json()); + } + if (SlotTypeName == FName(TEXT("GridSlot"))) + { + return MakeShareable(new FLQA_GridSlot2Json()); + } + if (SlotTypeName == FName(TEXT("HorizontalBoxSlot"))) + { + return MakeShareable(new FLQA_HorizontalBoxSlot2Json()); + } + if (SlotTypeName == FName(TEXT("OverlaySlot"))) + { + return MakeShareable(new FLQA_OverlaySlot2Json()); + } + if (SlotTypeName == FName(TEXT("SafeZoneSlot"))) + { + return MakeShareable(new FLQA_SafeZoneSlot2Json()); + } + if (SlotTypeName == FName(TEXT("ScaleBoxSlot"))) + { + return MakeShareable(new FLQA_ScaleBoxSlot2Json()); + } + if (SlotTypeName == FName(TEXT("ScrollBoxSlot"))) + { + return MakeShareable(new FLQA_ScrollBoxSlot2Json()); + } + if (SlotTypeName == FName(TEXT("SizeBoxSlot"))) + { + return MakeShareable(new FLQA_SizeBoxSlot2Json()); + } + if (SlotTypeName == FName(TEXT("UniformGridSlot"))) + { + return MakeShareable(new FLQA_UniformGridSlot2Json()); + } + if (SlotTypeName == FName(TEXT("VerticalBoxSlot"))) + { + return MakeShareable(new FLQA_VerticalBoxSlot2Json()); + } + if (SlotTypeName == FName(TEXT("WrapBoxSlot"))) + { + return MakeShareable(new FLQA_WrapBoxSlot2Json()); + } + if (SlotTypeName == LQASlotNames::LQA_WidgetSwitcherSlot) + { + return MakeShareable(new FLQA_WidgetSwitcherSlot2Json()); + } + if (SlotTypeName == LQASlotNames::LQA_StackBoxSlot) + { + return MakeShareable(new FLQA_StackBoxSlot2Json()); + } + if (SlotTypeName == LQASlotNames::LQA_WindowTitleBarAreaSlot) + { + return MakeShareable(new FLQA_WindowTitleBarAreaSlot2Json()); + } + + // 未匹配到任何已知槽类型: 记录警告日志并返回空指针 + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Unknown SlotTypeName: %s"), *SlotType); + return nullptr; +} + +// 从 JSON 数据还原面板槽 (Panel Slot) +bool FSlot2JsonFactory::SlotFromJson(const TSharedPtr& SlotJsonObj, UPanelSlot* PanelSlot) +{ + // 先根据槽类型创建对应的接口实例 + const TSharedPtr Interface = MakeSlotData(SlotJsonObj); + if (Interface.IsValid()) + { + // 接口有效时, 取出 "Slot" 子对象, 调用 FromJson 将其中的属性还原到目标 PanelSlot 上 + return Interface->FromJson(SlotJsonObj->GetObjectField(TEXT("Slot")), PanelSlot); + } + + // 未能创建有效接口 (槽类型未知或 JSON 缺少必要字段), 还原失败 + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonInterface.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce2516d516657f2516bfc86c9d87976928f52f72 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Slot2JsonInterface.cpp @@ -0,0 +1,33 @@ +#include "WidgetSlots/Core/Slot2JsonInterface.h" +#include "Utils/JsonUtils.h" // 字段名大小写对齐工具 (修复嵌套字段被静默跳过) + +// 定义头文件中声明的日志分类 (与 DECLARE_LOG_CATEGORY_EXTERN 配对使用) +DEFINE_LOG_CATEGORY(LogLQARestoreSlot2Json); + +/** + * 根据 JSON 数据设置面板槽属性的通用实现 + * 通过 UE 的 JSON->UStruct 转换器, 依据反射信息把 JSON 字段写入 Slot 对象 + */ +bool FSlot2JsonInterface::SetPanelSlotProperties(const TSharedPtr InJsonData, UPanelSlot* PanelSlot) +{ + // 入参合法性校验: JSON 数据必须有效, 且目标 Slot 指针不能为空 + if (!InJsonData.IsValid() || !PanelSlot) + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Invalid input to SetPanelSlotProperties")); + return false; + } + + // JsonObjectToUStruct 需要 TSharedRef 参数, 这里把 TSharedPtr 转为 TSharedRef + TSharedRef JsonObjectRef = InJsonData.ToSharedRef(); + + // 把字段名大小写对齐到目标 Slot 的反射属性名 + FJsonUtils::StandardizeCaseForImport(InJsonData, PanelSlot->GetClass()); + + // 利用反射将 JSON 对象映射到 PanelSlot 对应的 UPROPERTY: + // 参数: JSON 源数据、目标对象的 UClass、目标对象实例、 + // CheckFlags (0 表示不限制属性标记)、SkipFlags (0 表示不跳过任何属性) + bool bSuccess = FJsonObjectConverter::JsonObjectToUStruct(JsonObjectRef, PanelSlot->GetClass(), PanelSlot, 0, 0); + + // 返回转换结果 + return bSuccess; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Widget2JsonInterface.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Widget2JsonInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..098aa1c8459de6f08fe873623609c93b1e8a3e0e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/Widget2JsonInterface.cpp @@ -0,0 +1,74 @@ +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +#include "Utils/TranslationUtils/LoaderUtils.h" // 翻译工具类, 提供按 Key/原文 查询译文的能力 + +// 定义头文件中声明的日志分类 (与 DECLARE_LOG_CATEGORY_EXTERN 配对使用) +DEFINE_LOG_CATEGORY(LogLQARestoreWidget2Json); + +/** + * 从 JSON 数据中解析文本, 并根据 TextKey 的不同形态选择对应的翻译策略, + * 最终返回翻译 (或原文) 后的 FText + */ +FText FWidget2JsonInterface::GetTextFromJson(const TSharedPtr JsonData, const FString& TextEntryName, + const FString& TextKeyName, const FString& SourceStringKeyName) +{ + // TextStr: 源字符串 (原文); TextKey: 翻译定位 Key; TransStr: 最终输出的译文 + FString TextStr, TextKey, TransStr; + + // 若 JSON 中存在源字符串字段, 则读取原文 + if (JsonData->HasField(SourceStringKeyName)) + TextStr = JsonData->GetStringField(SourceStringKeyName); + + // 若 JSON 中存在文本 Key 字段, 则读取 Key + if (JsonData->HasField(TextKeyName)) + TextKey = JsonData->GetStringField(TextKeyName); + + // 仅在原文非空时才进行翻译处理 + if (TextStr != TEXT("")) + { + if (TextKey.Equals(TEXT(",FORTEST"))) + { + // 测试标记: 直接使用原文, 不做翻译 + TransStr = TextStr; + } + else if (TextKey.Equals(TEXT(",INVALIDKEY"))) + { + // 无效 Key: 以空 Key 结合原文去查询译文 (通常走原文匹配逻辑) + TransStr = FLoaderUtils::GetTranslateString(TEXT(""), TextStr); + } + else if (TextKey.Contains(TEXT("##"))) + { + // Key 中包含 "##" 的特殊格式: 直接使用完整 Key 查询译文 + TransStr = FLoaderUtils::GetTranslateString(TextKey, TextStr); + } + else + { + // 常规情况: Key 可能形如 "命名空间,实际Key", 需要截取逗号右侧部分作为真正的 Key + int32 CommaIndex; + if (TextKey.FindChar(',', CommaIndex)) + { + FString LeftPart = TextKey.Left(CommaIndex); // 逗号左侧 (命名空间, 此处暂不使用) + FString RightPart = TextKey.Mid(CommaIndex + 1); // 逗号右侧 (真正的 Key) + TextKey = RightPart; + } + + // 使用处理后的 Key 与原文查询译文 + TransStr = FLoaderUtils::GetTranslateString(TextKey, TextStr); + + // 若返回 "##Notrans" 表示未找到翻译, 则附加 Key 信息以便定位问题 + if (TransStr == TEXT("##Notrans")) + { + TransStr += TEXT("("); + TransStr += TextKey; + TransStr += TEXT(")"); + } + } + } + + // 输出调试日志: 打印原文与最终译文, 便于排查翻译结果 + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("TextStr: %s"), *TextStr); + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("TransStr: %s"), *TransStr); + + // 将译文字符串转换为 FText 返回 + return FText::FromString(TransStr); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/WidgetDefines.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/WidgetDefines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7aa909d4da89b7a9ef9a38e4bf006c05c7474772 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Core/WidgetDefines.cpp @@ -0,0 +1,28 @@ +#include "WidgetSlots/Core/WidgetDefines.h" + +// ============================================================= +// 在实现文件 (.cpp) 中为头文件声明的常量提供唯一定义 +// ------------------------------------------------------------- +// 与头文件中的 extern 声明相对应: +// - 头文件负责 “声明” (告诉编译器这些常量存在); +// - 本文件负责 “定义” (为常量分配实际存储并赋值) +// 这样可确保全工程只有一处字符串实例, 既节省内存, +// 又避免多重定义的链接冲突 +// +// 使用 TEXT() 宏可确保字符串字面量在不同平台/字符集下 +// 都以 UE 所需的 TCHAR 宽字符形式存储 +// ============================================================= +namespace LQAWidgetConstants +{ +// “源字符串” 键名, 与 JSON 字段 "SourceString" 一一对应 +const FString SourceStringKey = TEXT("SourceString"); + +// “通用字符串” 键名, 与 JSON 字段 "textStr" 一一对应 +const FString CommonStrKey = TEXT("textStr"); + +// “通用文本键”键名, 与 JSON 字段 "TextKey" 一一对应 +const FString CommonTextKey = TEXT("TextKey"); + +// “通用对象” 键名, 与 JSON 字段 "ObjectData" 一一对应 +const FString CommonObjectKey = TEXT("ObjectData"); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_BorderSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_BorderSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1149f12682104e3c4f46d5b8084cc095a50623f7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_BorderSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_BorderSlot2Json.h" + +#include "Components/BorderSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_BorderSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UBorderSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UBorderSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ButtonSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ButtonSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75a5b2f01ee62951ca87065760ca4758f3fb1607 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ButtonSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_ButtonSlot2Json.h" + +#include "Components/ButtonSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_ButtonSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UButtonSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UButtonSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..478684dc56e4fe09c25db3eea3782b33f62e2fa1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.h" + +#include "Components/CanvasPanelSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_CanvasPanelSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UCanvasPanelSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UCanvasPanelSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_GridSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_GridSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f96f92a81872152b2dd9da03042f6592114bda5c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_GridSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_GridSlot2Json.h" + +#include "Components/GridSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_GridSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UGridSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UGridSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8803fb4c7ea95b760625b581fdd54d56e0dc8bda --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.h" + +#include "Components/HorizontalBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_HorizontalBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UHorizontalBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UHorizontalBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_OverlaySlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_OverlaySlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf184e4c9dc332219d22848f9acc95bc24f8234c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_OverlaySlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_OverlaySlot2Json.h" + +#include "Components/OverlaySlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_OverlaySlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UOverlaySlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UOverlaySlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..279615c255376cddfbf0c3c66280484b7bcc937b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_SafeZoneSlot2Json.h" + +#include "Components/SafeZoneSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_SafeZoneSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + USafeZoneSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to USafeZoneSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d4261e51ed97ca029341e7180cc5436eb3970d6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.h" + +#include "Components/ScaleBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_ScaleBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UScaleBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UScaleBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98ac8a073929b2f4cccb6878b1158397ff161d45 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.h" + +#include "Components/ScrollBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_ScrollBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UScrollBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UScrollBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a355bb66d8427e64feb61b59dc30f9f8b88cf94 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_SizeBoxSlot2Json.h" + +#include "Components/SizeBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_SizeBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + USizeBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to USizeBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_StackBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_StackBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6b74b566f685f8f485aafc570e3ba21921f57fb --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_StackBoxSlot2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Slots/LQA_StackBoxSlot2Json.h" + +#if ENGINE_MAJOR_VERSION >= 5 + +#include "Components/Widget.h" +#include "Components/StackBoxSlot.h" +#include "Utils/JsonUtils.h" + +bool FLQA_StackBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UStackBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, + TEXT("Failed to cast PanelSlot to UStackBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} + +#else + +bool FLQA_StackBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + return false; +} + +#endif // ENGINE_MAJOR_VERSION >= 5 diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_UniformGridSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_UniformGridSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef6ec288f878c7afa11debb86557ab342ff044a3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_UniformGridSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_UniformGridSlot2Json.h" + +#include "Components/UniformGridSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_UniformGridSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UUniformGridSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UUniformGridSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ab19700efc48991939ec960f58f97d976942f47c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.h" + +#include "Components/VerticalBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/JsonUtils.h" + +bool FLQA_VerticalBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UVerticalBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UVerticalBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..406a93ebfe515538806a1e34338cdcbbb1d85374 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.cpp @@ -0,0 +1,26 @@ +#include "WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WidgetSwitcherSlot.h" +#include "Utils/JsonUtils.h" + +bool FLQA_WidgetSwitcherSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UWidgetSwitcherSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, + TEXT("Failed to cast PanelSlot to UWidgetSwitcherSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0528756b4cce8e0cb0a290f3965a31d7e277b45c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.cpp @@ -0,0 +1,26 @@ +#include "WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WindowTitleBarAreaSlot.h" +#include "Utils/JsonUtils.h" + +bool FLQA_WindowTitleBarAreaSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UWindowTitleBarAreaSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, + TEXT("Failed to cast PanelSlot to UWindowTitleBarAreaSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4378b2cfcff202a906d3e1ca96e40b64cda5edf8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Slots/LQA_WrapBoxSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WrapBoxSlot.h" +#include "Utils/JsonUtils.h" + +bool FLQA_WrapBoxSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) +{ + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + UWrapBoxSlot* Slot = Cast(PanelSlot); + if (Slot) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); + Slot->SynchronizeProperties(); + return bResult; + } + else + { + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UWrapBoxSlot. Actual type: %s"), + PanelSlot ? *PanelSlot->GetClass()->GetName() : TEXT("nullptr")); + } + } + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85cd39f899c10c241872d5a71e9573ae0c1e6ca7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_BackgroundBlur2Json.h" + +#include "Components/BackgroundBlur.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_BackgroundBlur2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for BackgroundBlur")); + return nullptr; + } + + UBackgroundBlur* BackgroundBlur = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + BackgroundBlur = GetAsObject(ObjectData, UBackgroundBlur::StaticClass()); + } + } + else + { + BackgroundBlur = NewObject(); + } + + if (!BackgroundBlur) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore BackgroundBlur Failed!")); + return nullptr; + } + return BackgroundBlur; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Border2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Border2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82306edf67c3d0cfa5be12eda0839350e9abe3f3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Border2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_Border2Json.h" + +#include "Components/Border.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Border2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Border")); + return nullptr; + } + + UBorder* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UBorder::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UBorder Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Button2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Button2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cd5af141b900c69193ea304fc71c8372be30803 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Button2Json.cpp @@ -0,0 +1,61 @@ +#include "WidgetSlots/Widgets/LQA_Button2Json.h" + +#include "Components/Button.h" +#include "Core/RestoreWindowUtils.h" +#include "Engine/Texture2D.h" +#include "Utils/TextureUtils.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Button2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Button")); + return nullptr; + } + + UButton* NewButton = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewButton = GetAsObject(ObjectData, UButton::StaticClass()); + NewButton->PostLoad(); + } + } + + if (!NewButton) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore Button Failed!")); + return nullptr; + } + + const TSharedPtr TextureData = JsonData->GetObjectField(TEXT("TextureData")); + UTexture2D* NewTexture = FTextureUtils::GetTextureFromJsonObj(TextureData, RestoreWindowProxy); + // UTexture2D* NewTexture = FTextureUtils::GetTextureFromMergedTexture(JsonData, TextureName); + if (NewTexture) + { + FSlateBrush Brush; + Brush.SetResourceObject(NewTexture); + + NewTexture->bForceMiplevelsToBeResident = true; + NewTexture->bIgnoreStreamingMipBias = true; + + FButtonStyle ButtonStyle; + ButtonStyle.SetNormal(Brush); + ButtonStyle.SetPressed(Brush); + ButtonStyle.SetDisabled(Brush); + ButtonStyle.SetHovered(Brush); + + NewButton->SetStyle(ButtonStyle); + } + return NewButton; +} + +ELQAWidgetType FLQA_Button2Json::GetType() +{ + return ELQAWidgetType::LQA_Button; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CanvasPanel2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CanvasPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f952c0d18c4d60adc858002130e4ad4108270048 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CanvasPanel2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_CanvasPanel2Json.h" + +#include "Components/CanvasPanel.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_CanvasPanel2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for CanvasPanel")); + return nullptr; + } + + UCanvasPanel* CanvasPanel = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + CanvasPanel = GetAsObject(ObjectData, UCanvasPanel::StaticClass()); + } + } + else + { + CanvasPanel = NewObject(); + } + + if (!CanvasPanel) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore CanvasPanel Failed!")); + return nullptr; + } + return CanvasPanel; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CheckBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CheckBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c96b46f26aacfe826e5127463d1760ece7b095ce --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CheckBox2Json.cpp @@ -0,0 +1,41 @@ +#include "WidgetSlots/Widgets/LQA_CheckBox2Json.h" + +#include "Components/CheckBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_CheckBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for CheckBox")); + return nullptr; + } + + UCheckBox* CheckBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + CheckBox = GetAsObject(ObjectData, UCheckBox::StaticClass()); + } + } + else + { + CheckBox = NewObject(); + } + + if (!CheckBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UCheckBox Failed!")); + return nullptr; + } + return CheckBox; +} + +ELQAWidgetType FLQA_CheckBox2Json::GetType() +{ + return ELQAWidgetType::LQA_CheckBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CircularThrobber2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CircularThrobber2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc90de65cafc2577a5e50e24f3f336ff99334e97 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_CircularThrobber2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_CircularThrobber2Json.h" + +#include "Components/CircularThrobber.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_CircularThrobber2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for CircularThrobber")); + return nullptr; + } + + UCircularThrobber* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UCircularThrobber::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UCircularThrobber Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_CircularThrobber2Json::GetType() +{ + return ELQAWidgetType::LQA_CircularThrobber; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ComboBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ComboBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22ff40d9dae214bf16f8eeff32304dd82925a3e1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ComboBox2Json.cpp @@ -0,0 +1,82 @@ +#include "WidgetSlots/Widgets/LQA_ComboBox2Json.h" + +#include "Components/ComboBoxString.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ComboBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ComboBox")); + return nullptr; + } + + TSharedPtr ObjectData; + if (JsonData->HasField(CommonObjectKey)) + { + ObjectData = JsonData->GetObjectField(CommonObjectKey); + } + + UComboBoxString* Widget = nullptr; + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UComboBoxString::StaticClass()); + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UComboBoxString Failed!")); + return nullptr; + } + + if (JsonData->HasField(TEXT("OptionStrings"))) + { + const TArray>& OptionValues = JsonData->GetArrayField(TEXT("OptionStrings")); + for (const TSharedPtr& OptionValue : OptionValues) + { + if (OptionValue.IsValid()) + { + Widget->AddOption(OptionValue->AsString()); + } + } + } + else if (ObjectData.IsValid() && ObjectData->HasField(TEXT("Options"))) + { + const TArray>& OptionValues = ObjectData->GetArrayField(TEXT("Options")); + for (const TSharedPtr& OptionValue : OptionValues) + { + if (OptionValue.IsValid()) + { + Widget->AddOption(OptionValue->AsString()); + } + } + } + + FString SelectedOption; + if (JsonData->HasField(CommonStrKey)) + { + SelectedOption = JsonData->GetStringField(CommonStrKey); + } + if (SelectedOption.IsEmpty() && ObjectData.IsValid() && ObjectData->HasField(TEXT("SelectedOption"))) + { + SelectedOption = ObjectData->GetStringField(TEXT("SelectedOption")); + } + + if (!SelectedOption.IsEmpty() && Widget->FindOptionIndex(SelectedOption) != INDEX_NONE) + { + Widget->SetSelectedOption(SelectedOption); + } + + return Widget; +} + +ELQAWidgetType FLQA_ComboBox2Json::GetType() +{ + return ELQAWidgetType::LQA_ComboBoxStringText; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18fe0719055df25863d8c2ca05f5cee1af64f651 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.cpp @@ -0,0 +1,116 @@ +#include "WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.h" + +#include "Components/HorizontalBox.h" +#include "Components/Overlay.h" +#include "Components/VerticalBox.h" +#include "Components/WrapBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +// UDynamicEntryBoxBase::EntryBoxType 字段名, 决定动态条目采用何种布局容器 +static const FString EntryBoxTypeKey = TEXT("EntryBoxType"); + +UWidget* FLQA_DynamicEntryBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for DynamicEntryBox")); + return nullptr; + } + + // 取 ObjectData (UDynamicEntryBox 的属性集合) + TSharedPtr ObjectData; + if (JsonData->HasField(CommonObjectKey)) + { + ObjectData = JsonData->GetObjectField(CommonObjectKey); + } + + // —— 判定布局方式 —— + // 优先取 ObjectData.EntryBoxType; 缺失时从 WidgetType (Slate 根类型名) 反推, + // 二者皆无则按水平布局兜底。 + FString LayoutType; + if (ObjectData.IsValid()) + { + ObjectData->TryGetStringField(EntryBoxTypeKey, LayoutType); + } + if (LayoutType.IsEmpty() && JsonData->HasField(TEXT("WidgetType"))) + { + const FString SlateRootType = JsonData->GetStringField(TEXT("WidgetType")); + if (SlateRootType == TEXT("SVerticalBox")) + { + LayoutType = TEXT("Vertical"); + } + else if (SlateRootType == TEXT("SWrapBox")) + { + LayoutType = TEXT("Wrap"); + } + else if (SlateRootType == TEXT("SOverlay")) + { + LayoutType = TEXT("Overlay"); + } + else + { + LayoutType = TEXT("Horizontal"); + } + } + if (LayoutType.IsEmpty()) + { + LayoutType = TEXT("Horizontal"); + } + + // —— 按布局方式降级还原为等价的 UPanelWidget 容器 —— + // Radial (SRadialBox) 还原端暂无对应实现, 与 Horizontal 一并按水平布局降级。 + UWidget* RestoredWidget = nullptr; + if (ObjectData.IsValid()) + { + if (LayoutType == TEXT("Vertical")) + { + RestoredWidget = GetAsObject(ObjectData, UVerticalBox::StaticClass()); + } + else if (LayoutType == TEXT("Wrap") || LayoutType == TEXT("VerticalWrap")) + { + RestoredWidget = GetAsObject(ObjectData, UWrapBox::StaticClass()); + } + else if (LayoutType == TEXT("Overlay")) + { + RestoredWidget = GetAsObject(ObjectData, UOverlay::StaticClass()); + } + else + { + RestoredWidget = GetAsObject(ObjectData, UHorizontalBox::StaticClass()); + } + } + + // ObjectData 缺失或反序列化失败: 按布局方式兜底创建对应的空容器 + if (!RestoredWidget) + { + if (LayoutType == TEXT("Vertical")) + { + RestoredWidget = NewObject(); + } + else if (LayoutType == TEXT("Wrap") || LayoutType == TEXT("VerticalWrap")) + { + RestoredWidget = NewObject(); + } + else if (LayoutType == TEXT("Overlay")) + { + RestoredWidget = NewObject(); + } + else + { + RestoredWidget = NewObject(); + } + } + + if (!RestoredWidget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UDynamicEntryBox Failed!")); + return nullptr; + } + + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("DynamicEntryBox restored as '%s' (EntryBoxType=%s)"), + *RestoredWidget->GetClass()->GetName(), *LayoutType); + return RestoredWidget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..021ce9990a5dea133d05d826884793be38a323e7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.cpp @@ -0,0 +1,48 @@ +#include "WidgetSlots/Widgets/LQA_EditableTextBlock2Json.h" + +#include "Components/EditableText.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_EditableTextBlock2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for EditableText")); + return nullptr; + } + + UEditableText* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewTextBlock = GetAsObject(ObjectData, UEditableText::StaticClass()); + } + } + + if (NewTextBlock) + { + const FText Text = GetTextFromJson(JsonData); + const FText HintText = + GetTextFromJson(JsonData, TEXT("hinttextStr"), TEXT("HintTextKey"), TEXT("HintTextSourceStr")); + NewTextBlock->SetText(Text); + NewTextBlock->SetHintText(HintText); + + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore RichTextBlock Failed!")); + } + + return nullptr; +} + +ELQAWidgetType FLQA_EditableTextBlock2Json::GetType() +{ + return ELQAWidgetType::LQA_EditableText; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c68ac9594da6b7de2056fcb161bf9e0315ad27c2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_EditableTextBox2Json.cpp @@ -0,0 +1,48 @@ +#include "WidgetSlots/Widgets/LQA_EditableTextBox2Json.h" + +#include "Components/EditableTextBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_EditableTextBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for EditableTextBox")); + return nullptr; + } + + UEditableTextBox* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewTextBlock = GetAsObject(ObjectData, UEditableTextBox::StaticClass()); + } + } + + if (NewTextBlock) + { + const FText Text = GetTextFromJson(JsonData); + const FText HintText = + GetTextFromJson(JsonData, TEXT("hinttextStr"), TEXT("HintTextKey"), TEXT("HintTextSourceStr")); + NewTextBlock->SetText(Text); + NewTextBlock->SetHintText(HintText); + + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore RichTextBlock Failed!")); + } + + return nullptr; +} + +ELQAWidgetType FLQA_EditableTextBox2Json::GetType() +{ + return ELQAWidgetType::LQA_EditableTextBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ExpandableArea2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ExpandableArea2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfb56faa0b63dec9e1b85e319b559445eba784da --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ExpandableArea2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_ExpandableArea2Json.h" + +#include "Components/ExpandableArea.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ExpandableArea2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ExpandableArea")); + return nullptr; + } + + UExpandableArea* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UExpandableArea::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UExpandableArea Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_GridPanel2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_GridPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7554fe63b269051bb64b260c8bcb9c9af384905d --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_GridPanel2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_GridPanel2Json.h" + +#include "Components/GridPanel.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_GridPanel2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for GridPanel")); + return nullptr; + } + + UGridPanel* GridPanel = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + GridPanel = GetAsObject(ObjectData, UGridPanel::StaticClass()); + } + } + else + { + GridPanel = NewObject(); + } + + if (!GridPanel) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UGridPanel Failed!")); + return nullptr; + } + return GridPanel; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_HorizontalBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_HorizontalBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a10fd7a0d39d85e5ef4c6dbdffc2b218574e7b56 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_HorizontalBox2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_HorizontalBox2Json.h" + +#include "Components/HorizontalBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_HorizontalBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for HorizontalBox")); + return nullptr; + } + + UHorizontalBox* HorizontalBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + HorizontalBox = GetAsObject(ObjectData, UHorizontalBox::StaticClass()); + } + } + else + { + HorizontalBox = NewObject(); + } + + if (!HorizontalBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UHorizontalBox Failed!")); + return nullptr; + } + return HorizontalBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Image2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Image2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2acf0f989366bf41bcbb6dce90011910e3099225 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Image2Json.cpp @@ -0,0 +1,67 @@ +#include "WidgetSlots/Widgets/LQA_Image2Json.h" + +#include "Components/Image.h" +#include "Core/RestoreWindowUtils.h" +#include "Engine/Texture2D.h" +#include "Utils/TextureUtils.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Image2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Image")); + return nullptr; + } + + TSharedPtr TextureData; + UImage* NewImage = nullptr; + FString ResourceName; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewImage = GetAsObject(ObjectData, UImage::StaticClass()); + if (!ObjectData->HasField(TEXT("Brush"))) + { + return nullptr; + } + + if (JsonData->HasField(TEXT("TextureData"))) + { + TextureData = JsonData->GetObjectField(TEXT("TextureData")); + const TSharedPtr BrushData = ObjectData->GetObjectField(TEXT("Brush")); + TextureData->SetObjectField(TEXT("Brush"), BrushData); + + if (BrushData->HasField(TEXT("resourceObject"))) + { + ResourceName = BrushData->GetStringField(TEXT("resourceObject")); + TextureData->SetStringField(TEXT("resourceObject"), ResourceName); + } + } + } + } + + if (!NewImage) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore Image Failed!")); + return nullptr; + } + + if (TextureData.IsValid() && ResourceName != "") + { + FTextureUtils::UpdateImageBrushFromJsonObj(NewImage, TextureData, RestoreWindowProxy); + // FTextureUtils::SetImageBrushFromJsonObj(NewImage, TextureData, RestoreWindowProxy); + NewImage->SynchronizeProperties(); + } + + return NewImage; +} + +ELQAWidgetType FLQA_Image2Json::GetType() +{ + return ELQAWidgetType::LQA_Image; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InputKeySelector2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InputKeySelector2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55088e47c58e93ebb676d1214db9818cc7376baf --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InputKeySelector2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_InputKeySelector2Json.h" + +#include "Components/InputKeySelector.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_InputKeySelector2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for InputKeySelector")); + return nullptr; + } + + UInputKeySelector* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UInputKeySelector::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UInputKeySelector Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_InputKeySelector2Json::GetType() +{ + return ELQAWidgetType::LQA_InputKeySelector; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InvalidationBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InvalidationBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16f6dc3ad7b0b0ff6349cd6caf5166a6d8e12d3a --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_InvalidationBox2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_InvalidationBox2Json.h" + +#include "Components/InvalidationBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_InvalidationBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for InvalidationBox")); + return nullptr; + } + + UInvalidationBox* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UInvalidationBox::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UInvalidationBox Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListView2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListView2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21db8aa111030448e813a73ef2fc0f056bd58520 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListView2Json.cpp @@ -0,0 +1,272 @@ +#include "WidgetSlots/Widgets/LQA_ListView2Json.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/ListView.h" +#include "Components/ListViewBase.h" +#include "Components/TileView.h" +#include "Components/TreeView.h" +#include "Core/RestoreWindowProxy.h" +#include "Core/RootObjWidget.h" +#include "JsonObjectConverter.h" +#include "UObject/UnrealType.h" +#include "Utils/JsonUtils.h" +#include "WidgetSlots/Core/WidgetDefines.h" +#include "WidgetSlots/Widgets/LQA_ListViewEntry.h" + +#if ENGINE_MAJOR_VERSION < 5 && WITH_EDITOR +#include "Engine/Blueprint.h" +#endif + +using namespace LQAWidgetConstants; + +namespace +{ +/** + * 三种列表控件的还原逻辑完全一致: 按 ObjectData 重建控件本身。 + * + * 列表控件必须挂到根控件的 WidgetTree 下 (Outer = WidgetTree), 否则列表生成条目控件时 + * UUserWidget::CreateWidgetInstance 会沿 Outer 链寻找 ParentUserWidget->WidgetTree, + * 找不到会返回 nullptr 并在 GenerateTypedEntry 中触发 check(ListEntryWidget) 崩溃。 + * + * @param JsonData 当前节点的 JSON + * @param RestoreWindowProxy 还原上下文, 用于取根控件的 WidgetTree + * @param InWidgetLabel 仅用于日志 + * @return 重建的控件; 失败时退化为空控件, 保证节点不被整体跳过 + */ +template +TViewWidget* CreateViewWidget( + const TSharedPtr& JsonData, URestoreWindowProxy* RestoreWindowProxy, const TCHAR* InWidgetLabel) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for %s"), InWidgetLabel); + return nullptr; + } + + UWidgetTree* WidgetTree = nullptr; + if (RestoreWindowProxy && RestoreWindowProxy->GetRootWidget()) + { + WidgetTree = RestoreWindowProxy->GetRootWidget()->WidgetTree; + } + + TViewWidget* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = WidgetTree ? WidgetTree->ConstructWidget(TViewWidget::StaticClass(), NAME_None) + : NewObject(); + FJsonUtils::StandardizeCaseForImport(ObjectData, TViewWidget::StaticClass()); + // 反序列化失败时复用已创建的对象作为空控件, 保证节点仍出现在还原结果中 + FJsonObjectConverter::JsonObjectToUStruct( + ObjectData.ToSharedRef(), TViewWidget::StaticClass(), Widget, 0, 0); + } + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Warning, + TEXT("Restore %s failed, fallback to an empty widget. Check EntryWidgetClass."), InWidgetLabel); + Widget = WidgetTree ? WidgetTree->ConstructWidget(TViewWidget::StaticClass(), NAME_None) + : NewObject(); + } + + return Widget; +} + +/** + * 把列表的 EntryWidgetClass 替换为通用条目控件, 并标记为已 cook + * + * EntryWidgetClass 在 UListViewBase 中是 protected 且无 setter, 通过反射替换。 + * 编辑器构建下 UListViewBase::RebuildWidget 要求 EntryWidgetClass 为蓝图类 (或已 cook 的原生类), + * 否则整表会被替换成错误提示文本, 因此无论是否有条目都先把通用条目类标记为已 cook。 + * + * @return 成功返回 true + */ +bool PrepareEntryWidgetClass(UListViewBase* View) +{ + FClassProperty* EntryClassProperty = + FindFProperty(UListViewBase::StaticClass(), TEXT("EntryWidgetClass")); + if (!EntryClassProperty) + { + UE_LOG(LogLQARestoreWidget2Json, Warning, + TEXT("Cannot find EntryWidgetClass on UListViewBase, list entries will not be restored.")); + return false; + } + + ULQARestoreListEntryWidget::StaticClass()->bCooked = true; +#if ENGINE_MAJOR_VERSION < 5 && WITH_EDITOR + if (!ULQARestoreListEntryWidget::StaticClass()->ClassGeneratedBy) + { + UBlueprint* EntryWidgetShell = NewObject(GetTransientPackage(), NAME_None, RF_Transient); + EntryWidgetShell->ParentClass = ULQARestoreListEntryWidget::StaticClass()->GetSuperClass(); + EntryWidgetShell->GeneratedClass = ULQARestoreListEntryWidget::StaticClass(); + EntryWidgetShell->SkeletonGeneratedClass = ULQARestoreListEntryWidget::StaticClass(); + EntryWidgetShell->Status = BS_UpToDate; + EntryWidgetShell->AddToRoot(); + ULQARestoreListEntryWidget::StaticClass()->ClassGeneratedBy = EntryWidgetShell; + } +#endif + EntryClassProperty->SetObjectPropertyValue_InContainer(View, ULQARestoreListEntryWidget::StaticClass()); + return true; +} + +/** + * 依据采集端导出的 ListItems 重建列表项 (ListView / TileView 平铺) + * + * 采集端已把每个条目的文本 (textStr/TextKey/SourceString) 抽成 ListItems 数组, + * 这里直接读取并翻译, 用 ULQARestoreListItem 作为数据项加入列表。 + * 快照不包含列表项数据 (UListView::ListItems 为 Transient), 只能这样注入。 + * + * @param View 刚创建出来的列表控件 + * @param JsonData 该节点的 JSON + */ +template +void ApplyListEntries(TViewWidget* View, const TSharedPtr& JsonData) +{ + if (!View || !JsonData.IsValid() || !PrepareEntryWidgetClass(View)) + { + return; + } + + const TArray>* ListItems = nullptr; + if (!JsonData->TryGetArrayField(TEXT("ListItems"), ListItems) || !ListItems || ListItems->Num() == 0) + { + return; + } + + for (const TSharedPtr& ItemValue : *ListItems) + { + const TSharedPtr ItemJson = ItemValue.IsValid() ? ItemValue->AsObject() : nullptr; + const FText Label = ItemJson.IsValid() ? FWidget2JsonInterface::GetTextFromJson(ItemJson) : FText::GetEmpty(); + + ULQARestoreListItem* Item = NewObject(View); + Item->Label = Label; + View->AddItem(Item); + } + + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("Restored %d list entries."), ListItems->Num()); +} + +/** + * 依据采集端导出的 ListItems 重建树形条目 (TreeView, 支持层级) + * + * 采集端在每个条目上附带 Depth (层级深度), 这里用栈式算法由前序序列重建父子关系, + * 并通过 SetOnGetItemChildren 让 TreeView 能递归展开子节点。 + */ +void ApplyTreeEntries(UTreeView* View, const TSharedPtr& JsonData) +{ + if (!View || !JsonData.IsValid() || !PrepareEntryWidgetClass(View)) + { + return; + } + + const TArray>* ListItems = nullptr; + if (!JsonData->TryGetArrayField(TEXT("ListItems"), ListItems) || !ListItems || ListItems->Num() == 0) + { + return; + } + + // 先设置子节点回调, 再注入根节点数据 + ULQARestoreTreeChildrenResolver* Resolver = NewObject(View); + View->SetOnGetItemChildren(Resolver, &ULQARestoreTreeChildrenResolver::GetChildren); + + // 栈式重建: 栈保存当前路径, 弹出到与 Depth 对齐后挂到父节点 + TArray Roots; + TArray Stack; + for (const TSharedPtr& ItemValue : *ListItems) + { + const TSharedPtr ItemJson = ItemValue.IsValid() ? ItemValue->AsObject() : nullptr; + if (!ItemJson.IsValid()) + { + continue; + } + + const FText Label = FWidget2JsonInterface::GetTextFromJson(ItemJson); + double DepthValue = 0.0; + ItemJson->TryGetNumberField(TEXT("Depth"), DepthValue); + const int32 Depth = FMath::RoundToInt(DepthValue); + + ULQARestoreListItem* Item = NewObject(View); + Item->Label = Label; + + while (Stack.Num() > Depth) + { + Stack.Pop(); + } + + if (Stack.Num() == 0) + { + Roots.Add(Item); + } + else + { + Stack.Last()->Children.Add(Item); + } + Stack.Add(Item); + } + + for (ULQARestoreListItem* Root : Roots) + { + View->AddItem(Root); + } + + UE_LOG(LogLQARestoreWidget2Json, Log, TEXT("Restored %d tree entries (%d roots)."), ListItems->Num(), Roots.Num()); +} +} // namespace + +/** + * TreeView 子节点解析器实现 + * 提供 OnGetItemChildren 回调所需的方法: 从条目数据对象的 Children 数组取出子节点。 + * 采用 UObject 实现, 因为 UE4 的 SetOnGetItemChildren 只接受 UObject 方法委托。 + */ +void ULQARestoreTreeChildrenResolver::GetChildren(UObject* Item, TArray& OutChildren) +{ + if (const ULQARestoreListItem* ListItem = Cast(Item)) + { + for (ULQARestoreListItem* Child : ListItem->Children) + { + if (Child) + { + OutChildren.Add(Child); + } + } + } +} + +UWidget* FLQA_ListView2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + UListView* Widget = CreateViewWidget(JsonData, RestoreWindowProxy, TEXT("ListView")); + ApplyListEntries(Widget, JsonData); + return Widget; +} + +ELQAWidgetType FLQA_ListView2Json::GetType() +{ + return ELQAWidgetType::LQA_ListView; +} + +UWidget* FLQA_TileView2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + UTileView* Widget = CreateViewWidget(JsonData, RestoreWindowProxy, TEXT("TileView")); + ApplyListEntries(Widget, JsonData); + return Widget; +} + +ELQAWidgetType FLQA_TileView2Json::GetType() +{ + return ELQAWidgetType::LQA_TileView; +} + +UWidget* FLQA_TreeView2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + UTreeView* Widget = CreateViewWidget(JsonData, RestoreWindowProxy, TEXT("TreeView")); + ApplyTreeEntries(Widget, JsonData); + return Widget; +} + +ELQAWidgetType FLQA_TreeView2Json::GetType() +{ + return ELQAWidgetType::LQA_TreeView; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListViewEntry.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListViewEntry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b05191ba5f9c1e63213e3205cf0a45611c2e2853 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ListViewEntry.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Widgets/LQA_ListViewEntry.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/TextBlock.h" + +TSharedRef ULQARestoreListEntryWidget::RebuildWidget() +{ + // 列表条目只有一个 TextBlock, 首次构建时创建根控件 + if (WidgetTree && !WidgetTree->RootWidget) + { + EntryLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("LQA_Restore_Entry_Label")); + if (EntryLabel) + { + EntryLabel->SetText(CachedLabel); + WidgetTree->RootWidget = EntryLabel; + } + } + + return Super::RebuildWidget(); +} + +void ULQARestoreListEntryWidget::NativeOnListItemObjectSet(UObject* ListItemObject) +{ + IUserObjectListEntry::NativeOnListItemObjectSet(ListItemObject); + + // 条目控件会被列表复用, 每次绑定数据时都刷新文本 + const ULQARestoreListItem* ListItem = Cast(ListItemObject); + CachedLabel = ListItem ? ListItem->Label : FText::GetEmpty(); + + if (EntryLabel) + { + EntryLabel->SetText(CachedLabel); + } +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MenuAnchor2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MenuAnchor2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b32f53c19ff2bcc32adc587a51806b5be35e765c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MenuAnchor2Json.cpp @@ -0,0 +1,44 @@ +#include "WidgetSlots/Widgets/LQA_MenuAnchor2Json.h" + +#include "Components/MenuAnchor.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_MenuAnchor2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for MenuAnchor")); + return nullptr; + } + + // 注: UMenuAnchor 的 MenuContent 依赖 UClass 引用, JSON 快照中不含该引用, + // 此处仅还原 MenuAnchor 自身及其常规子控件 (子控件由外层框架递归挂载) + UMenuAnchor* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UMenuAnchor::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UMenuAnchor Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_MenuAnchor2Json::GetType() +{ + return ELQAWidgetType::LQA_MenuAnchor; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56a9d2f20da117c567e13cc06b8402549e4425a3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.cpp @@ -0,0 +1,48 @@ +#include "WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.h" + +#include "Components/MultiLineEditableText.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_MultilineEditableTextBlock2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for MultiLineEditableText")); + return nullptr; + } + + UMultiLineEditableText* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewTextBlock = GetAsObject(ObjectData, UMultiLineEditableText::StaticClass()); + } + } + + if (NewTextBlock) + { + const FText Text = GetTextFromJson(JsonData); + const FText HintText = + GetTextFromJson(JsonData, TEXT("hinttextStr"), TEXT("HintTextKey"), TEXT("HintTextSourceStr")); + NewTextBlock->SetText(Text); + NewTextBlock->SetHintText(HintText); + + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore RichTextBlock Failed!")); + } + + return nullptr; +} + +ELQAWidgetType FLQA_MultilineEditableTextBlock2Json::GetType() +{ + return ELQAWidgetType::LQA_MultilineEditableText; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1fd4922fd76451c3aafa4bc9d213b3e8e6f115a --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.cpp @@ -0,0 +1,47 @@ +#include "WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.h" + +#include "Components/MultiLineEditableTextBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_MultilineEditableTextBox::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for MultiLineEditableTextBox")); + return nullptr; + } + + UMultiLineEditableTextBox* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewTextBlock = GetAsObject(ObjectData, UMultiLineEditableTextBox::StaticClass()); + } + } + + if (NewTextBlock) + { + const FText Text = GetTextFromJson(JsonData); + const FText HintText = + GetTextFromJson(JsonData, TEXT("hinttextStr"), TEXT("HintTextKey"), TEXT("HintTextSourceStr")); + NewTextBlock->SetText(Text); + NewTextBlock->SetHintText(HintText); + + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore RichTextBlock Failed!")); + } + return nullptr; +} + +ELQAWidgetType FLQA_MultilineEditableTextBox::GetType() +{ + return ELQAWidgetType::LQA_MultilineEditableTextBox; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Overlay2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Overlay2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e64ce313fb16522361b41f91250e556061d0fd4e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Overlay2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_Overlay2Json.h" + +#include "Components/Overlay.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Overlay2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Overlay")); + return nullptr; + } + + UOverlay* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UOverlay::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UOverlay Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d443fd786823bc253157825f352ce00dce8ef80 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.h" + +#include "Components/SafeZone.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_PlatformPaddingBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for PlatformPaddingBox")); + return nullptr; + } + + USafeZone* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, USafeZone::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USafeZone Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fb90d69931fb8d86497ad0ec64147204176fc60 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.cpp @@ -0,0 +1,60 @@ +#include "WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.h" + +#if ENGINE_MAJOR_VERSION >= 5 + +#include "Components/PostBufferUpdate.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_PostBufferUpdate2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for PostBufferUpdate")); + return nullptr; + } + + UPostBufferUpdate* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UPostBufferUpdate::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UPostBufferUpdate Failed!")); + return nullptr; + } + + return Widget; +} + +ELQAWidgetType FLQA_PostBufferUpdate2Json::GetType() +{ + return ELQAWidgetType::LQA_PostBufferUpdate; +} + +#else + +// UE4.27 无 UPostBufferUpdate,提供空实现保证注册表链接通过 +UWidget* FLQA_PostBufferUpdate2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + return nullptr; +} + +ELQAWidgetType FLQA_PostBufferUpdate2Json::GetType() +{ + return ELQAWidgetType::LQA_PostBufferUpdate; +} + +#endif // ENGINE_MAJOR_VERSION >= 5 diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ProgressBar2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ProgressBar2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa725a3c7ed0337b194c8889410ec1a85ec5f469 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ProgressBar2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_ProgressBar2Json.h" + +#include "Components/ProgressBar.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ProgressBar2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ProgressBar")); + return nullptr; + } + + UProgressBar* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UProgressBar::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UProgressBar Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_ProgressBar2Json::GetType() +{ + return ELQAWidgetType::LQA_ProgressBar; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RetainerBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RetainerBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7fb7f5aeee207969a819583b600664b8fa2d1ddf --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RetainerBox2Json.cpp @@ -0,0 +1,41 @@ +#include "WidgetSlots/Widgets/LQA_RetainerBox2Json.h" + +#include "Components/RetainerBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_RetainerBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for RetainerBox")); + return nullptr; + } + + URetainerBox* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, URetainerBox::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore URetainerBox Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_RetainerBox2Json::GetType() +{ + return ELQAWidgetType::LQA_RetainerBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RichTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RichTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb91cd1ad36525a1c0204d729570b9db583888d9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_RichTextBlock2Json.cpp @@ -0,0 +1,98 @@ +#include "WidgetSlots/Widgets/LQA_RichTextBlock2Json.h" + +#include "Components/RichTextBlock.h" +#include "Engine/DataTable.h" +#include "Utils/JsonUtils.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +namespace +{ +UDataTable* RestoreRichTextStyleSet(const TSharedPtr& JsonData) +{ + if (!JsonData.IsValid() || !JsonData->HasField(TEXT("RichTextStyleSetData"))) + { + return nullptr; + } + + const TSharedPtr StyleSetObject = JsonData->GetObjectField(TEXT("RichTextStyleSetData")); + if (!StyleSetObject.IsValid()) + { + return nullptr; + } + + UDataTable* Table = NewObject(); + Table->RowStruct = FRichTextStyleRow::StaticStruct(); + + for (const TPair>& Pair : StyleSetObject->Values) + { + const TSharedPtr RowObject = Pair.Value.IsValid() ? Pair.Value->AsObject() : nullptr; + if (!RowObject.IsValid()) + { + continue; + } + + FRichTextStyleRow Row; + // 字段名大小写对齐到反射属性名, 保证反序列化命中 + FJsonUtils::StandardizeCaseForImport(RowObject, FRichTextStyleRow::StaticStruct()); + if (FJsonObjectConverter::JsonObjectToUStruct( + RowObject.ToSharedRef(), FRichTextStyleRow::StaticStruct(), &Row, 0, 0)) + { + Table->AddRow(FName(*Pair.Key), Row); + } + } + + return Table->GetRowMap().Num() > 0 ? Table : nullptr; +} +} // namespace + +UWidget* FLQA_RichTextBlock2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for RichTextBlock")); + return nullptr; + } + + URichTextBlock* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + // Use the TextStyleSet carried by the snapshot JSON (no hardcoded project asset path) + NewTextBlock = GetAsObject(ObjectData, URichTextBlock::StaticClass()); + } + } + + if (NewTextBlock) + { + // 样式表若未能随对象路径加载 (Transient 路径在还原环境不存在), 则从快照数据重建 +#if ENGINE_MAJOR_VERSION >= 5 + if (!NewTextBlock->GetTextStyleSet()) + { + NewTextBlock->SetTextStyleSet(RestoreRichTextStyleSet(JsonData)); + } +#else + NewTextBlock->SetTextStyleSet(RestoreRichTextStyleSet(JsonData)); +#endif + + const FText Text = GetTextFromJson(JsonData); + NewTextBlock->SetText(Text); + + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore RichTextBlock Failed!")); + } + + return nullptr; +} + +ELQAWidgetType FLQA_RichTextBlock2Json::GetType() +{ + return ELQAWidgetType::LQA_RichText; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SafeZone2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SafeZone2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55316aca27ceabff3819961d2872ad62c9d52868 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SafeZone2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_SafeZone2Json.h" + +#include "Components/SafeZone.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_SafeZone2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for SafeZone")); + return nullptr; + } + + USafeZone* SafeZone = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + SafeZone = GetAsObject(ObjectData, USafeZone::StaticClass()); + } + } + else + { + SafeZone = NewObject(); + } + + if (!SafeZone) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USafeZone Failed!")); + return nullptr; + } + return SafeZone; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScaleBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScaleBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62cea9ce4ff166909dfd61c09fcad0fb029feef6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScaleBox2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_ScaleBox2Json.h" + +#include "Components/ScaleBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ScaleBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ScaleBox")); + return nullptr; + } + + UScaleBox* ScaleBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + ScaleBox = GetAsObject(ObjectData, UScaleBox::StaticClass()); + } + } + else + { + ScaleBox = NewObject(); + } + + if (!ScaleBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UScaleBox Failed!")); + return nullptr; + } + return ScaleBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBar2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBar2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c0eb0cd1f3ab5a5e97799ff3359978aa8fd7d38 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBar2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_ScrollBar2Json.h" + +#include "Components/ScrollBar.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ScrollBar2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ScrollBar")); + return nullptr; + } + + UScrollBar* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UScrollBar::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UScrollBar Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_ScrollBar2Json::GetType() +{ + return ELQAWidgetType::LQA_ScrollBar; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9dd53ab78e79b3fda9be1a8b06a293a8554b070 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_ScrollBox2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_ScrollBox2Json.h" + +#include "Components/ScrollBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_ScrollBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for ScrollBox")); + return nullptr; + } + + UScrollBox* ScrollBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + ScrollBox = GetAsObject(ObjectData, UScrollBox::StaticClass()); + } + } + else + { + ScrollBox = NewObject(); + } + + if (!ScrollBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UScrollBox Failed!")); + return nullptr; + } + + if (JsonData->HasField(TEXT("ScrollOffset"))) + { + ScrollBox->SetScrollOffset(JsonData->GetNumberField(TEXT("ScrollOffset"))); + } + + return ScrollBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SizeBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SizeBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8d9dfbf2d501d379b3a74a477f84d502117f84b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SizeBox2Json.cpp @@ -0,0 +1,55 @@ +#include "WidgetSlots/Widgets/LQA_SizeBox2Json.h" + +#include "Components/SizeBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_SizeBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for SizeBox")); + return nullptr; + } + + USizeBox* SizeBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + + if (ObjectData.IsValid()) + { + TSharedPtr ProcessedObject = MakeShareable(new FJsonObject()); + for (const TPair>& KeyValuePair : ObjectData->Values) + { + const FString& Key = KeyValuePair.Key; + TSharedPtr Value = KeyValuePair.Value; + if (Key.Contains(TEXT("Mobile"))) + { + continue; + } + + FString NewKey = Key; + if (Key.Contains(TEXT("HD"))) + { + NewKey = Key.Replace(TEXT("HD"), TEXT(""), ESearchCase::CaseSensitive); + } + + ProcessedObject->SetField(NewKey, Value); + } + SizeBox = GetAsObject(ProcessedObject, USizeBox::StaticClass()); + } + } + else + { + SizeBox = NewObject(); + } + + if (!SizeBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USizeBox Failed!")); + return nullptr; + } + return SizeBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Slider2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Slider2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14bb6b1acd7750560821c8eb378e9ac02dbd7528 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Slider2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_Slider2Json.h" + +#include "Components/Slider.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Slider2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Slider")); + return nullptr; + } + + USlider* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, USlider::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USlider Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_Slider2Json::GetType() +{ + return ELQAWidgetType::LQA_Slider; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Spacer2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Spacer2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1747fd241158f9179fbee9a1b20a7b211a079a85 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Spacer2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_Spacer2Json.h" + +#include "Components/Spacer.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Spacer2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Spacer")); + return nullptr; + } + + USpacer* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, USpacer::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USpacer Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_Spacer2Json::GetType() +{ + return ELQAWidgetType::LQA_Spacer; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SpinBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SpinBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e02c2f754a522b66c88c00c192b4003499c2789 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_SpinBox2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_SpinBox2Json.h" + +#include "Components/SpinBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_SpinBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for SpinBox")); + return nullptr; + } + + USpinBox* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, USpinBox::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore USpinBox Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_SpinBox2Json::GetType() +{ + return ELQAWidgetType::LQA_SpinBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_StackBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_StackBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..369f33ed270906c5b1632bf98dc3cbc25b5d16b2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_StackBox2Json.cpp @@ -0,0 +1,49 @@ +#include "WidgetSlots/Widgets/LQA_StackBox2Json.h" + +#if ENGINE_MAJOR_VERSION >= 5 + +#include "Components/StackBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_StackBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for StackBox")); + return nullptr; + } + + UStackBox* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UStackBox::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UStackBox Failed!")); + return nullptr; + } + return Widget; +} + +#else + +UWidget* FLQA_StackBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + return nullptr; +} + +#endif // ENGINE_MAJOR_VERSION >= 5 diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextBlock2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..75aa3f04858853ecdd9432704d7f29fa8afaa8e1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextBlock2Json.cpp @@ -0,0 +1,43 @@ +#include "WidgetSlots/Widgets/LQA_TextBlock2Json.h" + +#include "Components/TextBlock.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_TextBlock2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for TextBlock")); + return nullptr; + } + + UTextBlock* NewTextBlock = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewTextBlock = GetAsObject(ObjectData, UTextBlock::StaticClass()); + } + } + + if (NewTextBlock) + { + FText Text = GetTextFromJson(JsonData); + NewTextBlock->SetText(Text); + return NewTextBlock; + } + else + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Restore TextBlock Failed!")); + } + + return nullptr; +} + +ELQAWidgetType FLQA_TextBlock2Json::GetType() +{ + return ELQAWidgetType::LQA_TextBlock; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextScroller2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextScroller2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..672f4ec58a9f8e43688767ae1d795102d3c95633 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_TextScroller2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_TextScroller2Json.h" + +#include "Components/TextBlock.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_TextScroller2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for TextScroller")); + return nullptr; + } + + UTextBlock* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UTextBlock::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UTextBlock Failed!")); + return nullptr; + } + return Widget; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Throbber2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Throbber2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cce7769b1c6d0108b93862d566beba673ebd041 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Throbber2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_Throbber2Json.h" + +#include "Components/Throbber.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_Throbber2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for Throbber")); + return nullptr; + } + + UThrobber* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UThrobber::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UThrobber Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_Throbber2Json::GetType() +{ + return ELQAWidgetType::LQA_Throbber; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c089459ae976552806a814b2f6794e1dc1235d3d --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_UniformGridPanel2Json.h" + +#include "Components/UniformGridPanel.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_UniformGridPanel2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for UniformGridPanel")); + return nullptr; + } + + UUniformGridPanel* UniformGridPanel = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + UniformGridPanel = GetAsObject(ObjectData, UUniformGridPanel::StaticClass()); + } + } + else + { + UniformGridPanel = NewObject(); + } + + if (!UniformGridPanel) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UUniformGridPanel Failed!")); + return nullptr; + } + return UniformGridPanel; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UserWidget2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UserWidget2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5deb6a9659d44bf05976ac527f2d4baa945a1e2b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_UserWidget2Json.cpp @@ -0,0 +1,216 @@ +#include "WidgetSlots/Widgets/LQA_UserWidget2Json.h" + +#include "Blueprint/UserWidget.h" +#include "Core/LQAContainerWidget.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +void FLQA_UserWidget2Json::ApplyJsonToWidget(UUserWidget* Widget, const TSharedPtr& JsonObject) +{ + if (!Widget || !JsonObject.IsValid()) + { + return; + } + + // Ignored fields list + static const TSet IgnoredFields = {TEXT("AutoLoadList"), TEXT("AnimsValiable"), TEXT("PresetAnimSettings"), + TEXT("AnimBindingSettings"), TEXT("AnimAutoPlaySettings"), TEXT("AudioEventCfg")}; + + // Iterate through Json fields + for (const TPair>& Pair : JsonObject->Values) + { + const FString& Key = Pair.Key; + + if (IgnoredFields.Contains(Key)) + { + continue; // Skip ignored fields + } + + else if (Key == TEXT("ColorAndOpacity")) + { + TSharedPtr ColorObj = JsonObject->GetObjectField(Key); + if (ColorObj.IsValid()) + { + float R = ColorObj->GetNumberField(TEXT("r")); + float G = ColorObj->GetNumberField(TEXT("g")); + float B = ColorObj->GetNumberField(TEXT("b")); + float A = ColorObj->GetNumberField(TEXT("a")); + Widget->SetColorAndOpacity(FLinearColor(R, G, B, A)); + } + } + + else if (Key == TEXT("Visibility")) + { + FString VisibilityStr = JsonObject->GetStringField(Key); + ESlateVisibility Visibility = ESlateVisibility::Visible; + + if (VisibilityStr == "SelfHitTestInvisible") + Visibility = ESlateVisibility::SelfHitTestInvisible; + else if (VisibilityStr == "Visible") + Visibility = ESlateVisibility::Visible; + else if (VisibilityStr == "Collapsed") + Visibility = ESlateVisibility::Collapsed; + else if (VisibilityStr == "Hidden") + Visibility = ESlateVisibility::Hidden; + else if (VisibilityStr == "HitTestInvisible") + Visibility = ESlateVisibility::HitTestInvisible; + + Widget->SetVisibility(Visibility); + } + else if (Key == TEXT("RenderTransform")) + { + TSharedPtr TransformObj = JsonObject->GetObjectField(Key); + if (TransformObj.IsValid()) + { + FVector2D Translation(0.f, 0.f); + FVector2D Scale(1.f, 1.f); + FVector2D Shear(0.f, 0.f); + float Angle = 0.f; + + if (TransformObj->HasField(TEXT("translation"))) + { + TSharedPtr TransObj = TransformObj->GetObjectField(TEXT("translation")); + Translation.X = TransObj->GetNumberField(TEXT("x")); + Translation.Y = TransObj->GetNumberField(TEXT("y")); + } + if (TransformObj->HasField(TEXT("scale"))) + { + TSharedPtr ScaleObj = TransformObj->GetObjectField(TEXT("scale")); + Scale.X = ScaleObj->GetNumberField(TEXT("x")); + Scale.Y = ScaleObj->GetNumberField(TEXT("y")); + } + if (TransformObj->HasField(TEXT("shear"))) + { + TSharedPtr ShearObj = TransformObj->GetObjectField(TEXT("shear")); + Shear.X = ShearObj->GetNumberField(TEXT("x")); + Shear.Y = ShearObj->GetNumberField(TEXT("y")); + } + if (TransformObj->HasField(TEXT("angle"))) + { + Angle = TransformObj->GetNumberField(TEXT("angle")); + } + + FWidgetTransform WidgetTransform(Translation, Scale, Shear, Angle); + Widget->SetRenderTransform(WidgetTransform); + } + } + else if (Key == TEXT("RenderTransformPivot")) + { + TSharedPtr PivotObj = JsonObject->GetObjectField(Key); + if (PivotObj.IsValid()) + { + float PX = PivotObj->GetNumberField(TEXT("x")); + float PY = PivotObj->GetNumberField(TEXT("y")); + Widget->SetRenderTransformPivot(FVector2D(PX, PY)); + } + } + else if (Key == TEXT("bIsEnabled")) + { + bool bEnabled = JsonObject->GetBoolField(Key); + Widget->SetIsEnabled(bEnabled); + } + else if (Key == TEXT("Cursor")) + { + FString CursorStr = JsonObject->GetStringField(Key); + // Simple example, only supports Default and None + if (CursorStr == "Default") + Widget->SetCursor(EMouseCursor::Default); + else if (CursorStr == "None") + Widget->SetCursor(EMouseCursor::None); + // You can extend more Cursor types + } + + // You can continue adding more field mappings + } + + if (JsonObject->HasField(TEXT("PageWidth")) && JsonObject->HasField(TEXT("PageHeight"))) + { + int32 Width = JsonObject->GetIntegerField(TEXT("PageWidth")); + int32 Height = JsonObject->GetIntegerField(TEXT("PageHeight")); + Widget->SetDesiredSizeInViewport(FVector2D(Width, Height)); + } +} + +UUserWidget* FLQA_UserWidget2Json::CreateBaseUserWidget() +{ + if (!GEngine) + return nullptr; + + UWorld* World = nullptr; + for (const FWorldContext& Context : GEngine->GetWorldContexts()) + { + if (Context.WorldType == EWorldType::Game || Context.WorldType == EWorldType::PIE) + { + World = Context.World(); + break; + } + } + + if (!World) + { + UE_LOG(LogLQARestoreWidget2Json, Warning, TEXT("No valid game world found")); + return nullptr; + } + + APlayerController* PC = World->GetFirstPlayerController(); + if (!PC) + { + UE_LOG(LogLQARestoreWidget2Json, Warning, TEXT("No player controller found")); + return nullptr; + } + + // Create a concrete container UserWidget purely in C++ (base UUserWidget is abstract) + UUserWidget* WidgetInstance = CreateWidget(PC, ULQAContainerWidget::StaticClass()); + if (!WidgetInstance) + { + UE_LOG(LogLQARestoreWidget2Json, Warning, TEXT("Failed to create UserWidget")); + } + + return WidgetInstance; +} + +UUserWidget* FLQA_UserWidget2Json::CreateWidgetFromJson(const TSharedPtr& JsonObject) +{ + UUserWidget* WidgetInstance = CreateBaseUserWidget(); + if (!WidgetInstance) + { + return nullptr; + } + + ApplyJsonToWidget(WidgetInstance, JsonObject); + + return WidgetInstance; +} + +UWidget* FLQA_UserWidget2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for UserWidget")); + return nullptr; + } + + UUserWidget* Widget = nullptr; + + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = CreateWidgetFromJson(ObjectData); + } + } + else + { + Widget = CreateBaseUserWidget(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UUserWidget Failed!")); + return nullptr; + } + + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_VerticalBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_VerticalBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..261a1649514656a2d82fb16e49390af95d0f0048 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_VerticalBox2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_VerticalBox2Json.h" + +#include "Components/VerticalBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_VerticalBox2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for VerticalBox")); + return nullptr; + } + + UVerticalBox* VerticalBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + VerticalBox = GetAsObject(ObjectData, UVerticalBox::StaticClass()); + } + } + else + { + VerticalBox = NewObject(); + } + + if (!VerticalBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UVerticalBox Failed!")); + return nullptr; + } + return VerticalBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09acbff1062ec3dd9cb44334cacfd39196ce4b77 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.cpp @@ -0,0 +1,42 @@ +#include "WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.h" + +#include "Components/WidgetSwitcher.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_WidgetSwitcher2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for WidgetSwitcher")); + return nullptr; + } + + UWidgetSwitcher* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UWidgetSwitcher::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UWidgetSwitcher Failed!")); + return nullptr; + } + return Widget; +} + +ELQAWidgetType FLQA_WidgetSwitcher2Json::GetType() +{ + return ELQAWidgetType::LQA_WidgetSwitcher; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9bd2a5c3ca0eb36e4aa514ed469f5245e15294b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.cpp @@ -0,0 +1,37 @@ +#include "WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.h" + +#include "Components/WindowTitleBarArea.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_WindowTitleBarArea2Json::FromJson( + const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for WindowTitleBarArea")); + return nullptr; + } + + UWindowTitleBarArea* Widget = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + Widget = GetAsObject(ObjectData, UWindowTitleBarArea::StaticClass()); + } + } + else + { + Widget = NewObject(); + } + + if (!Widget) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UWindowTitleBarArea Failed!")); + return nullptr; + } + return Widget; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WrapBox2Json.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WrapBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50a3a70e567b3a23910572842d4bde56a04a49e8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetSlots/Widgets/LQA_WrapBox2Json.cpp @@ -0,0 +1,36 @@ +#include "WidgetSlots/Widgets/LQA_WrapBox2Json.h" + +#include "Components/WrapBox.h" +#include "WidgetSlots/Core/WidgetDefines.h" + +using namespace LQAWidgetConstants; + +UWidget* FLQA_WrapBox2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) +{ + if (!JsonData.IsValid()) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("JsonData is invalid for WrapBox")); + return nullptr; + } + + UWrapBox* WrapBox = nullptr; + if (JsonData->HasField(CommonObjectKey)) + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + WrapBox = GetAsObject(ObjectData, UWrapBox::StaticClass()); + } + } + else + { + WrapBox = NewObject(); + } + + if (!WrapBox) + { + UE_LOG(LogLQARestoreWidget2Json, Error, TEXT("Try Restore UWrapBox Failed!")); + return nullptr; + } + return WrapBox; +} diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetTree/LQAWidgetNode.cpp b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetTree/LQAWidgetNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..895ec5cfbcd3f6c39fb26ae20bc3ec0e1ff2ed6d --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Private/WidgetTree/LQAWidgetNode.cpp @@ -0,0 +1,186 @@ +#include "WidgetTree/LQAWidgetNode.h" + +#include "LQABase.h" +#include "Layout/ArrangedWidget.h" // FArrangedWidget: 已排布控件 +#include "Types/ReflectionMetadata.h" // FReflectionMetaData: UMG 反射元数据 +#include "Widgets/SWidget.h" // SWidget: Slate 控件基类 + +// 关闭编译器优化 (通常用于调试, 便于单步跟踪本文件逻辑) +LQA_DISABLE_OPTIMIZATION + +// ===== 控件类型名 / 插槽类型名常量的实际定义 ===== + +namespace LQASlotNames +{ +// —— 插槽类型名: 字符串需与运行时插槽类型名严格一致 —— +const FName LQA_ButtonSlot(TEXT("ButtonSlot")); +const FName LQA_CanvasPanelSlot(TEXT("CanvasPanelSlot")); +const FName LQA_ScrollBoxSlot(TEXT("ScrollBoxSlot")); +const FName LQA_VerticalBoxSlot(TEXT("VerticalBoxSlot")); +const FName LQA_HorizontalBoxSlot(TEXT("HorizontalBoxSlot")); +const FName LQA_ScaleBoxSlot(TEXT("ScaleBoxSlot")); +const FName LQA_SafeZoneSlot(TEXT("SafeZoneSlot")); +const FName LQA_WrapBoxSlot(TEXT("WrapBoxSlot")); +const FName LQA_SizeBoxSlot(TEXT("SizeBoxSlot")); +const FName LQA_GridSlot(TEXT("GridSlot")); +const FName LQA_UniformGridSlot(TEXT("UniformGridSlot")); +const FName LQA_OverlaySlot(TEXT("OverlaySlot")); +const FName LQA_BorderSlot(TEXT("BorderSlot")); +const FName LQA_WidgetSwitcherSlot(TEXT("WidgetSwitcherSlot")); +const FName LQA_StackBoxSlot(TEXT("StackBoxSlot")); +const FName LQA_WindowTitleBarAreaSlot(TEXT("WindowTitleBarAreaSlot")); + +// 项目自定义插槽名可在此处添加 +} + +namespace LQAWidgetNames +{ +// —— 控件类型名: 字符串为 Slate 控件的运行时类型名 (SWidget::GetType 返回值) —— +const FName LQA_TextBlock(TEXT("STextBlock")); +const FName LQA_RichTextBlock(TEXT("SRichTextBlock")); +const FName LQA_EditableText(TEXT("SEditableText")); +const FName LQA_EditableTextBox(TEXT("SEditableTextBox")); +const FName LQA_MultilineEditableText(TEXT("SMultilineEditableText")); +const FName LQA_MultilineEditableTextBox(TEXT("SMultilineEditableTextBox")); +const FName LQA_ComboBox(TEXT("SComboBox")); +const FName LQA_LEDRichTextBlock(TEXT("SLEDRichTextBlock")); // 项目自定义控件 +const FName LQA_Image(TEXT("SImage")); +const FName LQA_Button(TEXT("SButton")); +const FName LQA_UserWidget(TEXT("SObjectWidget")); // UMG UserWidget 对应的 Slate 实现 +const FName LQA_Canvas(TEXT("SConstraintCanvas")); +const FName LQA_RetainerBox(TEXT("SRetainerWidget")); +const FName LQA_ScrollBox(TEXT("SScrollBox")); +const FName LQA_VerticalBox(TEXT("SVerticalBox")); +const FName LQA_HorizontalBox(TEXT("SHorizontalBox")); +const FName LQA_ScaleBox(TEXT("SScaleBox")); +const FName LQA_SafeZone(TEXT("SSafeZone")); +const FName LQA_WrapBox(TEXT("SWrapBox")); +const FName LQA_SizeBox(TEXT("SBox")); +const FName LQA_CheckBox(TEXT("SCheckBox")); +const FName LQA_GridPanel(TEXT("SGridPanel")); +const FName LQA_UniformGridPanel(TEXT("SUniformGridPanel")); +const FName LQA_Overlay(TEXT("SOverlay")); +const FName LQA_Border(TEXT("SBorder")); +const FName LQA_BackgroundBlur(TEXT("SBackgroundBlur")); +const FName LQA_WidgetSwitcher(TEXT("SWidgetSwitcher")); +const FName LQA_StackBox(TEXT("SStackBox")); + +const FName LQA_ProgressBar(TEXT("SProgressBar")); +const FName LQA_Throbber(TEXT("SThrobber")); +const FName LQA_CircularThrobber(TEXT("SCircularThrobber")); +const FName LQA_Slider(TEXT("SSlider")); +const FName LQA_SpinBox(TEXT("SSpinBox")); +const FName LQA_Spacer(TEXT("SSpacer")); + +const FName LQA_ScrollBar(TEXT("SScrollBar")); +const FName LQA_InputKeySelector(TEXT("SInputKeySelector")); +const FName LQA_MenuAnchor(TEXT("SMenuAnchor")); +const FName LQA_InvalidationBox(TEXT("SInvalidationPanel")); +const FName LQA_PostBufferUpdate(TEXT("SPostBufferUpdate")); +const FName LQA_ListView(TEXT("ListViewT")); +const FName LQA_TileView(TEXT("TileViewT")); +const FName LQA_TreeView(TEXT("TreeViewT")); +const FName LQA_WindowTitleBarArea(TEXT("SWindowTitleBarArea")); +const FName LQA_ExpandableArea(TEXT("SExpandableArea")); + +// 项目自定义控件名可在此处添加 +} + +namespace LQAWidgetClassNames +{ +// —— UMG 实际类型标识: 字符串需与采集侧输出的 "WidgetClass" 字段值严格一致 —— +const FName LQA_DynamicEntryBox(TEXT("DynamicEntryBox")); +} + +/** + * 构造函数: 从已排布控件中取出 Slate 控件引用, 交给 HandleWidget 处理 + */ +FLQAWidgetNode::FLQAWidgetNode(const FArrangedWidget& InWidgetGeometry) +{ + HandleWidget(InWidgetGeometry.Widget); +} + +/** + * 处理单个控件: 识别类型并提取来源对象 + * 处理流程: + * 1. 获取控件运行时类型名并转换为 LQA 枚举; + * 2. 读取 UMG 反射元数据, 无元数据则跳过 (非 UMG 生成的控件); + * 3. 类型未识别 (LQA_Undefined) 则跳过; + * 4. 记录元数据中的来源 UObject + */ +void FLQAWidgetNode::HandleWidget(const TSharedRef& InWidget) +{ + // 获取控件的运行时类型名, 并映射为 LQA 控件类型枚举 + const FName WidgetType = InWidget->GetType(); + const ELQAWidgetType WidgetNodeType = GetWidgetType(WidgetType); + + // UMG 控件会携带反射元数据, 用于反向追踪到对应的 UObject + const TSharedPtr MetaData = InWidget->GetMetaData(); + if (!MetaData.IsValid()) + { + // 没有元数据: 说明不是 UMG 蓝图生成的控件, 无法追踪来源, 直接返回 + return; + } + + if (WidgetNodeType == ELQAWidgetType::LQA_Undefined) + { + // 不是 LQA 关心的控件类型, 跳过 + return; + } + + // 记录创建该控件的来源对象 (弱引用) + SourceObject = MetaData->SourceObject; +} + +/** + * 控件类型名 -> LQA 控件类型枚举 的映射查询 + * 使用静态局部 TMap (只初始化一次), 避免每次调用重复构建映射表 + * @return 命中则返回对应枚举, 未命中返回 LQA_Undefined + */ +ELQAWidgetType FLQAWidgetNode::GetWidgetType(const FName& WidgetTypeName) +{ + using namespace LQAWidgetNames; + + // 静态映射表: 键为控件类型名常量, 值为 LQA 枚举; 首次调用时构建并常驻 + static const TMap WidgetTypeMap = { + // 文本类控件 + {LQA_TextBlock, ELQAWidgetType::LQA_TextBlock}, {LQA_RichTextBlock, ELQAWidgetType::LQA_RichText}, + {LQA_EditableText, ELQAWidgetType::LQA_EditableText}, + {LQA_EditableTextBox, ELQAWidgetType::LQA_EditableTextBox}, + {LQA_MultilineEditableText, ELQAWidgetType::LQA_MultilineEditableText}, + {LQA_MultilineEditableTextBox, ELQAWidgetType::LQA_MultilineEditableTextBox}, + {LQA_ComboBox, ELQAWidgetType::LQA_ComboBoxStringText}, {LQA_LEDRichTextBlock, ELQAWidgetType::LQA_LEDRichText}, + + // 可视化类控件 + {LQA_Image, ELQAWidgetType::LQA_Image}, {LQA_Button, ELQAWidgetType::LQA_Button}, + {LQA_CheckBox, ELQAWidgetType::LQA_CheckBox}, + + // 容器类控件 + {LQA_UserWidget, ELQAWidgetType::LQA_UserWidget}, {LQA_Canvas, ELQAWidgetType::LQA_Canvas}, + {LQA_RetainerBox, ELQAWidgetType::LQA_RetainerBox}, {LQA_ScrollBox, ELQAWidgetType::LQA_ScrollBox}, + {LQA_VerticalBox, ELQAWidgetType::LQA_VerticalBox}, {LQA_HorizontalBox, ELQAWidgetType::LQA_HorizontalBox}, + {LQA_ScaleBox, ELQAWidgetType::LQA_ScaleBox}, {LQA_SafeZone, ELQAWidgetType::LQA_SafeZone}, + {LQA_WrapBox, ELQAWidgetType::LQA_WrapBox}, {LQA_SizeBox, ELQAWidgetType::LQA_SizeBox}, + {LQA_GridPanel, ELQAWidgetType::LQA_GridPanel}, {LQA_UniformGridPanel, ELQAWidgetType::LQA_UniformGridPanel}, + {LQA_Overlay, ELQAWidgetType::LQA_Overlay}, {LQA_Border, ELQAWidgetType::LQA_Border}, + {LQA_BackgroundBlur, ELQAWidgetType::LQA_BackgroundBlur}, + {LQA_WidgetSwitcher, ELQAWidgetType::LQA_WidgetSwitcher}, + {LQA_StackBox, ELQAWidgetType::LQA_StackBox}, + {LQA_WindowTitleBarArea, ELQAWidgetType::LQA_WindowTitleBarArea}, + {LQA_InvalidationBox, ELQAWidgetType::LQA_InvalidationBox}, + {LQA_ExpandableArea, ELQAWidgetType::LQA_ExpandableArea}, + + // 项目自定义控件映射可在此处添加 + }; + + // 在映射表中查找: 命中返回对应枚举值 + if (const ELQAWidgetType* FoundType = WidgetTypeMap.Find(WidgetTypeName)) + { + return *FoundType; + } + // 未命中: 返回未定义类型作为兜底 + return ELQAWidgetType::LQA_Undefined; +} + +// 恢复编译器优化 (与前面的 LQA_DISABLE_OPTIMIZATION 配对) +LQA_ENABLE_OPTIMIZATION \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/ConfigManager.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/ConfigManager.h new file mode 100644 index 0000000000000000000000000000000000000000..333cd99b02d1781e99a41ae9d85b7e4dd345f9ab --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/ConfigManager.h @@ -0,0 +1,205 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Utils/TranslationUtils/LoaderUtils.h" + +// UHT (Unreal Header Tool) 自动生成的头文件, 必须放在所有 UCLASS/USTRUCT 相关宏之后、 +// 且作为本头文件最后一个 include, 否则会编译报错 +#include "ConfigManager.generated.h" + +// 声明一个专属的日志分类 LogLQARestoreConfig, 供 ConfigManager 相关日志输出使用 +// 第二个参数 Log 表示默认日志级别, 第三个参数 All 表示编译期允许的最高详细级别 +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreConfig, Log, All); + +/** + * 配置管理器 (Config Manager) + * 负责 LQA Restore 工具的配置与命令行参数管理 + * 职责包括: 解析命令行参数、存储配置项, 并对外提供统一的访问接口 + */ +UCLASS() +class LQARESTORE_API UConfigManager : public UObject +{ + GENERATED_BODY() + +public: + /** + * 初始化配置管理器并解析命令行参数 + * 应在子系统 (Subsystem) 初始化期间调用一次 + */ + void Initialize(); + + /** + * 获取指定的命令行参数值 + * @param Key - 要查找的参数键名 + * @param DefaultValue - 当参数不存在时返回的默认值 + * @return 参数对应的值; 若未找到则返回 DefaultValue + */ + FString GetCommandLineParam(const FString& Key, const FString& DefaultValue) const; + + /** + * 将内部语言代码转换为 PO 文件使用的语言代码 + * @param InLanguage - 内部语言标识 (例如 "LAN_EU_EN") + * @return PO 语言代码 (例如 "en"); 若未匹配到则默认返回 "en" + */ + FString ConvertToPoLanguage(const FString& InLanguage) const; + + // ============================================================ + // 配置项 Getter (只读访问接口) + // 使用 FORCEINLINE 强制内联, 返回 const 引用以避免字符串拷贝开销 + // ============================================================ + + /** 获取项目 ID */ + FORCEINLINE const FString& GetProjectId() const + { + return ProjectId; + } + /** 获取任务 (Job) ID */ + FORCEINLINE const FString& GetJobId() const + { + return JobId; + } + /** 获取内部语言代码 */ + FORCEINLINE const FString& GetLanguage() const + { + return Language; + } + /** 获取 PO 语言代码 */ + FORCEINLINE const FString& GetPoLanguage() const + { + return PoLanguage; + } + /** 获取回归测试标志 */ + FORCEINLINE const FString& GetRegression() const + { + return Regression; + } + /** 获取是否创建 Bug 的标志 */ + FORCEINLINE const FString& GetCreateBug() const + { + return CreateBug; + } + /** 获取 Bug 跟踪 ID */ + FORCEINLINE const FString& GetBugId() const + { + return BugId; + } + /** 获取 AI 签名标志 */ + FORCEINLINE const FString& GetAISign() const + { + return AISign; + } + /** 获取默认拉取数量 */ + FORCEINLINE const FString& GetDefaultNums() const + { + return DefaultNums; + } + /** 获取查询用的最小数据 ID */ + FORCEINLINE const FString& GetMinID() const + { + return MinID; + } + /** 获取模块过滤列表 */ + FORCEINLINE const FString& GetModules() const + { + return Modules; + } + /** 获取是否覆盖已有文件的标志 */ + FORCEINLINE const FString& GetIsCover() const + { + return IsCover; + } + /** 获取基线对比数据 ID */ + FORCEINLINE const FString& GetBaseDataId() const + { + return BaseDataId; + } + /** 获取基线对比数据文件路径 */ + FORCEINLINE const FString& GetBaseDataFilePath() const + { + return BaseDataFilePath; + } + /** 获取 PNG 文件保存的根目录 */ + FORCEINLINE const FString& GetPngSaveRootDir() const + { + return PngSaveRootDir; + } + /** 是否运行在本地模式 (true 表示本地模式) */ + FORCEINLINE bool IsLocalMode() const + { + return bIsLocalMode; + } + + /** 获取还原语言方向 */ + FORCEINLINE ERestoreDirection GetRestoreDirection() const + { + return RestoreDirection; + } + +private: + /** 解析命令行参数并填充各配置项 */ + void ParseCommandLineParams(); + + /** 初始化语言代码映射表 (内部语言代码 -> PO 语言代码) */ + void InitializeLanguageMap(); + + /** 缓存解析后的命令行参数 (键 -> 值) */ + TMap CommandLineParams; + + /** 语言代码映射表: 内部语言代码 映射到 PO 语言代码 */ + TMap LanguageMap; + + // ============================================================ + // 配置成员变量 + // ============================================================ + + /** PNG 文件保存的根目录 */ + FString PngSaveRootDir; + + /** 项目标识 ID */ + FString ProjectId; + + /** 任务 (Job) 标识 ID */ + FString JobId; + + /** 内部语言代码 (例如 LAN_EU_EN) */ + FString Language; + + /** PO 语言代码 (例如 en) */ + FString PoLanguage; + + /** 回归测试标志 (0 或 1) */ + FString Regression; + + /** 创建 Bug 标志 (0 或 1) */ + FString CreateBug; + + /** Bug 跟踪 ID */ + FString BugId; + + /** AI 签名标志 */ + FString AISign; + + /** 默认拉取的条目数量 */ + FString DefaultNums; + + /** 查询时使用的最小数据 ID */ + FString MinID; + + /** 模块过滤列表 */ + FString Modules; + + /** 是否覆盖已存在的文件 */ + FString IsCover; + + /** 基线对比数据 ID */ + FString BaseDataId; + + /** 基线对比数据文件路径 */ + FString BaseDataFilePath; + + /** 是否运行在本地模式 */ + bool bIsLocalMode; + + /** 还原语言方向 (默认: 外文 -> 中文) */ + ERestoreDirection RestoreDirection; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/FileManager.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/FileManager.h new file mode 100644 index 0000000000000000000000000000000000000000..90a726ec48cfb24eb842b2effa8e4bb0fcc01072 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/FileManager.h @@ -0,0 +1,88 @@ +#pragma once + +#include "CoreMinimal.h" + +// UHT (Unreal Header Tool) 自动生成的头文件, 必须放在所有自定义声明之后、本文件最后一个 include +// 它为带有 UCLASS/UPROPERTY/UFUNCTION 宏的类型生成反射相关的样板代码 +#include "FileManager.generated.h" + +// 声明一个专用的日志分类 LogLQARestoreFile, 供本模块文件操作打印日志使用 +// 参数依次为: 分类名、默认日志等级 (Log)、编译期允许的最高等级 (All) +// EXTERN 表示仅声明, 真正的定义在 .cpp 中通过 DEFINE_LOG_CATEGORY 完成 +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreFile, Log, All); + +/** + * LQA 还原工具的文件系统操作管理器 + * 负责文件读写(I/O)、目录操作, 以及 JSON 文件的加载与处理 + * 继承自 UObject, 可纳入 UE 的垃圾回收 (GC) 与反射系统管理 + */ +UCLASS() +class LQARESTORE_API UFileManager : public UObject +{ + // UE 反射系统所需的样板宏, 为该类注入生成代码 + GENERATED_BODY() + +public: + /** + * 递归查找某个目录下的所有 JSON 文件 + * @param Path 要搜索的目录路径 (可为相对路径, 内部会转为绝对路径) + * @param OutJsonFiles 输出参数, 用于接收找到的所有 JSON 文件的完整路径 + */ + void FindJsonFilesRecursive(const FString& Path, TArray& OutJsonFiles); + + /** + * 根据传入路径解析出待处理的文件列表 + * 支持两种情况: 传入的是单个文件, 或传入的是一个目录 (此时递归收集其中的 JSON) + * @param DumpFilePath 文件路径或目录路径 + * @param OutFilePaths 输出参数, 用于接收解析得到的文件路径列表 + */ + void GetFilePaths(const FString& DumpFilePath, TArray& OutFilePaths); + + /** + * 将 JSON 内容保存为一个 dump 数据文件 + * @param DataId 数据标识符, 用于生成文件名 (格式为 "LQA_{DataId}.json") + * @param JsonContent 要写入文件的 JSON 字符串内容 + * @param SaveDir 文件保存所在的目录 + * @return 保存成功时返回文件的完整路径; 失败时返回空字符串 + */ + FString SaveDumpDataToFile(const FString& DataId, const FString& JsonContent, const FString& SaveDir); + + /** + * 加载并解析一个 JSON 文件 + * @param FilePath JSON 文件的路径 + * @return 解析成功返回 JSON 对象; 文件不存在、读取失败或解析失败时返回 nullptr + */ + TSharedPtr LoadJsonFromFile(const FString& FilePath); + + /** + * 检查指定 DataId 对应的 dump 文件是否存在 + * @param DataId 数据标识符 + * @param SaveDir 要检查的目录 + * @return 若对应的 dump 文件存在则返回 true + */ + bool DumpFileExists(const FString& DataId, const FString& SaveDir) const; + + /** + * 删除一个目录及其全部内容 + * @param DirectoryPath 要删除的目录路径 + * @return 删除成功或目录本就不存在时返回 true; 删除失败返回 false + */ + bool DeleteDirectory(const FString& DirectoryPath); + + /** + * 确保某个目录存在, 如不存在则创建它 (含多级父目录) + * @param DirectoryPath 目录路径 + * @return 目录已存在或创建成功返回 true; 创建失败返回 false + */ + bool EnsureDirectoryExists(const FString& DirectoryPath); + +private: + /** + * 根据 DataId 和目录拼装出 dump 文件的完整路径 + * 规则: {SaveDir}/LQAData/LQA_{DataId}.json + * @param DataId 数据标识符 + * @param SaveDir 基础保存目录 + * @return 拼装好的完整文件路径 + */ + FString GetDumpFilePath(const FString& DataId, const FString& SaveDir) const; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQAContainerWidget.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQAContainerWidget.h new file mode 100644 index 0000000000000000000000000000000000000000..b9bbe23537131181df63a8dbbf4f0542ec6747d8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQAContainerWidget.h @@ -0,0 +1,24 @@ +#pragma once + +// UUserWidget 基类所在头文件, 提供 UMG 用户控件的基础实现 +#include "Blueprint/UserWidget.h" +// UE 核心最小依赖集合 (基础类型、宏、模板等) +#include "CoreMinimal.h" + +// 由 UHT (UnrealHeaderTool) 生成的反射代码头文件, 必须放在所有包含的最后一行 +#include "LQAContainerWidget.generated.h" + +/** + * LQA 还原过程中使用的「最小化具体 UserWidget」, 纯粹作为 C++ 层的容器使用 + * + * 设计原因: + * UUserWidget 本身是抽象类 (abstract), 无法被直接实例化 (CreateWidget / NewObject 会失败) + * 因此这里派生出一个不添加任何额外逻辑的最小子类, 仅用于在代码中创建可用的控件实例, + * 充当承载 LQA 还原内容的容器 + */ +UCLASS() +class ULQAContainerWidget : public UUserWidget +{ + // UE 反射系统所需的样板宏, 自动生成构造、序列化等支持代码 + GENERATED_BODY() +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQARestoreManager.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQARestoreManager.h new file mode 100644 index 0000000000000000000000000000000000000000..4f3cf484474a1bba72db268fe55ef76a25db30e2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/LQARestoreManager.h @@ -0,0 +1,181 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Subsystems/GameInstanceSubsystem.h" + +#include "LQARestoreManager.generated.h" + +// 声明本类专用的日志分类, 便于在输出日志中按 "LogLQARestoreManager" 过滤 +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreManager, Log, All); + +// 前置声明, 避免在头文件中包含完整定义, 降低编译依赖 +class URestoreWindowProxy; // 还原窗口代理: 负责具体窗口的创建/构建/销毁 +class UConfigManager; // 配置管理器: 读取语言、模式、路径等配置 +class UTaskManager; // 任务管理器: 负责网络请求 (拉任务/下载/上传) +class UFileManager; // 文件管理器: 负责本地文件/目录读写与查找 + +/** + * 截图取景范围: 决定截图链路走哪一条 + * 两种模式产出的是两种不同用途的图, 不可互相替代: + * - WidgetOnly: 只有还原出来的控件本身, 没有周围环境, 适合校验单个控件 + * - Viewport: 玩家真正看到的画面, 包含背景与其他 UI, 适合还原比对 + */ +UENUM(BlueprintType) +enum class ELQAScreenshotMode : uint8 +{ + WidgetOnly UMETA(DisplayName = "仅控件 (离屏渲染)"), + + Viewport UMETA(DisplayName = "游戏视口 (含 UI)") +}; + +/** + * LQA 还原工具的主控制器 (GameInstance 子系统) + * 职责: + * 1. 协调 配置(Config) / 网络(Task) / 文件(File) 三大模块的工作流 + * 2. 同时支持两种还原流程: + * - 平台模式 (Platform): 从远端服务器拉取任务、下载、还原、上传 + * - 本地模式 (Local): 直接扫描本地 JSON 文件逐个还原 + * 生命周期跟随 GameInstance, 游戏实例创建时 Initialize, 销毁时 Deinitialize + */ +UCLASS() +class LQARESTORE_API ULQARestoreManager : public UGameInstanceSubsystem +{ + GENERATED_BODY() + +public: + // 子系统初始化入口: 创建管理器、绑定委托、启动工作定时器 + virtual void Initialize(FSubsystemCollectionBase& Collection) override; + // 子系统反初始化入口: 销毁所有窗口、清理定时器 + virtual void Deinitialize() override; + + /** + * 根据 dump 文件创建一个还原窗口 (蓝图可调用) + * @param DumpFilePath dump JSON 文件的完整路径 + * @param DataId 数据标识符, 用于命名输出目录及区分任务项 + * @return 创建成功返回 true, 失败返回 false + */ + UFUNCTION(BlueprintCallable, Category = "LQA Restore") + bool MakeRestoredWindow(const FString& DumpFilePath, const FString& DataId = TEXT("0")); + + /** + * 清理当前所有活动的还原窗口, 并将进度推进到下一项 (蓝图可调用) + */ + UFUNCTION(BlueprintCallable, Category = "LQA Restore") + void ClearRestoreWindow(); + + /** + * 设置截图模式, 决定后续每次截图取哪一块画面 (蓝图可调用) + * @param InMode WidgetOnly=仅还原控件, Viewport=整个游戏视口 (含 UI) + */ + UFUNCTION(BlueprintCallable, Category = "LQA Restore") + void SetScreenshotMode(ELQAScreenshotMode InMode); + + /** 获取当前截图模式 (蓝图可调用) */ + UFUNCTION(BlueprintCallable, Category = "LQA Restore") + ELQAScreenshotMode GetScreenshotMode() const; + +private: + /** 初始化并启动整个还原工作流 (在 Initialize 延迟后调用) */ + void StartWork(); + + /** + * 处理平台模式工作流 + * @param bIsFirstRequest 是否为首次请求 (首次需要插入基准数据并启动定时器) + */ + void HandlePlatformWorkflow(bool bIsFirstRequest); + + /** 处理本地文件模式工作流: 扫描本地 JSON 并启动本地处理定时器 */ + void HandleLocalWorkflow(); + + /** 根据配置的语言, 加载对应的翻译数据文件 */ + void LoadTranslationData(); + + /** 若配置开启了对比 (cover) 模式, 则准备基准对比数据并插入待处理队列首位 */ + void SetupBaseDataIfNeeded(); + + /** 设置平台模式下所有周期性定时器 (拉任务/下载/还原/上传) */ + void SetupPlatformTimers(); + + // ===== 定时器回调 (周期性触发) ===== + void OnGetJobDataTick(); // 周期性向平台拉取任务数据 + void OnDownloadTick(); // 周期性处理下载队列 + void OnRestoreTick(); // 周期性尝试还原当前待处理项 + void OnUploadTick(); // 周期性处理上传队列 + void OnLocalJobTick(); // 本地模式下周期性处理下一个本地文件 + + // ===== 网络委托回调 (由 TaskManager 触发) ===== + // 收到平台返回的任务列表 (ID 列表 + 对应文件路径列表) + void OnJobDataReceived(const TArray& IdList, const TArray& IdPathList); + // 某个 dump 数据下载完成 + void OnDumpDataDownloaded(const FString& DataId, const FString& FilePath); + // 某个还原结果上传完成 + void OnRestoreResultUploaded(const FString& DataId); + + /** 处理当前索引指向的还原项 (含文件就绪的重试逻辑) */ + void ProcessCurrentRestoreItem(); + + /** 窗口构建完成后, 安排延迟截图与结果上传 */ + void ScheduleScreenshotAndUpload(URestoreWindowProxy* Proxy, const FString& DataId); + + /** 截取整个视口 (Viewport) 画面并保存为文件 */ + bool CaptureViewportScreenshot(const FString& FilePath); + + /** 截取指定 UMG 控件的画面并保存为文件 */ + bool CaptureWidgetScreenshot(UUserWidget* Widget, const FString& FilePath); + + // ===== 核心管理器 (UPROPERTY 保证被 GC 引用, 不会被回收) ===== + UPROPERTY() + UConfigManager* ConfigManager; // 配置管理器实例 + + UPROPERTY() + UTaskManager* TaskManager; // 任务 (网络) 管理器实例 + + UPROPERTY() + UFileManager* FileManager; // 文件管理器实例 + + // 当前所有活动的还原窗口: 键为窗口 ID, 值为窗口代理 + UPROPERTY() + TMap ActiveWindows; + + // 截图取景范围 + ELQAScreenshotMode ScreenshotMode = ELQAScreenshotMode::WidgetOnly; + + // ===== 工作数据 ===== + TArray PendingDataIds; // 待还原的数据 ID 列表 + TArray PendingFilePaths; // 与 PendingDataIds 一一对应的文件路径列表 + TArray LocalJsonFiles; // 本地模式下扫描到的 JSON 文件路径列表 + TQueue CompletedDataIds; // 已完成还原的数据 ID 队列 + + // ===== 对比数据 ===== + TSharedPtr BaseComparisonData; // 基准对比数据 (对比模式下使用) + + // ===== 状态跟踪 ===== + uint32 NextWindowId; // 下一个窗口 ID (自增, 保证唯一) + int32 CurrentRestoreIndex; // 平台模式下当前还原项的索引 + int32 CurrentLocalFileIndex; // 本地模式下当前处理文件的索引 + int32 CurrentRestoreRetryCount; // 当前还原项的重试计数 (等待文件下载完成) + bool bCanStartRestore; // 是否允许开始新的还原 (防止并发还原) + + // ===== 定时器句柄 ===== + FTimerHandle StartWorkTimer; // 启动工作流的延迟定时器 + FTimerHandle JobDataTimer; // 拉取任务数据定时器 + FTimerHandle DownloadTimer; // 下载处理定时器 + FTimerHandle RestoreTimer; // 还原处理定时器 + FTimerHandle UploadTimer; // 上传处理定时器 + FTimerHandle LocalJobTimer; // 本地任务处理定时器 + FTimerHandle RefreshTextTimer; // 文本刷新后构建窗口的延迟定时器 + FTimerHandle ScreenshotTimer; // 截图的延迟定时器 + + // ===== 定时器间隔 / 延迟 (单位: 秒) ===== + static constexpr float InitialStartDelay = 1.0f; // 初始化后延迟多久启动工作流 + static constexpr float JobDataInterval = 150.0f; // 拉取任务数据的周期 + static constexpr float DownloadInterval = 3.0f; // 处理下载队列的周期 + static constexpr float RestoreInterval = 10.0f; // 处理还原的周期 + static constexpr float UploadInterval = 4.0f; // 处理上传队列的周期 + static constexpr float LocalJobInterval = 25.0f; // 本地文件处理的周期 + static constexpr float RefreshTextDelay = 1.3f; // 文本刷新到构建窗口的等待时间 + static constexpr float ScreenshotDelay = 8.0f; // 窗口构建到截图的等待时间 + + // ===== 重试配置 ===== + static constexpr int32 MaxRestoreRetryTimes = 3; // 还原项等待文件的最大重试次数 +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowProxy.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowProxy.h new file mode 100644 index 0000000000000000000000000000000000000000..06ab56da50c0f2cdd350d61b957d4c00787a029b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowProxy.h @@ -0,0 +1,319 @@ +#pragma once + +#include "Components/CanvasPanel.h" +#include "Core/RestoreWindowUtils.h" +#include "CoreMinimal.h" +#include "Engine/TextureRenderTarget.h" +#include "Engine/TextureRenderTarget2D.h" +#include "WidgetSlots/Core/RestoreWidget2JsonFactory.h" +#include "Widgets/Layout/SBox.h" +#include "Widgets/SCompoundWidget.h" + +#include "RestoreWindowProxy.generated.h" + +// 前向声明: 根节点控件与 2D 纹理, 避免引入完整头文件以减少编译依赖 +class URootObjWidget; +class UTexture2D; +class UWorld; +class INamedSlotInterface; + +/** + * LQA 还原窗口的代理 (Proxy) 类 + * 职责:管理还原窗口的整个生命周期以及控件 (Widget) 层级结构, + * 包括窗口的创建、控件的递归添加以及相关资源的管理与释放 + */ +UCLASS() +class URestoreWindowProxy : public UObject +{ + GENERATED_BODY() + +public: + // ======================================================================== + // 生命周期管理 (Lifecycle Management) + // ======================================================================== + + /** + * 初始化还原窗口代理, 传入窗口 ID 与游戏实例 + * @param InWindowId 窗口的唯一标识 ID + * @param InGameInstance 游戏实例, 用于定时器 (Timer) 管理 + */ + void Initialize(int32 InWindowId, UGameInstance* InGameInstance); + + /** + * 创建并显示还原窗口 + * @param Size 屏幕空间下的窗口尺寸 + */ + void CreateWindow(const FVector2D& Size); + + /** 销毁窗口并释放全部资源 */ + void DestroyWindow(); + + // ======================================================================== + // 控件与面板管理 (Widget & Panel Management) + // ======================================================================== + + /** + * 根据 JSON 数据添加面板控件层级 (递归入口) + * @param OwningUserWidget 拥有当前面板的 UserWidget (顶层时为 nullptr) + * @param OwningUserWidgetParentPanel 该 UserWidget 的父面板 + * @param OwningUserWidgetAdditionalInfo 该 UserWidget 的附加数据 + * @param OwningUserWidgetMetaData 该 UserWidget 的元数据 + * @param ParentPanel 父面板控件 (用于 UNDEFINE 类型的继承) + * @param ParentPanelType 父面板类型 + * @param ParentCorners 父节点的四角坐标 + * @param ParentScroll 父节点是否可滚动 + * @param ParentScrollCorners 父滚动框的四角坐标 + * @param CurrentPanelJsonObject 当前面板的 JSON 数据 + * @param WindowSize 窗口尺寸 + * @param RootPos 根坐标偏移量 + * @return 创建出的面板控件; 若失败则返回 nullptr + */ + UPanelWidget* AddPanel(UUserWidget* OwningUserWidget, UPanelWidget* OwningUserWidgetParentPanel, + const TSharedPtr& OwningUserWidgetAdditionalInfo, FRestoreWidgetMeta OwningUserWidgetMetaData, + UPanelWidget* ParentPanel, FString ParentPanelType, TArray> ParentCorners, + bool ParentScroll, TArray> ParentScrollCorners, + const TSharedPtr& CurrentPanelJsonObject, const FVector2D& WindowSize, FVector2D RootPos); + + // ======================================================================== + // 视觉更新 (Visual Updates) + // ======================================================================== + + /** + * 更新还原窗口的背景图片 + * @param ImagePath 背景图片文件的路径 + */ + void ProcessImageBackground(const FString& ImagePath); + + // ======================================================================== + // 校验与导出 (Validation & Export) + // ======================================================================== + + /** + * 生成用于校验的四角坐标检查数据 + * @param CheckInfoFilePath 检查数据的输出文件路径 + * @param CheckParentWidgets 需要校验的父控件列表 + */ + void GenerateCheckCorners(FString CheckInfoFilePath, TArray CheckParentWidgets); + + // ======================================================================== + // 访问器 (Accessors) + // ======================================================================== + + /** 获取根控件, 通常用于截图捕获 */ + FORCEINLINE URootObjWidget* GetRootWidget() const + { + return RootObj; + } + + /** + * 获取本次还原所依据的 dump session 目录 + * 该目录下可能包含 Textures/.png, 用于还原磁盘上不存在的运行时纹理 + */ + FORCEINLINE const FString& GetSnapshotDirectory() const + { + return SnapshotDirectory; + } + + /** 设置 dump session 目录 (通常为 dump json 文件所在的目录) */ + FORCEINLINE void SetSnapshotDirectory(const FString& InDirectory) + { + SnapshotDirectory = InDirectory; + } + + // ======================================================================== + // 公有属性 (Public Properties) + // ======================================================================== + + /** 延迟初始化控件所使用的定时器句柄 */ + FTimerHandle TimerHandle; + + /** 控件渲染所用的共享纹理缓存 (键为路径, 值为纹理) */ + UPROPERTY() + TMap SharedTextureMap; + +private: + // ======================================================================== + // 控件生命周期回调 (Widget Lifecycle Callbacks) + // ======================================================================== + + /** 初始化延迟结束、控件系统就绪后触发的回调 */ + UFUNCTION() + void OnWidgetSystemReady(); + + // ======================================================================== + // 控件与面板管理 (Widget & Panel Management) + // ======================================================================== + + /** + * 根据面板类型与父节点滚动状态, 判定当前的滚动上下文 + * @param PanelType 当前面板控件类型 + * @param PanelJsonObject 面板 JSON 数据 + * @param ParentScroll 父节点是否可滚动 + * @param ParentScrollCorners 父滚动框四角坐标 + * @param OutIsScroll 输出: 当前面板是否可滚动 + * @param OutScrollCorners 输出: 滚动框四角坐标 + */ + void DetermineScrollContext(const FString& PanelType, const TSharedPtr& PanelJsonObject, + bool ParentScroll, const TArray>& ParentScrollCorners, bool& OutIsScroll, + TArray>& OutScrollCorners); + + /** + * 处理控件实际为 UserWidget (而非面板容器) 的情况 + * 负责准备 UserWidget 的元数据 (插槽、尺寸、视频路径、四角坐标等) + * @param UserWidgetAsWidget 需要转换为 UserWidget 的控件 + * @param UserWidgetJsonObject UserWidget 的 JSON 数据 + * @param UserWidgetParentPanel 该 UserWidget 的父面板 + * @param ParentCorners 父节点四角坐标 + * @param UserWidgetMetaData UserWidget 元数据 + * @param OutUserWidget 输出: UserWidget 实例 + * @param OutUserWidgetParentPanel 输出: 父面板 + * @param OutUserWidgetAdditionalData 输出: 附加数据 (插槽、尺寸、视频、四角等) + * @param OutUserWidgetMetaData 输出: 控件元数据 + */ + void HandleUserWidget(UWidget* UserWidgetAsWidget, const TSharedPtr& UserWidgetJsonObject, + UPanelWidget* UserWidgetParentPanel, const TArray>& ParentCorners, + const FRestoreWidgetMeta& UserWidgetMetaData, UUserWidget*& OutUserWidget, UPanelWidget*& OutUserWidgetParentPanel, + TSharedPtr& OutUserWidgetAdditionalData, FRestoreWidgetMeta& OutUserWidgetMetaData); + + /** + * 将 UserWidget 添加到根对象, 并进行可见性校验 + * @param ParentUserWidget 包含该嵌套 UserWidget 的父 UserWidget + * @param CurrentPanel 来自嵌套 UserWidget 的面板 + * @param ParentPanel 控件层级中的父面板 + * @param UserWidgetAdditionalInfo UserWidget 元数据 (尺寸、视频、四角等) + * @param CurrentPanelAdditionalInfo 当前面板的 JSON 数据 + * @param UserWidgetMetaData 控件元数据 (位置、尺寸、ZOrder) + */ + void AddUserWidget(UUserWidget* ParentUserWidget, UPanelWidget* CurrentPanel, UPanelWidget* ParentPanel, + const TSharedPtr& UserWidgetAdditionalInfo, + const TSharedPtr& CurrentPanelAdditionalInfo, const FRestoreWidgetMeta& UserWidgetMetaData); + + // ======================================================================== + // JSON 处理工具 (JSON Processing Utilities) + // ======================================================================== + + /** + * 递归解包 UNDEFINE 占位节点, 向下寻找真正有效的节点 + * @param NodeJson 面板节点 JSON + * @return 解包后的 JSON 对象; 若无效则返回 nullptr + */ + TSharedPtr UnwrapUndefinedNode(TSharedPtr NodeJson); + + /** + * 将某个字段从源 JSON 拷贝到目标 JSON + * @param Source 源 JSON + * @param Target 目标 JSON + * @param FieldName 需要拷贝的字段名 + */ + void CopyJsonField( + const TSharedPtr& Source, TSharedPtr& Target, const FString& FieldName); + + /** + * 判断 JSON 对象是否含有子节点 + * @param JsonObject 待检查的 JSON 对象 + * @return 存在子节点时返回 true + */ + bool HasChildNodes(const TSharedPtr& JsonObject) const; + + /** + * 还原命名插槽容器 (INamedSlotInterface, 如 UExpandableArea) 的各命名插槽内容 + * 命名插槽容器不是 UPanelWidget, 其内容需通过 SetContentForSlot 挂载 + * @param NamedSlotContainer 命名插槽容器控件 + * @param ChildNodes 命名插槽子节点 JSON 数组 (每个子节点带 SlotName 字段) + * @param WindowSize 窗口尺寸 + * @param WorldInstance 当前 World 实例 + */ + void RestoreNamedSlotChildren(INamedSlotInterface* NamedSlotContainer, + const TArray>& ChildNodes, const FVector2D& WindowSize, UWorld* WorldInstance); + + /** + * 递归还原命名插槽内容子树, 返回根控件及其元数据 + * @param JsonObject 命名插槽内容节点的 JSON + * @param WindowSize 窗口尺寸 + * @param WorldInstance 当前 World 实例 + * @return 还原得到的控件元数据 (WidgetIns 为根控件) + */ + FRestoreWidgetMeta RestoreNamedSlotContent( + const TSharedPtr& JsonObject, const FVector2D& WindowSize, UWorld* WorldInstance); + + /** + * 通过 Slate 反射元数据获取当前 World 实例 + * @return 当前 World 实例; 失败返回 nullptr + */ + UWorld* GetWorldInstance() const; + + /** + * 拷贝子控件插槽数据, 并将其挂载到指定面板 + * @param Panel 目标面板 + * @param PanelPosition 面板位置 + * @param PanelType 面板类型 + * @param ChildJsonObject 子控件 JSON (含 Slot/SlotType 字段) + * @param ChildMeta 子控件还原元数据 + * @param WorldInstance 当前 World 实例 + */ + void AddChildToPanel(UPanelWidget* Panel, const FVector2D& PanelPosition, const FString& PanelType, + const TSharedPtr& ChildJsonObject, const FRestoreWidgetMeta& ChildMeta, UWorld* WorldInstance); + + // ======================================================================== + // 文本与翻译处理 (Text & Translation Processing) + // ======================================================================== + + /** + * 处理叶子节点的文本与翻译数据 + * 负责执行翻译,并从 objectData 中提取正文文本 (Text) 与提示文本 (HintText) + * @param LeafNodeJsonObject 叶子节点 JSON (会被就地修改) + */ + void ProcessLeafNodeTextData(TSharedPtr& LeafNodeJsonObject); + + // ======================================================================== + // 校验工具 (Validation Utilities) + // ======================================================================== + + /** + * 校验子控件是否与滚动框存在重叠 + * @param ChildWidgetCorners 子控件四角坐标 + * @param ScrollBoxCorners 滚动框四角坐标 + * @param ChildWidgetName 控件名称 (用于日志输出) + * @return 子控件与滚动框存在重叠时返回 true + */ + bool ValidateScrollBoxOverlap(const TArray>& ChildWidgetCorners, + const TArray>& ScrollBoxCorners, const FString& ChildWidgetName) const; + + /** + * 计算 UserWidget 与父容器的重叠比例, 判断是否应当忽略该控件 + * @param UserWidgetPanelJsonObject UserWidget 面板 JSON + * @param PanelJsonObject 当前面板 JSON + * @return 当重叠比例低于阈值时返回 true (表示应忽略) + */ + bool ShouldIgnoreUserWidget( + const TSharedPtr& UserWidgetPanelJsonObject, const TSharedPtr& PanelJsonObject) const; + + // ======================================================================== + // 私有属性 (Private Properties) + // ======================================================================== + + /** 承载窗口内容的主画布面板 */ + UPROPERTY() + UCanvasPanel* WindowPanel = nullptr; + + /** 承载整个 UI 层级结构的根对象控件 */ + UPROPERTY() + URootObjWidget* RootObj = nullptr; + + /** 缓存的游戏实例, 用于定时器管理 */ + UPROPERTY() + UGameInstance* CachedGameInstance = nullptr; + + /** 当前窗口的唯一标识 ID */ + int32 WindowId = 0; + + /** + * 本次还原所依据的 dump session 目录 (即 dump json 所在目录) + * 其中的 Textures/.png 用于在资源路径无法加载时兜底还原运行时生成的纹理 + */ + UPROPERTY() + FString SnapshotDirectory; + + /** 标记控件是否已准备好可以进行绘制 */ + bool bIsReadyToDraw = false; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..d6eb0047888f8f062f467f1eb1810377ca7dafa3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RestoreWindowUtils.h @@ -0,0 +1,160 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Engine/Texture2D.h" +#include "Json.h" +#include "Materials/MaterialInstanceConstant.h" +#include "PaperSprite.h" +#include "Styling/SlateBrush.h" + +// 前置声明, 避免头文件间的循环依赖, 减少编译耦合 +class UCanvasPanel; // 画布面板控件 +class UWidget; // 所有 UMG 控件的基类 +class URestoreWindowProxy; // 窗口代理, 提供窗口创建与渲染相关 API +class UImage; // 图片控件 + +// 声明一个单播/多播委托: 当还原窗口被销毁时广播, 参数为窗口的 int32 标识 +DECLARE_MULTICAST_DELEGATE_OneParam(FOnRestoreWindowDestroyed, int32); + +/** + * LQA 纹理的元数据结构 + * 用于记录某张纹理在图集中的 UV 坐标与尺寸信息 + */ +struct FLQATextureMeta +{ + int32 TextureIndex; // 纹理索引 (在纹理数组/图集中的序号) + FVector2D TextureUV; // 纹理在图集中的 UV 偏移坐标 + FVector2D TextureSize; // 纹理的尺寸 (宽、高) +}; + +/** + * UI 还原与校验的工具类 + * 提供窗口创建、控件还原以及 UI 树分析等一系列静态工具函数 + * 该类为纯工具类, 所有成员均为静态, 不需要实例化 + */ +class FRestoreWindowUtils +{ +public: + // ======================================== + // 窗口创建与构建 + // ======================================== + + /** + * 从 dump 文件创建并构建还原窗口 + * @param DumpFilePath dump 文件 (UI 数据快照) 的路径 + * @param WindowProxy 窗口代理, 提供渲染相关 API + * @return 窗口是否成功创建 + */ + static bool CreateWindow(const FString& DumpFilePath, URestoreWindowProxy* WindowProxy); + + /** + * 根据 dump 数据与基础 UI 数据构建窗口 + * @param DumpFilePath dump 文件路径 + * @param WindowProxy 用于渲染的窗口代理 + * @param BaseUIDataObj 基础 UI 数据的 JSON 对象 (可为空) + * @return 是否构建成功 + */ + static bool BuildWindow( + const FString& DumpFilePath, URestoreWindowProxy* WindowProxy, TSharedPtr BaseUIDataObj); + + /** + * 从 JSON 根对象中反序列化出窗口尺寸 + * @param RootObj 包含窗口元数据的 JSON 根对象 + * @param OutSize 输出参数:解析得到的窗口尺寸 + * @return 反序列化是否成功 + */ + static bool DeserializeWindowSize(const TSharedPtr& RootObj, FVector2D& OutSize); + + /** + * 在 JSON 节点树中查找并替换基础数据 + * @param Node 待搜索与替换的 JSON 节点 + * @param MatchParentWidget 需要匹配的父控件名称 + * @param MatchWidgetName 需要匹配的控件名称 + * @param ReplaceText 要替换成的文本内容 + * @param ReplaceKey 要替换成的文本 Key + * @return 是否成功执行了替换 + */ + static bool ReplaceBaseData(const TSharedPtr& Node, const FString& MatchParentWidget, + const FString& MatchWidgetName, const FString& ReplaceText, const FString& ReplaceKey); + + // ======================================== + // 控件类型检测 + // ======================================== + + /** + * 检查节点是否包含任意可显示控件 (文本或图片) + * @param JsonObject 待检查的 JSON 对象 + * @return 若 (递归地) 包含文本或图片控件则返回 true + */ + static bool ContainsDisplayableWidget(const TSharedPtr& JsonObject); + + /** + * 检查节点是否仅包含文本控件 (不含图片) + * @param JsonObject 待检查的 JSON 对象 + * @return 若 (递归地) 只包含纯文本控件则返回 true + */ + static bool ContainsOnlyTextWidget(const TSharedPtr& JsonObject); + + // ======================================== + // 校验与导出 + // ======================================== + + /** + * 生成用于校验的 JSON 文件 + * @param WindowProxy 包含控件数据的窗口代理 + * @param ResultDirPath 输出目录路径 + */ + static void GenerateCheckJson(URestoreWindowProxy* WindowProxy, const FString& ResultDirPath); + + // ======================================== + // 公有委托 + // ======================================== + + // 还原窗口被销毁时触发的委托(携带窗口标识) + static FOnRestoreWindowDestroyed OnRestoreWindowDestroyed; + +private: + // ======================================== + // 私有辅助函数 + // ======================================== + + /** + * 反序列化 dump 数据并还原 UI 控件 + * @param RootObj JSON 根对象 + * @param WindowProxy 提供渲染 API 的窗口代理 + * @param InWindowSize 窗口尺寸 + * @param RestoreWindowProxy 还原窗口代理实例 + * @param ObjectParentWidget 父控件名称过滤条件 (默认空字符串表示不过滤) + */ + static void DeserializeData(const TSharedPtr& RootObj, URestoreWindowProxy* WindowProxy, + const FVector2D& InWindowSize, URestoreWindowProxy* RestoreWindowProxy, + const FString& ObjectParentWidget = TEXT("")); + + /** + * 检查节点是否包含指定类型列表中的任意控件类型 + * @param JsonObject 待检查的 JSON 对象 + * @param TypeList 要匹配的控件类型名称列表 + * @return 若 (递归地) 找到任意匹配类型则返回 true + */ + static bool ContainsWidgetType(const TSharedPtr& JsonObject, const TArray& TypeList); + + /** + * 处理十六进制数据表示的背景图片 + * @param HexData 表示 PNG 数据的十六进制字符串 + * @return 保存后的背景图片文件路径 (失败时返回空字符串) + */ + static FString ProcessBackgroundImage(const FString& HexData); + + // ======================================== + // 私有静态数据 + // ======================================== + + /** 纯文本控件类型集合 (不包含图片控件) */ + static const TArray PureTextWidgetTypes; + + /** 文本与图片控件类型集合 (包含所有可显示的 UI 元素) */ + static const TArray TextAndImageWidgetTypes; + + /** 用于校验的父控件名称列表 */ + static TArray AllCheckParentWidgets; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RootObjWidget.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RootObjWidget.h new file mode 100644 index 0000000000000000000000000000000000000000..9c31f6da7136b296eefd42648efb79b87411248f --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/RootObjWidget.h @@ -0,0 +1,262 @@ +#pragma once + +#include "Blueprint/UserWidget.h" +#include "Components/CanvasPanel.h" +#include "Components/Widget.h" +#include "CoreMinimal.h" + +// 由 UHT (Unreal Header Tool) 自动生成的反射代码, 必须放在所有 include 的最后 +#include "RootObjWidget.generated.h" + +// 声明本模块专用的日志分类 LogLQARestoreRootObj (在 .cpp 中用 DEFINE_LOG_CATEGORY 定义) +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreRootObj, Log, All); + +// 前置声明, 减少头文件依赖 +class UCanvasPanel; +class UPaperSprite; + +/** + * LQA (Localization Quality Assurance, 本地化质量保证) 还原流程的根控件类 + * 职责: + * 1. 动态管理控件层级 (纯 C++ 构建, 无需蓝图资源) + * 2. 加载并管理媒体资源 (如背景图) + * 3. 收集文本/图片控件信息并执行本地化质量检查 + */ +UCLASS() +class URootObjWidget : public UUserWidget +{ + GENERATED_BODY() + +protected: + // ======================================================================== + // UUserWidget 接口重写 + // ======================================================================== + + /** 纯 C++ 构建控件树 (不依赖任何蓝图资产), 在控件重建时调用 */ + virtual TSharedRef RebuildWidget() override; + +public: + // ======================================================================== + // LQA 检查相关数据 + // ======================================================================== + + /** 需要在 LQA 检查中忽略的控件唯一 ID 列表 (如嵌入的 UserWidget 子控件) */ + TArray IgnoreUniqueIds; + + /** 需要进行 LQA 检查的文本控件 (使用弱引用, 避免阻止 GC 回收) */ + TArray> CheckTextWidgets; + + /** 需要进行 LQA 检查的图片控件 (使用弱引用, 避免阻止 GC 回收) */ + TArray> CheckImageWidgets; + + /** 与文本控件一一对应的 JSON 属性 (用于 LQA 校验, 下标与 CheckTextWidgets 对应) */ + TArray> TextProperty; + + /** 与图片控件一一对应的 JSON 属性 (用于 LQA 校验, 下标与 CheckImageWidgets 对应) */ + TArray> ImageProperty; + + // ======================================================================== + // 公有方法 + // ======================================================================== + + /** + * 加载一张 PNG 图片并将其设置为全屏背景 + * 内部会对每一步 (文件读取、解码、创建纹理) 进行校验并输出详细错误日志 + * @param ImagePath - PNG 图片文件的绝对路径 (必须存在且为有效 PNG) + */ + void ProcessImageBackground(const FString& ImagePath); + + /** + * 将一个 UserWidget 添加到控件层级中, 并进行自定义定位与插槽配置 + * @param UserWidgetInstance - 要添加的 UserWidget 实例 + * @param UserWidgetRootCanvas - 该 UserWidget 的根画布控件 + * @param ParentPanel - 要挂载到的父面板 (为空时默认使用 MainCanvas) + * @param AdditionalInfo - 包含插槽配置与元数据的 JSON 对象 + * @param ParentRootPosition - 父控件的根位置偏移 + * @param AbsolutePosition - 控件要放置的绝对位置 + * @param SlotSize - 插槽尺寸 + * @param DesiredSize - UserWidget 的期望尺寸 + * @param ZOrder - 渲染层级 (Z 轴顺序) + * @param InPositionScale - 位置缩放系数 + * @param bShouldIgnore - 为 true 时, 将该控件整个层级加入 LQA 忽略列表 + */ + void AddUserWidget(UUserWidget* UserWidgetInstance, UWidget* UserWidgetRootCanvas, UPanelWidget* ParentPanel, + TSharedPtr AdditionalInfo, FVector2D ParentRootPosition, FVector2D AbsolutePosition, + FVector2D SlotSize, FVector2D DesiredSize, int32 ZOrder, int32 InPositionScale, bool bShouldIgnore); + + /** + * 将一个面板控件添加到另一个面板中, 并使用 JSON 配置插槽 + * 若 JSON 插槽配置无效, 则回退为默认的画布插槽定位 + * @param ParentPanel 父面板 (为空时默认使用 MainCanvas) + * @param ParentPanelType 父面板类型 + * @param ParentRootPosition 父面板根位置偏移 + * @param Panel 要添加的面板控件 + * @param PanelType 被添加面板的类型 + * @param PanelPosition 面板的屏幕位置 + * @param PanelSize 面板尺寸 + * @param UserWidgetInstance UserWidget 实例 (若有值则直接返回, 因为 UserWidget 由 AddUserWidget 单独处理) + * @param PanelSlotInfo 包含插槽配置的 JSON 对象 + * @param ZOrder 渲染层级 + * @param InPositionScale 位置计算的缩放系数 + */ + void AddPanel(UPanelWidget* ParentPanel, FString ParentPanelType, FVector2D ParentRootPosition, UPanelWidget* Panel, + FString PanelType, FVector2D PanelPosition, FVector2D PanelSize, UUserWidget* UserWidgetInstance, + TSharedPtr PanelSlotInfo, int32 ZOrder, int32 InPositionScale); + + /** + * 将一个子控件添加到指定面板中, 并进行相对定位 + * 若子控件 JSON 属性中 needOCR 为真, 会将其注册到对应的 LQA 检查列表 + * @param Panel 目标面板 + * @param PanelPosition 父面板位置 + * @param PanelType 面板类型标识 + * @param Child 要添加的子控件 + * @param ChildSlotInfo 子控件的 JSON 插槽配置 + * @param ChildPosition 子控件的绝对位置 + * @param ChildSize 子控件尺寸 + * @param ChildZOrder 子控件渲染层级 + * @param ChildProperty 用于 LQA 检查的 JSON 属性 + * @param WorldInstance 当前 World 实例 + */ + void AddWidgetInPanel(UPanelWidget* Panel, FVector2D PanelPosition, FString PanelType, UWidget* Child, + TSharedPtr ChildSlotInfo, FVector2D ChildPosition, FVector2D ChildSize, int32 ChildZOrder, + TSharedPtr ChildProperty, UWorld* WorldInstance); + + /** + * 计算控件在屏幕空间中的四个角点坐标 + * 支持文本对齐方式, 以及图片基于 Alpha 通道的边缘裁剪 + * @param Widget 控件对象 + * @param WorldInstance 当前 World + * @param bIsText 为 true 时按文本方式计算并应用对齐 + * @param Justification 水平对齐 (Left/Center/Right) + * @param VerticalJustification 垂直对齐 (Top/Center/Bottom) + * @return 四个角点: [左下, 左上, 右上, 右下] + */ + TArray> GetCorners(UWidget* Widget, UWorld* WorldInstance, bool bIsText, + FString Justification = TEXT(""), FString VerticalJustification = TEXT("")); + +private: + /** + * 计算文本控件的角点坐标 (支持对齐方式) + * @return 计算成功返回 true + */ + bool CalculateTextCorners(UWidget* Widget, const FVector2D& PixelPos, const FVector2D& ViewportSize, + const FString& Justification, const FString& VerticalJustification, FVector2D& OutLeftBottom, + FVector2D& OutLeftUpper, FVector2D& OutRightUpper, FVector2D& OutRightBottom); + + /** + * 计算图片控件的角点坐标 (基于 Alpha 通道裁剪透明边缘) + * @return 计算成功返回 true + */ + bool CalculateImageCorners(UWidget* Widget, UWorld* WorldInstance, const FVector2D& ViewportSize, + FVector2D& OutLeftBottom, FVector2D& OutLeftUpper, FVector2D& OutRightUpper, FVector2D& OutRightBottom); + + /** + * 针对 Texture2D 纹理, 根据 Alpha 边界对四个角点进行缩放裁剪 + */ + void ApplyTextureAlphaScaling(UTexture2D* Texture, FVector2D& LeftBottom, FVector2D& LeftUpper, + FVector2D& RightUpper, FVector2D& RightBottom); + + /** + * 针对 PaperSprite 精灵, 根据 Alpha 边界对四个角点进行缩放裁剪 + */ + void ApplySpriteAlphaScaling(UPaperSprite* Sprite, FVector2D& LeftBottom, FVector2D& LeftUpper, + FVector2D& RightUpper, FVector2D& RightBottom); + + /** + * 将四个角点坐标转换为 JSON 数值数组 + */ + TArray> CornersToJsonArray(const FVector2D& LeftBottom, const FVector2D& LeftUpper, + const FVector2D& RightUpper, const FVector2D& RightBottom); + +public: + /** + * 将二维向量位置转换为 JSON 对象格式 + * @param InPos - 要转换的位置 + * @return 包含 "x" 和 "y" 字段的 JSON 对象 + */ + TSharedPtr ConvertPos2Json(const FVector2D& InPos); + + /** + * 收集所有已注册文本控件的 LQA 检查信息 + * @param WorldInstance - 当前 World 实例 + * @param CheckParentWidgets - 用于过滤的父控件名列表 (为空时检查全部) + * @return 包含文本控件信息与角点坐标的 JSON 对象数组 + */ + TArray> GetTextCheckInfo(UWorld* WorldInstance, TArray CheckParentWidgets); + + /** + * 收集所有已注册图片控件的 LQA 检查信息 + * @param WorldInstance - 当前 World 实例 + * @param CheckParentWidgets - 用于过滤的父控件名列表 (为空时检查全部) + * @return 包含图片控件信息与角点坐标的 JSON 对象数组 + */ + TArray> GetImageCheckInfo(UWorld* WorldInstance, TArray CheckParentWidgets); + + /** + * 校验文本是否存在常见的 LQA 缺陷, 并将错误码写入 TextInfo + * 检查项包括: 行高过小、HTML 标签不匹配、Hash 标签(#标记)不匹配 + * @param TextInfo - 包含待校验文本属性的 JSON 对象 + */ + void CheckTextBugs(TSharedPtr TextInfo); + + /** + * 初始化画布缩放, 以保证正确渲染 + * 根据画布几何信息计算并存储位置缩放系数 + */ + void InitScale(); + + /** + * 获取当前位置缩放系数 + * @return 位置缩放值 (默认为 1) + */ + int32 GetPositionScale() const + { + return PositionScale; + } + + /** 作为根容器的主画布面板 (在 C++ 中动态创建) */ + UPROPERTY(Transient) + UCanvasPanel* MainCanvas; + +private: + /** + * 从 JSON 配置 UserWidget 的插槽布局; 若配置不可用则应用默认画布定位 + * @param UserWidgetInstance 要配置的 UserWidget + * @param AdditionalInfo 包含插槽配置的 JSON 对象 + * @param ParentPanel 包含该控件的父面板 + * @param ParentRootPosition 父控件根位置偏移 + * @param AbsolutePosition 绝对屏幕位置 + * @param SlotSize 插槽尺寸 + * @param ZOrder 渲染层级 + * @param InPositionScale 位置缩放系数 + */ + void ConfigureUserWidgetSlot(UUserWidget* UserWidgetInstance, const TSharedPtr& AdditionalInfo, + UPanelWidget* ParentPanel, const FVector2D& ParentRootPosition, const FVector2D& AbsolutePosition, + const FVector2D& SlotSize, int32 ZOrder, int32 InPositionScale); + + /** + * 当 JSON 插槽配置不可用时, 应用默认的画布面板插槽配置 + * @param PanelSlot 要配置的插槽 (必须是 UCanvasPanelSlot) + * @param ParentPanel 父画布面板 + * @param ParentRootPosition 父控件根位置偏移 + * @param AbsolutePosition 绝对屏幕位置 + * @param SlotSize 插槽尺寸 + * @param ZOrder 渲染层级 + * @param InPositionScale 位置缩放系数 + */ + void ApplyDefaultCanvasSlot(UPanelSlot* PanelSlot, UPanelWidget* ParentPanel, const FVector2D& ParentRootPosition, + const FVector2D& AbsolutePosition, const FVector2D& SlotSize, int32 ZOrder, int32 InPositionScale); + + /** + * 收集 UserWidget 层级中所有控件的唯一 ID, 用于 LQA 忽略列表 + * @param UserWidgetInstance 需要收集其层级 ID 的 UserWidget + */ + void CollectIgnoredWidgets(UUserWidget* UserWidgetInstance); + + // ======================================================================== + // 私有属性 + // ======================================================================== + + /** 控件定位时使用的位置缩放系数 (默认为 1) */ + int32 PositionScale = 1; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/TaskManager.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/TaskManager.h new file mode 100644 index 0000000000000000000000000000000000000000..d50041afa2ad26118390dd4d44452a836882013d --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Core/TaskManager.h @@ -0,0 +1,171 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Http.h" // UE HTTP 模块, 提供 FHttpResponsePtr 等类型 + +#include "TaskManager.generated.h" // UHT 自动生成的反射代码, 必须放在最后一个 include + +// 声明一个专属的日志分类 LogLQARestoreTask, 用于本模块所有日志输出 +// 参数: 分类名、默认日志级别 (Log)、编译期允许的最高日志级别 (All) +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreTask, Log, All); + +// 前向声明依赖的管理器类, 避免在头文件中引入其完整定义, 降低编译耦合 +class UConfigManager; +class UFileManager; + +/** + * 任务数据接收完成的委托 (多播, 两个参数) + * @param IdList 服务器返回的任务 ID 列表 + * @param IdPathList 与 ID 一一对应的远端文件路径列表 + */ +DECLARE_MULTICAST_DELEGATE_TwoParams( + FOnJobDataReceived, const TArray&, const TArray&); + +/** + * 单个 dump 数据下载成功的委托 + * @param DataId 数据 ID + * @param FilePath 本地保存路径 (若文件已存在则为空字符串) + */ +DECLARE_MULTICAST_DELEGATE_TwoParams(FOnDumpDataDownloaded, const FString&, const FString&); + +/** + * 单个 dump 数据下载失败 (已达到最大重试次数) 的委托 + * @param DataId 数据 ID + */ +DECLARE_MULTICAST_DELEGATE_OneParam(FOnDumpDataFailed, const FString&); + +/** + * 还原结果上传成功的委托 + * @param DataId 数据 ID + */ +DECLARE_MULTICAST_DELEGATE_OneParam(FOnRestoreResultUploaded, const FString&); + +/** + * LQA 还原工具的任务管理器 + * 负责处理 HTTP 业务逻辑, 包括: 任务数据请求、下载/上传队列调度, 以及失败重试逻辑 + * 内部通过串行队列保证同一时刻只进行一个下载/一个上传任务 + */ +UCLASS() +class LQARESTORE_API UTaskManager : public UObject +{ + GENERATED_BODY() + +public: + /** + * 初始化任务管理器, 注入依赖并重置内部状态 + * @param InConfigManager 配置管理器实例 (提供 JobId、语言、路径等配置) + * @param InFileManager 文件管理器实例 (负责文件读写与目录操作) + */ + void Initialize(UConfigManager* InConfigManager, UFileManager* InFileManager); + + /** + * 向服务器请求任务数据 + * @param bIsFirstRequest 是否为首次请求 (用于区分首次拉取与后续轮询的处理策略) + */ + void RequestJobData(bool bIsFirstRequest); + + /** 处理下载队列中的下一个任务 (若当前无下载进行中) */ + void ProcessDownloadQueue(); + + /** 处理上传队列中的下一个任务 (若当前无上传进行中) */ + void ProcessUploadQueue(); + + /** + * 将一条数据加入下载队列 + * @param DataId 数据标识 + * @param FilePath 远端文件路径 + */ + void EnqueueDownload(const FString& DataId, const FString& FilePath); + + /** + * 将一条数据加入上传队列 + * @param DataId 数据标识 + */ + void EnqueueUpload(const FString& DataId); + + /** 当前是否允许发起下载 (无下载正在进行时返回 true) */ + FORCEINLINE bool CanDownload() const + { + return !bIsDownloading; + } + + /** 当前是否允许发起上传 (无上传正在进行时返回 true) */ + FORCEINLINE bool CanUpload() const + { + return !bIsUploading; + } + + /** 获取当前正在下载的数据 ID */ + FORCEINLINE const FString& GetCurrentDownloadId() const + { + return ActiveDownloadDataId; + } + + /** 获取当前正在上传的数据 ID */ + FORCEINLINE const FString& GetCurrentUploadId() const + { + return ActiveUploadDataId; + } + + // ===== 对外广播的事件委托, 供外部模块 (如 UI、调度器) 绑定监听 ===== + FOnJobDataReceived OnJobDataReceived; // 任务数据接收完成 + FOnDumpDataDownloaded OnDumpDataDownloaded; // dump 数据下载成功 + FOnDumpDataFailed OnDumpDataFailed; // dump 数据下载失败 + FOnRestoreResultUploaded OnRestoreResultUploaded;// 还原结果上传成功 + +private: + /** 任务数据请求成功的 HTTP 回调: 解析 JSON 并广播 OnJobDataReceived */ + void OnJobDataSuccess(FHttpResponsePtr Response); + + /** 下载成功的 HTTP 回调: 校验/解压/保存数据, 并广播下载结果 */ + void OnDownloadSuccess(FHttpResponsePtr Response); + + /** 下载失败处理: 按最大重试次数决定重新入队或广播失败 */ + void OnDownloadFail(); + + /** 上传成功的 HTTP 回调: 重置状态并广播 OnRestoreResultUploaded */ + void OnUploadSuccess(FHttpResponsePtr Response); + + /** 上传失败处理: 按最大重试次数决定重新入队或放弃 */ + void OnUploadFail(); + + /** + * 解压 gzip 格式数据 + * @param CompressedData 输入的压缩数据 + * @param OutDecompressedData 输出的解压后数据 + * @return 解压成功返回 true, 失败返回 false + */ + bool DecompressGzipData(const TArray& CompressedData, TArray& OutDecompressedData); + + /** + * 计算指定数据的还原结果目录路径 + * @param DataId 数据标识 + * @param OutPngDir 输出的 PNG 文件所在目录 + * @param OutJsonDir 输出的 JSON 文件所在目录 (当前实现与 PNG 目录相同) + */ + void GetRestoreResultPaths(const FString& DataId, FString& OutPngDir, FString& OutJsonDir) const; + + /** 配置管理器引用 (UPROPERTY 保证被 GC 追踪, 防止被回收) */ + UPROPERTY() + UConfigManager* ConfigManager; + + /** 文件管理器引用 */ + UPROPERTY() + UFileManager* FileManager; + + // ===== 下载状态 ===== + TQueue> PendingDownloads; // 待下载队列, 元素为 + FString ActiveDownloadDataId; // 当前正在下载的数据 ID + FString ActiveDownloadFilePath; // 当前正在下载的远端文件路径 + bool bIsDownloading; // 是否有下载正在进行 (串行锁) + int32 DownloadRetryCount; // 当前任务已重试次数 + + // ===== 上传状态 ===== + TQueue PendingUploads; // 待上传队列, 元素为 DataId + FString ActiveUploadDataId; // 当前正在上传的数据 ID + bool bIsUploading; // 是否有上传正在进行 (串行锁) + int32 UploadRetryCount; // 当前任务已重试次数 + + // ===== 配置常量 ===== + static constexpr int32 MaxRetryTimes = 3; // 下载/上传的最大重试次数 +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQABase.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQABase.h new file mode 100644 index 0000000000000000000000000000000000000000..394ffc5d94f5cca34e2ea53aa57c75c7ecd71619 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQABase.h @@ -0,0 +1,29 @@ +#pragma once + +// 引入 Unreal Engine 核心最小依赖头文件, +// 包含了引擎开发中最常用的基础类型、宏与模板 (如 FString、TArray、日志宏等) +#include "CoreMinimal.h" + +#if defined(UE_DISABLE_OPTIMIZATION) +#define LQA_DISABLE_OPTIMIZATION UE_DISABLE_OPTIMIZATION +#define LQA_ENABLE_OPTIMIZATION UE_ENABLE_OPTIMIZATION +#else +#define LQA_DISABLE_OPTIMIZATION PRAGMA_DISABLE_OPTIMIZATION +#define LQA_ENABLE_OPTIMIZATION PRAGMA_ENABLE_OPTIMIZATION +#endif + +/** + * 声明 LQA Restore 工具的通用日志分类 (Log Category) + * + * 使用 DECLARE_LOG_CATEGORY_EXTERN 在头文件中 “对外声明” 一个日志分类, + * 以便本模块内任意源文件 include 该头文件后, 都能通过 + * UE_LOG(LogLQARestore, ...) 来输出日志 + * + * 参数说明: + * - LogLQARestore : 日志分类名称 (在日志输出中作为前缀标识, 便于过滤与排查) + * - Log : 默认的运行时日志级别 (低于该级别的日志默认不输出) + * - All : 编译期允许的最高日志级别 (All 表示所有级别都会被编译保留) + * + * 说明: 该分类用于非特定子模块的通用日志记录 + */ +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestore, Log, All) \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQARestore.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQARestore.h new file mode 100644 index 0000000000000000000000000000000000000000..f8d5359c235777ebc58aa81862cc40443b21ba13 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/LQARestore.h @@ -0,0 +1,26 @@ +#pragma once + +// UE 用户控件基类头文件 (UMG), 用于后续创建/引用蓝图 UserWidget +#include "Blueprint/UserWidget.h" +// UE 核心最小化头文件, 包含引擎最基础、最常用的类型与宏定义 +#include "CoreMinimal.h" +// 模块管理器头文件, 提供 IModuleInterface 接口及模块注册相关宏 (如 IMPLEMENT_MODULE) +#include "Modules/ModuleManager.h" + +/** + * FLQARestoreModule + * LQARestore 插件的主模块类 + * 继承自 IModuleInterface,是本插件在引擎中加载/卸载时的入口类 + * 引擎在加载该模块时会实例化此类, 并自动回调 Startup/Shutdown 生命周期函数 + */ +class FLQARestoreModule : public IModuleInterface +{ +public: + /** IModuleInterface 接口实现 */ + + // 模块启动时调用: 在此进行各类初始化工作 (如资源加载、配置读取、注册回调等) + virtual void StartupModule() override; + + // 模块关闭时调用: 在此进行清理工作 (如释放资源、注销回调等), 与 StartupModule 对应 + virtual void ShutdownModule() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/DataConverterUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/DataConverterUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..2276f1f877faea0bcd3fab8aa35d89c94892c072 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/DataConverterUtils.h @@ -0,0 +1,36 @@ +#pragma once + +#include "CoreMinimal.h" + +/** + * 数据转换工具类 (Data Converter Utils) + * + * 用于在「二进制数据」与「十六进制字符串」之间进行相互转换 + * 本类仅提供静态方法, 无需实例化即可调用, 常用于: + * - 将接口返回/文件读取到的十六进制文本还原为原始字节数据; + * - 将原始字节数据序列化为可读、可传输的十六进制字符串 + * + * 说明: LQARESTORE_API 为模块导出宏, 保证该类可被其他模块引用 + */ +class LQARESTORE_API FDataConverterUtils +{ +public: + /** + * 将十六进制字符串转换为二进制字节数组 + * + * @param InData 输入的十六进制字符串 (例如 "48656C6C6F") + * @param OutData 输出参数, 用于接收转换后的二进制字节数组; 调用前会被清空 + * @return 转换成功返回 true; 失败 (如字符串格式非法) 返回 false + */ + static bool GetBinaryDataFromString(const FString& InData, TArray& OutData); + + /** + * 将二进制字节数组转换为十六进制字符串 + * + * 每个字节会被格式化为两位大写十六进制字符(例如字节 0x0A -> "0A") + * + * @param InData 输入的二进制字节数组 + * @param OutStr 输出参数, 用于接收转换后的十六进制字符串; 调用前会被清空 + */ + static void TransBinaryDataToString(const TArray& InData, FString& OutStr); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/GeometryUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/GeometryUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..4442922a6aaad2a9e187a10fa3b7daea3c050157 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/GeometryUtils.h @@ -0,0 +1,121 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Dom/JsonObject.h" +#include "Dom/JsonValue.h" + +/** + * 几何工具类 (FGeometryUtils) + * + * 提供多边形 / 矩形相关的几何运算以及 JSON 数据转换功能, + * 主要用于控件 (Widget) 边界校验与重叠检测等场景 + * + * 该类中所有方法均为静态方法 (static), 无需实例化即可直接调用, + * 可将其视为一个纯函数工具集 + */ +class FGeometryUtils +{ +public: + /** + * 将 JSON 数组转换为 FVector2D (二维向量) 数组, 并可选地进行数量校验 + * + * JSON 数组中的每个元素应为形如 { "x": , "y": } 的对象 + * + * @param JsonArray 输入的 JSON 数组 + * @param OutPoints 输出参数, 转换后得到的二维点数组 + * @param ExpectedCount 期望的点数量; 传入 -1 表示不做数量校验 + * @return 转换成功返回 true;若指定了 ExpectedCount, 则还需实际数量与之一致 + */ + static bool JsonArrayToVector2DArray( + const TArray>& JsonArray, TArray& OutPoints, int32 ExpectedCount = -1); + + /** + * 从 JSON 数组中解析四个角点坐标到 FVector2D 数组 + * + * 本函数是对 JsonArrayToVector2DArray 的封装, 固定要求解析出 4 个角点, + * 常用于矩形 / 四边形控件边框的解析 + * + * @param CornersParent 包含角点数据的 JSON 数组 + * @param OutCorners 输出参数, 解析得到的角点坐标数组 + * @return 恰好成功解析出 4 个角点时返回 true + */ + static FORCEINLINE bool ParseCornersFromJsonArray( + const TArray>& CornersParent, TArray& OutCorners) + { + // 内联函数的定义必须在头文件中, 否则会导致 C4506 (没有定义)错误 + // 四边形固定有 4 个角点 + constexpr int32 PolygonCornerCount = 4; + return JsonArrayToVector2DArray(CornersParent, OutCorners, PolygonCornerCount); + } + + /** + * 根据一组角点计算其轴对齐包围盒 (AABB) + * + * @param Corners 角点坐标数组 + * @return 覆盖所有角点的轴对齐包围盒 (FBox2D) + */ + static FBox2D GetBoundingBox(const TArray& Corners); + + /** + * 计算两个包围盒之间的重叠比例 + * + * 比例以 BoxB 的面积为基准, 即: 重叠面积 / BoxB 面积 + * + * @param BoxA 第一个包围盒 + * @param BoxB 第二个包围盒 (作为比例计算的基准) + * @return 重叠面积占 BoxB 面积的比例, 取值范围 [0.0, 1.0] + */ + static float GetOverlapRatio(const FBox2D& BoxA, const FBox2D& BoxB); + + /** + * 使用射线投射算法 (Ray Casting) 判断某个点是否位于多边形内部 + * + * @param Point 待测试的点 + * @param Polygon 多边形的顶点数组 (按顺序排列) + * @return 点在多边形内部返回 true + */ + static bool IsPointInPolygon(const FVector2D& Point, const TArray& Polygon); + + /** + * 判断两条线段是否相交 + * + * @param P1 线段 1 的起点 + * @param P2 线段 1 的终点 + * @param Q1 线段 2 的起点 + * @param Q2 线段 2 的终点 + * @return 两条线段相交返回 true + */ + static bool DoLinesIntersect(const FVector2D& P1, const FVector2D& P2, const FVector2D& Q1, const FVector2D& Q2); + + /** + * 判断两个多边形的边是否存在相交 + * + * @param A 第一个多边形 + * @param B 第二个多边形 + * @return 任意一条边相交则返回 true + */ + static bool DoPolygonsEdgesIntersect(const TArray& A, const TArray& B); + + /** + * 判断两个多边形是否重叠 + * + * 重叠的判定综合考虑三种情况: 顶点互相包含、边相交 + * + * @param A 第一个多边形 + * @param B 第二个多边形 + * @return 两个多边形存在重叠返回 true + */ + static bool DoPolygonsOverlap(const TArray& A, const TArray& B); + +#if !UE_BUILD_SHIPPING + /** + * 调试辅助函数: 将 JSON 数组中的点坐标打印到日志 + * + * 仅在非 Shipping (开发 / 调试) 版本中可用, 用于排查数据问题 + * + * @param JsonArray 待打印的 JSON 数组 + * @param ArrayName 数组名称, 用于在日志中标识 + */ + static void PrintJsonArrayPoints(const TArray>& JsonArray, const FString& ArrayName); +#endif +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestConfig.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestConfig.h new file mode 100644 index 0000000000000000000000000000000000000000..5f6b6e881179048dc46105200f4c1f10f484e81f --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestConfig.h @@ -0,0 +1,42 @@ +#pragma once + +#include "CoreMinimal.h" + +/** + * 声明一个专用于 LQARestore 插件 HTTP 模块的日志分类 (Log Category) + * - LogLQARestoreHttp: 日志分类名称, 使用 UE_LOG 时作为第一个参数 + * - Log: 默认 (编译期) 日志详细级别, 低于该级别的日志会被编译掉 + * - All: 运行期允许输出的最高详细级别 (不做运行期限制) + * EXTERN 版本只做 `声明`, 真正的 `定义` 在 .cpp 中通过 DEFINE_LOG_CATEGORY 完成 + */ +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreHttp, Log, All); + +/** + * HttpRequestConfig 命名空间 + * ------------------------------------------------------------------ + * 集中管理 HTTP 请求所需的全局配置 (服务器地址、鉴权信息) + * 这些配置从插件目录下的 Config/LQARestore.ini 文件读取, + * 供插件内发起 HTTP 请求的各处统一复用 + */ +namespace HttpRequestConfig +{ +/** 从配置文件 (LQARestore.ini) 中加载 Host 与 Authorization, 需在使用前调用一次 */ +void Initialize(); + +/** + * 服务器主机地址 (已拼接 "http://" 前缀), 例如 "http://127.0.0.1:8080/api-pro" + * 用于 API 接口 (拉任务 / 传结果), 可带网关路径前缀 + * 使用 LQARESTORE_API 导出宏, 保证跨模块可访问; extern 表示定义在 .cpp 中 + */ +extern LQARESTORE_API FString Host; + +/** + * 文件下载基址 (已拼接 "http://" 前缀), 例如 "http://127.0.0.1:8080" + * 专用于下载 dump 文件: 任务返回的 file_path 是域名根下的绝对路径 (/media/...), + * 不带 API 网关前缀, 故与 Host 分开配置; 为空时回退使用 Host + */ +extern LQARESTORE_API FString FileHost; + +/** HTTP 请求头使用的鉴权令牌 (Authorization),同样在 .cpp 中定义 */ +extern LQARESTORE_API FString Authorization; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestHelper.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..2acd926623d5fb19066df5afac6d47ab0d77ee5f --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/HttpUtils/HttpRequestHelper.h @@ -0,0 +1,116 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Http.h" // UE HTTP 核心类型 (IHttpRequest / IHttpResponse 等) +#include "HttpModule.h" // FHttpModule 模块单例, 用于创建请求 +#include "Interfaces/IHttpResponse.h" // HTTP 响应接口定义 +#include "Utils/HttpUtils/HttpRequestConfig.h" // HTTP 配置 (Host、Authorization、日志分类等) + +// 声明「请求成功」委托, 携带一个 FHttpResponsePtr 参数 (服务器返回的响应体) +DECLARE_DELEGATE_OneParam(FOnRequestSuccess, FHttpResponsePtr); +// 声明「请求失败」委托, 无参数 +DECLARE_DELEGATE(FOnRequestFail); + +/** + * HTTP 请求的用户自定义数据载体 + * 用于在异步请求发起到回调完成之间传递上下文信息 + */ +struct FHttpRequestData +{ + FString DataId; // 本次请求关联的数据 ID, 回调时用于识别是哪条数据 +}; + +/** + * 底层 HTTP 请求辅助类 + * 提供基础的 HTTP 通信能力, 不维护任何业务状态 (无状态静态工具类) + */ +class LQARESTORE_API FHttpRequestHelper +{ +public: + /** + * 向服务器发送 dump 文件数据 + * @param JsonData - 需要发送的 JSON 格式数据 + * @param ProjectId - 目标项目标识 + */ + static void SendDumpFile(const FString& JsonData, const FString& ProjectId); + + /** + * 向服务器发送还原 (restore) 操作结果 + * @param ProjectId - 项目标识 + * @param JobId - 任务标识 + * @param DataId - 数据标识 + * @param CheckInfoFilePath - 校验信息文件路径 (会作为文件内容上传) + * @param PngFilePaths - 需要上传的 PNG 图片路径数组 + * @param Language - 语言设置 + * @param Regression - 回归测试标记 + * @param CreateBug - 是否创建 bug 的标记 + * @param BugId - bug 标识 + * @param AISign - AI 签名 + */ + static void SendRestoreResult(const FString& ProjectId, const FString& JobId, const FString& DataId, + const FString& CheckInfoFilePath, const TArray& PngFilePaths, const FString& Language, + const FString& Regression, const FString& CreateBug, const FString& BugId, const FString& AISign); + + /** + * 从服务器获取 dump 数据 + * @param DataId - 要下载的数据标识 + * @param FilePath - 服务器上的文件路径 + */ + static void GetDumpData(const FString& DataId, const FString& FilePath); + + /** + * 从服务器获取项目信息 + * @param ProjectId - 项目标识 + */ + static void GetProjectInfo(const FString& ProjectId); + + /** + * 从服务器获取任务 (job) 数据 + * @param JobId - 任务标识 + * @param IsRegression - 回归测试标记 + * @param Language - 语言设置 + * @param Count - 需要获取的条目数量 + * @param MinId - 分页用的最小 ID (起始游标) + * @param Modules - 模块标识 (以下划线分隔, 内部会转换为逗号) + */ + static void GetJobData(const FString& JobId, const FString& IsRegression, const FString& Language, + const FString& Count, const FString& MinId, const FString& Modules); + + // ===== 用于异步回调的静态委托 ===== + static FOnRequestSuccess OnRequestSuccess; // 通用请求成功回调 + static FOnRequestSuccess OnRequestSuccessForDump; // 获取 dump 数据成功回调 + static FOnRequestSuccess OnRequestSuccessForSendResult; // 发送结果成功回调 + static FOnRequestFail OnRequestFailForDump; // 获取 dump 数据失败回调 + static FOnRequestFail OnRequestFailForSendResult; // 发送结果失败回调 + +private: + /** + * 创建 HTTP 请求对象并设置 URL 与请求方法 + * @param URL - 目标 URL + * @param Verb - HTTP 方法 (GET、POST 等) + * @return 线程安全的 HTTP 请求引用 + */ + static TSharedRef CreateRequest(const FString& URL, const FString& Verb); + + /** + * 统一处理 HTTP 响应, 根据结果分发到成功/失败委托 + * @param Response - HTTP 响应指针 + * @param bSuccess - 请求是否连接成功 + * @param SuccessDelegate - 成功时调用的委托 + * @param FailDelegate - 失败时调用的委托 + */ + static void HandleResponse( + FHttpResponsePtr Response, bool bSuccess, FOnRequestSuccess& SuccessDelegate, FOnRequestFail& FailDelegate); + + // 通用请求完成回调 (SendDumpFile / GetProjectInfo / SendRestoreResult 使用) + static void OnRequestResponseFinished( + FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully); + + // 获取 dump 数据请求完成回调 (携带 FHttpRequestData 用户数据) + static void OnGetDataRequestResponseFinished(FHttpRequestPtr Request, FHttpResponsePtr Response, + bool bConnectedSuccessfully, TSharedPtr UserData); + + // 获取任务数据请求完成回调 + static void OnGetJobDataRequestResponseFinished( + FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/ImageRenderUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/ImageRenderUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..295e4ee800065ff5215bf966b153efe49c91d491 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/ImageRenderUtils.h @@ -0,0 +1,92 @@ +#pragma once + +#include "Components/SlateWrapperTypes.h" // ESlateVisibility 等 Slate 包装类型 +#include "Components/Widget.h" // UWidget 控件基类 +#include "CoreMinimal.h" // UE 核心基础类型 (FVector2D、FIntRect 等) +#include "Engine/Texture2D.h" // UTexture2D 2D 纹理资源 +#include "Styling/SlateBrush.h" // FSlateBrush 画刷结构 + +/** + * 图像渲染与可见性计算的工具类 + * 提供画刷 (Brush) 可见性检测、纹理 Alpha 通道分析、以及几何边界运算等能力 + * 该类是纯静态工具类, 无需实例化, 所有方法均通过 FImageRenderUtils::Xxx 直接调用 + */ +class FImageRenderUtils +{ +public: + //============================================================================== + // 画刷与控件可见性 (Brush & Widget Visibility) + //============================================================================== + + /** + * 根据多个因素综合判断一个 Slate 画刷是否 “可见” (即是否会真正渲染出内容) + * 依次检查: 可见性状态、渲染不透明度、渲染缩放、绘制类型、图像尺寸、着色颜色、以及资源对象 + * @param Brush - 待检测的画刷 + * @param Visibility - 控件的可见性状态 + * @param RenderOpacity - 渲染不透明度 (取值范围 0.0 ~ 1.0) + * @param RenderScale - 渲染缩放向量 + * @return 画刷可见返回 true, 否则返回 false + */ + static bool IsBrushVisible( + const FSlateBrush& Brush, ESlateVisibility Visibility, float RenderOpacity, FVector2D RenderScale); + + /** + * 判断一个画刷是否没有可绘制的背景 (即无绘制类型或无资源对象) + * @param Brush - 待检测的画刷 + * @return 画刷无背景返回 true + */ + static bool IsBrushNoBackground(const FSlateBrush& Brush); + + /** + * 判断一个控件在其所有状态下是否都没有背景 + * 目前支持 UButton (检查 Normal/Hovered/Pressed/Disabled 四个状态) 和 UImage 控件 + * @param Widget - 待检测的控件 + * @return 控件无背景返回 true + */ + static bool IsWidgetNoBackground(UWidget* Widget); + + //============================================================================== + // 纹理 Alpha 通道分析 (Texture Alpha Analysis) + //============================================================================== + + /** + * 计算纹理中可见 (非透明) 像素的包围矩形 + * 基于 PlatformData (平台已烘焙的运行时数据) 进行分析 + * @param Texture - 待分析的纹理 + * @param AlphaThreshold - Alpha 值大于该阈值的像素被视为可见 (默认 10) + * @return 可见像素的包围矩形 + */ + static FIntRect GetVisiblePixelRect(UTexture2D* Texture, uint8 AlphaThreshold = 10); + + /** + * 检查纹理的指定区域内是否存在任意透明像素 + * 使用纹理的 Source (源) 数据进行精确的 Alpha 通道分析 + * @param Texture - 待检测的纹理 + * @param AlphaThreshold - Alpha 值小于等于该阈值的像素被视为透明 (默认 0) + * @param RegionUV - 检测区域的左上角 UV 坐标 (默认 0,0) + * @param RegionSize - 检测区域的尺寸 (默认 0,0 表示整张纹理) + * @return 存在透明像素返回 true + */ + static bool HasTransparencyFromSource(UTexture2D* Texture, uint8 AlphaThreshold = 0, + FIntPoint RegionUV = FIntPoint(0, 0), FIntPoint RegionSize = FIntPoint(0, 0)); + + /** + * 计算非透明像素的包围盒 (边界框) + * 采用 “由外向内” 扫描策略: 从矩形四条边向中心逐行/逐列扫描, 找到第一条含不透明像素的边界即停止 + * @param Texture - 待分析的纹理 + * @param AlphaThreshold - Alpha 值大于该阈值视为不透明 (默认 0) + * @param RegionUV - 检测区域的左上角 UV 坐标 (默认 0,0) + * @param RegionSize - 检测区域的尺寸 (默认 0,0 表示整张纹理) + * @return 不透明区域的包围盒 (Min 为闭区间, Max 为开区间) + */ + static FIntRect GetAlphaBoundsFromSource_OuterToInner(UTexture2D* Texture, uint8 AlphaThreshold = 0, + FIntPoint RegionUV = FIntPoint(0, 0), FIntPoint RegionSize = FIntPoint(0, 0)); + + /** + * 判断一个点是否超出了视口 (Viewport) 边界 + * @param Point - 待检测的点坐标 + * @param ViewportSize - 视口尺寸 + * @return 点在视口外返回 true + */ + static bool IsPointOutOfViewport(const FVector2D& Point, const FVector2D& ViewportSize); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/JsonUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/JsonUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..8dad0cdbb54c34048296e3f246bd2a875a8e1b62 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/JsonUtils.h @@ -0,0 +1,83 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" // UE 提供的 JSON 读写核心模块 (FJsonObject / FJsonValue 等) +#include "PaperSprite.h" // Paper2D 精灵资源相关声明 (此处为依赖所需) + +/** + * FJsonUtils + * JSON 序列化 / 反序列化工具类 + * + * 该类所有成员均为静态函数,无需实例化即可调用,主要提供两类能力: + * 1. 将常见数据类型 (Vector2D、bool、int、float、double、FString) 写入 JSON 对象; + * 2. 从 JSON 对象中读取对应类型的数据; + * 3. 基于 UE 反射系统 (UProperty) 对任意 UObject / UStruct 进行通用的序列化与反序列化 + */ +class FJsonUtils +{ +public: + // 通用数据接口 (Common Data API) + + /** + * 利用反射遍历 UObject 的所有属性, 并序列化为 JSON 对象 + * @param Object 待序列化的对象 (输入) + * @param OutJsonObject 用于接收序列化结果的 JSON 对象 (输出, 须为有效指针) + * @return 成功写入至少一个字段时返回 true, 否则返回 false + */ + static bool SerializeObject2Json(const UObject* Object, TSharedPtr& OutJsonObject); + + // 将 FVector2D 以 { "x":.., "y":.. } 的子对象形式写入 RootObj 的 EntryName 字段 + static bool SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const FVector2D& InVector); + // 将布尔值写入指定字段 + static bool SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const bool InBool); + // 将 32 位整数写入指定字段 (JSON 中统一存为数值) + static bool SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const int32 InNum); + // 将单精度浮点数写入指定字段 + static bool SerializeData2Json(const TSharedPtr& RootObj, const FString& EntryName, const float InNum); + // 将双精度浮点数写入指定字段 + static bool SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const double InNum); + // 将字符串写入指定字段 + static bool SerializeData2Json( + const TSharedPtr& RootObj, const FString& EntryName, const FString& InStr); + + // 从 JSON 对象读取 Vector2D, 字段不存在或无效时返回零向量 + static FVector2D DeserializeFromJson_Vector2D(const TSharedPtr& RootObj, const FString& EntryName); + // 从 JSON 对象读取布尔值, 字段不存在时返回 false + static bool DeserializeFromJson_Bool(const TSharedPtr& RootObj, const FString& EntryName); + // 从 JSON 对象读取 int32, 字段不存在时返回 0 + static int32 DeserializeFromJson_Int32(const TSharedPtr& RootObj, const FString& EntryName); + // 从 JSON 对象读取 float, 字段不存在时返回 0.0f + static float DeserializeFromJson_Float(const TSharedPtr& RootObj, const FString& EntryName); + // 从 JSON 对象读取字符串, 字段不存在时返回空串 + static FString DeserializeFromJson_FString(const TSharedPtr& RootObj, const FString& EntryName); + + /** + * 将单个 JSON 值写入对应的反射属性 (支持递归处理数组、结构体等) + * @param JsonValue 源 JSON 值 + * @param Property 目标反射属性 + * @param ValuePtr 目标属性在内存中的地址 + * @return 转换成功返回 true; 类型不匹配或不支持返回 false + */ + static bool JsonValueToProperty(const TSharedPtr& JsonValue, FProperty* Property, void* ValuePtr); + + /** + * 修正 JSON 对象中字段名的大小写, 使其与目标结构体 (UStruct) 的反射属性名严格一致 + * @param JsonObject 待修正的 JSON 对象 (原地修改) + * @param StructDefinition 目标结构体 / 类的反射定义 + */ + static void StandardizeCaseForImport(const TSharedPtr& JsonObject, const UStruct* StructDefinition); + + /** + * 将 JSON 对象反序列化到指定的结构体 / 对象实例 (基于反射逐字段填充) + * @param JsonObject 源 JSON 对象 + * @param StructDefinition 目标类型的反射定义 (UStruct / UClass) + * @param StructPtr 目标实例在内存中的地址 + * @return 全部字段处理成功返回 true,中途失败返回 false + */ + static bool DeserializeFromJson_Object( + const TSharedRef& JsonObject, UStruct* StructDefinition, void* StructPtr); + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/SlateBrushUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/SlateBrushUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..22a60f361be0df8cd42a1998bcd8f430a0d6faf7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/SlateBrushUtils.h @@ -0,0 +1,83 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Dom/JsonObject.h" +#include "Styling/SlateBrush.h" + +/** + * FSlateBrushUtils + * + * Slate 画刷(Brush)工具类 + * 提供一组静态辅助函数, 用于从 JSON 对象中解析数据并构建 FSlateBrush 实例, + * 常用于将配置文件/序列化数据中的样式信息还原为运行时可用的 Slate 画刷 + */ +class FSlateBrushUtils +{ +public: + /** + * 根据 JSON 对象创建一个 FSlateBrush + * + * @param JsonObject 包含画刷各字段配置的 JSON 对象 (如 ImageSize、Margin、TintColor 等) + * @param ResourceObject 画刷所引用的资源对象 (通常是纹理/材质), 可为空 + * @return 解析并填充完成后的 FSlateBrush 实例; 未提供的字段将保留默认值 + */ + static FSlateBrush CreateSlateBrushFromJson(const TSharedPtr& JsonObject, UObject* ResourceObject); + +private: + /** + * 从 JSON 中解析一个二维向量字段 (要求 JSON 中为长度为 2 的数组 [X, Y]) + * + * @param JsonObject 源 JSON 对象 + * @param FieldName 要解析的字段名 + * @param OutVector [输出] 解析成功时写入的二维向量 + * @return 解析成功返回 true, 否则返回 false + */ + static bool ParseVector2D( + const TSharedPtr& JsonObject, const FString& FieldName, FVector2D& OutVector); + + /** + * 从 JSON 中解析一个边距 (Margin) 字段 (要求为包含 Left/Top/Right/Bottom 的子对象) + * + * @param JsonObject 源 JSON 对象 + * @param FieldName 要解析的字段名 + * @param OutMargin [输出] 解析成功时写入的边距 + * @return 解析成功返回 true, 否则返回 false + */ + static bool ParseMargin(const TSharedPtr& JsonObject, const FString& FieldName, FMargin& OutMargin); + + /** + * 从 JSON 中解析一个线性颜色 (FLinearColor) 字段 (要求为包含 R/G/B 的子对象, A 可选, 默认 1.0) + * + * @param JsonObject 源 JSON 对象 + * @param FieldName 要解析的字段名 + * @param OutColor [输出] 解析成功时写入的线性颜色 + * @return 解析成功返回 true, 否则返回 false + */ + static bool ParseLinearColor( + const TSharedPtr& JsonObject, const FString& FieldName, FLinearColor& OutColor); + + /** + * 从 JSON 中解析一个 Slate 颜色 (FSlateColor) 字段 + * 内部复用 ParseLinearColor, 将解析得到的线性颜色包装为 FSlateColor + * + * @param JsonObject 源 JSON 对象 + * @param FieldName 要解析的字段名 + * @param OutColor [输出] 解析成功时写入的 Slate 颜色 + * @return 解析成功返回 true, 否则返回 false + */ + static bool ParseSlateColor( + const TSharedPtr& JsonObject, const FString& FieldName, FSlateColor& OutColor); + + /** + * 从 JSON 中解析一个枚举字段 (JSON 中以字符串形式存储枚举名) + * 通过模板 + if constexpr 支持多种 Slate 画刷相关枚举类型的字符串->枚举值映射 + * + * @tparam EnumType 目标枚举类型 (如 ESlateBrushDrawType::Type 等) + * @param JsonObject 源 JSON 对象 + * @param FieldName 要解析的字段名 + * @param OutEnum [输出] 解析成功时写入的枚举值 + * @return 解析成功返回 true, 否则返回 false + */ + template + static bool ParseEnum(const TSharedPtr& JsonObject, const FString& FieldName, EnumType& OutEnum); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TextureUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TextureUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..5e84f5bfeeb5be0d40341ac5b6fa342172a1c9d6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TextureUtils.h @@ -0,0 +1,116 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Engine/Texture2D.h" // UTexture2D 定义 +#include "Json.h" // JSON 解析相关类型 (FJsonObject 等) +#include "Materials/MaterialInstanceConstant.h" // UMaterialInstanceConstant 定义 +#include "PaperSprite.h" // UPaperSprite (2D 精灵) 定义 +#include "Styling/SlateBrush.h" // FSlateBrush (Slate 画刷) 定义 + +// 前向声明, 避免在头文件中引入额外依赖 +class UImage; // UMG 图片控件 +class URestoreWindowProxy; // 还原窗口代理 (持有纹理缓存等共享状态) + +/** + * LQA 纹理元数据, 包含 UV 坐标与尺寸信息 + * 注意:该结构体同时在 RestoreWindowUtils.h 中声明, + * 后续建议抽取到一个公共头文件中统一管理, 避免重复声明 + */ +struct FLQATextureMeta; + +/** + * 纹理资源管理工具类 + * 提供一组静态方法, 用于从 JSON 数据中加载、转换和管理纹理资源 + * 所有方法均为静态方法, 无需实例化即可调用 + */ +class LQARESTORE_API FTextureUtils +{ +public: + /** + * 根据包含纹理数据的 JSON 对象, 更新图片控件 (UImage) 的画刷 (Brush) + * @param InImage 需要更新的目标图片控件 + * @param InTextureDataRoot 包含纹理元数据的 JSON 对象 + * @param RestoreWindowProxy 窗口代理, 用于访问纹理缓存 + */ + static void UpdateImageBrushFromJsonObj( + UImage* InImage, const TSharedPtr& InTextureDataRoot, URestoreWindowProxy* RestoreWindowProxy); + + /** + * 根据资源字符串设置图片画刷 + * @param InImage 目标图片控件 + * @param OutBrush 输出参数, 被填充的 Slate 画刷 + * @param ResourceString 资源标识字符串 (格式: "Type'Path'") + * @param JsonObject 包含附加画刷数据的 JSON 对象 + * @return 成功设置画刷返回 true, 否则返回 false + */ + static bool SetBrushFromResourceString(UImage* InImage, FSlateBrush& OutBrush, const FString& ResourceString, + const TSharedPtr& JsonObject); + + /** + * 将资源字符串解析为「类型」和「路径」两部分 + * @param ResourceString 输入资源字符串 (格式: "Type'Path'") + * @param OutType 输出参数, 资源类型 (如 "Texture2D"、"PaperSprite") + * @param OutPath 输出参数, 资源路径 + * @return 解析成功返回 true, 否则返回 false + */ + static bool ParseResourceString(const FString& ResourceString, FString& OutType, FString& OutPath); + + /** + * 根据类型和路径加载 UObject 资源 + * @param Type 资源类型 (如 "Texture2D"、"PaperSprite"、"MaterialInstanceConstant") + * @param Path 资源的资产路径 + * @return 加载成功返回资源对象, 失败返回 nullptr + */ + static UObject* LoadResourceByType(const FString& Type, const FString& Path); + + /** + * 从 JSON 对象中获取纹理 (UTexture2D) + * @param InTextureDataRoot 包含纹理数据的 JSON 对象 + * @param RestoreWindowProxy 窗口代理, 用于访问纹理缓存 + * @return 加载成功返回纹理, 失败返回 nullptr + */ + static UTexture2D* GetTextureFromJsonObj( + const TSharedPtr& InTextureDataRoot, URestoreWindowProxy* RestoreWindowProxy); + + /** + * 获取 Texture2D 的原始数据, 并以 PNG 二进制格式输出 + * @param Texture2D 源纹理 + * @param OutData 输出参数, PNG 格式的二进制数据 + * @return 数据提取成功返回 true, 否则返回 false + */ + static bool GetTexture2DData(UTexture2D* Texture2D, TArray& OutData); + + /** + * 从 JSON 对象中获取纹理元数据 + * @param TextureDataObj 包含纹理数据的 JSON 对象 + * @return 纹理元数据结构体 + */ + static FLQATextureMeta GetTextureMeta(const TSharedPtr& TextureDataObj); + +private: + /** + * 材质画刷缓存, 用于避免对同一材质实例重复创建画刷 + * 键为材质实例指针, 值为对应的 Slate 画刷 + */ + static TMap MaterialBrushCache; + + /** + * 将资源类型字符串归一化为短名 + * dump 端可能写出全限定名 (如 "/Script/Engine.Texture2D"), 需归一化为 "Texture2D" 才能参与类型判定 + * @param InType 原始类型字符串 + * @return 归一化后的短类型名 + */ + static FString NormalizeAssetType(const FString& InType); + + /** + * 从 dump session 目录的 Textures/.png 还原运行时生成的纹理 + * 用于兜底那些因不存在于磁盘而无法按路径加载的资源 (如 /Engine/Transient.Texture2D_x) + * 解析结果会缓存在 RestoreWindowProxy 的 SharedTextureMap 中, 避免重复解码 + * @param RestoreWindowProxy 窗口代理, 持有纹理缓存 (同时确保 UObject 不被 GC 回收) + * @param SnapshotDirectory dump session 目录 + * @param NameMD5 纹理名称的 MD5, 即 PNG 文件名 (不含扩展名) + * @return 还原成功返回纹理, 失败返回 nullptr + */ + static UTexture2D* LoadRuntimeTextureFromSnapshot( + URestoreWindowProxy* RestoreWindowProxy, const FString& SnapshotDirectory, const FString& NameMD5); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/LoaderUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/LoaderUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..61b655d09f8d18aa5e26732f41f97077b6921759 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/LoaderUtils.h @@ -0,0 +1,97 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" + +// 前置声明 LQA 控件节点类, 避免头文件相互包含 +class FLQAWidgetNode; + +// 外部声明的控制台变量: 用于控制是否绘制 LQA 调试线 (在其他 cpp 中定义) +extern TAutoConsoleVariable CVarEnableDrawLQADebugLine; + +/** + * 还原翻译的语言方向 + */ +enum class ERestoreDirection : uint8 +{ + /** 中文原文 -> 外文译文 (默认): 中文是待翻译原文, 必须先查字典 */ + ChineseToForeign, + /** 外文原文 -> 中文译文: 原文含中文则视为已翻译, 原样返回 */ + ForeignToChinese +}; + +/** + * 翻译数据加载与处理工具类 + * 负责从 JSON 文件中加载翻译数据, 并提供核心的翻译查询功能 + */ + +/** + * 大小写敏感的字符串键函数 (用于翻译映射表) + * 为翻译的键值对提供「区分大小写」的匹配与哈希逻辑 + * 默认的 TMap 键比较通常不区分大小写, 这里通过自定义 KeyFuncs 强制区分大小写, + * 从而保证例如 "Key" 与 "key" 被视为两个不同的键 + */ +struct FCaseSensitiveStringKeyFuncs : public TDefaultMapKeyFuncs +{ + /** 区分大小写的字符串匹配: 使用 Strcmp 精确比较, 完全相等才返回 true */ + static FORCEINLINE bool Matches(const FString& A, const FString& B) + { + return FCString::Strcmp(*A, *B) == 0; + } + + /** + * 区分大小写的哈希函数: 基于宽字符数组按字节做 CRC32 哈希 + * 之所以自定义哈希, 是因为默认哈希可能忽略大小写, 必须让大小写不同的字符串 + * 产生不同的哈希值, 才能配合上面的 Matches 实现真正的大小写敏感 + */ + static FORCEINLINE uint32 GetKeyHash(const FString& Key) + { + // Key.Len() 返回的是 TCHAR 的数量, 而非字节数 + // 在 Windows 平台上 TCHAR 为 wchar (2 字节) + // 因此需要按 Key.Len() * sizeof(TCHAR) 个字节来计算哈希 + return FCrc::MemCrc32(reinterpret_cast(*Key), Key.Len() * sizeof(TCHAR)); + } +}; + +/** + * 翻译数据加载工具类 + * 提供加载与处理翻译数据的核心功能 (全部为静态成员, 作为全局翻译数据的容器) + */ +class FLoaderUtils +{ +public: + /** JSON 中表示「翻译内容」的字段名称 */ + static constexpr const TCHAR* TranslationFieldName = TEXT("translation"); + + /** 当找不到任何匹配的翻译时返回的标记字符串 */ + static constexpr const TCHAR* UnmatchedMarker = TEXT("##UnMatched"); + + /** 「翻译键 -> 翻译文本」的映射表 (使用大小写敏感的键函数) */ + static TMap AllKeyText; + + /** 「源文本 -> 翻译文本」的映射表 (使用大小写敏感的键函数) */ + static TMap AllTextKey; + + /** + * 从 JSON 文件加载翻译数据 + * @param FilePath 「键-翻译」JSON 文件的路径 (填充 AllKeyText) + * @param FilePathForText 「文本-翻译」JSON 文件的路径 (填充 AllTextKey) + * @param Language 语言标识符 + * @return 加载成功返回 true, 否则返回 false + */ + static bool LoadJsonFromFile(const FString& FilePath, const FString& FilePathForText, const FString& Language); + + /** + * 同时根据「键」和「内容」查询翻译后的字符串 + * @param QueryKey 翻译键 + * @param QueryContent 源内容文本 + * @return 最终翻译得到的字符串 (若无匹配则返回 UnmatchedMarker 标记) + */ + static FString GetTranslateString(const FString& QueryKey, const FString& QueryContent); + + /** 当前还原方向 (默认: 外文 -> 中文) */ + static ERestoreDirection RestoreDirection; + + /** 设置还原方向 (在加载译文时由上层根据配置写入) */ + static void SetRestoreDirection(ERestoreDirection InDirection) { RestoreDirection = InDirection; } +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/ValidatorUtils.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/ValidatorUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..30ba665fa3106083094bc4cfce3493f59e6f97a2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/Utils/TranslationUtils/ValidatorUtils.h @@ -0,0 +1,82 @@ +#pragma once + +#include "CoreMinimal.h" + +/** + * 翻译校验工具类 (FValidatorUtils) + * + * 提供一组与「翻译规则校验」和「文本处理」相关的静态工具函数, 主要用于: + * 1. 检测文本中是否包含中文 / 英文字符; + * 2. 提取并比较原文与译文中的 HTML 标签, 确保翻译前后标签一致; + * 3. 提取并比较 #tag# 形式的占位符 (哈希标签), 确保翻译未破坏占位符 + * + * 本类所有成员均为静态函数, 无需实例化即可直接通过 FValidatorUtils::XXX 调用 + */ +class FValidatorUtils +{ +public: + /** + * 检测字符串中是否包含中文字符 + * + * @param Text 待检测的字符串 + * @return 若包含中文字符返回 true, 否则返回 false + */ + static bool ContainsChinese(const FString& Text); + + /** + * 检测字符串中是否包含英文字母 (A-Z 或 a-z) + * + * @param Text 待检测的字符串 + * @return 若包含英文字母返回 true, 否则返回 false + */ + static bool ContainsEn(const FString& Text); + + /** + * 从输入字符串中提取 HTML 标签: 包括开标签、闭标签以及所有匹配到的标签 + * + * @param Input 待分析的输入字符串 + * @param OutOpenTags 输出参数:提取到的开标签数组 (已转小写并排序) + * @param OutCloseTags 输出参数:提取到的闭标签数组 (已转小写并排序) + * @param OutAllTags 输出参数:提取到的所有标签数组 (已转小写并排序) + */ + static void ExtractHtmlTags( + const FString& Input, TArray& OutOpenTags, TArray& OutCloseTags, TArray& OutAllTags); + + /** + * 比较两个输入字符串中提取出的 HTML 标签集合是否相等 + * + * 常用于校验原文 (S1) 与译文 (S2) 的标签结构是否保持一致, + * 避免翻译过程中误删、误改或打乱了 HTML 标签 + * + * @param S1 第一个输入字符串 (通常为原文) + * @param S2 第二个输入字符串 (通常为译文) + * @param OutTags1 输出参数: 从第一个字符串提取到的所有标签 + * @param OutTags2 输出参数: 从第二个字符串提取到的所有标签 + * @return 当两者的开标签集合与闭标签集合均相等时返回 true, 否则返回 false + */ + static bool AreHtmlTagSetsEqual( + const FString& S1, const FString& S2, TArray& OutTags1, TArray& OutTags2); + + /** + * 从输入字符串中提取形如 #tag# 的哈希标签 (占位符) + * + * @param Input 待分析的输入字符串 + * @param OutHashTags 输出参数:提取到的哈希标签数组 (已转小写并排序) + */ + static void ExtractHashTags(const FString& Input, TArray& OutHashTags); + + /** + * 比较两个输入字符串中提取出的哈希标签集合是否相等 + * + * 常用于校验原文与译文中的 #tag# 占位符是否保持一致, + * 防止翻译时丢失或改动了占位符 + * + * @param S1 第一个输入字符串 (通常为原文) + * @param S2 第二个输入字符串 (通常为译文) + * @param OutTags1 输出参数: 从第一个字符串提取到的哈希标签 + * @param OutTags2 输出参数: 从第二个字符串提取到的哈希标签 + * @return 当两者的哈希标签集合相等时返回 true, 否则返回 false + */ + static bool AreHashTagSetsEqual( + const FString& S1, const FString& S2, TArray& OutTags1, TArray& OutTags2); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/RestoreWidget2JsonFactory.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/RestoreWidget2JsonFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..b2de1a258c35bbac8635e659ba1df75d730a46cb --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/RestoreWidget2JsonFactory.h @@ -0,0 +1,127 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" + +// 由 UHT(UnrealHeaderTool) 自动生成的反射代码头文件, 必须放在所有 UCLASS/USTRUCT 之后、本文件头文件包含的最后一行 +#include "RestoreWidget2JsonFactory.generated.h" + +// 前置声明, 避免在头文件中引入完整定义, 减少编译依赖 +class FWidget2JsonInterface; // Widget 与 JSON 相互转换的接口类 +class UWidget; // UMG 控件基类 +class URestoreWindowProxy; // 还原窗口的代理对象, 承载还原上下文 + +/** + * 控件还原元数据结构体 + * 保存从 JSON 还原出来的控件实例及其布局属性 (位置、尺寸、层级、附加属性) + * 作为 WidgetFromJson 系列函数的返回结果, 供上层逻辑摆放和配置控件使用 + */ +USTRUCT() +struct FRestoreWidgetMeta +{ + GENERATED_BODY() + +public: + /** 还原得到的控件实例指针 (由工厂创建并填充属性) */ + UPROPERTY() + UWidget* WidgetIns = nullptr; + + /** 控件在窗口中的位置 (左上角坐标, 单位: 像素) */ + FVector2D WidgetPosition; + + /** 控件的尺寸 (宽、高,单位: 像素) */ + FVector2D WidgetSize; + + /** 渲染层级 / Z 轴顺序, 数值越大越靠上层显示 */ + int32 ZOrder = 0; + + /** 控件的附加属性, 以 JSON 对象形式存储 (如文本内容、OCR 标记、对齐方式等) */ + TSharedPtr Property; +}; + +/** + * 控件工厂类 + * 负责根据 JSON 数据创建并还原 UMG 控件对象, + * 处理控件属性和布局信息的反序列化 + * 所有方法均为静态方法, 无需实例化即可使用 + */ +class FWidget2JsonFactory +{ +public: + /** + * 从 JSON 数据还原一个控件, 并填充完整的元数据 + * 会创建控件实例, 并计算其位置、尺寸、层级以及附加属性数据 + * + * @param InJsonObj - 包含控件类型与属性数据的 JSON 对象 + * @param InWindowSize - 窗口尺寸, 用于计算相对位置 / 坐标系转换 + * @param RestoreWindowProxy - 控件还原上下文的代理对象 + * @return 返回包含还原控件及其元数据的 FRestoreWidgetMeta + */ + static FRestoreWidgetMeta WidgetFromJson(const TSharedPtr& InJsonObj, const FVector2D& InWindowSize, + URestoreWindowProxy* RestoreWindowProxy); + + /** + * 从 JSON 数据还原一个面板 (容器) 控件, 仅填充基础元数据 + * 与 WidgetFromJson 类似, 但针对面板容器做了简化处理 (不解析文本/OCR 相关属性) + * + * @param InJsonObj - 包含控件类型与属性数据的 JSON 对象 + * @param InWindowSize - 窗口尺寸, 用于计算相对位置 + * @param RestoreWindowProxy - 控件还原上下文的代理对象 + * @return 返回包含还原面板控件及其元数据的 FRestoreWidgetMeta + */ + static FRestoreWidgetMeta WidgetFromJsonForPanel(const TSharedPtr& InJsonObj, const FVector2D& InWindowSize, + URestoreWindowProxy* RestoreWindowProxy); + + /** + * 从 JSON 根对象中解析窗口尺寸 + * + * @param RootObj - 根 JSON 对象, 其中的 meta 字段应包含 sizeX 与 sizeY + * @param OutSize - 输出参数, 用于返回解析得到的窗口尺寸 + * @return 成功解析返回 true, 否则返回 false + */ + static bool DeserializeWindowSize(const TSharedPtr& RootObj, FVector2D& OutSize); + +private: + /** + * 根据 JSON 中的控件类型 (WidgetType 字段) 创建对应的 Widget2Json 接口实现 + * + * @param InWidgetData - 包含 WidgetType 字段的 JSON 对象 + * @return 对应控件类型的 FWidget2JsonInterface 实现的共享指针; 类型未知时返回 nullptr + */ + static TSharedPtr MakeWidgetData(const TSharedPtr InWidgetData); + + /** + * 移除 JSON 对象中的委托 (Delegate) 字段, 因为委托无法被还原 + * @param InJsonObj - 待清理的 JSON 对象 + */ + static void RemoveDelegateFields(const TSharedPtr& InJsonObj); + + /** + * 移除 ObjectData 中的 Slots 字段, 避免还原过程中产生冲突 (插槽由父容器单独处理) + * @param InJsonObj - 包含 ObjectData 的 JSON 对象 + */ + static void RemoveSlotsFromObjectData(const TSharedPtr& InJsonObj); + + /** + * 清理 JSON 对象, 移除所有无法还原的字段 (委托字段与插槽字段) + * @param InJsonObj - 待清理的 JSON 对象 + */ + static void CleanJsonObject(const TSharedPtr& InJsonObj); + + /** 从 JSON 数据中获取控件位置, 并将坐标系从左下角原点转换为左上角原点 */ + static FVector2D GetWidgetPos(const TSharedPtr InWidgetData, const FVector2D& InWindowSize); + + /** + * 从 JSON 数据中获取控件尺寸 + * @param bUseAbsoluteSize - 为 true 时根据四角坐标计算绝对尺寸 (图片/按钮等); + * 为 false 时读取 LocalSize 相对尺寸 (文本等) + */ + static FVector2D GetWidgetSize( + const TSharedPtr InWidgetData, const FVector2D& InWindowSize, bool bUseAbsoluteSize); + + /** 从各种文本类控件中提取文本内容 */ + static FString GetText(UWidget* UI); + + /** 从 JSON 中解析一个二维坐标点, 并进行坐标系转换 (左下角 -> 左上角) */ + static FVector2D DeserializePoint(const TSharedPtr InPosData, const FVector2D& InWindowSize); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonFactory.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..4429dc6f1ba58f0cf61ba26630a95615589e9851 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonFactory.h @@ -0,0 +1,33 @@ +#pragma once + +#include "Components/PanelSlot.h" // UPanelSlot: UMG 面板槽的基类 +#include "CoreMinimal.h" // UE 核心基础类型 (FString、FName、TSharedPtr 等) +#include "Json.h" // JSON 相关类型 (FJsonObject 等) + +// 前向声明: Slot 与 JSON 相互转换的接口类, 具体定义在 Slot2JsonInterface.h 中 +class FSlot2JsonInterface; + +/** + * 工厂类: 负责根据 JSON 数据创建并还原 UMG 面板槽 (Panel Slot) 对象 + * 处理各种面板类型 (Canvas、Grid、HorizontalBox 等) 槽属性的反序列化 + */ +class FSlot2JsonFactory +{ +public: + /** + * 根据 JSON 数据中指定的槽类型 (SlotType), 创建对应的 Slot2Json 接口实例 + * + * @param JsonData - 包含 "SlotType" 和 "Slot" 字段的 JSON 对象 + * @return 指向对应 FSlot2JsonInterface 实现的共享指针; 若槽类型未知则返回 nullptr + */ + static TSharedPtr MakeSlotData(const TSharedPtr JsonData); + + /** + * 从 JSON 数据中还原 UPanelSlot 的属性 + * + * @param SlotJsonObj - 包含槽类型及属性数据的 JSON 对象 + * @param PanelSlot - 目标 UPanelSlot 实例, 用 JSON 中的数据填充它 + * @return 若槽还原成功返回 true, 否则返回 false + */ + static bool SlotFromJson(const TSharedPtr& SlotJsonObj, UPanelSlot* PanelSlot); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonInterface.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..620eaaf273fa55522fdba09c4bb9f280b2267cdf --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Slot2JsonInterface.h @@ -0,0 +1,50 @@ +#pragma once + +#include "Components/PanelSlot.h" // UPanelSlot: 控件在父面板中的布局槽基类 +#include "CoreMinimal.h" // UE 核心最小依赖集合 +#include "Json.h" // JSON 数据结构 (FJsonObject 等) +#include "JsonObjectConverter.h" // JSON 与 UStruct/UObject 互转工具 +#include "WidgetSlots/Core/WidgetDefines.h" // 本模块控件相关的公共定义 + +// 声明一个专用于 Slot 转 JSON 的日志分类 (在 .cpp 中通过 DEFINE_LOG_CATEGORY 定义) +// 参数依次为: 日志分类名、默认日志级别(Log)、编译期允许的最高级别(All) +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreSlot2Json, Log, All); + +/** + * FSlot2JsonInterface + * Slot 与 JSON 相互转换的抽象接口基类 + * 负责把 JSON 中记录的布局数据还原 (反序列化) 到 UPanelSlot 上, + * 具体不同类型的 Slot (如 CanvasPanelSlot、HorizontalBoxSlot 等) + * 由派生类实现各自的 FromJson 逻辑 + */ +class FSlot2JsonInterface +{ +public: + // 默认构造函数 (无特殊初始化) + FSlot2JsonInterface() + { + } + + // 虚析构函数: 保证通过基类指针删除派生类对象时能正确释放资源 + virtual ~FSlot2JsonInterface() + { + } + + /** + * 根据 JSON 数据设置面板槽 (PanelSlot) 的属性 + * 这是一个通用实现: 利用反射把 JSON 字段批量映射到 Slot 的 UPROPERTY + * @param InJsonData - 包含槽属性数据的 JSON 对象 + * @param PanelSlot - 目标 UPanelSlot 实例 (将被写入属性) + * @return 成功设置属性返回 true, 否则返回 false + */ + bool SetPanelSlotProperties(const TSharedPtr InJsonData, UPanelSlot* PanelSlot); + + /** + * 从 JSON 对象构建/还原 Slot (纯虚函数, 必须由派生类实现) + * 不同类型的 Slot 布局字段不同, 派生类在此实现各自的解析与应用逻辑 + * @param JsonData - 源 JSON 对象 + * @param PanelSlot - 目标 UPanelSlot 实例 + * @return 还原成功返回 true, 否则返回 false + */ + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) = 0; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Widget2JsonInterface.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Widget2JsonInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..2c71664af57c53d793e8ac01146389828fb52e20 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/Widget2JsonInterface.h @@ -0,0 +1,103 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Internationalization/TextLocalizationManager.h" // 文本本地化管理器, 用于处理多语言文本 +#include "Json.h" // UE JSON 基础类型 (FJsonObject 等) +#include "Utils/JsonUtils.h" // 字段名大小写对齐工具 (修复嵌套字段被静默跳过) +#include "JsonObjectConverter.h" // JSON 与 UStruct/UObject 之间的转换工具 +#include "WidgetSlots/Core/WidgetDefines.h" // Widget 相关的常量与枚举定义 (如 ELQAWidgetType、各类 Key 名) +#include "WidgetTree/LQAWidgetNode.h" // LQA Widget 节点定义 + +// 声明一个专用于 "Widget 转 JSON" 模块的日志分类, 便于在输出日志中过滤定位 +DECLARE_LOG_CATEGORY_EXTERN(LogLQARestoreWidget2Json, Log, All); + +// 前置声明, 避免在头文件中引入完整头文件, 减少编译依赖 +class UWidget; +class URestoreWindowProxy; + +/** + * FWidget2JsonInterface + * -------------------------------------------------------------------- + * Widget 与 JSON 相互转换的抽象接口基类 + * 各种具体类型的 Widget (如文本、图片、按钮等) 应派生此类, + * 并实现 FromJson / GetType, 以完成「从 JSON 数据还原出对应 UWidget」的逻辑 + */ +class FWidget2JsonInterface +{ +public: + // 默认构造函数 (无额外初始化逻辑) + FWidget2JsonInterface() + { + } + + // 虚析构函数, 确保通过基类指针删除派生类对象时能正确释放资源 + virtual ~FWidget2JsonInterface() + { + } + + /** + * 从 JSON 数据中提取并解析文本, 返回经过翻译处理后的 FText + * + * @param JsonData 包含文本信息的 JSON 对象 + * @param TextEntryName 文本条目的字段名 (默认使用通用字符串 Key) + * @param TextKeyName 文本 Key 的字段名 (用于定位翻译表中的条目) + * @param SourceStringKeyName 源字符串 (原文) 的字段名 + * @return 解析并翻译后的文本 + */ + static FText GetTextFromJson(const TSharedPtr JsonData, + const FString& TextEntryName = LQAWidgetConstants::CommonStrKey, + const FString& TextKeyName = LQAWidgetConstants::CommonTextKey, + const FString& SourceStringKeyName = LQAWidgetConstants::SourceStringKey); + + /** + * 根据 JSON 对象创建 (还原) 对应的 Widget + * 这是纯虚函数, 必须由派生类实现具体的创建逻辑 + * + * @param JsonData 包含 Widget 数据的 JSON 对象 + * @param RestoreWindowProxy 还原上下文 (提供还原过程中所需的环境/窗口信息) + * @return 创建成功返回对应的 Widget 指针, 失败返回 nullptr + */ + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) = 0; + + /** + * 获取当前接口对应的 Widget 类型 + * 基类默认返回「未定义」类型, 派生类应重写以返回具体类型 + */ + virtual ELQAWidgetType GetType() + { + return ELQAWidgetType::LQA_Undefined; + } + + /** + * 模板方法: 将 JSON 对象反序列化为指定类型 T 的 UObject 实例 + * + * @tparam T 目标对象类型 (需为 UObject 派生类) + * @param InJsonData 待反序列化的 JSON 对象 + * @param InStructData 目标类型对应的结构描述 (UStruct),用于指导字段映射 + * @return 反序列化成功返回新建对象指针, 失败返回 nullptr + */ + template + T* GetAsObject(const TSharedPtr InJsonData, const UStruct* InStructData) + { + // 先校验输入参数的有效性, 避免在无效输入时进行不必要的对象分配 + if (!InJsonData.IsValid() || !InStructData) + { + return nullptr; + } + + // 创建目标类型的新对象实例 + T* ObjIns = NewObject(); + + // 将 JSON 数据按 InStructData 的结构映射填充到新对象中 + // 字段名大小写对齐到目标结构的反射属性名: + FJsonUtils::StandardizeCaseForImport(InJsonData, InStructData); + + if (FJsonObjectConverter::JsonObjectToUStruct(InJsonData.ToSharedRef(), InStructData, ObjIns, 0, 0)) + { + return ObjIns; + } + + // 反序列化失败: 此处不手动销毁, ObjIns 会在后续由垃圾回收 (GC) 机制自动清理 + return nullptr; + } +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/WidgetDefines.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/WidgetDefines.h new file mode 100644 index 0000000000000000000000000000000000000000..8e1f2210f7d1efe2038303b9eb1ad4f61d84c6f3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Core/WidgetDefines.h @@ -0,0 +1,33 @@ +#pragma once + +#include "CoreMinimal.h" + +// ============================================================= +// LQAWidgetConstants 命名空间 +// ------------------------------------------------------------- +// 集中声明 LQA (本地化质量保证) 控件在解析 JSON 数据时 +// 所使用的公共键名 (Key) 常量 +// +// 设计说明: +// - 这里只做 extern 声明, 真正的字符串值定义放在对应的 +// .cpp 实现文件中 (WidgetDefines.cpp) +// - 使用 extern 可避免在多个翻译单元 (.cpp) 中重复定义 +// 同名全局变量而导致的链接错误 (重定义), 同时保证 +// 整个工程共享同一份常量实例 +// - 将 JSON 键名统一收敛为常量, 便于集中维护、避免魔法 +// 字符串散落各处造成的拼写不一致问题 +// ============================================================= +namespace LQAWidgetConstants +{ +// JSON 中 “源字符串” 字段对应的键名, 表示原始 (未翻译) 文本内容 +extern const FString SourceStringKey; + +// JSON 中 “通用字符串” 字段对应的键名, 表示普通文本字符串数据 +extern const FString CommonStrKey; + +// JSON 中 “通用文本键” 字段对应的键名, 表示文本条目的唯一标识 Key +extern const FString CommonTextKey; + +// JSON 中 “通用对象” 字段对应的键名, 表示嵌套的对象/结构化数据 +extern const FString CommonObjectKey; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_BorderSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_BorderSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..6988fcf4982b83d97f4ff2bffe8c1f2d94757c14 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_BorderSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_BorderSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ButtonSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ButtonSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7b3c5b7ff8fab1d119f57b554630c03bda90f501 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ButtonSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_ButtonSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..947f44c7a5400989ad409ad99d119e27a77c39fa --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_CanvasPanelSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_CanvasPanelSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_GridSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_GridSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..6de744aa1d0df83cee2e2f571954f3fb850acb75 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_GridSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_GridSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..32939085d39f3d4a90c4a34d348c993d00c39fcc --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_HorizontalBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_HorizontalBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_OverlaySlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_OverlaySlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..c65c5b8665b5433518c2e3638b95a83eda793946 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_OverlaySlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_OverlaySlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e5ed0927644380304d22fd4c1ea420741850de --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SafeZoneSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_SafeZoneSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..16c5ceb59866f8734a5429329827ce56168c1d1d --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScaleBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_ScaleBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ffdad8443516341bca48f9ee292e4360fc32df89 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_ScrollBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_ScrollBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..b0a9734cb5bfd800934470d0f998f3db39987cd5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_SizeBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_SizeBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_StackBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_StackBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..f93707a94850b441982effd424400413345ddd31 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_StackBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_StackBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_UniformGridSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_UniformGridSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..2a7122c399aed4f18bd676a41f8c30fb5fc15369 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_UniformGridSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_UniformGridSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7c17e7fcbb9e0f0a3b7863b72176db116e77a5c3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_VerticalBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_VerticalBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..1ca54a0d7b5a97d6d4fc95b7fa8b8c4267660104 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WidgetSwitcherSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_WidgetSwitcherSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..286123c50965ce54fe6b0a8c699e9e26cefdbffb --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WindowTitleBarAreaSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_WindowTitleBarAreaSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..00552ea82772a8b6aaa3067db81a96655048b952 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Slots/LQA_WrapBoxSlot2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Core/Slot2JsonInterface.h" + +class FLQA_WrapBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + +private: +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..69edcabac1801e0af4b48106d004d7f11a0a6ed9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_BackgroundBlur2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UBackgroundBlur; + +// For BackgroundBlur +class FLQA_BackgroundBlur2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Border2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Border2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ff2b5bb9e7893a57c00ab25eb1e1db82f356aff3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Border2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UBorder; + +// For Border +class FLQA_Border2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Button2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Button2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..d845f7f74e19cea43d18d56fadc462c44b934077 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Button2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For Button +class FLQA_Button2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CanvasPanel2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CanvasPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..e33d5ec8d698fe14b730b0930325155bb162151a --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CanvasPanel2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UCanvasPanel; + +// For CanvasPanel +class FLQA_CanvasPanel2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CheckBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CheckBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a41b1ec819916be9ac46e341620a12ecc296f424 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CheckBox2Json.h @@ -0,0 +1,13 @@ +#pragma once +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UCheckBox; + +// For CheckBox +class FLQA_CheckBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CircularThrobber2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CircularThrobber2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..11dff63b169601b5be8fda59ea0d05832013008e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_CircularThrobber2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UCircularThrobber; + +// For CircularThrobber +class FLQA_CircularThrobber2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ComboBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ComboBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..756b38ce9d1a7273fbfdb36e4cc6c9ce9089afae --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ComboBox2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UComboBoxString; + +// For ComboBox +class FLQA_ComboBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7d4d66d81dd4750f1edb207f0770f9f3d2766bbc --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_DynamicEntryBox2Json.h @@ -0,0 +1,23 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For DynamicEntryBox (动态条目框) +// -------------------------------------------------------------------- +// 采集侧特点: +// UDynamicEntryBox 的 Slate 根随 EntryBoxType 分别为 SHorizontalBox / SVerticalBox / +// SWrapBox 等, 故 JSON 中 "WidgetType" 输出的是 Slate 根类型名, +// 真实 UMG 类型由 "WidgetClass": "DynamicEntryBox" 标识。 +// +// 还原策略 (降级为等价布局容器): +// UDynamicEntryBoxBase 继承自 UWidget 而非 UPanelWidget, 无法作为面板承载子控件; +// 而 Slate 根本身即标准布局容器。因此还原时按 EntryBoxType 降级为等价的 +// UPanelWidget 容器 (UHorizontalBox/UVerticalBox/UWrapBox/UOverlay): +// - 视觉表现等价 (原控件渲染即由该 Slate 根完成); +// - 可作为面板正常挂载 JSON 中采集到的动态条目子控件。 +// UWidget 通用属性 (Visibility/RenderOpacity 等) 由 ObjectData 反序列化继承。 +class FLQA_DynamicEntryBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..8ddc61af19bb14b91359dfce7a1f490044d8c322 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBlock2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For EditableTextBlock +class FLQA_EditableTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a51280df1a26182a422a315a78f59e35f27a2056 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_EditableTextBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For EditableTextBox +class FLQA_EditableTextBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ExpandableArea2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ExpandableArea2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..666c6b17604b97c3f35bdec59bebb26a0d967872 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ExpandableArea2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UExpandableArea; + +// For ExpandableArea (Slate: SExpandableArea) +class FLQA_ExpandableArea2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_GridPanel2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_GridPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..81c65df3d85137d73af4b34eeebd2ad42fa18bd6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_GridPanel2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UGridPanel; + +// For CanvasPanel +class FLQA_GridPanel2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_HorizontalBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_HorizontalBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..8331c682974d85c9fe97a3d26cdc0b30fbfbee5c --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_HorizontalBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UHorizontalBox; + +// For HorizontalBox +class FLQA_HorizontalBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Image2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Image2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..cbdeec61d80061b3188a629b3be5ff8c0f955fd4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Image2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UTexture2D; + +// For Image +class FLQA_Image2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InputKeySelector2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InputKeySelector2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..c158753b928f0c0f4ecdc1504fd3998f104e54f3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InputKeySelector2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UInputKeySelector; + +// For InputKeySelector +class FLQA_InputKeySelector2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InvalidationBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InvalidationBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..380c121d2237453273dfc9f009feaf045868fd21 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_InvalidationBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UInvalidationBox; + +// For InvalidationBox (Slate: SInvalidationPanel) +class FLQA_InvalidationBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListView2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListView2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..b83acbf4f25b1a77f4176899ef9fd37a321341c3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListView2Json.h @@ -0,0 +1,30 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For ListView +class FLQA_ListView2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; + +// For TileView +class FLQA_TileView2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; + +// For TreeView +class FLQA_TreeView2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListViewEntry.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListViewEntry.h new file mode 100644 index 0000000000000000000000000000000000000000..456c5a4396fba0e16c45bd8b430a9e5acf472e37 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ListViewEntry.h @@ -0,0 +1,57 @@ +#pragma once + +#include "Blueprint/IUserObjectListEntry.h" +#include "Blueprint/UserWidget.h" +#include "CoreMinimal.h" +#include "UObject/Object.h" + +#include "LQA_ListViewEntry.generated.h" + +class UTextBlock; + +UCLASS() +class ULQARestoreListItem : public UObject +{ + GENERATED_BODY() + +public: + UPROPERTY() + FText Label; + + /** 子条目 (TreeView 层级使用) */ + UPROPERTY() + TArray Children; +}; + +/** TreeView 子节点解析器(UObject 实现,兼容 UE4 的 SetOnGetItemChildren 绑定要求) */ +UCLASS() +class ULQARestoreTreeChildrenResolver : public UObject +{ + GENERATED_BODY() + +public: + void GetChildren(UObject* Item, TArray& OutChildren); +}; + +UCLASS() +class ULQARestoreListEntryWidget : public UUserWidget, public IUserObjectListEntry +{ + GENERATED_BODY() + +public: + //~ Begin UUserWidget Interface + virtual TSharedRef RebuildWidget() override; + //~ End UUserWidget Interface + +protected: + //~ Begin IUserObjectListEntry Interface + virtual void NativeOnListItemObjectSet(UObject* ListItemObject) override; + //~ End IUserObjectListEntry Interface + + /** 条目文本控件 */ + UPROPERTY(Transient) + UTextBlock* EntryLabel = nullptr; + + /** 条目数据可能在 Slate 控件构建前下发, 先缓存文本待构建时应用 */ + FText CachedLabel; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MenuAnchor2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MenuAnchor2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..d42c6eb41d183c974cf5ea283b8d7c67504ee175 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MenuAnchor2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UMenuAnchor; + +// For MenuAnchor +class FLQA_MenuAnchor2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ccac3406ece90b65e73381ef217b055091a5ce4f --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBlock2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For MultilineEditableTextBlock +class FLQA_MultilineEditableTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..cef9f4a5c41ce5bf9230bb46d0236de6b98eacde --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_MultilineEditableTextBox2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For MultilineEditableTextBox +class FLQA_MultilineEditableTextBox : public FWidget2JsonInterface +{ + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Overlay2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Overlay2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..2ac200823bc67d3cb2d7a82c1d22be829b3b5935 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Overlay2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UOverlay; + +// For Overlay +class FLQA_Overlay2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..bd12cd393abdec82cfdb59481baaaa2ad11822d4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PlatformPaddingBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UPlatformPaddingBox; + +// For PlatformPaddingBox +class FLQA_PlatformPaddingBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..6d642392eb4727d033fe9ad1b62b82a9dcf8597b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_PostBufferUpdate2Json.h @@ -0,0 +1,15 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UPostBufferUpdate; + +// For PostBufferUpdate +// 说明: 该控件无视觉表现, 采集端只导出其 UPROPERTY, 还原时按 ObjectData 原样重建即可 +class FLQA_PostBufferUpdate2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ProgressBar2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ProgressBar2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..21bf9df0ddd57764c982a1f4502bf4953af1ad5b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ProgressBar2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UProgressBar; + +// For ProgressBar +class FLQA_ProgressBar2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RetainerBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RetainerBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..70fb92a1bdb575150b7d84615dceee0e454d50fc --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RetainerBox2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class URetainerBox; + +// For RetainerBox +class FLQA_RetainerBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RichTextBlock2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RichTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..6e9da0a55fe25343b9dd9704714c1465799e16bb --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_RichTextBlock2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "Components/RichTextBlock.h" +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For RichTextBlock +class FLQA_RichTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SafeZone2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SafeZone2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..54107486b2ba7c5867fb15d466b454592f052b1e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SafeZone2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class USafeZone; + +// For SafeZone +class FLQA_SafeZone2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScaleBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScaleBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..26897f470f8e4ea354530e9f3f49a53e673bfb13 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScaleBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UScaleBox; + +// For ScaleBox +class FLQA_ScaleBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBar2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBar2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..2a089dd8894b46cc246dcc31a482f50138097043 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBar2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UScrollBar; + +// For ScrollBar +class FLQA_ScrollBar2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..b5057c9ad3347f4e06057d81749e55d75bcea6db --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_ScrollBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UScrollBox; + +// For ScrollBox +class FLQA_ScrollBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SizeBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SizeBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a7dbcfe7d447616dcb05b1850f8147db41971b2e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SizeBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class USizeBox; + +// For SizeBox +class FLQA_SizeBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Slider2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Slider2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..1ac3c937d1347277ce9ff8a4676b7136c20b7cb5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Slider2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class USlider; + +// For Slider +class FLQA_Slider2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Spacer2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Spacer2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a7db6f3e6c0dee6faa9da1d3a33b6507d1f6c571 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Spacer2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class USpacer; + +// For Spacer +class FLQA_Spacer2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SpinBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SpinBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..b4f6fd3449bfb619dee142e52e8681734946e9cc --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_SpinBox2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class USpinBox; + +// For SpinBox +class FLQA_SpinBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_StackBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_StackBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ef93a107d11a56f8c68a6868a7ab2868ed0c6179 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_StackBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UStackBox; + +// For StackBox (Slate: SStackBox) +class FLQA_StackBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextBlock2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..3660c1caccd57e94802f332f0b8ff3c701350762 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextBlock2Json.h @@ -0,0 +1,15 @@ +#pragma once + +#include "Components/TextBlock.h" +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UTextBlock; + +// For TextBlock +class FLQA_TextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextScroller2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextScroller2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..1cd1411bba7d3ec3b26c93a2aa4e4b208852285b --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_TextScroller2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" +class UTextScroller; + +// For TextScroller +class FLQA_TextScroller2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Throbber2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Throbber2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ac2606eaf1761a51a64de9b7139cd0c130e3a091 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Throbber2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UThrobber; + +// For Throbber +class FLQA_Throbber2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..42e14df6d931271719ca7f30e4c04ad4cdbc3dd4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UniformGridPanel2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UUniformGridPanel; + +// For UniformGridPanel +class FLQA_UniformGridPanel2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UserWidget2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UserWidget2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..aa06ab103e8cdbd62d1bb76302ad49dc4f740797 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_UserWidget2Json.h @@ -0,0 +1,22 @@ +#pragma once + +#include "Blueprint/UserWidget.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/Image.h" +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +// For UserWidget +class FLQA_UserWidget2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + UUserWidget* CreateWidgetFromJson(const TSharedPtr& JsonObject); + + void ApplyJsonToWidget(UUserWidget* Widget, const TSharedPtr& JsonObject); + +private: + /** Create a plain UserWidget container purely in C++ (no blueprint asset dependency) */ + UUserWidget* CreateBaseUserWidget(); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_VerticalBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_VerticalBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7a3fcb04241adb0bfa0b53a4c2728c880a301737 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_VerticalBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UVerticalBox; + +// For VerticalBox +class FLQA_VerticalBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..5f30451b6bc6bdade087e9e6e696843a2dca0c1f --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WidgetSwitcher2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UWidgetSwitcher; + +// For WidgetSwitcher +class FLQA_WidgetSwitcher2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + + virtual ELQAWidgetType GetType() override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..889730e09aa7a6811b710c4d66f571f2c483a366 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WindowTitleBarArea2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UWindowTitleBarArea; + +// For WindowTitleBarArea (Slate: SWindowTitleBarArea) +class FLQA_WindowTitleBarArea2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WrapBox2Json.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WrapBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..63c39af349ec0fc1537ec48bba7760497b56f332 --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetSlots/Widgets/LQA_WrapBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "WidgetSlots/Core/Widget2JsonInterface.h" + +class UWrapBox; + +// For WrapBox +class FLQA_WrapBox2Json : public FWidget2JsonInterface +{ +public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetTree/LQAWidgetNode.h b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetTree/LQAWidgetNode.h new file mode 100644 index 0000000000000000000000000000000000000000..0dc831cb8e66fe5e34d8f12154e2dd1b2a7861db --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/Plugins/LQARestore/Source/LQARestore/Public/WidgetTree/LQAWidgetNode.h @@ -0,0 +1,232 @@ +#pragma once + +#include "Templates/SharedPointer.h" + +// 前向声明, 减少头文件依赖, 加快编译速度 +class SWidget; // Slate 控件基类 +class UObject; // UE 对象基类 +// struct FArrangedWidget; // 已排布的控件 (含几何信息), 此处用注释保留说明 + +/** + * 命名空间: 存放各类 “控件类型名” 常量 (FName) + * 这些名字对应 Slate 控件运行时的类型名 (如 "STextBlock"), + * 用于在 LQA 处理流程中识别控件类型 + */ +namespace LQAWidgetNames +{ +// —— 控件类型名常量 (extern 声明, 定义在 .cpp 中) —— +extern const FName LQA_TextBlock; // 普通文本块 +extern const FName LQA_RichTextBlock; // 富文本块 +extern const FName LQA_EditableText; // 单行可编辑文本 +extern const FName LQA_EditableTextBox; // 单行可编辑文本框 +extern const FName LQA_MultilineEditableText; // 多行可编辑文本 +extern const FName LQA_MultilineEditableTextBox; // 多行可编辑文本框 +extern const FName LQA_ComboBox; // 下拉框 +extern const FName LQA_LEDRichTextBlock; // 项目自定义的 LED 富文本块 +extern const FName LQA_Image; // 图片控件 +extern const FName LQA_Button; // 按钮 +extern const FName LQA_UserWidget; // 用户控件 (UMG 包装的 SObjectWidget) +extern const FName LQA_Canvas; // 画布容器 +extern const FName LQA_RetainerBox; // 渲染缓存容器 +extern const FName LQA_ScrollBox; // 滚动容器 +extern const FName LQA_VerticalBox; // 垂直布局容器 +extern const FName LQA_HorizontalBox; // 水平布局容器 +extern const FName LQA_ScaleBox; // 缩放容器 +extern const FName LQA_SafeZone; // 安全区容器 (适配刘海屏等) +extern const FName LQA_WrapBox; // 自动换行容器 +extern const FName LQA_SizeBox; // 固定尺寸容器 +extern const FName LQA_CheckBox; // 复选框 +extern const FName LQA_GridPanel; // 网格面板 +extern const FName LQA_UniformGridPanel; // 等分网格面板 +extern const FName LQA_Overlay; // 层叠容器 +extern const FName LQA_Border; // 边框容器 +extern const FName LQA_BackgroundBlur; // 背景模糊容器 +extern const FName LQA_WidgetSwitcher; // 控件切换器 +extern const FName LQA_StackBox; // 堆叠盒 (垂直/水平堆叠布局) +extern const FName LQA_ProgressBar; // 进度条 +extern const FName LQA_Throbber; // 加载指示器 +extern const FName LQA_CircularThrobber; // 环形加载指示器 +extern const FName LQA_Slider; // 滑动条 +extern const FName LQA_SpinBox; // 数值输入框 +extern const FName LQA_Spacer; // 空白占位 +extern const FName LQA_ScrollBar; // 滚动条 +extern const FName LQA_InputKeySelector; // 按键选择器 +extern const FName LQA_MenuAnchor; // 菜单锚点 +extern const FName LQA_InvalidationBox; // 失效缓存容器 (性能优化) +extern const FName LQA_PostBufferUpdate; // 后处理缓冲更新控件 (无视觉表现) +extern const FName LQA_ListView; // 列表视图 +extern const FName LQA_TileView; // 平铺视图 +extern const FName LQA_TreeView; // 树形视图 +extern const FName LQA_WindowTitleBarArea; // 窗口标题栏区域 +extern const FName LQA_ExpandableArea; // 可展开/折叠区域 +} // namespace LQAWidgetNames + +/** + * 命名空间: 存放 UMG 实际控件类型标识 (FName) + * -------------------------------------------------------------------- + * 部分 UMG 控件的 Slate 根类型是复用的 (例如 UDynamicEntryBox 依 EntryBoxType + * 分别以 SHorizontalBox / SVerticalBox / SWrapBox 作为 Slate 根), 仅凭 WidgetType + * (Slate 运行时类型名) 无法区分其真实 UMG 类型。 + * 采集侧对这些控件会通过 JSON 的 "WidgetClass" 字段输出该标识, + * 还原侧据此还原出正确的布局语义。 + */ +namespace LQAWidgetClassNames +{ +extern const FName LQA_DynamicEntryBox; // 动态条目框 (UDynamicEntryBox) +} // namespace LQAWidgetClassNames + +/** + * 命名空间: 存放各类 “插槽类型名” 常量 (FName) + * 插槽(Slot)描述子控件在父容器中的布局方式, + * 用于在 LQA 处理流程中识别布局插槽类型 + */ +namespace LQASlotNames +{ +// —— 插槽类型名常量 (extern 声明, 定义在 .cpp 中) —— +extern const FName LQA_ButtonSlot; // 按钮插槽 +extern const FName LQA_CanvasPanelSlot; // 画布插槽 (支持锚点/绝对定位) +extern const FName LQA_ScrollBoxSlot; // 滚动容器插槽 +extern const FName LQA_VerticalBoxSlot; // 垂直布局插槽 +extern const FName LQA_HorizontalBoxSlot; // 水平布局插槽 +extern const FName LQA_ScaleBoxSlot; // 缩放容器插槽 +extern const FName LQA_SafeZoneSlot; // 安全区插槽 +extern const FName LQA_WrapBoxSlot; // 换行容器插槽 +extern const FName LQA_SizeBoxSlot; // 固定尺寸插槽 +extern const FName LQA_GridSlot; // 网格插槽 +extern const FName LQA_UniformGridSlot; // 等分网格插槽 +extern const FName LQA_OverlaySlot; // 层叠插槽 +extern const FName LQA_BorderSlot; // 边框插槽 +extern const FName LQA_WidgetSwitcherSlot;// 控件切换器插槽 +extern const FName LQA_StackBoxSlot; // 堆叠盒插槽 +extern const FName LQA_WindowTitleBarAreaSlot; // 窗口标题栏区域插槽 +} // namespace LQASlotNames + +/** + * 枚举: LQA 支持的控件类型 + * 将各种 UI 控件归类, 便于 LQA 流程按类型做差异化处理 + * 底层类型为 uint8, 以节省内存 + */ +enum class ELQAWidgetType : uint8 +{ + // —— 文本类控件 —— + LQA_TextBlock, // 普通文本块 + LQA_RichText, // 富文本 + LQA_EditableText, // 单行可编辑文本 + LQA_EditableTextBox, // 单行可编辑文本框 + LQA_MultilineEditableText, // 多行可编辑文本 + LQA_MultilineEditableTextBox, // 多行可编辑文本框 + LQA_ComboBoxStringText, // 下拉框文本 + LQA_LEDRichText, // LED 富文本 + + // —— 可视化类控件 —— + LQA_Image, // 图片 + LQA_Button, // 按钮 + LQA_CheckBox, // 复选框 + LQA_ProgressBar, // 进度条 + LQA_Slider, // 滑动条 + LQA_SpinBox, // 数值输入框 + LQA_Throbber, // 加载指示器 + LQA_CircularThrobber, // 环形加载指示器 + LQA_Spacer, // 空白占位 + + // —— 容器类控件 —— + LQA_UserWidget, // 用户控件 + LQA_Canvas, // 画布 + LQA_RetainerBox, // 渲染缓存容器 + LQA_ScrollBox, // 滚动容器 + LQA_VerticalBox, // 垂直布局容器 + LQA_HorizontalBox, // 水平布局容器 + LQA_ScaleBox, // 缩放容器 + LQA_SafeZone, // 安全区容器 + LQA_WrapBox, // 换行容器 + LQA_SizeBox, // 固定尺寸容器 + LQA_GridPanel, // 网格面板 + LQA_UniformGridPanel, // 等分网格面板 + LQA_Overlay, // 层叠容器 + LQA_Border, // 边框容器 + LQA_BackgroundBlur, // 背景模糊容器 + LQA_WidgetSwitcher, // 控件切换器 + LQA_StackBox, // 堆叠盒 + LQA_WindowTitleBarArea,// 窗口标题栏区域 + LQA_ScrollBar, // 滚动条 + LQA_InputKeySelector, // 按键选择器 + LQA_MenuAnchor, // 菜单锚点 + LQA_InvalidationBox, // 失效缓存容器 + LQA_PostBufferUpdate, // 后处理缓冲更新控件 (无视觉表现) + LQA_ListView, // 列表视图 + LQA_TileView, // 平铺视图 + LQA_TreeView, // 树形视图 + LQA_ExpandableArea, // 可展开/折叠区域 + + // 项目自定义控件类型可在此处扩展 + + // 未定义 / 未知控件类型 (兜底值) + LQA_Undefined +}; + +/** + * 枚举: LQA 支持的插槽类型 + * 将各种布局插槽归类, 便于 LQA 流程做布局相关处理 + * 底层类型为 uint8, 以节省内存 + */ +enum class ELQASlotType : uint8 +{ + // —— 标准插槽 —— + LQA_ButtonSlot, // 按钮插槽 + LQA_CanvasPanelSlot, // 画布插槽 + LQA_ScrollBoxSlot, // 滚动容器插槽 + LQA_VerticalBoxSlot, // 垂直布局插槽 + LQA_HorizontalBoxSlot, // 水平布局插槽 + LQA_ScaleBoxSlot, // 缩放容器插槽 + LQA_SafeZoneSlot, // 安全区插槽 + LQA_WrapBoxSlot, // 换行容器插槽 + LQA_SizeBoxSlot, // 固定尺寸插槽 + LQA_GridSlot, // 网格插槽 + LQA_UniformGridSlot, // 等分网格插槽 + LQA_OverlaySlot, // 层叠插槽 + LQA_BorderSlot, // 边框插槽 + LQA_WidgetSwitcherSlot,// 控件切换器插槽 + LQA_StackBoxSlot, // 堆叠盒插槽 + LQA_WindowTitleBarAreaSlot, // 窗口标题栏区域插槽 + + + // 项目自定义插槽类型可在此处扩展 + + // 未定义 / 未知插槽类型 (兜底值) + LQA_UndefinedSlot +}; + +/** + * 控件节点数据模型 + * 以树形层级结构描述一个 UI 控件, 供 LQA 分析使用 + * 每个节点对应一个已排布的 Slate 控件, 并记录其来源 UObject + */ +class FLQAWidgetNode +{ +public: + /** + * 构造函数 + * @param InWidgetGeometry 已排布的控件 (包含控件引用与几何信息) + * explicit 禁止隐式转换, 避免 FArrangedWidget 被意外当作构造参数 + */ + explicit FLQAWidgetNode(const FArrangedWidget& InWidgetGeometry); + +private: + /** + * 处理控件: 检测控件类型并提取元数据 + * @param InWidget 需要处理的 Slate 控件 + */ + void HandleWidget(const TSharedRef& InWidget); + + /** + * 将控件类型名转换为 LQA 控件类型枚举 + * @param WidgetTypeName 控件类型名 (如 "STextBlock") + * @return 对应的 ELQAWidgetType 枚举值; 未匹配时返回 LQA_Undefined + * static: 不依赖实例状态, 可作为工具函数直接调用 + */ + static ELQAWidgetType GetWidgetType(const FName& WidgetTypeName); + +public: + /** 对创建该控件的 UObject 的弱引用 (不影响其生命周期, 避免循环引用) */ + TWeakObjectPtr SourceObject; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQARestore_Plugin/README.md b/timi_hok_game_translator/UE_LQARestore_Plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5bd2d270752652f3a395026138eed187d52f2d3e --- /dev/null +++ b/timi_hok_game_translator/UE_LQARestore_Plugin/README.md @@ -0,0 +1,760 @@ +# LQARestore 插件 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +## 项目简介 + +LQARestore 是一个虚幻引擎 (Unreal Engine) 工程, 核心功能通过 `LQARestore` 插件实现 + +### 核心功能 + +可以读取包含控件信息的 UI 数据 (JSON格式), 动态重构并还原 UI 界面, 支持多语言文本替换, 用于本地化质量保证 (Localization Quality Assurance, LQA) 测试 + +### 前置依赖: 采集端 LQATool + +本插件是 **还原端**, 还原所需的 UI 快照数据 (`LQA_Snapshot_*.json`, 即 dump) 由 **采集端 LQATool** 生成, 两者需配合使用: + +| 插件 | 作用 | +| --- | --- | +| LQATool (采集端) | 运行时导出 Widget 树为 JSON 快照 (含布局 / 样式 / 文本) | +| LQARestore (还原端, 本插件) | 读取快照并还原 UI、替换多语言文本 | + +> 没有采集端生成的 dump 数据, 还原端无从还原, 接入前请先确保能通过 LQATool 生成 dump 快照 (采集产物位于 `{工程}/Saved/LQA/<时间戳_WBP名>/LQA_Snapshot_*.json`, 采集方式见 LQATool 的 README) + +### 仓库组成 + +#### LQARestore + +- **功能**: 还原 UI 在多语言下的实际表现, 以用于 LQA 测试, 保障本地化质量 +- **代码规范**: 遵循 UE C++ 代码风格规范 (缩进、命名、反射宏使用等与引擎保持一致) + +#### 目录结构 + +本仓库是一个 UE 插件仓库, 仓库根目录下有一层 `Plugins/` (含还原插件 `LQARestore`), 接入时把该插件目录拷贝到目标工程的 `Plugins/` 下 + +``` +UE_LQARestore_Plugin/ # 仓库根 +├── Plugins/ +│ └── LQARestore/ # 还原插件 (本仓库主体) +└── README.md + +LQARestore/ # 插件根目录 (即 Plugins/LQARestore) +├── LQARestore.uplugin # 插件描述文件 (依赖 Paper2D) +├── Config/ +│ └── LQARestore.ini # LQA 还原工具配置 (Host / Authorization) +├── Resources/ +│ └── Icon128.png # 插件图标 +├── README.md # 插件说明文档 +└── Source/ + └── LQARestore/ # 插件主模块 + ├── LQARestore.Build.cs # 模块构建脚本 + ├── Private/ # 私有实现文件 + │ ├── Core/ # 核心功能模块 + │ │ ├── ConfigManager.cpp # 配置管理器 + │ │ ├── FileManager.cpp # 文件管理器 + │ │ ├── LQAContainerWidget.cpp # LQA 容器控件 + │ │ ├── LQARestoreManager.cpp # LQA 还原管理器 + │ │ ├── RestoreWindowProxy.cpp # 还原窗口代理 + │ │ ├── RestoreWindowUtils.cpp # 还原窗口工具 + │ │ ├── RootObjWidget.cpp # 根对象控件 + │ │ └── TaskManager.cpp # 任务管理器 + │ ├── Utils/ # 工具类集合 + │ │ ├── DataConverterUtils.cpp # 数据转换工具 + │ │ ├── GeometryUtils.cpp # 几何工具 + │ │ ├── ImageRenderUtils.cpp # 图像渲染工具 + │ │ ├── JsonUtils.cpp # JSON 处理工具 + │ │ ├── SlateBrushUtils.cpp # Slate 笔刷工具 + │ │ ├── TextureUtils.cpp # 纹理工具 + │ │ ├── HttpUtils/ # HTTP 请求工具 + │ │ │ ├── HttpRequestConfig.cpp # HTTP 配置 (从插件 Config/ 读取) + │ │ │ └── HttpRequestHelper.cpp # HTTP 请求辅助 + │ │ └── TranslationUtils/ # 翻译工具 + │ │ ├── LoaderUtils.cpp # 翻译加载 + │ │ └── ValidatorUtils.cpp # 翻译校验 + │ ├── WidgetSlots/ # 控件/槽位转 JSON 模块 + │ │ ├── Core/ # 核心转换系统 + │ │ │ ├── RestoreWidget2JsonFactory.cpp # 还原控件转 JSON 工厂 + │ │ │ ├── Slot2JsonFactory.cpp # 槽位转 JSON 工厂 + │ │ │ ├── Slot2JsonInterface.cpp # 槽位转 JSON 接口 + │ │ │ ├── Widget2JsonInterface.cpp # 控件转 JSON 接口 + │ │ │ └── WidgetDefines.cpp # 控件定义 + │ │ ├── Slots/ # 各类槽位实现 (所有的 LQA_*Slot2Json) + │ │ │ ├── LQA_BorderSlot2Json.cpp + │ │ │ ├── LQA_CanvasPanelSlot2Json.cpp + │ │ │ ├── LQA_HorizontalBoxSlot2Json.cpp + │ │ │ ├── LQA_StackBoxSlot2Json.cpp + │ │ │ ├── LQA_WindowTitleBarAreaSlot2Json.cpp + │ │ │ └── ... # Button/Grid/Overlay/SafeZone/ScaleBox/WrapBox 等 + │ │ └── Widgets/ # 各类控件实现 (所有的 LQA_*2Json, 另含 LQA_ListViewEntry) + │ │ ├── LQA_Button2Json.cpp + │ │ ├── LQA_TextBlock2Json.cpp + │ │ ├── LQA_Image2Json.cpp + │ │ ├── LQA_UserWidget2Json.cpp + │ │ ├── LQA_ListView2Json.cpp # 定义 ListView / TileView / TreeView 三个转换器 + │ │ ├── LQA_ListViewEntry.cpp + │ │ ├── LQA_DynamicEntryBox2Json.cpp + │ │ ├── LQA_StackBox2Json.cpp + │ │ ├── LQA_InvalidationBox2Json.cpp + │ │ ├── LQA_WindowTitleBarArea2Json.cpp + │ │ ├── LQA_ExpandableArea2Json.cpp + │ │ ├── LQA_PostBufferUpdate2Json.cpp + │ │ └── ... # RichText/CheckBox/EditableText/ProgressBar 等 + │ ├── WidgetTree/ # 控件树模块 + │ │ └── LQAWidgetNode.cpp # LQA 控件节点 + │ ├── LQABase.cpp # LQA 基类实现 + │ └── LQARestore.cpp # 插件主模块入口 + └── Public/ # 公共头文件 (结构与 Private 对应) + └── [与 Private 目录对应的 .h 文件] +``` + +### 工作模式 + +- **本地模式**: 读取本地目录下的多份 JSON 数据文件, 逐个加载并还原 UI 界面 +- **远端模式**: 基于任务驱动, 持续从远端获取任务数据, 并还原任务中包含的 UI 数据 + +该工具帮助 QA 团队快速验证 UI 在不同语言环境下的实际表现, 无需手动切换游戏语言或重新打包 + +### 扩展说明 + +插件具备基础控件还原能力, 针对实际游戏项目, 需要按需增加自定义控件和 Slot 类型到 `WidgetSlots` 目录, 参考现有的 `LQA_Button2Json`、`LQA_ButtonSlot2Json` 等实现示例 + +--- + +## 接入插件 + +### 1. 拷贝插件到工程 + +将 `LQARestore` 插件目录完整拷贝到目标 UE 工程的 `Plugins/` 目录下: + +``` +YourProject/ +└── Plugins/ + └── LQARestore/ # LQA 还原工具插件 (模块名 LQARestore) +``` + +> 注意: 插件当前仅支持 **Win64** 平台 (见 `LQARestore.uplugin` 的 `SupportedTargetPlatforms`) + +### 2. 启用插件与引擎依赖 + +1. 插件 `LoadingPhase` 为 `Default`、`Type` 为 `Runtime`, 拷贝后通常会被自动识别, 可在编辑器 **Edit → Plugins** 中确认 `LQARestore` 已勾选启用 +2. 确认工程启用了插件所需的引擎插件, 重点是 **Paper2D** (`Edit → Plugins → 2D → Paper2D`) +3. 其余所需引擎模块 (`UMG`、`Slate`、`Json`、`HTTP`、`zlib`、`MediaAssets`、`RHI`、`RenderCore` 等) 已在 `LQARestore.Build.cs` 中声明, 无需手动添加 + +### 3. 重新生成工程并编译 + +1. 右键 `YourProject.uproject` → **Generate Visual Studio project files** +2. 使用 Rider 或 Visual Studio 打开解决方案, 编译 **Development Editor** 目标 +3. 编译成功后启动编辑器, 日志中出现 `LQARestoreManager initializing` 即表示插件已正常加载 + +### 4. 准备运行所需资源 + +| 资源 | 路径 | 说明 | +| --- | --- | --- | +| 翻译文件 | `Plugins/LQARestore/LQALocalization/GameLocalizationExport_{lang}.json`、`Text_Translations_{lang}.json` | 多语言文本替换数据,`{lang}` 如 `en`、`ja`、`ko` 等 | + +> 译文示例可直接参考 `Plugins/LQARestore/LQALocalization/` 下的 `*_en.json`、`*_ja.json`、`*_ko.json` (仓库已内置英/日/韩三套译文) + +### 5. 配置文件 (远端模式必需) + +在插件的 `Config/` 目录下创建 `LQARestore.ini`, 填入远端服务地址与鉴权信息: + +```ini +[HttpConfig] +Host=xx.xx.xx.xx:xx +Authorization=xxxxxxxxxx +``` + +> `Host` 无需带 `http://` 前缀, 程序会自动补全; 本地模式可不配置此文件 + +### 6. 运行与模式说明 + +`LQARestore` 的核心 `ULQARestoreManager` 是 `UGameInstanceSubsystem`, 会随 GameInstance 启动自动运行 (PIE 或打包运行均可), 延迟约 1 秒后开始工作 + +- **本地模式 (默认, `JobId=0`)**: 自动递归扫描 `{项目}/Saved/LQA/` 目录下的 JSON 数据文件, **每 25 秒处理一份** (`LocalJobInterval`), 逐个还原 UI, 全部处理完后停止定时器; 直接 PIE 运行即可 +- **远端模式 (`JobId` 非 0)**: 通过命令行传入任务参数, 走 HTTP 从远端拉取任务数据 + +> 模式仅由 `JobId` 决定: 等于 `0` 为本地模式, 非 `0` 为远端模式, 参数均为 `Key=Value` 形式, `-` 前缀可省略, 带空格的路径需加引号 + +**本地模式示例** + +编辑器下直接点 Play 即可, 无需命令行; 打包后运行: + +> **关于 `YourProject.exe`** +> +> 下文命令中的 `YourProject.exe` 只是 **占位示例**, 并非真实文件名, 它 **不会出现在工程根目录** (工程根目录只有 `.uproject`、`Source/`、`Intermediate/` 等开发态文件), +> 该 exe 仅在对工程执行 **打包 (Package Project)** 后才会生成, 实际名称为你的工程名, 路径类似: +> `<打包输出目录>/Windows/{工程名}/Binaries/Win64/{工程名}.exe` +> 运行时把 `YourProject.exe` 替换为该文件 (如 `UE5Demo.exe`) 即可, 若只是本地测试还原, 无需打包, 直接在编辑器点 Play 更方便 + +```bash +# 使用默认语言 (LAN_EU_EN) +YourProject.exe + +# 指定语言 (决定加载哪份翻译文件) +YourProject.exe -Language=LAN_JP_JP +``` + +> **本地模式如何指定还原哪一份 Dump 数据?** +> +> 本地模式不支持通过命令行指定单份数据, 它会 **递归扫描 `{项目}/Saved/LQA/` 下的所有 `*.json` 并逐个还原** (文件名去掉扩展名即作为 `DataId`, 同时用于结果目录命名 `Restore_{DataId}_{语言}`), +> 若只想还原某一份, 只能通过控制目录内容实现: +> - 只在 `Saved/LQA/` 下保留你要还原的那一份 json +> - 或将其余 json 移出 `Saved/LQA/` 整个目录树 (递归扫描会包含所有子目录) +> +> 注意: `IsCover=true` + `BaseDataId`/`BaseDataFilePath` 是 "基准数据对比" 用途, 会把基准数据插入队列最前, **并非** 用于筛选单个还原目标, 不要混用 + +**本地模式产物位置** + +每还原一份数据, 会在工程 `Saved/` 下生成一个独立结果目录: + +``` +{项目}/Saved/LQAResult/Restore_{DataId}_{语言}/ +├── screenshot.png # 还原后 UI 的控件截图 +└── check_info.json # 校验信息 (控件角点等) +``` + +- `{DataId}` 为 `Saved/LQA/` 下 json 文件名去掉扩展名, `{语言}` 为运行时语言 (如 `LAN_EU_EN`) +- 编辑器 PIE 运行时, `{项目}/Saved/` 即工程的 `Saved/` 目录; 打包运行时则是打包产物自身的 `Saved/` 目录 +- **本地模式不上传、不清理产物**, 结果会一直保留在本地 (远端模式上传成功后会自动删除该目录) +- 若还原过程涉及背景图, 另会存到 `{项目}/Saved/LQABg/{时间戳}_BG.png` + +**端到端快速验证 (采集 → 还原)** + +初次接入时, 可按以下最小路径验证整套链路是否打通: + +1. **采集**: 在采集端工程 (已接入 LQATool) 中运行目标 UI, 执行 `r.EnableLQATool 1` 导出快照, 确认生成 `{工程}/Saved/LQA/<时间戳_WBP名>/LQA_Snapshot_*.json` +2. **放置数据**: 把采集产物目录 (或其中的 `LQA_Snapshot_*.json`) 拷到还原端工程的 `Saved/LQA/` 下 (可直接拷整个 `<时间戳_WBP名>/` 目录, 本地模式会递归扫描) +3. **还原**: 还原端工程 PIE 运行 (默认 `en`), 等待约 1 秒自动开始还原 +4. **核对**: 查看 `Saved/LQAResult/Restore_{DataId}_{语言}/screenshot.png` 与 `check_info.json`, 确认 UI 被还原且文本已替换为目标语言 + +**远端模式示例** + +```bash +# 最小示例 +YourProject.exe -JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS + +# 回归测试 + 基准数据对比 +YourProject.exe -JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS -Regression=1 -IsCover=true -BaseDataId=67890 -BaseDataFilePath="D:/LQA/base_67890.json" +``` + +**不打包运行远端模式 (编辑器 / PIE / Standalone)** + +远端模式不是打包后才能用的功能, `ULQARestoreManager` 作为 `GameInstanceSubsystem`, 只要 GameInstance 启动就会运行, 而模式判定来自 `FCommandLine::Get()` (即当前进程的整条命令行), 因此只要让进程命令行带上 `-JobId=...` 等参数即可, 无需打包 + +> 前提: `Config/LQARestore.ini` 已配好 `Host` / `Authorization` (远端模式必需), 且已准备好翻译文件 + +**方式 A: 带参数启动编辑器, 再直接 PIE (推荐, 可断点调试)** + +普通 PIE 读取的是 “编辑器主进程” 的命令行, 所以要在 **启动编辑器时** 就把远端参数加上, 退出已开的编辑器, 用命令行启动: + +```bash +# UE5 (引擎可执行文件在 <引擎安装目录>/Engine/Binaries/Win64/ 下) +UnrealEditor.exe "D:/Path/To/YourProject.uproject" -JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS + +# UE4 同理, 可执行文件名为 UE4Editor.exe +UE4Editor.exe "D:/Path/To/YourProject.uproject" -JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS +``` + +编辑器会忽略这些它不认识的自定义参数, 但 `FCommandLine::Get()` 会保留它们, 编辑器打开后点 **Play(在编辑器中运行)**, 日志出现 `LQARestoreManager initializing` 且 `IsLocalMode: false` 即表示已进入远端模式 + +> Rider / Visual Studio 调试: 在运行/调试配置的「程序参数(Program arguments)」里追加 `-JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS`, F5 启动编辑器后 Play 即可带断点调试远端流程 + +**方式 B: Standalone 独立游戏窗口 + 附加启动参数** + +1. **Editor Preferences → Level Editor → Play → Additional Launch Parameters** 填入: + `-JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS` +2. 以 **Play → New Editor Window (Standalone Game)** 方式运行 (Standalone 会以独立子进程启动, 上述参数会被拼进该子进程命令行) + +> 该附加参数仅对 Standalone / Launch 这类独立进程生效, 对同进程 PIE 无效 + +**方式 C: 以 `-game` 独立进程运行 (无编辑器界面, 最接近打包行为)** + +​```bash +UnrealEditor.exe "D:/Path/To/YourProject.uproject" -game -JobId=79 -ProjectId=107 -Language=LAN_CHS_CHS +​``` + +此方式不打开编辑器界面, 直接以游戏模式启动当前默认地图并运行远端任务, 适合联调验证 + +> 远端模式必须在插件工程 `Config/LQARestore.ini` 中配好 `Host` 与 `Authorization`, 否则 HTTP 请求无法发出 + +常用命令行参数: + +| 参数 | 说明 | 默认值 | +| --- | --- | --- | +| `JobId` | 远端任务 ID, 非 `0` 时进入远端模式 | `0` | +| `ProjectId` | 项目 ID | `0` | +| `Language` | 目标语言, 如 `LAN_EU_EN`/`LAN_JP_JP`/`LAN_KO_KO`/`LAN_CHS_CHS` | `LAN_EU_EN` | +| `RestoreDirection` | 还原方向: `F2C` 外文→中文 / `C2F` 中文→外文 | `F2C` | +| `Regression` | 回归测试开关 | `0` | +| `IsCover` | 是否启用基准数据对比 | `false` | +| `BaseDataId` / `BaseDataFilePath` | 对比模式的基准数据 | 空 | +| `CreateBug` / `bugId` / `AISign` / `DefaultNums` / `MinID` / `Modules` | 远端平台扩展参数 | 见 `ConfigManager.cpp` | + +> **`RestoreDirection` 决定“翻不翻”**: +> - `F2C` (默认): 原文含中文就直接原样输出 (中文守卫不查表), 用于 **中文验证** +> - `C2F`: 把中文原文当作待翻译文本去查翻译表, 用于 **目标语言(英/日/韩…)验证** +> +> **只传 `-Language=LAN_JP_JP` 而方向仍为默认 `F2C` 时, 中文原文会被中文守卫直接返回, 界面还是中文、看不到日语**, 验证目标语言必须同时传 `-RestoreDirection=C2F` +> +> 示例: +> ```bash +> # 中文验证 (不查翻译表, 直接显示采集到的中文原文) +> YourProject.exe +> +> # 日语验证 +> YourProject.exe -Language=LAN_JP_JP -RestoreDirection=C2F +> +> # 韩语验证 +> YourProject.exe -Language=LAN_KO_KO -RestoreDirection=C2F +> ``` + +支持的语言枚举详见 `ConfigManager.cpp` 中的 `InitializeLanguageMap()` + +### 7. 扩展自定义控件 + +针对实际游戏项目中的自定义控件, 需在 `Plugins/LQARestore/Source/LQARestore/.../WidgetSlots/` 下新增对应的 `LQA_XxxWidget2Json` / `LQA_XxxSlot2Json` 实现, 可参考现有的 `LQA_Button2Json`、`LQA_ButtonSlot2Json` + +--- + +## 译文接入与自定义 + +本章说明如何为具体项目准备 / 自定义多语言译文数据, 使还原出的 UI 显示为目标语言文本 + +### 1. 译文系统工作原理 + +插件在还原流程启动时 (`LoadTranslationData()`) 按 **当前语言** 加载两份 JSON, 缓存进内存两张表, 供还原每个文本控件时查询: + +| 文件 | 内存表 | 查询键 | 典型来源 | +| --- | --- | --- | --- | +| `GameLocalizationExport_{lang}.json` | `AllKeyText` | 文本的 **TextKey** | 由 UE 本地化导出文件转换 | +| `Text_Translations_{lang}.json` | `AllTextKey` | 文本的 **原文(SourceString)** | 由 UE 本地化导出文件转换 | + +> **译文 Key 与 json 的来历**: +> - 采集端 (`LQATool`) 导出快照时, 会读取每个文本控件在 **UE 本地化机制下** 的译文 Key (`TextKey`), 一并写入 dump JSON +> - 还原端 (`LQARestore`) 用这个 `TextKey` 从 `GameLocalizationExport_{lang}.json` 匹配译文, 无 Key 命中时再按原文从 `Text_Translations` 匹配 +> +> 注意: 这两份 json **并不是 UE 自带本地化工具直接输出的文件**, UE 本地化工具 (Localization Dashboard) 导出的是 `.po` 等本地化文件, 需要接入方编写转换脚本把它们转换成这里的 json 结构 + +还原文本时调用 `FLoaderUtils::GetTranslateString(TextKey, SourceString)`, **先按 TextKey 查, 再按原文查**, 命中即替换; `TextKey` 为 `,INVALIDKEY`(无 Key)时不做翻译, 直接输出原文 + +### 2. 存放位置与命名 + +译文文件统一放在插件根目录下的 `LQALocalization/` (与 `Config/`、`Resources/` 平级): + +``` +Plugins/ +└── LQARestore/ + ├── Config/ + ├── Resources/ + └── LQALocalization/ # ← 译文目录 + ├── GameLocalizationExport_en.json + ├── Text_Translations_en.json + ├── GameLocalizationExport_ja.json + ├── Text_Translations_ja.json + ├── GameLocalizationExport_ko.json + └── Text_Translations_ko.json +``` + +文件名中的 `{lang}` 是 **PO 语言码**, 由运行时 `-Language` 参数换算而来 (见下表), 默认语言 `LAN_EU_EN` 对应 `en` + +### 3. 语言码对照表 + +`{lang}` 取值由 `ConfigManager::InitializeLanguageMap()` 决定: + +| 命令行 `-Language` | `{lang}` (文件名后缀) | 语言 | +| --- | --- | --- | +| `LAN_EU_EN` (默认) | `en` | 英语 | +| `LAN_EU_DE` | `de` | 德语 | +| `LAN_FR_FR` | `fr` | 法语 | +| `LAN_RU_RU` | `ru` | 俄语 | +| `LAN_JP_JP` | `ja` | 日语 | +| `LAN_KO_KO` | `ko` | 韩语 | +| `LAN_CHT_CHT` | `zh-TW` | 繁体中文 | +| `LAN_AR_AR` | `ar` | 阿拉伯语 | +| `LAN_ES_LT` | `es` | 西班牙语 | +| `LAN_PT_BR` | `pt-BR` | 巴西葡萄牙语 | +| `LAN_TR_TR` | `tr` | 土耳其语 | +| `LAN_TH_TH` | `th` | 泰语 | +| `LAN_ID_ID` | `id` | 印尼语 | +| `LAN_CHS_CHS` | `zh` | 简体中文 | + +> 未匹配到的语言会回退为 `en` + +### 4. 两份文件的格式 + +**`GameLocalizationExport_{lang}.json`** —— 顶层 key 是 **TextKey**, value 必须是对象且含 `translation` 字段 (其余字段可选, 仅 `translation` 会被读取): + +```json +{ + "ST_Menu_Start": { + "TextKey": "ST_Menu_Start", + "SourceStr": "Start", + "translation": "Start Game" + }, + "ST_Menu_Exit": { + "TextKey": "ST_Menu_Exit", + "SourceStr": "Exit", + "translation": "Exit" + } +} +``` + +**`Text_Translations_{lang}.json`** —— 顶层 key 是**原文**, value 直接是译文字符串: + +```json +{ + "Hello World": "Hello World (translated)", + "Settings": "Settings (translated)" +} +``` + +### 5. 译文匹配规则 + +还原文本时先按 `TextKey` 的形态分流 (`FWidget2JsonInterface::GetTextFromJson`): + +| `TextKey` 形态 | 处理方式 | +| --- | --- | +| `,FORTEST` | 测试标记, 直接输出原文, 不翻译 | +| `,INVALIDKEY` | 无本地化 Key, **直接输出原文** (游戏里本来就是原文, 不查表) | +| 含 `##` | 用完整 `TextKey` 查表 | +| `Namespace,Key` | 取 **逗号右半部分** 作为真正的 Key 查表 | + +分流后调用 `FLoaderUtils::GetTranslateString(Key, SourceString)`, 按以下顺序判定, 命中即返回: + +1. **`F2C` 方向 + 原文含中文字符 → 原样返回** (中文守卫; `C2F` 方向 **不启用**, 中文会被当作待翻译原文继续查表) +2. 原文仅含数字 / 标点 / 空白 → 原样返回 +3. 按 `TextKey` 查 `GameLocalizationExport_{lang}.json` → 命中返回 +4. 按原文 `SourceString` 查 `Text_Translations_{lang}.json` → 命中返回 +5. 都未命中 → 返回 `##UnMatched` + +> - 匹配 **大小写敏感**, key / 原文需完全一致 +> - `,INVALIDKEY` 文本 (无 Key) **不会进入查表流程**, 不会输出 `##UnMatched` +> - `##UnMatched` 只表示「有 Key 或可翻译文本, 但两张表都没命中」 + +### 6. 为具体项目添加自定义译文 + +1. **确定目标语言**: 根据运行时 `-Language` 参数, 对照上表得到 `{lang}` +2. **准备译文数据**, 二选一: + - **转换脚本生成 (推荐, 生产用)**: UE 项目通常用 **虚幻自带本地化工具 (Localization Dashboard)** 做本地化, 其导出的是 `.po` 等本地化文件, 不能被本插件直接读取, 需**编写一个 Python 转换脚本**, 把这些导出文件转换成 `GameLocalizationExport_{lang}.json` 与 `Text_Translations_{lang}.json` + - **手写 (调试 / 小范围验证用)**: 按第 4 节格式手工编写 +3. **放入目录**: 将两份文件拷到 `Plugins/LQARestore/LQALocalization/` +4. **多语言**: 每种语言各放一套 `*_{lang}.json`, 运行时按 `-Language` 自动选择加载 +5. **编码**: 文件统一用 **UTF-8(无 BOM)**, 避免非 ASCII 文本乱码 + +> **重点说明: 转换脚本需接入方自己实现** +> 这个转换脚本 **每个项目都不一样** —— 各项目的文本 Key 命名、目录结构、本地化工具配置均不相同, 无法提供一套通用脚本, +> 接入方需参考本插件 `LQALocalization/` 下的 json 示例自行编写 (通常几十行 Python: 读取 `.po` 的 msgid/msgstr 或平台导出文件, 输出为第 4 节的 json 结构); 此前各接入项目也都是单独为其编写转换脚本的 + +### 7. 调试与验证 + +1. 准备一份 dump 放入 `{工程}/Saved/LQA/test.json` (dump 结构复杂, 建议基于已有快照修改文本节点, 不要从零手写) +2. 修改其文本节点以命中不同分支: + - 命中 Key: `"TextKey": "ST_Menu_Start"` + - 命中原文: `"SourceString": "Hello World"` (`F2C` 下原文不能是中文, 否则会被中文守卫直接返回; `C2F` 下原文是中文才会去查表) +3. 以目标语言运行: 命令行加 `-Language=LAN_JP_JP -RestoreDirection=C2F` (只加 `-Language` 会因默认 `F2C` 方向而看不到外语) +4. 查看结果: `Saved/LQAResult/Restore_test_{语言}/screenshot.png`, 并在日志中确认出现 `LoadFileToString: .../LQALocalization/...` + +### 8. 常见问题排查 + +| 现象 | 可能原因 | +| --- | --- | +| 文本显示 `##UnMatched` | 有 Key 但两张表都没有对应条目; 大小写不符; 翻译文件未加载 | +| 文本显示 `Invalid/xxx` 这类原文 | `TextKey` 为 `,INVALIDKEY` (无本地化 Key), 属预期行为, 不是漏译 | +| 文本未被翻译 (保持原文) | 方向为 `F2C` 且原文含中文; 或原文仅数字标点 —— 属预期行为 | +| 传了 `-Language` 但界面还是中文 | 方向仍是默认 `F2C`, 中文守卫直接返回原文; 验证目标语言需同时传 `-RestoreDirection=C2F` | +| 日志无 `LoadFileToString` | 文件路径 / 文件名 `{lang}` 后缀不对, 或文件不在插件 `LQALocalization/` 下 | +| 非 ASCII 文本乱码 | 文件未用 UTF-8 保存 | +| 切换语言无变化 | 对应 `*_{lang}.json` 不存在, 或参数未生效 (PIE 需在启动编辑器时带参) | + +--- + +## 扩展还原控件与槽 + +针对实际游戏项目中的自定义 UI, 适配同学通常要做两件事: **调试还原效果** 与 **新增控件 / 槽的还原实现** + +### 新增还原控件 (Widget) + +以新增 `UFooWidget` (对应 Slate 类型名 `SFoo`) 为例: + +1. **新建实现文件** (参考 `LQA_Button2Json`): + - 头文件 `Source/LQARestore/Public/WidgetSlots/Widgets/LQA_Foo2Json.h` + - 源文件 `Source/LQARestore/Private/WidgetSlots/Widgets/LQA_Foo2Json.cpp` + + ```cpp + // LQA_Foo2Json.h + #pragma once + #include "WidgetSlots/Core/Widget2JsonInterface.h" + + class FLQA_Foo2Json : public FWidget2JsonInterface + { + public: + virtual UWidget* FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) override; + virtual ELQAWidgetType GetType() override; + }; + ``` + + ```cpp + // LQA_Foo2Json.cpp + #include "WidgetSlots/Widgets/LQA_Foo2Json.h" + #include "Components/FooWidget.h" + #include "WidgetSlots/Core/WidgetDefines.h" + using namespace LQAWidgetConstants; + + UWidget* FLQA_Foo2Json::FromJson(const TSharedPtr JsonData, URestoreWindowProxy* RestoreWindowProxy) + { + if (!JsonData.IsValid()) { return nullptr; } + UFooWidget* NewWidget = nullptr; + if (JsonData->HasField(CommonObjectKey)) // "ObjectData" + { + const TSharedPtr ObjectData = JsonData->GetObjectField(CommonObjectKey); + if (ObjectData.IsValid()) + { + NewWidget = GetAsObject(ObjectData, UFooWidget::StaticClass()); + } + } + // 可在此处理纹理 / 文本 / 样式等自定义字段 + return NewWidget; + } + + ELQAWidgetType FLQA_Foo2Json::GetType() { return ELQAWidgetType::LQA_Foo; } + ``` + +2. **声明类型名常量** — `Public/WidgetSlots/Core/WidgetDefines.h` 的 `LQAWidgetNames` 命名空间中 `extern const FName LQA_Foo;`, 并在 `Private/WidgetTree/LQAWidgetNode.cpp` 中定义 `const FName LQA_Foo(TEXT("SFoo"));` (字符串须与该控件对应的 **Slate 类型名** 一致, 可在 `SWidget::GetType()` 处打印确认) + +3. **新增枚举值** — `WidgetDefines.h` 的 `ELQAWidgetType` 中加入 `LQA_Foo`; 若该控件需要特殊的尺寸/OCR 后处理, 在 `RestoreWidget2JsonFactory::WidgetFromJson` 对应分支中补充逻辑 + +4. **登记控件树映射** — `LQAWidgetNode.cpp` 的 `WidgetTypeMap` 中加入 `{LQA_Foo, ELQAWidgetType::LQA_Foo}` + +5. **工厂注册 (必需)** — `RestoreWidget2JsonFactory.cpp` 顶部 `#include "WidgetSlots/Widgets/LQA_Foo2Json.h"`, 并在 `MakeWidgetData` 中新增: + + ```cpp + if (WidgetType == LQAWidgetNames::LQA_Foo) + { + return MakeShareable(new FLQA_Foo2Json()); + } + ``` + +### 新增还原槽 (Slot) + +以新增 `UFooSlot` (dump JSON 中 `SlotType` 为 `"UFooSlot"`) 为例: + +1. **新建实现文件** (参考 `LQA_ButtonSlot2Json`): + + ```cpp + // LQA_FooSlot2Json.h + #pragma once + #include "CoreMinimal.h" + #include "Json.h" + #include "WidgetSlots/Core/Slot2JsonInterface.h" + + class FLQA_FooSlot2Json : public FSlot2JsonInterface + { + public: + virtual bool FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) override; + }; + ``` + + ```cpp + // LQA_FooSlot2Json.cpp + #include "WidgetSlots/Slots/LQA_FooSlot2Json.h" + #include "Components/FooSlot.h" + + bool FLQA_FooSlot2Json::FromJson(const TSharedPtr JsonData, UPanelSlot* PanelSlot) + { + if (JsonData.IsValid() && JsonData->Values.Num() > 0) + { + if (UFooSlot* Slot = Cast(PanelSlot)) + { + bool bResult = SetPanelSlotProperties(JsonData, Slot); // 基类统一反序列化 + Slot->SynchronizeProperties(); + return bResult; + } + UE_LOG(LogLQARestoreSlot2Json, Warning, TEXT("Failed to cast PanelSlot to UFooSlot")); + } + return false; + } + ``` + +2. **工厂注册 (必需)** — `Slot2JsonFactory.cpp` 顶部 `#include "WidgetSlots/Slots/LQA_FooSlot2Json.h"`, 并在 `MakeSlotData` 中新增 (注意: 工厂会先去掉 `SlotType` 的首字母 `U`, 这里匹配去 `U` 后的名字): + + ```cpp + if (SlotTypeName == FName(TEXT("FooSlot"))) + { + return MakeShareable(new FLQA_FooSlot2Json()); + } + ``` + +> 槽的还原只要「新建实现 + 工厂分支」两步即可生效; `WidgetDefines.h` 中的 `LQASlotNames` / `ELQASlotType` 为预留项, 当前工厂使用字面量匹配, 非必改, +> 大多数槽属性 (对齐、边距、锚点、尺寸规则等) 由基类 `SetPanelSlotProperties` 通过 `JsonObjectToUStruct` 自动灌入, 仅当存在无法直接反序列化的特殊字段时才需在 `FromJson` 中手动处理 + +### 新增后的验证 + +1. 右键 `.uproject` → Generate project files, 重新编译 Development Editor +2. 准备一份包含新控件 / 槽的 dump json, 放入 `{项目}/Saved/LQA/`, PIE 运行 +3. 查看 `Saved/LQAResult/Restore_*/screenshot.png` 与日志, 确认无 `Unknown SlotTypeName` / `Try Restore Xxx Failed` 等告警 + +--- + +## 平台交互 + +> 适用于平台模式 (非本地模式), 四个循环定时器在 `ULQARestoreManager::SetupPlatformTimers()` 中注册, +> 各自按固定间隔驱动 `TaskManager` 的队列处理与还原流程 + +### 日志分类对照 + +| 分类 | 定义位置 | 覆盖模块 | +|------|----------|----------| +| `LogLQARestoreManager` | `LQARestoreManager.cpp` | 主控制器 / 定时器回调 / 还原 / 截图 | +| `LogLQARestoreTask` | `TaskManager.cpp` | 下载/上传队列、重试、解压、JSON 解析 | +| `LogLQARestoreHttp` | `HttpRequestConfig.cpp` | 底层 HTTP 请求、配置加载 | + +### 定时器总览 + +| 定时器 | 间隔 | 回调函数 | 作用 | +|--------|------|----------|------| +| `JobDataTimer` | 150s | `OnGetJobDataTick` | 周期性向平台拉取任务数据 | +| `DownloadTimer` | 3s | `OnDownloadTick` | 处理下载队列 | +| `RestoreTimer` | 10s | `OnRestoreTick` | 处理当前还原项 (建窗/截图/生成结果) | +| `UploadTimer` | 4s | `OnUploadTick` | 处理上传队列 | + +### 1. JobDataTimer (拉取任务, 150s) + +**调用链** +`OnGetJobDataTick` → `HandlePlatformWorkflow(false)` → `TaskManager::RequestJobData` → `FHttpRequestHelper::GetJobData` → (回调) `OnJobDataSuccess` → 广播 → `Manager::OnJobDataReceived` → `EnqueueDownload` + +**日志清单** + +| 级别 | 分类 | 日志信息 | 源码位置 | 排查含义 | +|------|------|----------|----------|----------| +| Error | Task | `ConfigManager is null` | `TaskManager::RequestJobData` | 依赖未初始化, 子系统初始化异常 | +| Warning | Task | `JobId is 0, skipping job data request` | `TaskManager::RequestJobData` | JobId 未配置, 不会发起请求 (正常跳过) | +| Log | Http | `GET: {URL}` | `FHttpRequestHelper::CreateRequest` | 确认实际请求 URL 与参数是否正确 | +| Warning | Http | `Request failed` | `FHttpRequestHelper::HandleResponse` | 网络层失败 (连接/超时) | +| Warning | Task | `Job data response is invalid` | `TaskManager::OnJobDataSuccess` | 响应指针无效 | +| Error | Task | `Failed to parse job data response` | `TaskManager::OnJobDataSuccess` | 返回体非合法 JSON | +| Warning | Task | `No data field in job data response` | `TaskManager::OnJobDataSuccess` | JSON 缺少 `data` 字段, 接口协议异常 | +| Log | Task | `Received N job data items` | `TaskManager::OnJobDataSuccess` | 成功解析出的任务数 (0 表示无新任务) | +| Log | Manager | `Received N job data items` | `Manager::OnJobDataReceived` | 去重后加入待处理/下载队列 | + +### 2. DownloadTimer (下载队列, 3s) + +**调用链** +`OnDownloadTick` → (`CanDownload()` 为真时) `TaskManager::ProcessDownloadQueue` → `FHttpRequestHelper::GetDumpData` → (回调) `OnDownloadSuccess` / `OnDownloadFail` → 广播 → `Manager::OnDumpDataDownloaded` + +**日志清单** + +| 级别 | 分类 | 日志信息 | 源码位置 | 排查含义 | +|------|------|----------|----------|----------| +| Log | Task | `Dump file already exists: {DataId}` | `ProcessDownloadQueue` | 命中本地缓存, 跳过网络下载 | +| Log | Task | `Downloading dump data: {DataId}` | `ProcessDownloadQueue` | 开始下载, `bIsDownloading` 加锁 | +| Log | Http | `GET: {URL}` | `CreateRequest` | 下载地址 (注意端口 8080→80 替换) | +| Error | Task | `Response is invalid: {DataId}` | `OnDownloadSuccess` | 响应指针无效 | +| Log | Task | `Download response code: {Code}, DataId: {DataId}` | `OnDownloadSuccess` | HTTP 状态码 | +| Error | Task | `HTTP error response: {Code}, Content: {...}` | `OnDownloadSuccess` | 非 2xx, 附带返回体 | +| Log | Task | `Downloaded data size: N bytes` | `OnDownloadSuccess` | 下载字节数 (0 需警惕) | +| Error | Task | `Download data is empty: {DataId}` | `OnDownloadSuccess` | 返回体为空 | +| Log | Task | `Data format check - IsGzip: {Y/N}, First bytes: XX XX` | `OnDownloadSuccess` | gzip 魔数检测结果 | +| Warning | Task | `Data is not gzip compressed, treating as raw JSON` | `OnDownloadSuccess` | 走原始 JSON 兼容分支 | +| Error | Task | `Invalid JSON data (raw): {DataId}, Preview: {...}` | `OnDownloadSuccess` | 原始 JSON 解析失败 | +| Log | Task | `Download success (raw JSON): {DataId}` | `OnDownloadSuccess` | 原始 JSON 分支下载成功 | +| Error | Task | `Failed to decompress gzip data: {DataId}` | `OnDownloadSuccess` | zlib 解压失败 | +| Error | Task | `Invalid JSON data: {DataId}` | `OnDownloadSuccess` | 解压后 JSON 非法 | +| Log | Task | `Download success: {DataId}` | `OnDownloadSuccess` | 下载并落盘成功 | +| Error | Task | `Download failed: {DataId} (Retry: n/3)` | `OnDownloadFail` | 失败重试计数, 达 3 次后放弃并广播失败 | +| Log | Manager | `Dump data downloaded: {DataId}` | `Manager::OnDumpDataDownloaded` | 下载完成回调 | +| Log | Manager | `Base comparison data loaded: {DataId}` | `Manager::OnDumpDataDownloaded` | 基准对比数据加载成功 (对比模式) | + +### 3. RestoreTimer (还原流程, 10s) + +**调用链** +`OnRestoreTick` → (有待处理项且 `bCanStartRestore`) `ProcessCurrentRestoreItem` → `MakeRestoredWindow` → (延迟) `BuildWindow` → `ScheduleScreenshotAndUpload` → (延迟) 截图 + 生成结果 JSON → `ClearRestoreWindow` → `EnqueueUpload` + +**日志清单** + +| 级别 | 分类 | 日志信息 | 源码位置 | 排查含义 | +|------|------|----------|----------|----------| +| Log | Manager | `Restoring data ID: {DataId}` | `ProcessCurrentRestoreItem` | dump 文件就绪, 开始还原 | +| Log | Manager | `Waiting for file download: {DataId} (Attempt: n/3)` | `ProcessCurrentRestoreItem` | 文件未就绪, 等待下载, 不推进索引 | +| Warning | Manager | `File not found after 3 attempts, skipping: {Path}` | `ProcessCurrentRestoreItem` | 等待超限, 跳过该项 | +| Error | Manager | `Failed to create RestoreWindowProxy` | `MakeRestoredWindow` | 窗口代理创建失败 | +| Error | Manager | `Failed to build window for: {DataId}` | `MakeRestoredWindow`(lambda) | 窗口内容构建失败, 解锁并推进 | +| Warning | Manager | `Failed to capture screenshot for: {DataId}` | `ScheduleScreenshotAndUpload` | 截图失败 (仍会生成结果 JSON) | +| Log | Manager | `Generating output for: {DataId}` | `ScheduleScreenshotAndUpload` | 生成校验/结果 JSON | +| Log | Manager | `Restore windows cleared, ready for next item` | `ClearRestoreWindow` | 窗口清理完成, 可处理下一项 | + +**截图子流程日志 (均为 Manager 分类)** + +> 截图有两种取景模式 (`ELQAScreenshotMode`), 默认 `WidgetOnly`, 运行时可通过 `ULQARestoreManager::SetScreenshotMode(...)` 切换: +> - `WidgetOnly` → `CaptureWidgetScreenshot`: 用 `FWidgetRenderer` 离屏渲染根控件 (不带视口背景) +> - `Viewport` → `CaptureViewportScreenshot`: 用 `FSlateApplication::TakeScreenshot` 截游戏视口 (含全部 UI) + +**`CaptureWidgetScreenshot` (WidgetOnly 离屏渲染)** + +| 级别 | 日志信息 | 排查含义 | +|------|----------|----------| +| Error | `CaptureWidgetScreenshot must run on the game thread` | 非游戏线程调用 | +| Error | `Widget is invalid` | 根控件为空 | +| Error | `Screenshot file path is empty` | 输出路径为空 | +| Error | `Invalid widget size: %fx%f` | 控件尺寸非法 (未完成布局) | +| Error | `Screenshot size is too large: %dx%d` | 尺寸非正或超上限 | +| Error | `Failed to create directory: {Path}` | 输出目录创建失败 | +| Error | `Failed to create render target` | 渲染目标创建失败 | +| Error | `Failed to get render target resource` | 渲染目标资源获取失败 | +| Error | `Failed to read pixels from render target` | 读像素失败 | +| Error | `Pixel count mismatch: RT=%dx%d, Pixels=%d` | 读回像素数量不符 | +| Error | `Failed to compress image to PNG` | PNG 压缩失败 | +| Error | `PNG compression returned empty data` | PNG 压缩结果为空 | +| Error | `Failed to save screenshot to: {Path}` | PNG 落盘失败 | +| Log | `Widget screenshot saved to: {Path} (Size: WxH)` | 截图成功 | + +**`CaptureViewportScreenshot` (Viewport 视口截图)** + +| 级别 | 日志信息 | 排查含义 | +|------|----------|----------| +| Error | `Failed to get GameViewportClient` | 取游戏视口客户端失败 | +| Error | `Failed to get game viewport widget` | 取视口控件失败 | +| Error | `Failed to create directory: {Path}` | 输出目录创建失败 | +| Error | `Failed to take screenshot of game viewport` | 视口截图失败 | +| Error | `Pixel count mismatch: ViewportWidget=%dx%d, Pixels=%d` | 读回像素数量不符 | +| Error | `Failed to compress image to PNG` | PNG 压缩失败 | +| Error | `PNG compression returned empty data` | PNG 压缩结果为空 | +| Error | `Failed to save screenshot to: {Path}` | PNG 落盘失败 | +| Log | `Screenshot saved to: {Path} (Size: WxH)` | 截图成功 | + +### 4. UploadTimer (上传队列, 4s) + +**调用链** +`OnUploadTick` → (`CanUpload()` 为真时) `TaskManager::ProcessUploadQueue` → `FHttpRequestHelper::SendRestoreResult` → (回调) `OnUploadSuccess` / `OnUploadFail` → 广播 → `Manager::OnRestoreResultUploaded` + +**日志清单** + +| 级别 | 分类 | 日志信息 | 源码位置 | 排查含义 | +|------|------|----------|----------|----------| +| Log | Task | `Uploading restore result: {DataId}` | `ProcessUploadQueue` | 开始上传,`bIsUploading` 加锁 | +| Warning | Task | `Result directory not found: {Path}` | `ProcessUploadQueue` | 结果目录缺失, 判为失败 | +| Warning | Task | `No PNG or JSON files found for upload: {DataId}` | `ProcessUploadQueue` | 结果文件不全, 判为失败 | +| Log | Http | `POST: {URL}` | `CreateRequest` | 上传地址 `/api/image/entity` | +| Warning | Http | `Request failed` | `HandleResponse` | 网络层失败 | +| Log | Task | `Upload success: {DataId}` | `OnUploadSuccess` | 上传成功, 成功后清理本地结果目录 | +| Error | Task | `Upload failed: {DataId} (Retry: n/3)` | `OnUploadFail` | 失败重试计数, 达 3 次后放弃 | +| Log | Manager | `Restore result uploaded: {DataId}` | `Manager::OnRestoreResultUploaded` | 上传完成回调 | + +### 典型排查路径 + +- **一直没有新任务**: 查 `JobDataTimer` 链路 → `Received N job data items` (N=0 或无该日志) → 核对 `GET` URL 参数、`JobId is 0`、`No data field` +- **下载卡住不动**: 查 `DownloadTimer` → 是否长期无 `Download success` → 关注 `Download failed (Retry)`、`HTTP error response`、`Failed to decompress` +- **还原项被跳过**: 查 `RestoreTimer` → `File not found after 3 attempts` (下载未跟上) 或 `Failed to build window` +- **结果未回传平台**: 查 `UploadTimer` → `No PNG or JSON files found`、`Result directory not found`、`Upload failed (Retry)` + +### 配置加载日志 (启动期, LogLQARestoreHttp) + +| 级别 | 日志信息 | 含义 | +|------|----------|------| +| Error | `Plugin 'LQARestore' not found` | 插件未找到 | +| Warning | `Config file not found: {Path}` | `Config/LQARestore.ini` 缺失 | +| Log | `Loaded Host: {Host}` | 平台地址加载成功 | +| Warning | `Host not found in config` | ini 缺少 Host | +| Log | `Loaded Authorization (length: N)` | 鉴权令牌加载成功 | +| Warning | `Authorization not found in config` | ini 缺少 Authorization | + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/.gitattributes b/timi_hok_game_translator/UE_LQATool_Plugin/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..1e2101c54e0c992dffb1ba9b67b58eac12eb21c2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/.gitattributes @@ -0,0 +1,8 @@ +# auto generated by UGit +*.png filter=lfs diff=lfs merge=binary -text + +# auto generated by UGit + + +# auto generated by UGit + diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/.gitignore b/timi_hok_game_translator/UE_LQATool_Plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..825d381fe484064a05e8f07d7b534b6e3ce56e05 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/.gitignore @@ -0,0 +1,25 @@ +# Unreal Engine +Binaries/ +DerivedDataCache/ +Intermediate/ +Saved/ +Build/ +*.suo +*.sln +*.xcodeproj +*.xcworkspace + +# Visual Studio +.vs/ +*.user +*.opendb +*.db +*.ipch + +# Rider +.idea/ +*.sln.iml + +# Mac +.DS_Store +*.dSYM diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/.clang-format b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..1fdb4ac36da7be909631871d3f098f1fe955a1d3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/.clang-format @@ -0,0 +1,127 @@ +--- +Language: Cpp +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false +# BreakInheritanceList: AfterComma +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: true +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +FixNamespaceComments: true +ForEachMacros: + - for +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '.*\.generated\.h' + Priority: 100 + - Regex: '.*(PCH).*' + Priority: -1 + - Regex: '".*"' + Priority: 1 + - Regex: '^<.*\.(h)>' + Priority: 3 + - Regex: '^<.*>' + Priority: 4 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + CanonicalDelimiter: '' +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: true +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 4 +UseTab: Always +... diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/LQATool.uplugin b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/LQATool.uplugin new file mode 100644 index 0000000000000000000000000000000000000000..b43435b6f160fa7367f9acaaa3d00c4f1ffe4054 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/LQATool.uplugin @@ -0,0 +1,35 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "1.0.0", + "FriendlyName": "LQATool", + "Description": "A comprehensive plugin for Language Quality Assurance (LQA) testing and UI analysis in Unreal Engine projects", + "Category": "Testing", + "CreatedBy": "Tencent", + "CanContainContent": true, + "IsBetaVersion": false, + "IsExperimentalVersion": false, + "Installed": false, + "Plugins": [ + { + "Name": "Paper2D", + "Enabled": true + } + ], + "Modules": [ + { + "Name": "LQATool", + "Type": "Runtime", + "LoadingPhase": "PostConfigInit", + "WhitelistPlatforms": [ + "Win64", + "Mac", + "IOS", + "Android" + ], + "BlacklistTargetConfigurations": [ + "Shipping" + ] + } + ] +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Resources/Icon128.png b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Resources/Icon128.png new file mode 100644 index 0000000000000000000000000000000000000000..1231d4aad4d0d462fb7b178eb5b30aa61a10df0b Binary files /dev/null and b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Resources/Icon128.png differ diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/LQATool.Build.cs b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/LQATool.Build.cs new file mode 100644 index 0000000000000000000000000000000000000000..9e788d0c89437d8140890e3970b26e435a033e3c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/LQATool.Build.cs @@ -0,0 +1,41 @@ +// 引入 UnrealBuildTool 命名空间, 该命名空间提供了 ModuleRules 等编译系统所需的类型 +using UnrealBuildTool; + +// LQATool 模块的构建规则类, 继承自 ModuleRules +// UBT (Unreal Build Tool) 在编译时会读取此类来决定该模块如何编译、依赖哪些其他模块 +public class LQATool : ModuleRules +{ + // 构造函数: 接收目标平台/配置的只读规则 (Target), 用于初始化本模块的编译设置 + public LQATool(ReadOnlyTargetRules Target) : base(Target) + { + // 设置预编译头 (PCH) 的使用模式 + // UseExplicitOrSharedPCHs: 使用显式指定的 PCH 或引擎共享的 PCH, 可加快编译速度 (UE 推荐设置) + PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; + + // 公有依赖模块: 这些模块会同时暴露给依赖本模块的其他模块 + // 此处为实现基础功能所必需的核心引擎模块 + PublicDependencyModuleNames.AddRange(new string[] + { + "Core", // UE 核心基础库 (容器、字符串、数学、文件 IO 等) + "CoreUObject", // UObject 反射与对象系统 (UClass、序列化、GC 等) + "Engine" // 引擎运行时核心 (Actor、World、组件等游戏框架) + }); + + // 私有依赖模块: 仅本模块内部使用, 不会向外部模块暴露 + // 说明: 这是基础配置, 可按项目需要额外添加特定的 UI Widget 模块 + PrivateDependencyModuleNames.AddRange(new string[] + { + "Slate", // Slate UI 框架 (底层 UI 控件系统) + "SlateCore", // Slate 核心功能 (基础绘制、布局、输入等) + "UMG", // 控件蓝图 (Unreal Motion Graphics, 可视化 UI) + "Json", // JSON 解析 (序列化/反序列化 JSON 数据) + "JsonUtilities", // JSON 辅助函数 (UStruct 与 JSON 互转等便捷工具) + "HTTP", // 网络请求 (发送 HTTP 请求与接收响应) + "RHI", // 渲染硬件接口 (Rendering Hardware Interface, 抽象底层图形 API) + "RenderCore", // 核心渲染功能 (渲染线程、渲染资源管理等) + "Paper2D", // 2D 精灵支持 (Sprite、Flipbook 等 2D 内容) + "InputCore", // 输入处理 (按键、鼠标等输入事件定义) + "ImageWrapper" // 图像格式支持 (PNG/JPEG/BMP 等图片的编解码) + }); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQABase.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQABase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..209c0f7c4c6553108acc4a15393b0f8045be2b87 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQABase.cpp @@ -0,0 +1,10 @@ +// LQABase.cpp +// 与 LQABase.h 配套的源文件, 负责对头文件中声明的日志类别进行实际定义 + +// 引入本模块的基础头文件, 获取 LogLQATool 日志类别的声明 +#include "LQABase.h" + +// 定义 (实例化) 在 LQABase.h 中通过 DECLARE_LOG_CATEGORY_EXTERN 声明的日志类别 +// 整个插件中该日志类别只能被定义一次, 否则会产生重复定义的链接错误 +// 定义之后, 插件内任意包含了 LQABase.h 的文件即可使用该日志类别输出日志 +DEFINE_LOG_CATEGORY(LogLQATool) \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAInputProcessor.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAInputProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ce0dbe6e1c50520ae6993f98df5e97d1f04f56b --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAInputProcessor.cpp @@ -0,0 +1,32 @@ +#include "LQAInputProcessor.h" + +/** + * 每帧更新逻辑 + * 当前 LQA 输入处理器不需要逐帧处理任何内容, 因此函数体为空 + * 保留该重写是为了满足 IInputProcessor 接口的纯虚函数要求 + */ +void FLQAInputProcessor::Tick(const float DeltaTime, FSlateApplication& SlateApp, TSharedRef Cursor) +{ + // 目前无需任何逐帧 (Tick) 处理逻辑 +} + +/** + * 处理鼠标按键按下事件 + * 仅关心 "鼠标右键" 的按下: 当检测到右键按下时,将事件转发给 + * FLQAExportUtil::OnPointerDown 进行后续的控件检测与上报处理 + */ +bool FLQAInputProcessor::HandleMouseButtonDownEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) +{ + // 判断本次触发的按键是否为鼠标右键 + if (MouseEvent.GetEffectingButton() == EKeys::RightMouseButton) + { + // 将右键按下事件交给 LQA 导出工具处理 (例如定位并记录当前点击的控件) + FLQAExportUtil::OnPointerDown(MouseEvent); + + // 返回 true: 表示该右键事件已被本处理器消费, 阻止其继续向下层控件传递 + return true; + } + + // 非右键事件不做处理, 返回 false 让其正常传递给其他控件 + return false; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAManager.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb666675fb87597fc686b42575ad190258392245 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQAManager.cpp @@ -0,0 +1,139 @@ +#include "LQAManager.h" + +#include "Components/Image.h" +#include "Engine/GameEngine.h" +#include "Framework/Application/SlateApplication.h" +#include "Snapshot/LQAWidgetNodeUtil.h" +#include "Utils/LQAExportUtil.h" + +// 静态单例指针的定义与初始化 (声明在头文件中) +ULQAManager* ULQAManager::Instance = nullptr; + +// 子系统初始化: 调用父类初始化后, 将就绪标志置为 true, 表示 LQA 系统可用 +void ULQAManager::Initialize(FSubsystemCollectionBase& Collection) +{ + Super::Initialize(Collection); + bIsLQAReady = true; +} + +// 子系统反初始化: 先清理所有 LQA 组件, 再重置单例指针, 最后调用父类反初始化 +void ULQAManager::Deinitialize() +{ + DeInitAll(); + Instance = nullptr; + Super::Deinitialize(); +} + +// 获取 LQA 管理器单例 +ULQAManager* ULQAManager::GetLQAManager(UObject* GameIns) +{ + // 若已缓存且有效, 直接返回, 避免重复查找 + if (Instance && IsValid(Instance)) + { + return Instance; + } + + // 优先从传入的 GameInstance 中获取子系统 + const UGameInstance* GameInstance = Cast(GameIns); + if (GameInstance) + { + Instance = GameInstance->GetSubsystem(); + return Instance; + } + +#if WITH_EDITOR + // 编辑器下的 PIE (Play In Editor, 编辑器内运行) 模式不被推荐使用, 直接返回空并给出警告 + if (GWorld && GWorld->IsPlayInEditor()) + { + UE_LOG(LogLQATool, Warning, TEXT("PIE mode is not recommended, please use Standalone mode.")); + return nullptr; + } +#endif + + // 若上述方式均未取得, 则尝试从全局 GameEngine 的 GameInstance 中获取 + if (const UGameEngine* GameEngine = Cast(GEngine)) + { + if (GameEngine->GameInstance) + { + Instance = GameEngine->GameInstance->GetSubsystem(); + UE_LOG(LogLQATool, Warning, TEXT("ULQAManager Get From GameEngine!")); + return Instance; + } + } + + // 所有途径都未找到, 返回 nullptr + return nullptr; +} + +// 初始化所有 LQA 组件 +void ULQAManager::InitAll() +{ + // 创建并显示 LQA 面板 + InitLQAWidget(); + // 移除世界 Tick 开始的委托绑定, 避免在初始化完成后仍被重复触发 + FWorldDelegates::OnWorldTickStart.RemoveAll(this); +} + +// 反初始化所有 LQA 组件: 移除面板 +void ULQAManager::DeInitAll() +{ + RemoveLQAWidget(); +} + +// 导出视图数据 (高级版) +void ULQAManager::LQADumpViewAdvanced(bool bContainsTextures, bool bNeedObjectData) const +{ + // 获取当前时间, 作为本次导出的统一时间戳 (用于数据文件与截图文件命名关联) + const FDateTime CurTime = FDateTime::Now(); + // 导出视图数据, 返回对应的 WBP (Widget Blueprint, 控件蓝图) 名称 + const FString WBPName = FLQAExportUtil::DumpViewAdvanced(CurTime, bContainsTextures, bNeedObjectData); + // 基于同一时间戳与 WBP 名称进行截图, 保证截图与数据一一对应 + FLQAExportUtil::ScreenShot(CurTime, WBPName); +} + +// 创建 LQA 控件并添加到视口 +void ULQAManager::InitLQAWidget() +{ + UE_LOG(LogLQATool, Log, TEXT("ULQAManager::InitLQAWidget()")); + + // 若 LQA 系统尚未就绪, 则不创建面板并给出警告 + if (!bIsLQAReady) + { + UE_LOG(LogLQATool, Warning, TEXT("LQA Module Invalid!")); + return; + } + + // 若已存在旧的面板实例, 先从父级移除并置空, 避免重复叠加 + if (LQAWidget) + { + LQAWidget->RemoveFromParent(); + LQAWidget = nullptr; + } + + // 以当前 GameInstance 为 Owner 创建 LQA 面板控件 + LQAWidget = CreateWidget(GetGameInstance()); + + if (LQAWidget) + { + // 使用极高的 ZOrder (层级) 添加到视口, 确保面板显示在所有其他 UI 之上 + LQAWidget->AddToViewport(5000000); + } + else + { + // 创建失败时记录错误日志 + UE_LOG(LogLQATool, Error, TEXT("Create LQA Widget Failed!")); + } +} + +// 从视口中移除 LQA 控件 +void ULQAManager::RemoveLQAWidget() +{ + UE_LOG(LogLQATool, Log, TEXT("ULQAManager::RemoveLQAWidget()")); + + // 若面板存在, 则从父级移除并置空指针, 释放引用 + if (LQAWidget) + { + LQAWidget->RemoveFromParent(); + LQAWidget = nullptr; + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQATool.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQATool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa8002505e5bfdfffbe4184d0fbf051383a824f1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/LQATool.cpp @@ -0,0 +1,130 @@ +#include "LQATool.h" + +#include "Engine/GameEngine.h" // 提供 GEngine、GameViewport 等引擎相关类型 +#include "LQABase.h" // LQA 基础定义 (如日志分类 LogLQATool 等) +#include "LQAManager.h" // LQA 管理器, 负责具体的初始化/反初始化逻辑 + +// 定义本地化文本命名空间, 供 LOCTEXT 宏使用 (本文件作用域内有效) +#define LOCTEXT_NAMESPACE "FLQAToolModule" + +// 初始化静态成员变量: Dump 延迟默认值为 0 秒 (即不延迟) +float FLQAToolModule::LQADumpDelay = 0.0f; + +// 模块启动入口: 在模块被加载时由引擎自动调用 +void FLQAToolModule::StartupModule() +{ + // 注册控制台命令, 使外部可通过控制台控制 LQA 工具 + RegisterConsoleCommands(); +} + +// 模块关闭入口: 在模块被卸载时由引擎自动调用 (此处暂无清理逻辑) +void FLQAToolModule::ShutdownModule() +{ +} + +// 获取当前的 Dump 延迟时间 (秒) +float FLQAToolModule::GetLQADumpDelay() +{ + return FLQAToolModule::LQADumpDelay; +} + +// 设置 Dump 延迟时间 (秒), 并保证其不为负数 +void FLQAToolModule::SetLQADumpDelay(float InDelay) +{ + // 使用 FMath::Max 将延迟钳制到 [0, +∞), 避免出现负值 + FLQAToolModule::LQADumpDelay = FMath::Max(0.0f, InDelay); +} + +// 注册 LQA 相关的控制台命令 +void FLQAToolModule::RegisterConsoleCommands() const +{ + // 注册 LQA 主控制台命令 "r.EnableLQATool" + // 用途: 控制 LQA 按钮/功能的开关 + // 用法: r.EnableLQATool <0/1> [DelayInSeconds] + // 第 1 个参数: 0 表示关闭, >=1 表示开启 + // 第 2 个参数 (可选): Dump 延迟时间, 单位秒 + IConsoleManager::Get().RegisterConsoleCommand(TEXT("r.EnableLQATool"), + TEXT("Control the switch of LQA button. Usage: r.EnableLQATool <0/1> [DelayInSeconds]"), + // 使用 Lambda 作为命令的回调委托, 接收命令行参数数组 Args + FConsoleCommandWithArgsDelegate::CreateLambda( + [this](const TArray& Args) + { + // ===== 第一步: 获取当前的 World (世界) 上下文 ===== + UWorld* CurrentWorld = nullptr; + if (GEngine) + { + // 优先尝试获取当前 “正在游玩” 的 World (PIE 或运行时) + if (GEngine->GetCurrentPlayWorld()) + { + CurrentWorld = GEngine->GetCurrentPlayWorld(); + } + // 若没有 Play World,则退而求其次, 使用 GameViewport 对应的 World + else if (GEngine->GameViewport) + { + CurrentWorld = GEngine->GameViewport->GetWorld(); + } + } + + // 若未能获取到有效的 World, 则记录警告并提前返回 + if (!CurrentWorld) + { + UE_LOG(LogLQATool, Warning, TEXT("Invalid world for r.EnableLQATool.")); + return; + } + + // ===== 第二步: 获取 LQA 管理器实例 ===== + // 通过当前 World 获取 (或创建) 对应的 ULQAManager 单例对象 + ULQAManager* LQAManager = ULQAManager::GetLQAManager(CurrentWorld); + if (!LQAManager) + { + // 获取失败时记录警告并返回 + UE_LOG(LogLQATool, Warning, TEXT("Failed to get ULQAManager instance.")); + return; + } + + // ===== 第三步: 解析并处理命令行参数 ===== + // 只接受 1 个或 2 个参数的情况 + if (Args.Num() == 1 || Args.Num() == 2) + { + // 将第 1 个参数解析为整数开关值 (0=关, >=1=开) + int32 Switch = FCString::Atoi(*Args[0]); + + // 处理可选的第 2 个参数: 延迟时间 + if (Args.Num() >= 2) + { + // 将第 2 个参数解析为浮点数 (秒) + float Delay = FCString::Atof(*Args[1]); + // 设置延迟 (内部会钳制为非负) + FLQAToolModule::SetLQADumpDelay(Delay); + UE_LOG(LogLQATool, Log, TEXT("Set LQA dump delay to %f seconds."), Delay); + } + + // 根据开关值执行 “开启 / 关闭” 逻辑 + if (Switch == 0) + { + // 关闭: 反初始化所有 LQA 相关功能 + LQAManager->DeInitAll(); + UE_LOG(LogLQATool, Log, TEXT("LQA Tool Disabled.")); + } + else if (Switch >= 1) + { + // 开启: 初始化所有 LQA 相关功能 + LQAManager->InitAll(); + UE_LOG(LogLQATool, Log, TEXT("LQA Tool Enabled.")); + } + } + else + { + // 参数数量不合法, 提示正确用法 + UE_LOG(LogLQATool, Warning, + TEXT("Invalid argument count for r.EnableLQATool. Usage: r.EnableLQATool <0/1>.")); + } + }), + ECVF_Default); // 控制台变量标志: 使用默认行为 +} + +// 取消本地化文本命名空间定义 (与前面的 #define 成对出现) +#undef LOCTEXT_NAMESPACE + +// 实现并注册该模块: 第 1 个参数为模块类, 第 2 个参数为模块名 (LQATool) +IMPLEMENT_MODULE(FLQAToolModule, LQATool) \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNode.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf66a47dbfeb977e4d33f0f6a58a1b5a6aff92fc --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNode.cpp @@ -0,0 +1,455 @@ +#include "Snapshot/LQAWidgetNode.h" + +#include "Blueprint/SlateBlueprintLibrary.h" +#include "Components/PanelSlot.h" +#include "Components/Widget.h" +#include "Internationalization/TextNamespaceUtil.h" +#include "JsonObjectConverter.h" +#include "LQABase.h" +#include "Types/ReflectionMetadata.h" +#include "Utils/LQAJsonUtils.h" +#include "Widgets/SWidget.h" +#include "WidgetSlots/LQAWidgetTypeRegistry.h" +#include "WidgetSlots/WidgetDefines.h" + +// 关闭本文件的编译器优化 (便于调试; 文件末尾会重新开启) +#if ENGINE_MAJOR_VERSION >= 5 +UE_DISABLE_OPTIMIZATION +#else +PRAGMA_DISABLE_OPTIMIZATION +#endif + +// ================== 控件 / 插槽类型名称常量 ================== + +// 插槽类型名 (与 Slate/UMG 的插槽类名字符串一一对应) +namespace LQASlotNames +{ +// Slot type names +const FName LQA_ButtonSlot(TEXT("ButtonSlot")); +const FName LQA_CanvasPanelSlot(TEXT("CanvasPanelSlot")); +const FName LQA_ScrollBoxSlot(TEXT("ScrollBoxSlot")); +const FName LQA_VerticalBoxSlot(TEXT("VerticalBoxSlot")); +const FName LQA_HorizontalBoxSlot(TEXT("HorizontalBoxSlot")); +const FName LQA_ScaleBoxSlot(TEXT("ScaleBoxSlot")); +const FName LQA_SafeZoneSlot(TEXT("SafeZoneSlot")); +const FName LQA_WrapBoxSlot(TEXT("WrapBoxSlot")); +const FName LQA_SizeBoxSlot(TEXT("SizeBoxSlot")); +const FName LQA_GridSlot(TEXT("GridSlot")); +const FName LQA_UniformGridSlot(TEXT("UniformGridSlot")); +const FName LQA_OverlaySlot(TEXT("OverlaySlot")); +const FName LQA_BorderSlot(TEXT("BorderSlot")); +const FName LQA_WidgetSwitcherSlot(TEXT("WidgetSwitcherSlot")); +const FName LQA_BackgroundBlurSlot(TEXT("BackgroundBlurSlot")); +const FName LQA_StackBoxSlot(TEXT("StackBoxSlot")); +const FName LQA_WindowTitleBarAreaSlot(TEXT("WindowTitleBarAreaSlot")); +const FName LQA_PanelSlot(TEXT("PanelSlot")); + +// 项目自定义插槽名称可在此处追加 +} + +namespace LQAWidgetNames +{ +// 控件类型名 (与 Slate 控件的 GetType() 返回字符串一一对应) +const FName LQA_TextBlock(TEXT("STextBlock")); +const FName LQA_RichTextBlock(TEXT("SRichTextBlock")); +const FName LQA_EditableText(TEXT("SEditableText")); +const FName LQA_EditableTextBox(TEXT("SEditableTextBox")); +const FName LQA_MultilineEditableText(TEXT("SMultilineEditableText")); +const FName LQA_MultilineEditableTextBox(TEXT("SMultilineEditableTextBox")); +const FName LQA_TextScroller(TEXT("STextScroller")); +const FName LQA_InputKeySelector(TEXT("SInputKeySelector")); +const FName LQA_ComboBox(TEXT("SComboBox")); +const FName LQA_ComboBoxString(TEXT("SComboBox< TSharedPtr >")); +const FName LQA_ComboBoxKey(TEXT("SComboBox")); +const FName LQA_LEDRichTextBlock(TEXT("SLEDRichTextBlock")); +const FName LQA_Image(TEXT("SImage")); +const FName LQA_Button(TEXT("SButton")); +const FName LQA_UserWidget(TEXT("SObjectWidget")); +const FName LQA_Canvas(TEXT("SConstraintCanvas")); +const FName LQA_RetainerBox(TEXT("SRetainerWidget")); +const FName LQA_ScrollBox(TEXT("SScrollBox")); +const FName LQA_CommonHierarchicalScrollBox(TEXT("SCommonHierarchicalScrollBox")); +const FName LQA_VerticalBox(TEXT("SVerticalBox")); +const FName LQA_HorizontalBox(TEXT("SHorizontalBox")); +const FName LQA_ScaleBox(TEXT("SScaleBox")); +const FName LQA_SafeZone(TEXT("SSafeZone")); +const FName LQA_WrapBox(TEXT("SWrapBox")); +const FName LQA_SizeBox(TEXT("SBox")); +const FName LQA_NamedSlot(TEXT("SBox")); +const FName LQA_NativeWidgetHost(TEXT("SBox")); +const FName LQA_CheckBox(TEXT("SCheckBox")); +const FName LQA_GridPanel(TEXT("SGridPanel")); +const FName LQA_UniformGridPanel(TEXT("SUniformGridPanel")); +const FName LQA_Overlay(TEXT("SOverlay")); +const FName LQA_Border(TEXT("SBorder")); +const FName LQA_BackgroundBlur(TEXT("SBackgroundBlur")); +const FName LQA_ProgressBar(TEXT("SProgressBar")); +const FName LQA_Throbber(TEXT("SThrobber")); +const FName LQA_CircularThrobber(TEXT("SCircularThrobber")); +const FName LQA_Slider(TEXT("SSlider")); +const FName LQA_SpinBox(TEXT("SSpinBox")); +const FName LQA_SpinBoxFloat(TEXT("SSpinBox")); +const FName LQA_Spacer(TEXT("SSpacer")); +const FName LQA_WidgetSwitcher(TEXT("SWidgetSwitcher")); +const FName LQA_StackBox(TEXT("SStackBox")); +const FName LQA_WindowTitleBarArea(TEXT("SWindowTitleBarArea")); +const FName LQA_MenuAnchor(TEXT("SMenuAnchor")); +const FName LQA_InvalidationBox(TEXT("SInvalidationPanel")); +const FName LQA_ScrollBar(TEXT("SScrollBar")); +const FName LQA_PostBufferUpdate(TEXT("SPostBufferUpdate")); +const FName LQA_ObjectTableRow(TEXT("ObjectTableRowT")); +const FName LQA_ListView(TEXT("ListViewT")); +const FName LQA_TileView(TEXT("TileViewT")); +const FName LQA_TreeView(TEXT("TreeViewT")); +const FName LQA_ExpandableArea(TEXT("SExpandableArea")); + +// 项目自定义控件名称可在此处追加 +} + +namespace +{ +/** + * 将非有限数值归一为 0 + * 用于防止 NaN / Inf 写入 JSON 导致解析异常 + * @param InValue 待归一化的数值 + * @return 有限值原样返回; NaN / Inf 返回 0 + */ +double SanitizeFinite(const double InValue) +{ + return FMath::IsFinite(InValue) ? InValue : 0.0; +} +} // namespace + +// 构造函数: 缓存几何信息, 并处理控件以识别类型、提取元数据 +FLQAWidgetNode::FLQAWidgetNode(const FArrangedWidget& InWidgetGeometry) : CachedGeometry(InWidgetGeometry.Geometry) +{ + HandleWidget(InWidgetGeometry.Widget); +} + +// 追加一个子节点到子节点数组 +void FLQAWidgetNode::AddChildNode(TSharedRef InChildNode) +{ + ChildNodes.Emplace(InChildNode); +} + +// 清空所有子节点 +void FLQAWidgetNode::ClearChildNodes() +{ + ChildNodes.Empty(); +} + +// 返回子节点数组 (常量引用) +const TArray>& FLQAWidgetNode::GetChildNodes() const +{ + return ChildNodes; +} + +// 填充控件的通用 JSON 数据 (名称、角点、视口坐标、尺寸、包围盒、图层、插槽类型等) +void FLQAWidgetNode::FillCommonData(TSharedPtr InObject, bool bNeedObjectData) const +{ + // JSON 对象无效则记录警告并提前返回 + if (!InObject.IsValid()) + { + UE_LOG(LogLQATool, Warning, TEXT("[LQA] Invalid JSON object passed to FillCommonData")); + return; + } + + // 写入基础字段 + InObject->SetStringField(TEXT("WidgetName"), WidgetName.ToString()); + InObject->SetArrayField(TEXT("corners"), GetCornerPosition()); + InObject->SetObjectField(TEXT("ViewportPos"), ConvertViewportPos2Json()); + InObject->SetObjectField(TEXT("LocalSize"), ConvertLocalSize2Json()); + InObject->SetArrayField(TEXT("BoxSize"), GetBoxSizePosition()); + InObject->SetNumberField(TEXT("LayerId"), LayerId); + InObject->SetStringField(TEXT("ExcludedSlotType"), BaseSlotType); + + // 需要附加对象元数据, 且源对象有效时, 序列化源对象到 JSON + if (bNeedObjectData && SourceObject.IsValid()) + { + bool bGetStructJsonData = false; + TSharedPtr JsonObject = MakeShared(); + + // 仅对已识别类型的控件进行序列化 + if (NodeType != ELQAWidgetType::LQA_Undefined) + { + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, SourceObject.Get())) + { + bGetStructJsonData = true; + } + } + + // 序列化成功且确有数据, 才写入 ObjectData 字段 + if (bGetStructJsonData && JsonObject->Values.Num() > 0) + { + InObject->SetField(TEXT("ObjectData"), MakeShared(JsonObject)); + } + } +} + +// 为 "未定义类型" 控件填充通用 JSON 数据 (额外写入排除的控件/插槽类型, 并识别蓝图 UserWidget) +void FLQAWidgetNode::FillCommonDataForUndefinedWidget(TSharedPtr InObject) const +{ + // JSON 对象无效则记录警告并提前返回 + if (!InObject.IsValid()) + { + UE_LOG(LogLQATool, Warning, TEXT("[LQA] Invalid JSON object passed to FillCommonDataForUndefinedWidget")); + return; + } + + // 写入基础字段 + InObject->SetStringField(TEXT("WidgetName"), WidgetName.ToString()); + InObject->SetArrayField(TEXT("corners"), GetCornerPosition()); + InObject->SetObjectField(TEXT("ViewportPos"), ConvertViewportPos2Json()); + InObject->SetObjectField(TEXT("LocalSize"), ConvertLocalSize2Json()); + InObject->SetArrayField(TEXT("BoxSize"), GetBoxSizePosition()); + InObject->SetNumberField(TEXT("LayerId"), LayerId); + // 未定义控件额外记录被排除的插槽类型与控件类型 + InObject->SetStringField(TEXT("ExcludedSlotType"), BaseSlotType); + InObject->SetStringField(TEXT("ExcludedWidgetType"), BaseWidgetType); + + const FString WidgetNameString = WidgetName.ToString(); + if (SourceObject.IsValid()) + { + bool bGetStructJsonData = false; + TSharedPtr JsonObject = MakeShared(); + + // 控件名不为 "None" 时才尝试序列化源对象 + if (WidgetNameString != TEXT("None")) + { + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, SourceObject.Get())) + { + bGetStructJsonData = true; + } + } + + // 序列化成功且确有数据, 才写入 ObjectData 字段 + if (bGetStructJsonData && JsonObject->Values.Num() > 0) + { + InObject->SetField(TEXT("ObjectData"), MakeShared(JsonObject)); + } + } + + // 控件名包含 "_C_" 说明是蓝图生成类实例, 标记为 UserWidget 类型 + if (WidgetNameString.Contains(TEXT("_C_"))) + { + InObject->SetStringField(TEXT("NewWidgetType"), LQAWidgetNames::LQA_UserWidget.ToString()); + } +} + +// 核心处理: 识别控件类型、读取反射元数据、确定插槽类型并计算 UI 位置 +void FLQAWidgetNode::HandleWidget(const TSharedRef& InWidget) +{ + const FName SlateTypeName = InWidget->GetType(); + BaseWidgetType = SlateTypeName.ToString(); + + const TSharedPtr InWidgetMetaData = InWidget->GetMetaData(); + if (!InWidgetMetaData.IsValid()) + { + NodeType = ELQAWidgetType::LQA_Undefined; + return; + } + + if (InWidgetMetaData->Name != NAME_None) + { + WidgetName = InWidgetMetaData->Name; + } + SourceObject = InWidgetMetaData->SourceObject; + + // 类型判定: Slate 类型名 + UMG 类 (Slate 根类型复用时靠 UMG 类区分) + if (const FLQAWidgetTypeDesc* TypeDesc = FLQAWidgetTypeRegistry::TryGetWidgetTypeDesc(SlateTypeName, SourceObject.Get())) + { + NodeType = TypeDesc->WidgetType; // 命中登记项: 取 LQA 控件类型 + WidgetClassTag = TypeDesc->WidgetClassTag; // Slate 根类型复用组内的 UMG 侧标识 (1:1 类型为 None) + } + else + { + NodeType = ELQAWidgetType::LQA_Undefined; // 未登记: 视为 Slate 内部控件 + } + + if (SourceObject.IsValid()) + { + if (UWidget* SourceUWidget = Cast(SourceObject)) + { + if (UPanelSlot* DefaultSlot = SourceUWidget->Slot) + { + const FString SlotClassNameStr = DefaultSlot->GetClass()->GetName(); + const FName SlotClassName(*SlotClassNameStr); + BaseSlotType = SlotClassNameStr; + SlotType = GetSlotType(SlotClassName); + } + } + } + + if (NodeType == ELQAWidgetType::LQA_Undefined) + { + return; + } + + LayerId = 0; + if (!SetUIPosition()) + { + NodeType = ELQAWidgetType::LQA_Undefined; + } +} + +ELQASlotType FLQAWidgetNode::GetSlotType(const FName& SlotTypeName) +{ + using namespace LQASlotNames; + + // 插槽类型名 -> 枚举 的静态映射表 (首次调用时构建并缓存) + static const TMap SlotTypeMap = { + {LQA_ButtonSlot, ELQASlotType::LQA_ButtonSlot}, {LQA_CanvasPanelSlot, ELQASlotType::LQA_CanvasPanelSlot}, + {LQA_ScrollBoxSlot, ELQASlotType::LQA_ScrollBoxSlot}, {LQA_VerticalBoxSlot, ELQASlotType::LQA_VerticalBoxSlot}, + {LQA_HorizontalBoxSlot, ELQASlotType::LQA_HorizontalBoxSlot}, + {LQA_ScaleBoxSlot, ELQASlotType::LQA_ScaleBoxSlot}, {LQA_SafeZoneSlot, ELQASlotType::LQA_SafeZoneSlot}, + {LQA_WrapBoxSlot, ELQASlotType::LQA_WrapBoxSlot}, {LQA_SizeBoxSlot, ELQASlotType::LQA_SizeBoxSlot}, + {LQA_GridSlot, ELQASlotType::LQA_GridSlot}, {LQA_UniformGridSlot, ELQASlotType::LQA_UniformGridSlot}, + {LQA_OverlaySlot, ELQASlotType::LQA_OverlaySlot}, {LQA_BorderSlot, ELQASlotType::LQA_BorderSlot}, + {LQA_WidgetSwitcherSlot, ELQASlotType::LQA_WidgetSwitcherSlot}, + {LQA_BackgroundBlurSlot, ELQASlotType::LQA_BackgroundBlurSlot}, + {LQA_StackBoxSlot, ELQASlotType::LQA_StackBoxSlot}, + {LQA_WindowTitleBarAreaSlot, ELQASlotType::LQA_WindowTitleBarAreaSlot}, + {LQA_PanelSlot, ELQASlotType::LQA_PanelSlot} + + // 项目自定义插槽映射可在此处追加 + }; + + // 命中返回对应枚举, 否则返回未定义 + if (const ELQASlotType* FoundType = SlotTypeMap.Find(SlotTypeName)) + { + return *FoundType; + } + return ELQASlotType::LQA_UndefinedSlot; +} + +// 将四个角点坐标 (左下、左上、右上、右下) 打包为 JSON 数组 +TArray> FLQAWidgetNode::GetCornerPosition() const +{ + TArray> CornerPosList; + CornerPosList.Reserve(4); // 预留 4 个元素, 避免扩容 + CornerPosList.Emplace(MakeShared(ConvertPos2Json(LeftBottomPos))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(LeftUpperPos))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(RightUpperPos))); + CornerPosList.Emplace(MakeShared(ConvertPos2Json(RightBottomPos))); + return CornerPosList; +} + +// 将包围盒的最小点与最大点打包为 JSON 数组 +TArray> FLQAWidgetNode::GetBoxSizePosition() const +{ + TArray> BoxPosList; + BoxPosList.Reserve(2); // 预留 2 个元素(Min / Max) + BoxPosList.Emplace(MakeShared(ConvertPos2Json(BoxSize.Min))); + BoxPosList.Emplace(MakeShared(ConvertPos2Json(BoxSize.Max))); + return BoxPosList; +} + +// 将视口坐标转换为 {x, y} 形式的 JSON 对象 (数值做有限化保护) +TSharedPtr FLQAWidgetNode::ConvertViewportPos2Json() const +{ + TSharedPtr PosValue = MakeShared(); + PosValue->SetNumberField(TEXT("x"), SanitizeFinite(ViewportPos.X)); + PosValue->SetNumberField(TEXT("y"), SanitizeFinite(ViewportPos.Y)); + return PosValue; +} + +// 将本地尺寸转换为 {x, y} 形式的 JSON 对象 (数值做有限化保护) +TSharedPtr FLQAWidgetNode::ConvertLocalSize2Json() const +{ + TSharedPtr PosValue = MakeShared(); + PosValue->SetNumberField(TEXT("x"), SanitizeFinite(LocalSize.X)); + PosValue->SetNumberField(TEXT("y"), SanitizeFinite(LocalSize.Y)); + return PosValue; +} + +// 将任意二维坐标转换为 {x, y} 形式的 JSON 对象 (数值做有限化保护) +TSharedPtr FLQAWidgetNode::ConvertPos2Json(const FVector2D& InPos) const +{ + TSharedPtr PosValue = MakeShared(); + + PosValue->SetNumberField(TEXT("x"), SanitizeFinite(InPos.X)); + PosValue->SetNumberField(TEXT("y"), SanitizeFinite(InPos.Y)); + return PosValue; +} + +// 计算并设置控件在屏幕上的位置数据 (四角坐标、视口坐标、本地尺寸、包围盒) +bool FLQAWidgetNode::SetUIPosition() +{ + // 获取 World; 无效则无法进行坐标换算 + UWorld* WorldInstance = SourceObject.IsValid() ? SourceObject->GetWorld() : nullptr; + if (!WorldInstance) + { + UE_LOG(LogLQATool, Error, TEXT("[LQA] Get Invalid World!")); + return false; + } + + // 获取视口尺寸 (用于后续 Y 轴翻转) + FVector2D ViewportSize = FVector2D::ZeroVector; + if (const UGameViewportClient* ViewportClient = WorldInstance->GetGameViewport()) + { + ViewportClient->GetViewportSize(ViewportSize); + } + + // 将控件本地原点换算为视口像素坐标, 并获取绝对尺寸与本地尺寸 + FVector2D PixelPos; + USlateBlueprintLibrary::LocalToViewport( + WorldInstance, CachedGeometry, FVector2D(0.0f, 0.0f), PixelPos, ViewportPos); + const FVector2D AbsoluteSize = USlateBlueprintLibrary::GetAbsoluteSize(CachedGeometry); + LocalSize = CachedGeometry.GetLocalSize(); + + // 依次计算四个角点坐标; + // 注意:Slate 的 Y 轴向下, 这里统一翻转为 "Y 轴向上" 的屏幕坐标系 (ViewportSize.Y - Y) + + // 左下角 = 原点 + (0,1)*尺寸 + LeftBottomPos = PixelPos + FVector2D(0.0f, 1.0f) * AbsoluteSize; + LeftBottomPos.Y = ViewportSize.Y - LeftBottomPos.Y; + + // 左上角 = 原点 + (0,0)*尺寸 + LeftUpperPos = PixelPos + FVector2D(0.0f, 0.0f) * AbsoluteSize; + LeftUpperPos.Y = ViewportSize.Y - LeftUpperPos.Y; + + // 右上角 = 原点 + (1,0)*尺寸 + RightUpperPos = PixelPos + FVector2D(1.0f, 0.0f) * AbsoluteSize; + RightUpperPos.Y = ViewportSize.Y - RightUpperPos.Y; + + // 右下角 = 原点 + (1,1)*尺寸 + RightBottomPos = PixelPos + FVector2D(1.0f, 1.0f) * AbsoluteSize; + RightBottomPos.Y = ViewportSize.Y - RightBottomPos.Y; + + // 以左下、右上两点构建 2D 包围盒 + BoxSize = FBox2D(LeftBottomPos, RightUpperPos); + return true; +} + +// 设置节点唯一标识 +void FLQAWidgetNode::SetNodeId(int32 Id) +{ + NodeId = Id; +} + +// 判断是否为用户自定义控件 (UserWidget) +bool FLQAWidgetNode::CheckNodeIsUserWidget() const +{ + return NodeType == ELQAWidgetType::LQA_UserWidget; +} + +// 递归设置包围盒: 把当前节点的包围盒下传给 "非 UserWidget" 子节点 +// (UserWidget 作为独立单元, 保留自身包围盒, 不被父级覆盖) +void FLQAWidgetNode::SetBoxSize() +{ + for (const auto& Item : ChildNodes) + { + if (!Item->CheckNodeIsUserWidget()) + { + Item->BoxSize = BoxSize; // 继承父节点包围盒 + Item->SetBoxSize(); // 继续向下递归 + } + } +} + +// 重新开启本文件的编译器优化 +#if ENGINE_MAJOR_VERSION >= 5 +UE_ENABLE_OPTIMIZATION +#else +PRAGMA_ENABLE_OPTIMIZATION +#endif \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNodeUtil.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNodeUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c211472db145fcf187fd1dd76fd949f6a65c888 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Snapshot/LQAWidgetNodeUtil.cpp @@ -0,0 +1,190 @@ +#include "Snapshot/LQAWidgetNodeUtil.h" + +#include "Components/ExpandableArea.h" // UExpandableArea: 命名插槽 (Header/Body) 容器 +#include "Components/Widget.h" // UWidget: 获取命名插槽内容的 CachedWidget +#include "Debugging/SlateDebugging.h" +#include "Layout/ArrangedChildren.h" // FArrangedChildren: 子控件排布结果容器 +#include "Layout/Children.h" // FChildren: Slate 控件子节点容器的抽象接口 +#include "Misc/Optional.h" // TOptional: 表示可能存在的排布节点 +#include "Snapshot/LQAWidgetNode.h" // 控件节点类型 FLQAWidgetNode +#include "Types/ReflectionMetadata.h" // Slate 反射元数据 (用于获取控件调试/标识信息) + +// 关闭当前编译单元的代码优化 +// 常用于调试: 便于在该文件内逐行断点调试递归逻辑, 避免优化导致变量被折叠或无法观察 +#if ENGINE_MAJOR_VERSION >= 5 +UE_DISABLE_OPTIMIZATION +#else +PRAGMA_DISABLE_OPTIMIZATION +#endif + +namespace +{ +/** + * 为从未参与绘制的控件补一次 Tick。 + * 绘制期几何为 0 表示该控件从未被绘制与 Tick, 其按需构建的子内容尚未生成。 + */ +void TickIfNeverPainted(const TSharedRef& Widget, const FGeometry& InGeometry) +{ + if (!Widget->GetTickSpaceGeometry().GetLocalSize().IsNearlyZero() || InGeometry.GetLocalSize().IsNearlyZero()) + { + return; + } + + Widget->Tick(InGeometry, FPlatformTime::Seconds(), 0.0f); +} + +/** + * 在排布结果中递归查找指定 Slate 控件, 返回其携带正确几何的排布节点。 + * 用于穿透命名插槽容器 (如 SExpandableArea) 内部的 Slate 包装层 (SBorder/SButton 等), + * 定位真正的命名插槽内容控件, 从而拿到其正确坐标与尺寸。 + */ +TOptional FindArrangedWidget( + const TSharedRef& Target, const FArrangedChildren& InChildren) +{ + for (int32 ChildIndex = 0; ChildIndex < InChildren.Num(); ++ChildIndex) + { + const FArrangedWidget& Child = InChildren[ChildIndex]; + if (Child.Widget == Target) + { + return TOptional(Child); + } + + // 递归子层级继续查找 + FArrangedChildren GrandChildren(EVisibility::Visible); +#if ENGINE_MAJOR_VERSION >= 5 + Child.Widget->ArrangeChildren(Child.Geometry, GrandChildren, true); +#else + Child.Widget->ArrangeChildren(Child.Geometry, GrandChildren); +#endif + TOptional Found = FindArrangedWidget(Target, GrandChildren); + if (Found.IsSet()) + { + return Found; + } + } + return TOptional(); +} +} // namespace + +/** + * 根据已排布的控件几何信息, 递归构建控件节点树。 + * 子控件几何取自当前控件的排布结果, 不依赖控件是否被绘制。 + */ +TSharedRef FLQAWidgetNodeUtil::GetNodeFromTree(const FArrangedWidget& InWidgetGeometry, int32& Index) +{ + // 取出当前要处理的控件引用 + const TSharedRef CurrentWidget = InWidgetGeometry.Widget; + + // 为当前控件创建一个新的节点实例 (携带其排布几何信息) + TSharedRef NewNodeInstance = MakeShared(InWidgetGeometry); + + // 索引自增, 并作为该节点的唯一 NodeId (引用传入, 整棵树范围内持续累加) + ++Index; + NewNodeInstance->SetNodeId(Index); + + // 视口外的子树不会进入绘制流程, 先按排布几何补一次 Tick, 使其按需构建的子内容就位 + TickIfNeverPainted(CurrentWidget, InWidgetGeometry.Geometry); + + // 特殊处理 UExpandableArea: 其 Header/Body 是命名插槽内容, 直接采集对应的 UWidget, + // 避免递归进入 SExpandableArea 内部的 Slate 包装层 (SBorder/SButton/SHorizontalBox 等)。 + // 这些内部包装层没有 UMG 反射元数据, 会被识别为 UNDEFINE, 导致内容丢失。 + if (UExpandableArea* ExpandableArea = Cast(NewNodeInstance->SourceObject.Get())) + { + // 主动排布一次, 让命名插槽内容获得正确几何 (滚出视口的控件可能从未被 Tick) + FArrangedChildren ArrangedChildren(EVisibility::Visible); +#if ENGINE_MAJOR_VERSION >= 5 + CurrentWidget->ArrangeChildren(InWidgetGeometry.Geometry, ArrangedChildren, true); +#else + CurrentWidget->ArrangeChildren(InWidgetGeometry.Geometry, ArrangedChildren); +#endif + + TArray SlotNames; + ExpandableArea->GetSlotNames(SlotNames); + + for (const FName& SlotName : SlotNames) + { + UWidget* Content = ExpandableArea->GetContentForSlot(SlotName); + if (!IsValid(Content)) + { + continue; + } + + TSharedPtr ContentWidget = Content->GetCachedWidget(); + if (!ContentWidget.IsValid()) + { + continue; + } + + // 从排布结果中穿透包装层, 找到内容控件对应的排布节点 (携带正确几何) + TOptional ArrangedContent = + FindArrangedWidget(ContentWidget.ToSharedRef(), ArrangedChildren); + if (ArrangedContent.IsSet()) + { + TSharedRef ChildNode = GetNodeFromTree(ArrangedContent.GetValue(), Index); + ChildNode->SlotName = SlotName; // 记录命名插槽名, 供还原侧区分 Header/Body + NewNodeInstance->AddChildNode(ChildNode); + } + } + + return NewNodeInstance; + } + + // 无子控件容器或容器为空时, 当前节点即为叶子节点。 + FChildren* ChildrenContainer = nullptr; +#if WITH_SLATE_DEBUGGING && ENGINE_MAJOR_VERSION >= 5 + ChildrenContainer = CurrentWidget->Debug_GetChildrenForReflector(); +#else + ChildrenContainer = CurrentWidget->GetChildren(); +#endif + + if (!ChildrenContainer || ChildrenContainer->Num() == 0) + { + return NewNodeInstance; + } + + // 取当前控件的排布结果: 可见性过滤由容器完成, Collapsed / Hidden 子控件不会进入结果 + FArrangedChildren ArrangedChildren(EVisibility::Visible); +#if ENGINE_MAJOR_VERSION >= 5 + CurrentWidget->ArrangeChildren(InWidgetGeometry.Geometry, ArrangedChildren, true); +#else + CurrentWidget->ArrangeChildren(InWidgetGeometry.Geometry, ArrangedChildren); +#endif + + // 遍历所有已完成排布的子控件 + for (int32 ChildIndex = 0; ChildIndex < ArrangedChildren.Num(); ++ChildIndex) + { + const FArrangedWidget& ArrangedChild = ArrangedChildren[ChildIndex]; + + // 完全透明的控件在界面上不可见, 跳过 + if (ArrangedChild.Widget->GetRenderOpacity() == 0.0f) + { + continue; + } + + // 过滤条件 3: 检查排布后的尺寸 + // 绝对尺寸与期望尺寸分开判定, 两者都无效才跳过 + const FVector2D ChildAbsoluteSize = ArrangedChild.Geometry.GetAbsoluteSize(); + const FVector2D ChildDesiredSize = ArrangedChild.Widget->GetDesiredSize(); + const bool bAbsoluteSizeInvalid = + FMath::IsNearlyZero(ChildAbsoluteSize.X) || FMath::IsNearlyZero(ChildAbsoluteSize.Y); + const bool bDesiredSizeInvalid = + FMath::IsNearlyZero(ChildDesiredSize.X) || FMath::IsNearlyZero(ChildDesiredSize.Y); + if (bAbsoluteSizeInvalid && bDesiredSizeInvalid) + { + continue; // 跳过没有可见面积的控件 + } + + // 递归为该子控件构建子节点, 并挂接到当前节点下 + NewNodeInstance->AddChildNode(GetNodeFromTree(ArrangedChild, Index)); + } + + // 返回构建好的 (含所有合格子节点的) 当前节点 + return NewNodeInstance; +} + +// 重新开启代码优化, 恢复后续编译单元的默认优化行为 +#if ENGINE_MAJOR_VERSION >= 5 +UE_ENABLE_OPTIMIZATION +#else +PRAGMA_ENABLE_OPTIMIZATION +#endif diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/ToolPanel/LQABaseView.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/ToolPanel/LQABaseView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5152d06ccdc12646064bcd9b90a6b501fac3ea80 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/ToolPanel/LQABaseView.cpp @@ -0,0 +1,315 @@ +#include "ToolPanel/LQABaseView.h" + +#include "Blueprint/WidgetTree.h" // WidgetTree: 用于以代码构造控件 +#include "Components/CanvasPanelSlot.h" // CanvasPanelSlot: 画布上子控件的布局槽 +#include "Engine/Engine.h" +#include "Engine/GameInstance.h" // UGameInstance +#include "Engine/LocalPlayer.h" // ULocalPlayer +#include "Engine/World.h" // UWorld / 定时器管理 +#include "LQAInputProcessor.h" // 自定义输入预处理器 +#include "LQAManager.h" // LQA 管理器, 负责实际 Dump 逻辑 +#include "LQATool.h" // 模块类与日志分类 +#include "Modules/ModuleManager.h" // 模块管理器, 用于获取模块配置 +#include "TimerManager.h" // 定时器 + +// 构造函数: 仅调用父类构造, 无额外初始化 +ULQABaseView::ULQABaseView(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) +{ +} + +// 析构函数: 确保对象销毁时注销并释放输入预处理器 +ULQABaseView::~ULQABaseView() +{ + CleanupInputProcessor(); +} + +// 以代码方式重建整个控件树 +TSharedRef ULQABaseView::RebuildWidget() +{ + // WidgetTree 不存在时无法构造控件, 返回空控件 + if (!WidgetTree) + { + return SNullWidget::NullWidget; + } + + // 创建根画布面板 + RootCanvasPanel = WidgetTree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvasPanel")); + if (!RootCanvasPanel) + { + return SNullWidget::NullWidget; + } + + // 将根画布面板设置为控件树的根控件 + WidgetTree->RootWidget = RootCanvasPanel; + + // 创建各 UI 元素: 创建失败仅记录错误日志, 不中断整体构建 + if (!CreateDumpViewButton()) + { + UE_LOG(LogLQATool, Error, TEXT("LQABaseView: Failed to create dump view button - UI may be incomplete")); + } + + if (!CreateGetKeyButton()) + { + UE_LOG(LogLQATool, Error, TEXT("LQABaseView: Failed to create get key button - UI may be incomplete")); + } + + // 返回根画布面板对应的底层 Slate 控件 + return RootCanvasPanel->TakeWidget(); +} + +#if ENGINE_MAJOR_VERSION < 5 +// [UE4] 关卡从世界移除时的虚函数重写: 清理输入预处理器 +void ULQABaseView::OnLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld) +{ + Super::OnLevelRemovedFromWorld(InLevel, InWorld); + + // 关卡被移除时清理输入预处理器, 避免悬空引用 + CleanupInputProcessor(); +} +#else +// [UE5] 关卡从世界移除的委托回调: 清理输入预处理器 +void ULQABaseView::HandleLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld) +{ + // 关卡被移除时清理输入预处理器 + CleanupInputProcessor(); +} + +// [UE5] 对象销毁前注销关卡移除委托, 避免回调访问已失效对象 +void ULQABaseView::BeginDestroy() +{ + if (LevelRemovedFromWorldHandle.IsValid()) + { + FWorldDelegates::LevelRemovedFromWorld.Remove(LevelRemovedFromWorldHandle); + LevelRemovedFromWorldHandle.Reset(); + } + + Super::BeginDestroy(); +} +#endif + +// 控件构造完成后的初始化: 注册委托、绑定按钮点击事件 +void ULQABaseView::NativeConstruct() +{ + Super::NativeConstruct(); + +#if ENGINE_MAJOR_VERSION >= 5 + // [UE5] 注册关卡移除委托 (仅注册一次) + if (!LevelRemovedFromWorldHandle.IsValid()) + { + LevelRemovedFromWorldHandle = FWorldDelegates::LevelRemovedFromWorld.AddUObject( + this, &ULQABaseView::HandleLevelRemovedFromWorld); + } +#endif + + // 绑定 Dump 按钮点击事件 + if (DumpViewBtn) + { + DumpViewBtn->OnClicked.AddDynamic(this, &ULQABaseView::OnDumpViewClicked); + } + + // 绑定 GetKey 按钮点击事件 + if (GetKeyBtn) + { + GetKeyBtn->OnClicked.AddDynamic(this, &ULQABaseView::OnGetKeyClicked); + } +} + +// Dump 按钮点击响应: 根据配置的延迟, 立即或延迟执行界面转储 +void ULQABaseView::OnDumpViewClicked() +{ + float Delay = 0.0f; + + // 从模块配置中读取转储延迟时间 + if (FModuleManager::Get().IsModuleLoaded(TEXT("LQATool"))) + { + FLQAToolModule& LQAToolModule = FModuleManager::GetModuleChecked(TEXT("LQATool")); + Delay = LQAToolModule.GetLQADumpDelay(); + } + + // 没有有效世界则无法设置定时器, 直接返回 + UWorld* World = GetWorld(); + if (!World) + { + return; + } + + // 延迟 <= 0 立即执行; 否则通过定时器延迟执行 + // 延迟的意义: 便于操作者先把游戏界面切换到目标状态, 再捕获 + if (Delay <= 0.f) + { + HandleDumpViewClicked(); + } + else + { + FTimerHandle TimerHandle; + World->GetTimerManager().SetTimer(TimerHandle, [this]() { HandleDumpViewClicked(); }, Delay, false); + } +} + +// GetKey 按钮点击响应: 切换按键捕获开关, 并同步更新按钮文本与捕获状态 +void ULQABaseView::OnGetKeyClicked() +{ + bLQAEnableKeyDump = !bLQAEnableKeyDump; // 翻转开关状态 + UpdateGetKeyButtonText(bLQAEnableKeyDump); // 更新按钮文本 (On/Off) + SetKeyCapture(bLQAEnableKeyDump); // 启用/禁用输入捕获 +} + +// 执行实际的界面转储操作: 通过 LQAManager 导出当前界面层级与属性 +void ULQABaseView::HandleDumpViewClicked() const +{ + // 逐级获取 LocalPlayer -> GameInstance -> LQAManager, 任一为空则放弃 + ULocalPlayer* LocalPlayer = GetOwningLocalPlayer(); + if (!LocalPlayer) + { + return; + } + + UGameInstance* GameInstance = LocalPlayer->GetGameInstance(); + if (!GameInstance) + { + return; + } + + ULQAManager* LQAManager = ULQAManager::GetLQAManager(GameInstance); + if (!LQAManager) + { + return; + } + + // 执行高级转储: 同时导出控件层级结构 (true) 与属性 (true) + LQAManager->LQADumpViewAdvanced(true, true); +} + +// 创建并配置 Dump View 按钮 +bool ULQABaseView::CreateDumpViewButton() +{ + // 依赖的控件树或根画布缺失时直接失败 + if (!WidgetTree || !RootCanvasPanel) + { + return false; + } + + // 创建按钮及其文本控件 + DumpViewBtn = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("DumpView_Btn")); + DumpViewBtnText = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("TextBlock_Dump")); + + if (!DumpViewBtn || !DumpViewBtnText) + { + return false; + } + + // 设置按钮文本并作为按钮子控件 + DumpViewBtnText->SetText(FText::FromString(TEXT("Dump"))); + DumpViewBtn->AddChild(DumpViewBtnText); + + // 将按钮加入画布, 并配置其布局 (锚点、对齐、位置、尺寸) + UCanvasPanelSlot* CanvasSlot = RootCanvasPanel->AddChildToCanvas(DumpViewBtn); + if (CanvasSlot) + { + CanvasSlot->SetAutoSize(false); // 关闭自动尺寸, 使用固定尺寸 + CanvasSlot->SetAnchors(FAnchors(0.f, BUTTON_ANCHOR_Y, 0.f, BUTTON_ANCHOR_Y)); // 锚定到屏幕左侧中部 + CanvasSlot->SetAlignment(FVector2D(0.f, BUTTON_ANCHOR_Y)); // 对齐方式 + CanvasSlot->SetPosition(FVector2D(0.f, 0.f)); // 位置: 最左侧 + CanvasSlot->SetSize(FVector2D(BUTTON_WIDTH, BUTTON_HEIGHT)); // 固定尺寸 + } + + return true; +} + +// 创建并配置 Get Key 按钮 +bool ULQABaseView::CreateGetKeyButton() +{ + if (!WidgetTree || !RootCanvasPanel) + { + return false; + } + + // 创建按钮及其文本控件 + GetKeyBtn = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("GetKey_Btn")); + GetKeyBtnText = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("GetKeyBtn_Text")); + + if (!GetKeyBtn || !GetKeyBtnText) + { + return false; + } + + // 根据当前捕获状态初始化按钮文本, 并作为按钮子控件 + UpdateGetKeyButtonText(bLQAEnableKeyDump); + GetKeyBtn->AddChild(GetKeyBtnText); + + // 将按钮加入画布并配置布局, X 方向偏移使其位于 Dump 按钮右侧 + UCanvasPanelSlot* CanvasSlot = RootCanvasPanel->AddChildToCanvas(GetKeyBtn); + if (CanvasSlot) + { + CanvasSlot->SetAutoSize(false); + CanvasSlot->SetAnchors(FAnchors(0.f, BUTTON_ANCHOR_Y, 0.f, BUTTON_ANCHOR_Y)); + CanvasSlot->SetAlignment(FVector2D(0.f, BUTTON_ANCHOR_Y)); + CanvasSlot->SetPosition(FVector2D(GETKEY_BUTTON_OFFSET_X, 0.f)); // X 偏移, 避免与 Dump 按钮重叠 + CanvasSlot->SetSize(FVector2D(GETKEY_BUTTON_WIDTH, BUTTON_HEIGHT)); + } + + return true; +} + +// 根据按键捕获状态更新 Get Key 按钮文本 +void ULQABaseView::UpdateGetKeyButtonText(bool bIsKeyEnabled) +{ + if (!GetKeyBtnText) + { + return; + } + + // 启用显示 [On], 禁用显示 [Off] + const FText ButtonText = + bIsKeyEnabled ? FText::FromString(TEXT("GetKey\n [On]")) : FText::FromString(TEXT("GetKey\n [Off]")); + GetKeyBtnText->SetText(ButtonText); +} + +// 启用或禁用按键捕获: 向 Slate 注册/注销输入预处理器 +void ULQABaseView::SetKeyCapture(bool bEnable) +{ + // Slate 未初始化时无法操作输入预处理器 + if (!FSlateApplication::IsInitialized()) + { + UE_LOG( + LogLQATool, Error, TEXT("LQABaseView: SlateApplication is not initialized - cannot manage input processor")); + return; + } + + FSlateApplication& SlateApp = FSlateApplication::Get(); + + if (bEnable) + { + // 启用: 若尚未创建则创建输入预处理器, 然后向 Slate 注册 + if (!InputProcessor.IsValid()) + { + InputProcessor = MakeShared(); + if (!InputProcessor.IsValid()) + { + UE_LOG(LogLQATool, Error, TEXT("LQABaseView: Failed to create input processor")); + return; + } + } + SlateApp.RegisterInputPreProcessor(InputProcessor); + } + else + { + // 禁用: 若已存在则从 Slate 注销并释放 + if (InputProcessor.IsValid()) + { + SlateApp.UnregisterInputPreProcessor(InputProcessor); + InputProcessor.Reset(); + } + } +} + +// 清理输入预处理器: 注销、释放并复位状态标志 (供析构与关卡移除时调用) +void ULQABaseView::CleanupInputProcessor() +{ + if (InputProcessor.IsValid() && FSlateApplication::IsInitialized()) + { + FSlateApplication::Get().UnregisterInputPreProcessor(InputProcessor); + InputProcessor.Reset(); + bLQAEnableKeyDump = false; + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQACommonUtil.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQACommonUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0626461c35df6a0f1c7399ce441d107bdfc9cc95 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQACommonUtil.cpp @@ -0,0 +1,162 @@ +#include "Utils/LQACommonUtil.h" + +#include "HAL/PlatformFilemanager.h" // 提供平台文件管理器, 用于路径转换 +#include "HAL/PlatformMisc.h" // 提供平台杂项接口, 用于获取系统/设备信息 +#include "Misc/App.h" // 提供应用信息, 如项目名称 +#include "Misc/ConfigCacheIni.h" // 提供配置文件 (ini) 读取能力 +#include "Misc/Paths.h" // 提供路径相关工具函数 + +// 定义 (实现) 在头文件中声明的日志分类 +DEFINE_LOG_CATEGORY(LogLQAToolCommonUtil); + +// 获取游戏 Saved 存档目录的绝对路径, 根据不同平台采用不同的获取逻辑 +FString FLQACommonUtil::GetGameSavedPath() +{ + FString SavedPath; + +#if PLATFORM_ANDROID + // ------- Android 平台 ------- + // Android 上 Saved 目录位于持久化下载目录下, 需要用项目名拼接出完整路径 + + // 获取项目名称, 若为空则无法构造路径, 直接返回空字符串 + const FString ProjectName = FApp::GetProjectName(); + if (ProjectName.IsEmpty()) + { + UE_LOG(LogLQAToolCommonUtil, Error, TEXT("Project name is empty")); + return FString(); + } + + // 获取持久化下载目录, 若为空同样无法构造路径 + const FString PersistentDownloadDir = FPaths::ProjectPersistentDownloadDir(); + if (PersistentDownloadDir.IsEmpty()) + { + UE_LOG(LogLQAToolCommonUtil, Error, TEXT("Persistent download directory is empty")); + return FString(); + } + + // 拼接出 Android 下的 Saved 目录完整路径 + SavedPath = PersistentDownloadDir / TEXT("UEGame") / ProjectName / ProjectName / TEXT("Saved"); + +#elif PLATFORM_IOS + // ------- iOS 平台 ------- + // 先获取项目 Saved 目录 + SavedPath = FPaths::ProjectSavedDir(); + if (!IsValidPath(SavedPath)) + { + UE_LOG(LogLQAToolCommonUtil, Error, TEXT("Invalid iOS saved directory: %s"), *SavedPath); + return FString(); + } + + // iOS 的沙盒机制特殊, 需要将路径转换为可供外部应用读取的绝对路径 + SavedPath = + FPlatformFileManager::Get().GetPlatformFile().GetPlatformPhysical().ConvertToAbsolutePathForExternalAppForRead( + *SavedPath); + +#else + // ------- 其他平台 (Windows / Mac / Linux 等) ------- + // 直接获取项目 Saved 目录 + SavedPath = FPaths::ProjectSavedDir(); + if (!IsValidPath(SavedPath)) + { + UE_LOG(LogLQAToolCommonUtil, Error, TEXT("Invalid saved directory: %s"), *SavedPath); + return FString(); + } + + // 将相对路径转换为绝对路径 + SavedPath = FPaths::ConvertRelativePathToFull(SavedPath); +#endif + + // 最终统一的路径合法性校验, 确保返回的路径有效 + if (!IsValidPath(SavedPath)) + { + UE_LOG(LogLQAToolCommonUtil, Error, TEXT("Final path validation failed: %s"), *SavedPath); + return FString(); + } + + return SavedPath; +} + +// 收集当前设备的系统信息, 并拼接为 URL 查询参数格式的字符串 +FString FLQACommonUtil::GetSystemInfo() +{ + // 获取平台名称 + const FString Platform = GetCurrentPlatformName(); + // 获取操作系统版本 (为空时回退为 Unknown) + const FString OSVersion = GetSafeStringValue(FPlatformMisc::GetOSVersion()); + // 获取设备厂商与型号 (为空时回退为 Unknown) + const FString DeviceMakeAndModel = GetSafeStringValue(FPlatformMisc::GetDeviceMakeAndModel()); + // 获取 CPU 厂商信息 (为空时回退为 Unknown) + const FString CPUInfo = GetSafeStringValue(FPlatformMisc::GetCPUVendor()); + + // 将各项信息进行 URL 编码后, 按 key=value&key=value 的格式拼接返回 + return FString::Printf(TEXT("Platform=%s&OSVersion=%s&DeviceMake=%s&CPUInfo=%s"), *UrlEncodeString(Platform), + *UrlEncodeString(OSVersion), *UrlEncodeString(DeviceMakeAndModel), *UrlEncodeString(CPUInfo)); +} + +// 从项目配置 (ini) 中读取客户端版本号 +FString FLQACommonUtil::GetClientVersion() +{ + FString ClientVersion; + + // 从 GameIni 的 GeneralProjectSettings 配置段中读取 ProjectVersion 字段 + if (GConfig && GConfig->GetString(TEXT("/Script/EngineSettings.GeneralProjectSettings"), TEXT("ProjectVersion"), + ClientVersion, GGameIni)) + { + // 读取成功且非空时才返回 + if (!ClientVersion.IsEmpty()) + { + return ClientVersion; + } + } + + // 读取失败或为空时, 返回默认版本号 + return DEFAULT_VERSION; +} + +// 对字符串进行 URL 编码, 转义会影响 URL 解析的特殊字符 +FString FLQACommonUtil::UrlEncodeString(const FString& InputString) +{ + // 空字符串无需处理, 直接返回 + if (InputString.IsEmpty()) + { + return InputString; + } + + // 依次替换特殊字符为对应的百分号编码: + // & -> %26、= -> %3D、空格 -> %20、# -> %23、? -> %3F + return InputString.Replace(TEXT("&"), TEXT("%26")) + .Replace(TEXT("="), TEXT("%3D")) + .Replace(TEXT(" "), TEXT("%20")) + .Replace(TEXT("#"), TEXT("%23")) + .Replace(TEXT("?"), TEXT("%3F")); +} + +// 返回安全字符串: 若原值为空则返回默认值, 避免出现空字段 +FString FLQACommonUtil::GetSafeStringValue(const FString& Value, const FString& DefaultValue) +{ + return Value.IsEmpty() ? DefaultValue : Value; +} + +// 校验路径是否合法: 必须非空, 且长度大于设定的最小长度 +bool FLQACommonUtil::IsValidPath(const FString& Path) +{ + return !Path.IsEmpty() && Path.Len() > MIN_PATH_LENGTH; +} + +// 根据编译期的平台宏, 返回当前运行平台的名称字符串 +FString FLQACommonUtil::GetCurrentPlatformName() +{ +#if PLATFORM_ANDROID + return TEXT("Android"); +#elif PLATFORM_IOS + return TEXT("iOS"); +#elif PLATFORM_WINDOWS + return TEXT("Windows"); +#elif PLATFORM_MAC + return TEXT("Mac"); +#elif PLATFORM_LINUX + return TEXT("Linux"); +#else + return TEXT("Unknown"); +#endif +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAExportUtil.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAExportUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9572cbec8bc41291252f8693f8761a3cb4de19d9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAExportUtil.cpp @@ -0,0 +1,868 @@ +#include "Utils/LQAExportUtil.h" + +// ---- 引擎与控件相关头文件 ---- +#include "Components/CanvasPanel.h" // 画布面板 +#include "Components/CanvasPanelSlot.h" // 画布面板插槽 +#include "Components/Image.h" // 图片控件 +#include "Engine/Engine.h" // GEngine 全局引擎对象 +#include "Engine/GameViewportClient.h" // 游戏视口客户端 +#include "Engine/TextureRenderTarget2D.h" // 2D 渲染目标纹理 +#include "EngineUtils.h" +#include "Framework/Application/SlateApplication.h" // Slate 应用 (窗口/输入管理) +#include "HighResScreenshot.h" // 高分辨率截图 +#include "ImageUtils.h" // 图像工具 +#include "Internationalization/Internationalization.h" // 国际化 (本地化) +#include "LQABase.h" +#include "LQAManager.h" +#include "RHICommandList.h" // 渲染硬件接口命令列表 +#include "Engine/Texture2D.h" +#include "HAL/FileManager.h" +#include "Misc/PackageName.h" +#include "Misc/SecureHash.h" +#include "RHIResources.h" +#include "SceneView.h" +#include "Slate/SceneViewport.h" +#include "Slate/WidgetRenderer.h" +#include "Snapshot/LQAWidgetNode.h" // LQA 控件节点定义 +#include "Snapshot/LQAWidgetNodeUtil.h" // LQA 控件节点工具 +#include "Utils/LQACommonUtil.h" // LQA 通用工具 +#include "Utils/LQATextureUtil.h" // LQA 纹理工具 +#include "WidgetSlots/Slot2JsonFactory.h" // 插槽转 JSON 工厂 +#include "UObject/Package.h" +#include "UObject/UObjectGlobals.h" +#include "WidgetSlots/Slot2JsonInterface.h" +#include "WidgetSlots/Widget2JsonFactory.h" // 控件转 JSON 工厂 +#include "WidgetSlots/Widget2JsonInterface.h" +#include "Widgets/SViewport.h" +#include "Widgets/SWindow.h" + +// Windows 平台专用头文件 (用于获取窗口句柄、坐标转换) +#if PLATFORM_WINDOWS +#include "Windows/AllowWindowsPlatformTypes.h" +#include +#include "Windows/HideWindowsPlatformTypes.h" +#endif + +// ======================================== +// 静态成员与常量定义 +// ======================================== + +// 静态成员变量在类外初始化 (默认空字符串) +FString FLQAExportUtil::ScreenshotPath = TEXT(""); +FString FLQAExportUtil::BgScreenshotPath = TEXT(""); + +namespace LQAExportConstants +{ +// 背景截图相对于前景截图的延迟秒数 +constexpr float SCREENSHOT_DELAY_SECONDS = 1.2f; +// 控件包围盒的角点数量 (矩形为 4 个角) +constexpr int32 EXPECTED_CORNER_COUNT = 4; + +// 所有被视为 “文本类” 的控件类型集合 +const TArray AllTextTypes = {ELQAWidgetType::LQA_TextBlock, ELQAWidgetType::LQA_RichText, + ELQAWidgetType::LQA_EditableText, ELQAWidgetType::LQA_EditableTextBox, ELQAWidgetType::LQA_MultilineEditableText, + ELQAWidgetType::LQA_MultilineEditableTextBox, ELQAWidgetType::LQA_TextScroller, + ELQAWidgetType::LQA_ComboBoxStringText, ELQAWidgetType::LQA_LEDRichText, ELQAWidgetType::LQA_InputKeySelector}; + +// 需要被排除 (不导出) 的控件名称前缀, 通常为调试/工具类控件 +const TArray ExcludedWidgetPrefixes = { + TEXT("LQABaseView"), + TEXT("Debugger_Widget"), + TEXT("GM_Widget"), +}; +} + +// ======================================== +// 辅助函数 (匿名命名空间, 仅本文件内可见) +// ======================================== + +namespace +{ +/** + * 判断控件名称是否包含被排除的前缀 + * @param TargetStr 待检查的控件名称 + * @return 若命中任意排除前缀则返回 true + */ +bool ContainsExcludedPrefix(const FString& TargetStr) +{ + for (const FString& Prefix : LQAExportConstants::ExcludedWidgetPrefixes) + { + if (TargetStr.Contains(Prefix)) + { + return true; + } + } + return false; +} + +/** + * 由当前控件名与父层级名构造 "父##子" 层级名 + * @param WidgetName 当前控件名, 会截去蓝图类名的 "_C_xxx" 后缀 + * @param ParentName 父层级名, 为 None 时表示当前控件已是顶层 + * @return 拼接后的层级名; 当前控件无名称时原样返回父层级名 + */ +FName MakeChildParentName(const FName WidgetName, const FName ParentName) +{ + FName CleanName = WidgetName; + + // 去除蓝图类名中的 "_C_xxx" 后缀 (取左半部分作为纯净名称) + FString Left, Right; + CleanName.ToString().Split(TEXT("_C_"), &Left, &Right, ESearchCase::IgnoreCase, ESearchDir::FromEnd); + if (!Left.IsEmpty()) + { + CleanName = FName(*Left); + } + + // 无名称的中间控件不参与层级拼接 + if (CleanName.IsNone()) + { + return ParentName; + } + + // 顶层控件直接使用自身名称 + if (ParentName.IsNone()) + { + return CleanName; + } + + return FName(*FString::Printf(TEXT("%s##%s"), *ParentName.ToString(), *CleanName.ToString())); +} + +/** + * 将屏幕点击坐标转换为视口 (Viewport) 坐标 + * 在 Windows 平台上会先把屏幕坐标转换为客户区坐标, + * 最后再做 Y 轴翻转 (屏幕坐标原点在左上, 视口坐标原点在左下) + */ +FVector2D AdjustClickPositionForViewport(const FVector2D& ClickPosition) +{ + // 引擎或游戏视口无效时直接返回原始坐标 + if (!GEngine || !GEngine->GameViewport) + { + return ClickPosition; + } + + FVector2D ViewportSize; + GEngine->GameViewport->GetViewportSize(ViewportSize); + FVector2D AdjustedPosition = ClickPosition; + +#if PLATFORM_WINDOWS + // 获取原生窗口句柄 + HWND WindowHandle = nullptr; + if (GEngine->GameViewport) + { + void* WindowPtr = GEngine->GameViewport->GetWindow()->GetNativeWindow()->GetOSWindowHandle(); + WindowHandle = static_cast(WindowPtr); + } + + if (WindowHandle) + { + RECT ClientRect; + // 获取窗口客户区矩形 + if (GetClientRect(WindowHandle, &ClientRect)) + { + // 计算客户区左上角在屏幕中的坐标 + POINT ClientTopLeft = {0, 0}; + if (ClientToScreen(WindowHandle, &ClientTopLeft)) + { + const FVector2D ClientScreenPos(ClientTopLeft.x, ClientTopLeft.y); + // 屏幕坐标减去客户区左上角坐标, 得到相对视口坐标 + const FVector2D ViewportPosition = ClickPosition - ClientScreenPos; + AdjustedPosition = ViewportPosition; + } + } + } +#endif + // Y 轴翻转: 将坐标系原点从左上角转换到左下角 + AdjustedPosition.Y = ViewportSize.Y - AdjustedPosition.Y; + return AdjustedPosition; +} + +/** + * 判断某个点是否落在控件的包围盒范围内 + * @param Point 待判断的坐标点 + * @param Corners 控件四个角点的 JSON 数组 + * @return 若点在包围盒内返回 true + */ +bool IsPointInWidgetBounds(const FVector2D& Point, const TArray>& Corners) +{ + // 角点数量不符 (非矩形) 直接返回 false + if (Corners.Num() != LQAExportConstants::EXPECTED_CORNER_COUNT) + { + return false; + } + + // 读取左下、右下、左上三个角点坐标 (用于构造矩形范围判断) + const FVector2D LeftBottom( + Corners[0]->AsObject()->GetNumberField(TEXT("x")), Corners[0]->AsObject()->GetNumberField(TEXT("y"))); + const FVector2D RightBottom( + Corners[3]->AsObject()->GetNumberField(TEXT("x")), Corners[3]->AsObject()->GetNumberField(TEXT("y"))); + const FVector2D LeftTop( + Corners[1]->AsObject()->GetNumberField(TEXT("x")), Corners[1]->AsObject()->GetNumberField(TEXT("y"))); + + // 判断点的 X 在左右范围内、Y 在上下范围内 + return Point.X >= LeftBottom.X && Point.X <= RightBottom.X && Point.Y >= LeftBottom.Y && Point.Y <= LeftTop.Y; +} + +/** + * 在屏幕上显示本地化 (Localization) 调试信息 + * @param TextStr 当前显示的文本 + * @param TextKey 文本的本地化 Key + * @param TextSource 文本源字符串 (可选, 为空时显示简略信息) + */ +void DisplayLocalizationInfo(const FString& TextStr, const FString& TextKey, const FString& TextSource = TEXT("")) +{ + // 根据是否有源字符串, 组装不同详细程度的调试信息 + const FString DebugMessage = + TextSource.IsEmpty() + ? FString::Printf(TEXT("localization: %s"), *TextStr) + : FString::Printf(TEXT("localization: %s\nsourceText: %s\ntextKey: %s"), *TextStr, *TextSource, *TextKey); + + // 在屏幕上输出调试信息: 简略信息橙色显示 2 秒, 详细信息红色显示 8 秒 + GEngine->AddOnScreenDebugMessage( + -1, TextSource.IsEmpty() ? 2.0f : 8.0f, TextSource.IsEmpty() ? FColor::Orange : FColor::Red, DebugMessage); +} + +/** + * 处理 “文本 Key 有效” 的场景: 尝试取出源字符串并显示本地化信息 + */ +void HandleValidKeyScenario( + const TSharedPtr& MatchedJsonObject, const FString& TextStr, const FString& TextKey) +{ + FString TextSource = TEXT(""); + if (MatchedJsonObject->HasField(TEXT("SourceString"))) + { + TextSource = MatchedJsonObject->GetStringField(TEXT("SourceString")); + } + DisplayLocalizationInfo(TextStr, TextKey, TextSource); +} +} + +// ======================================== +// 公共接口 —— 主要导出函数 +// ======================================== + +FString FLQAExportUtil::DumpViewAdvanced(const FDateTime& CurDate, bool bContainsTextures, bool bNeedObjectData) +{ + UE_LOG(LogLQATool, Log, TEXT("FLQAExportUtil::DumpView()")); + // 记录开始时间 (毫秒), 用于统计耗时 + const double Start = FDateTime::Now().GetTimeOfDay().GetTotalMilliseconds(); + + // 获取当前激活的顶层窗口 + const TSharedPtr ActiveWindow = FSlateApplication::Get().GetActiveTopLevelWindow(); + // 基于该窗口创建高级快照, 返回控件蓝图名称 + const FString WBPName = CreateSnapshotAdvanced(ActiveWindow, CurDate, bContainsTextures, bNeedObjectData); + + // 记录结束时间并输出总耗时 + const double End = FDateTime::Now().GetTimeOfDay().GetTotalMilliseconds(); + UE_LOG(LogLQATool, Log, TEXT("DumpView Takes: %f ms"), End - Start); + + return WBPName; +} + +TArray> FLQAExportUtil::DumpText() +{ + TArray> AllTexts; + // 获取当前激活窗口 + const TSharedPtr ActiveWindow = FSlateApplication::Get().GetActiveTopLevelWindow(); + if (!ActiveWindow.IsValid()) + { + return AllTexts; // 窗口无效则返回空数组 + } + + TSharedRef WidgetRef = ActiveWindow.ToSharedRef(); + int32 Index = 0; + // 从窗口的几何信息构建控件节点树 + TSharedPtr NodeTree = + FLQAWidgetNodeUtil::GetNodeFromTree(FArrangedWidget(WidgetRef, WidgetRef->GetWindowGeometryInScreen()), Index); + + // 递归收集所有文本节点 + GetAllTextNodes(NodeTree, AllTexts); + + return AllTexts; +} + +void FLQAExportUtil::ScreenShot(const FDateTime& CurDate, const FString& WBPName) +{ + UE_LOG(LogLQATool, Log, TEXT("FLQAExportUtil::ScreenShot()")); + const auto Start = FDateTime::Now().GetTimeOfDay().GetTotalMilliseconds(); + + // 生成截图保存路径并启动截图流程 + const FString ScreenshotFilePath = GetScreenShotFileName(CurDate, WBPName); + StartScreenshotSequence(ScreenshotFilePath); + + const auto End = FDateTime::Now().GetTimeOfDay().GetTotalMilliseconds(); + UE_LOG(LogLQATool, Log, TEXT("Screen Shot Takes: %f ms"), End - Start); +} + +// ======================================== +// 公共接口 —— 交互相关函数 +// ======================================== + +void FLQAExportUtil::OnPointerDown(const FPointerEvent& MouseEvent) +{ + // 获取鼠标点击的屏幕坐标 + const FVector2D ScreenSpacePosition = MouseEvent.GetScreenSpacePosition(); + // 提取当前视图中的所有文本控件 + const TArray> AllTextWidgets = DumpText(); + + // 查找点击位置命中的控件 + TArray> FoundWidgets; + FindAllWidgetsContainingPoint(ScreenSpacePosition, AllTextWidgets, FoundWidgets); +} + +bool FLQAExportUtil::FindAllWidgetsContainingPoint(const FVector2D& ClickPosition, + const TArray>& TextWidgets, TArray>& OutWidgets) +{ + OutWidgets.Empty(); + + // 校验游戏视口是否有效 + if (!GEngine || !GEngine->GameViewport) + { + UE_LOG(LogLQATool, Warning, TEXT("FindAllWidgetsContainingPoint: GameViewport is null")); + return false; + } + + // 校验世界 (World) 是否有效 + UWorld* World = GEngine->GetWorldContexts()[0].World(); + if (!World) + { + UE_LOG(LogLQATool, Warning, TEXT("FindAllWidgetsContainingPoint: World is null")); + return false; + } + + // 将屏幕点击坐标转换为视口坐标 + const FVector2D AdjustedClickPosition = AdjustClickPositionForViewport(ClickPosition); + + // 从后往前遍历 (后渲染的控件在上层, 优先命中) 查找匹配控件 + TSharedPtr MatchedJsonObject; + for (int32 i = TextWidgets.Num() - 1; i >= 0; --i) + { + const TSharedPtr& JsonObject = TextWidgets[i]; + if (!JsonObject.IsValid()) + { + continue; + } + + // 读取控件角点并判断点击点是否在其范围内 + const TArray> Corners = JsonObject->GetArrayField(TEXT("corners")); + if (IsPointInWidgetBounds(AdjustedClickPosition, Corners)) + { + OutWidgets.Add(JsonObject); + MatchedJsonObject = JsonObject; + break; // 命中最上层控件后即停止 + } + } + + // 未命中、或缺少必要字段则返回 false + if (!MatchedJsonObject.IsValid() || !MatchedJsonObject->HasField(TEXT("textStr")) || + !MatchedJsonObject->HasField(TEXT("TextKey"))) + { + return false; + } + + // 取出命中控件的文本内容与本地化 Key + const FString TextStr = MatchedJsonObject->GetStringField(TEXT("textStr")); + const FString TextKey = MatchedJsonObject->GetStringField(TEXT("TextKey")); + + // 显示基础本地化信息 + DisplayLocalizationInfo(TextStr, TextKey); + + // 根据 TextKey 是否有效走不同处理分支 + if (TextKey.Contains(TEXT("INVALIDKEY"))) + { + // 无效 Key —— 无需额外处理, 仅记录日志 + UE_LOG(LogLQATool, Verbose, TEXT("Found invalid localization key for text: %s"), *TextStr); + } + else + { + // 有效 Key —— 进一步展示源字符串等信息 + HandleValidKeyScenario(MatchedJsonObject, TextStr, TextKey); + } + + return OutWidgets.Num() > 0; +} + +// ======================================== +// 公共接口 —— 通用工具函数 +// ======================================== + +FString FLQAExportUtil::GetCurrentCulture() +{ + // 通过国际化模块获取当前 Culture, 并返回其名称 (如 "zh-CN") + const FCultureRef CurrentCultureRef = FInternationalization::Get().GetCurrentCulture(); + return CurrentCultureRef->GetName(); +} + +void FLQAExportUtil::AddSystemData(const TSharedPtr& JsonObject) +{ + // 获取设备信息与客户端版本号 + const FString DeviceInfo = FLQACommonUtil::GetSystemInfo(); + const FString Version = FLQACommonUtil::GetClientVersion(); + + // 组装元数据对象 + const TSharedPtr NewObject = MakeShareable(new FJsonObject()); + NewObject->SetStringField(TEXT("version"), Version); + NewObject->SetStringField(TEXT("device"), DeviceInfo); + + // 追加视口尺寸信息 + UGameViewportClient* GameViewportClient = GEngine->GameViewport; + if (GameViewportClient) + { + const TSharedPtr ViewportWidget = GameViewportClient->GetGameViewportWidget(); + const FVector2D ViewportSize = GameViewportClient->GetGameViewport()->GetSizeXY(); + NewObject->SetNumberField(TEXT("sizeX"), ViewportSize.X); + NewObject->SetNumberField(TEXT("sizeY"), ViewportSize.Y); + } + + // 将元数据挂载到 "meta" 字段下 + JsonObject->SetObjectField(TEXT("meta"), NewObject); +} + +bool FLQAExportUtil::SaveSnapshotData(const FString& InJsonData, const FString& WBPName, const FDateTime& CurDate) +{ + // 空数据不保存 + if (InJsonData.IsEmpty()) + { + return false; + } + + // 以时间戳 + 蓝图名拼接目录与文件名 + const FString CurTime = CurDate.ToString(TEXT("%Y_%m_%d_%H_%M_%S")); + const FString JsonFileName = FString::Printf(TEXT("LQA_Snapshot_%s_%s.json"), *WBPName, *CurTime); + const FString JsonFilePath = FPaths::Combine(GetSnapshotDirectory(CurDate, WBPName), *JsonFileName); + + // 以 UTF-8 (无 BOM) 编码保存字符串到文件 + return FFileHelper::SaveStringToFile(InJsonData, *JsonFilePath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM); +} + +// ======================================== +// 私有 —— 核心快照函数 +// ======================================== + +FString FLQAExportUtil::GetSnapshotDirectory(const FDateTime& CurDate, const FString& WBPName) +{ + const FString CurTime = CurDate.ToString(TEXT("%Y_%m_%d_%H_%M_%S")); + return FPaths::Combine( + *FLQACommonUtil::GetGameSavedPath(), TEXT("LQA"), *FString::Printf(TEXT("%s_%s"), *CurTime, *WBPName)); +} + +FString FLQAExportUtil::CreateSnapshotAdvanced( + const TSharedPtr& VisibleWindow, const FDateTime& CurDate, bool bContainsTextures, bool bNeedObjectData) +{ + // 窗口无效直接返回空 + if (!VisibleWindow.IsValid()) + { + UE_LOG(LogLQATool, Error, + TEXT("CreateSnapshotAdvanced aborted: no valid top-level window to capture. " + "This usually means the game/viewport window was not focused when the dump was triggered.")); + return TEXT(""); + } + + TSharedRef WidgetRef = VisibleWindow.ToSharedRef(); + int32 Index = 0; + // 构建控件节点树 + TSharedPtr NodeTree = + FLQAWidgetNodeUtil::GetNodeFromTree(FArrangedWidget(WidgetRef, WidgetRef->GetWindowGeometryInScreen()), Index); + + // 收集所有有效节点 (UserWidget 且未被排除) + TArray> ValidNodes; + GetAllValidNodes(NodeTree, ValidNodes); + + // UI 树 JSON 数组、纹理缓存、名称列表 + TArray> UITrees; + TMap SharedTextureMap; + TArray NameList; + + const TSharedPtr JsonObject = MakeShareable(new FJsonObject()); + + // 逐个有效节点序列化为 JSON 并加入 UI 树数组 + for (const auto& Node : ValidNodes) + { + TSharedPtr TreeObject = DumpNodeInfo(Node, SharedTextureMap, NameList, bNeedObjectData); + if (TreeObject.IsValid()) + { + UITrees.Add(MakeShareable(new FJsonValueObject(TreeObject))); + } + } + + // 将 UI 树挂到 "uitree" 字段 + JsonObject->SetArrayField(TEXT("uitree"), UITrees); + + // 追加系统元数据, 并解析控件蓝图名称 + AddSystemData(JsonObject); + FString WBPName = FindWBPName(NameList); + + // 将 JSON 对象序列化为字符串 + FString OutString; + const TSharedRef> JsonWriter = TJsonWriterFactory<>::Create(&OutString); + FJsonSerializer::Serialize(JsonObject.ToSharedRef(), JsonWriter); + + // 保存到磁盘, 失败则输出错误日志 + if (!SaveSnapshotData(OutString, WBPName, CurDate)) + { + UE_LOG(LogLQATool, Error, TEXT("Save Snapshot Data Failed!")); + } + if (bContainsTextures) + { + ExportSharedTextures(SharedTextureMap, CurDate, WBPName); + } + + return WBPName; +} + +bool FLQAExportUtil::IsRuntimeGeneratedTexture(const UTexture2D* Texture2D) +{ + if (!Texture2D) + { + return false; + } + + // Objects living in the transient package have no footprint on disk + const UPackage* Package = Texture2D->GetOutermost(); + if (!Package || Package == GetTransientPackage()) + { + return true; + } + + // Packages created this session that were never saved also have no file to load back + if (Package->HasAnyPackageFlags(PKG_NewlyCreated)) + { + return true; + } + + return !FPackageName::DoesPackageExist(Package->GetName()); +} + +void FLQAExportUtil::ExportSharedTextures( + const TMap& SharedTextureMap, const FDateTime& CurDate, const FString& WBPName) +{ + if (SharedTextureMap.Num() == 0) + { + return; + } + + const FString TextureDirectory = FPaths::Combine(GetSnapshotDirectory(CurDate, WBPName), TEXT("Textures")); + bool bTextureDirectoryReady = false; + + int32 ExportedCount = 0; + int32 SkippedAssetCount = 0; + for (const TPair& Pair : SharedTextureMap) + { + UTexture2D* Texture2D = IsValid(Pair.Value) ? Cast(Pair.Value) : nullptr; + if (!Texture2D) + { + continue; + } + + if (!IsRuntimeGeneratedTexture(Texture2D)) + { + ++SkippedAssetCount; + continue; + } + + TArray PngData; + if (!FLQATextureUtil::GetTexture2DData(Texture2D, PngData)) + { + UE_LOG(LogLQATool, Warning, TEXT("Failed to export texture pixels: %s"), *Pair.Key); + continue; + } + + if (!bTextureDirectoryReady) + { + IFileManager::Get().MakeDirectory(*TextureDirectory, true); + bTextureDirectoryReady = true; + } + + const FString FileName = FMD5::HashAnsiString(*Pair.Key) + TEXT(".png"); + if (FFileHelper::SaveArrayToFile(PngData, *FPaths::Combine(TextureDirectory, FileName))) + { + ++ExportedCount; + } + } + + UE_LOG(LogLQATool, Log, + TEXT("Exported %d shared texture(s) to %s (%d disk-backed asset(s) skipped, %d total)"), + ExportedCount, *TextureDirectory, SkippedAssetCount, SharedTextureMap.Num()); +} + +FString FLQAExportUtil::FindWBPName(TArray& NameList) +{ + // 默认名称 + FString Name = TEXT("None"); + if (NameList.Num() > 0) + { + Name = NameList[0].ToString(); + } + // 名称中包含 "##" 分隔符时, 解析出真正的蓝图名 + if (Name.Contains(TEXT("##"))) + { + FString Left, Right; + // 第一次从头部按 "##" 切分, 取右半部分 + Name.Split(TEXT("##"), &Left, &Right, ESearchCase::IgnoreCase, ESearchDir::FromStart); + Name = Right; + if (Right.Contains(TEXT("##"))) + { + // 右半部分仍含 "##" 时, 再次切分取左半部分 + Name.Split(TEXT("##"), &Left, &Right, ESearchCase::IgnoreCase, ESearchDir::FromStart); + Name = Left; + } + } + return Name; +} + +// ======================================== +// 私有 —— 控件树遍历处理 +// ======================================== + +void FLQAExportUtil::GetAllValidNodes( + const TSharedPtr& Node, TArray>& OutValidNodes) +{ + if (!Node.IsValid()) + { + return; + } + + const ELQAWidgetType NodeType = Node->GetNodeType(); + // 遇到 UserWidget 类型即作为一个 “有效根节点” 收集 (不再深入其内部) + if (NodeType == ELQAWidgetType::LQA_UserWidget) + { + // 若命中排除前缀则跳过 + if (ContainsExcludedPrefix(Node->WidgetName.ToString())) + { + return; + } + OutValidNodes.Add(Node); + return; + } + + // 非 UserWidget 则递归处理其子节点 + for (const auto& Child : Node->GetChildNodes()) + { + GetAllValidNodes(Child, OutValidNodes); + } +} + +void FLQAExportUtil::GetAllTextNodes( + const TSharedPtr& Node, TArray>& OutValidTextNodes) +{ + if (!Node.IsValid()) + { + return; + } + + // 若当前节点属于文本类型, 则序列化为 JSON 并收集 + if (LQAExportConstants::AllTextTypes.Contains(Node->GetNodeType())) + { + TMap EmptyTextureMap; // 文本节点无需纹理数据, 传入空映射 + const TSharedPtr TextNodeJson = FWidget2JsonFactory::Widget2Json(Node, EmptyTextureMap, false); + if (TextNodeJson.IsValid()) + { + OutValidTextNodes.Add(TextNodeJson); + } + return; + } + + // 非文本节点则递归处理其子节点 + for (const auto& Child : Node->GetChildNodes()) + { + GetAllTextNodes(Child, OutValidTextNodes); + } +} + +// ======================================== +// 私有 —— 节点序列化 +// ======================================== + +TSharedPtr FLQAExportUtil::DumpNodeInfo(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, const FName ParentName) +{ + if (!Node.IsValid()) + { + return nullptr; + } + + TSharedPtr NodeJson; + const ELQAWidgetType NodeType = Node->GetNodeType(); + + // 根据节点类型分发到不同的处理函数 + if (NodeType == ELQAWidgetType::LQA_UserWidget) + { + NodeJson = HandleUserWidget(Node, SharedTextureMap, NameList, bNeedObjectData, ParentName); + } + else if (NodeType == ELQAWidgetType::LQA_Undefined) + { + NodeJson = HandleUndefinedWidget(Node, SharedTextureMap, NameList, bNeedObjectData, ParentName); + } + else + { + NodeJson = HandleOtherWidget(Node, SharedTextureMap, NameList, bNeedObjectData, ParentName); + } + + return NodeJson.IsValid() ? NodeJson : nullptr; +} + +TSharedPtr FLQAExportUtil::HandleUserWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, const FName ParentName) +{ + // 以当前控件名作为子节点的父名称 + const FName ChildParentName = MakeChildParentName(Node->WidgetName, ParentName); + + // 序列化控件本身与其插槽 (Slot) 信息 + const TSharedPtr NewObject = FWidget2JsonFactory::Widget2Json(Node, SharedTextureMap, bNeedObjectData); + const TSharedPtr NewSlotObject = FSlot2JsonFactory::Slot2Json(Node); + + // 记录父控件名称 + NewObject->SetStringField(TEXT("ParentWidget"), ChildParentName.ToString()); + + // 若有有效插槽信息则写入 Slot / SlotType, 否则记录被排除的插槽类型 + if (NewSlotObject->Values.Num() > 0) + { + if (NewSlotObject->HasField(TEXT("Slot"))) + { + NewObject->SetObjectField(TEXT("Slot"), NewSlotObject->GetObjectField(TEXT("Slot"))); + } + if (NewSlotObject->HasField(TEXT("SlotType"))) + { + NewObject->SetStringField(TEXT("SlotType"), NewSlotObject->GetStringField(TEXT("SlotType"))); + } + } + else + { + NewObject->SetStringField(TEXT("ExcludedSlotType"), Node->BaseSlotType); + } + + // 递归处理子节点 + ProcessChildNodes(Node, NewObject, SharedTextureMap, NameList, bNeedObjectData, ChildParentName); + return NewObject; +} + +TSharedPtr FLQAExportUtil::HandleUndefinedWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, const FName ParentName) +{ + // 以当前控件名作为子节点的父名称 + const FName ChildParentName = MakeChildParentName(Node->WidgetName, ParentName); + + // 对未定义类型控件做专门的序列化 + TSharedPtr NewObject = FWidget2JsonFactory::UndefineWidget2Json(Node); + + // 记录父控件名称 + if (!ChildParentName.IsNone()) + { + NewObject->SetStringField(TEXT("ParentWidget"), ChildParentName.ToString()); + } + + // 先递归处理子节点 + ProcessChildNodes(Node, NewObject, SharedTextureMap, NameList, bNeedObjectData, ChildParentName); + + // 若没有任何子节点, 则该未定义节点无意义, 返回空 + if (NewObject->GetArrayField(TEXT("ChildNodes")).Num() == 0) + { + return nullptr; + } + + // 写入插槽信息 (同上逻辑) + const TSharedPtr NewSlotObject = FSlot2JsonFactory::Slot2Json(Node); + if (NewSlotObject->Values.Num() > 0) + { + if (NewSlotObject->HasField(TEXT("Slot"))) + { + NewObject->SetObjectField(TEXT("Slot"), NewSlotObject->GetObjectField(TEXT("Slot"))); + } + if (NewSlotObject->HasField(TEXT("SlotType"))) + { + NewObject->SetStringField(TEXT("SlotType"), NewSlotObject->GetStringField(TEXT("SlotType"))); + } + } + else + { + NewObject->SetStringField(TEXT("ExcludedSlotType"), Node->BaseSlotType); + } + + return NewObject; +} + +TSharedPtr FLQAExportUtil::HandleOtherWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, const FName ParentName) +{ + // 序列化普通控件与其插槽 + const TSharedPtr NewObject = FWidget2JsonFactory::Widget2Json(Node, SharedTextureMap, bNeedObjectData); + const TSharedPtr NewSlotObject = FSlot2JsonFactory::Slot2Json(Node); + + // 记录父控件名称, 并将其加入名称列表 (用于后续解析蓝图名) + if (!ParentName.IsNone()) + { + NewObject->SetStringField(TEXT("ParentWidget"), ParentName.ToString()); + NameList.Emplace(ParentName); + } + + // 写入插槽信息 + if (NewSlotObject->Values.Num() > 0) + { + NewObject->SetObjectField(TEXT("Slot"), NewSlotObject->GetObjectField(TEXT("Slot"))); + NewObject->SetStringField(TEXT("SlotType"), NewSlotObject->GetStringField(TEXT("SlotType"))); + } + else + { + NewObject->SetStringField(TEXT("ExcludedSlotType"), Node->BaseSlotType); + } + + // 递归处理子节点 + ProcessChildNodes(Node, NewObject, SharedTextureMap, NameList, bNeedObjectData, ParentName); + return NewObject; +} + +void FLQAExportUtil::ProcessChildNodes(const TSharedPtr& Node, + const TSharedPtr& ParentJsonObject, TMap& SharedTextureMap, + TArray& NameList, bool bNeedObjectData, const FName ParentName) +{ + TArray> ChildNodesJson; + + // 遍历所有子节点并递归序列化 + for (const auto& Child : Node->GetChildNodes()) + { + TSharedPtr ChildJson = + DumpNodeInfo(Child, SharedTextureMap, NameList, bNeedObjectData, ParentName); + if (ChildJson.IsValid()) + { + if (!Child->SlotName.IsNone()) + { + ChildJson->SetStringField(TEXT("SlotName"), Child->SlotName.ToString()); + } + ChildNodesJson.Add(MakeShareable(new FJsonValueObject(ChildJson))); + } + } + + // 将子节点数组写入父对象的 "ChildNodes" 字段 + ParentJsonObject->SetArrayField(TEXT("ChildNodes"), ChildNodesJson); +} + +// ======================================== +// 私有 —— 截图相关函数 +// ======================================== + +FString FLQAExportUtil::GetScreenShotFileName(const FDateTime& CurDate, const FString& WBPName) +{ + // 以时间戳 + 蓝图名拼接截图目录与 PNG 文件名 + const FString CurTime = CurDate.ToString(TEXT("%Y_%m_%d_%H_%M_%S")); + return FPaths::Combine( + GetSnapshotDirectory(CurDate, WBPName), *FString::Printf(TEXT("LQA_ScreenShot_%s_%s.png"), *WBPName, *CurTime)); +} + +void FLQAExportUtil::StartScreenshotSequence(const FString& InScreenshotPath) +{ + // 记录前景截图路径 + ScreenshotPath = InScreenshotPath; + // 基于前景路径推导背景截图路径 (追加 "_BG" 后缀) + const FString Dir = FPaths::GetPath(InScreenshotPath); + const FString BaseName = FPaths::GetBaseFilename(InScreenshotPath, true); + BgScreenshotPath = FPaths::Combine(Dir, BaseName + TEXT("_BG.png")); + + // 先请求前景截图 (包含 UI) + FScreenshotRequest::RequestScreenshot(ScreenshotPath, true, false); + + // 延迟一段时间后再请求背景截图 (不含 UI), 用于对比/抠图 + FTimerHandle TimerHandle; + GWorld->GetTimerManager().SetTimer( + TimerHandle, []() { FScreenshotRequest::RequestScreenshot(BgScreenshotPath, false, false); }, + LQAExportConstants::SCREENSHOT_DELAY_SECONDS, false); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAJsonUtils.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAJsonUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1634b89534369ef83a319534d9011faff60c0a52 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQAJsonUtils.cpp @@ -0,0 +1,317 @@ +#include "Utils/LQAJsonUtils.h" + +#include "JsonObjectConverter.h" // 提供 FJsonObjectConverter::UPropertyToJsonValue 等反射转换接口 + +// 定义 (实现) 头文件中声明的日志分类, 整个工程中只能定义一次 +DEFINE_LOG_CATEGORY(LogLQAToolJsonUtils); + +// ========== 私有辅助方法 ========== + +// 校验传入的 JSON 对象指针是否有效, 作为各方法的统一前置检查 +bool FLQAJsonUtils::IsValidJsonObject(const TSharedPtr& JsonObject) +{ + if (!JsonObject.IsValid()) + { + // 指针无效 (空指针), 记录警告并返回 false + UE_LOG(LogLQAToolJsonUtils, Warning, TEXT("Invalid JSON object passed")); + return false; + } + return true; +} + +// 判断 JSON 对象是否有效, 并且包含指定的字段 Key +bool FLQAJsonUtils::HasValidField(const TSharedPtr& JsonObject, const FString& Key) +{ + // 先校验对象本身有效性 + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + // 再检查字段是否存在 + if (!JsonObject->HasField(Key)) + { + // 字段不存在属正常情况, 用 Verbose 级别记录 (默认不输出, 便于调试时开启) + UE_LOG(LogLQAToolJsonUtils, Verbose, TEXT("JSON object does not have field: %s"), *Key); + return false; + } + + return true; +} + +// ========== 序列化方法 ========== + +// 将 FVector2D 写入 JSON: 生成一个含 X、Y 两个数值字段的子对象 +bool FLQAJsonUtils::SerializeToJson( + const TSharedPtr& JsonObject, const FString& Key, const FVector2D& Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + // 创建子对象并分别写入 X / Y 分量 + TSharedPtr VectorObject = MakeShareable(new FJsonObject); + VectorObject->SetNumberField(TEXT("X"), Value.X); + VectorObject->SetNumberField(TEXT("Y"), Value.Y); + + // 以 Key 作为字段名, 将子对象挂到父 JSON 对象上 + JsonObject->SetObjectField(Key, VectorObject); + return true; +} + +// 将 bool 值写入 JSON +bool FLQAJsonUtils::SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, bool Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + JsonObject->SetBoolField(Key, Value); + return true; +} + +// 将 int32 写入 JSON (JSON 内部统一以 number 存储) +bool FLQAJsonUtils::SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, int32 Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + JsonObject->SetNumberField(Key, Value); + return true; +} + +// 将 float 写入 JSON +bool FLQAJsonUtils::SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, float Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + JsonObject->SetNumberField(Key, Value); + return true; +} + +// 将 double 写入 JSON +bool FLQAJsonUtils::SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, double Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + JsonObject->SetNumberField(Key, Value); + return true; +} + +// 将 FString 写入 JSON +bool FLQAJsonUtils::SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, const FString& Value) +{ + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + JsonObject->SetStringField(Key, Value); + return true; +} + +// 通过反射遍历 UObject 的所有属性, 并逐一序列化到 JSON 对象中 +bool FLQAJsonUtils::SerializeObjectToJson(const TSharedPtr& JsonObject, UObject* Object) +{ + // 校验待序列化的对象非空 + if (!Object) + { + UE_LOG(LogLQAToolJsonUtils, Warning, TEXT("Null object passed for serialization")); + return false; + } + + // 校验目标 JSON 对象有效 + if (!IsValidJsonObject(JsonObject)) + { + return false; + } + + // 定义序列化时需要跳过的属性标记 (这些属性不应被持久化): + // 实例化引用、瞬态、复制瞬态、仅编辑器、已废弃、显式跳过序列化、 + // 非 PIE 复制瞬态、文本导出瞬态等 + constexpr int64 SkipFlags = CPF_InstancedReference | CPF_Transient | CPF_DuplicateTransient | CPF_EditorOnly | + CPF_Deprecated | CPF_SkipSerialization | CPF_NonPIEDuplicateTransient | + CPF_TextExportTransient; + + // 使用属性迭代器遍历该类 (含父类) 的全部反射属性 + for (TFieldIterator PropertyIterator(Object->GetClass()); PropertyIterator; ++PropertyIterator) + { + FProperty* Property = *PropertyIterator; + // 属性为空, 或命中任一跳过标记, 则忽略该属性 + if (!Property || Property->HasAnyPropertyFlags(static_cast(SkipFlags))) + { + continue; + } + + // 取得该属性在对象实例中的内存地址 (值指针) + const void* PropertyValue = Property->ContainerPtrToValuePtr(Object); + if (!PropertyValue) + { + continue; + } + + // 借助 UE 的转换器, 将单个属性值转换为对应的 JSON 值 + TSharedPtr JsonValue = + FJsonObjectConverter::UPropertyToJsonValue(Property, PropertyValue, 0, SkipFlags, nullptr); + + // 转换成功则以属性名作为字段名写入 + if (JsonValue.IsValid()) + { + JsonObject->SetField(Property->GetName(), JsonValue); + } + } + + // 清理空键, 保持输出整洁 + RemoveEmptyKeysRecursively(JsonObject); + // 只要至少写入了一个字段即视为成功 + return JsonObject->Values.Num() > 0; +} + +// ========== 反序列化方法 ========== + +// 从 JSON 读取 FVector2D; 字段缺失或无效时返回默认值 +FVector2D FLQAJsonUtils::DeserializeVector2D( + const TSharedPtr& JsonObject, const FString& Key, const FVector2D& DefaultValue) +{ + // 字段不存在则直接返回默认值 + if (!HasValidField(JsonObject, Key)) + { + return DefaultValue; + } + + // 取出该字段对应的子对象 (期望为 { X, Y } 结构) + const TSharedPtr VectorObject = JsonObject->GetObjectField(Key); + if (!IsValidJsonObject(VectorObject)) + { + return DefaultValue; + } + + // 以默认值为基础, 逐分量覆盖; 缺失的分量保留默认值 + FVector2D Result = DefaultValue; + if (VectorObject->HasField(TEXT("X"))) + { + Result.X = VectorObject->GetNumberField(TEXT("X")); + } + if (VectorObject->HasField(TEXT("Y"))) + { + Result.Y = VectorObject->GetNumberField(TEXT("Y")); + } + + return Result; +} + +// 从 JSON 读取 bool, 缺失时返回默认值 (三元运算符简写) +bool FLQAJsonUtils::DeserializeBool(const TSharedPtr& JsonObject, const FString& Key, bool DefaultValue) +{ + return HasValidField(JsonObject, Key) ? JsonObject->GetBoolField(Key) : DefaultValue; +} + +// 从 JSON 读取 int32 (JSON 数值为 double, 需显式转换), 缺失时返回默认值 +int32 FLQAJsonUtils::DeserializeInt32(const TSharedPtr& JsonObject, const FString& Key, int32 DefaultValue) +{ + return HasValidField(JsonObject, Key) ? static_cast(JsonObject->GetNumberField(Key)) : DefaultValue; +} + +// 从 JSON 读取 float (同样由 double 转换), 缺失时返回默认值 +float FLQAJsonUtils::DeserializeFloat(const TSharedPtr& JsonObject, const FString& Key, float DefaultValue) +{ + return HasValidField(JsonObject, Key) ? static_cast(JsonObject->GetNumberField(Key)) : DefaultValue; +} + +// 从 JSON 读取字符串, 缺失时返回默认值 +FString FLQAJsonUtils::DeserializeString( + const TSharedPtr& JsonObject, const FString& Key, const FString& DefaultValue) +{ + return HasValidField(JsonObject, Key) ? JsonObject->GetStringField(Key) : DefaultValue; +} + +// ========== 通用工具方法 ========== + +// 递归移除 JSON 中键名为空字符串的字段, 并深入嵌套对象/数组继续清理 +void FLQAJsonUtils::RemoveEmptyKeysRecursively(TSharedPtr JsonObject) +{ + if (!IsValidJsonObject(JsonObject)) + { + return; + } + + // 先收集需要删除的空键, 再统一删除 (避免遍历容器时边遍历边删除导致迭代器失效) + // 注意: UE5.8+ 中 FJsonObject::Values 的键类型由 FString 变更为 UE::FSharedString + // 这里按引擎版本拆分实现, 使每个分支都使用其目标引擎上原生、经过充分测试的 API: + // - UE4 : 键为 FString, 直接使用 TMap::Remove(const FString&) + // - UE5+: 键为 UE::FSharedString, 改用 FSetElementId 删除, 避免直接依赖键类型 +#if ENGINE_MAJOR_VERSION < 5 + // —— UE4 分支: 按键值收集并删除 —— + TArray EmptyKeys; + for (const auto& Pair : JsonObject->Values) + { + if (Pair.Key.IsEmpty()) + { + EmptyKeys.Add(Pair.Key); + } + } + + for (const FString& Key : EmptyKeys) + { + JsonObject->Values.Remove(Key); + } +#else + // —— UE5+ 分支: 按元素 Id 收集并删除 —— + TArray EmptyKeyIds; + for (auto It = JsonObject->Values.CreateConstIterator(); It; ++It) + { + if (It->Key.IsEmpty()) + { + EmptyKeyIds.Add(It.GetId()); + } + } + + for (const FSetElementId Id : EmptyKeyIds) + { + JsonObject->Values.Remove(Id); + } +#endif + + // 递归处理剩余字段中的嵌套对象与数组 + for (const auto& Pair : JsonObject->Values) + { + const TSharedPtr& Value = Pair.Value; + if (!Value.IsValid()) + { + continue; + } + + switch (Value->Type) + { + case EJson::Object: + // 嵌套对象: 直接递归清理 + RemoveEmptyKeysRecursively(Value->AsObject()); + break; + + case EJson::Array: + // 数组: 遍历元素, 仅对其中的对象元素递归清理 + for (const TSharedPtr& ArrayElement : Value->AsArray()) + { + if (ArrayElement.IsValid() && ArrayElement->Type == EJson::Object) + { + RemoveEmptyKeysRecursively(ArrayElement->AsObject()); + } + } + break; + + default: + // 其它基础类型无需处理 + break; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQATextureUtil.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQATextureUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5a75452bcc4674f5cf5018e0e73df15c0d054bf --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Utils/LQATextureUtil.cpp @@ -0,0 +1,363 @@ +#include "Utils/LQATextureUtil.h" + +#include "Engine/Texture.h" // UTexture 基类 +#include "Engine/Texture2D.h" +#include "Engine/TextureCube.h" // 立方体贴图 +#include "Engine/TextureRenderTarget2D.h" // 渲染目标纹理 +#include "ImageUtils.h" +#include "Materials/MaterialInstanceConstant.h" // 常量材质实例 +#include "Materials/MaterialInstanceDynamic.h" // 动态材质实例 +#include "PaperSprite.h" // Paper2D 精灵 +#include "Utils/LQAJsonUtils.h" // LQA 自定义 JSON 工具 +#include "LQABase.h" // 日志分类 LogLQATool 声明 + +// ============ JSON 字段名常量定义 (与头文件声明一一对应) ============ +const FString FLQATextureUtil::JsonFields::NAME = TEXT("name"); +const FString FLQATextureUtil::JsonFields::NAME_MD5 = TEXT("nameMD5"); +const FString FLQATextureUtil::JsonFields::TYPE = TEXT("type"); +const FString FLQATextureUtil::JsonFields::SPRITE_NAME = TEXT("spritename"); +const FString FLQATextureUtil::JsonFields::SPRITE_NAME_MD5 = TEXT("spritenameMD5"); +const FString FLQATextureUtil::JsonFields::MATERIAL_PATH = TEXT("MaterialPath"); +const FString FLQATextureUtil::JsonFields::SCALAR_PARAMS = TEXT("ScalarParameters"); +const FString FLQATextureUtil::JsonFields::VECTOR_PARAMS = TEXT("VectorParameters"); +const FString FLQATextureUtil::JsonFields::TEXTURE_PARAMS = TEXT("TextureParameters"); + +// 颜色分量字段名常量定义 +const FString FLQATextureUtil::JsonFields::ColorFields::R = TEXT("R"); +const FString FLQATextureUtil::JsonFields::ColorFields::G = TEXT("G"); +const FString FLQATextureUtil::JsonFields::ColorFields::B = TEXT("B"); +const FString FLQATextureUtil::JsonFields::ColorFields::A = TEXT("A"); + +// 纹理类型名称常量定义 +const FString FLQATextureUtil::TextureTypes::PAPER_SPRITE = TEXT("PaperSprite"); +const FString FLQATextureUtil::TextureTypes::TEXTURE_2D = TEXT("Texture2D"); +const FString FLQATextureUtil::TextureTypes::TEXTURE_CUBE = TEXT("TextureCube"); + +// =================== JSON 转换工具 =================== + +// 将线性颜色 (FLinearColor) 转换为含 R/G/B/A 四个数值字段的 JSON 对象 +TSharedPtr FLQATextureUtil::LinearColorToJson(const FLinearColor& Color) +{ + TSharedPtr JsonColor = MakeShared(); + JsonColor->SetNumberField(JsonFields::ColorFields::R, Color.R); // 写入红色分量 + JsonColor->SetNumberField(JsonFields::ColorFields::G, Color.G); // 写入绿色分量 + JsonColor->SetNumberField(JsonFields::ColorFields::B, Color.B); // 写入蓝色分量 + JsonColor->SetNumberField(JsonFields::ColorFields::A, Color.A); // 写入透明度分量 + return JsonColor; +} + +// 写入纹理的公共元数据: 全名、类型、全名的 MD5, 并缓存到共享纹理表 +void FLQATextureUtil::WriteTextureMetadata(UTexture* Texture, const TSharedPtr& JsonRoot, + const FString& TextureType, TMap& SharedTextureMap) +{ + // 入参校验: 纹理或 JSON 根对象无效则直接返回 + if (!Texture || !JsonRoot.IsValid()) + { + return; + } + + // 获取纹理全名 (包含类型前缀与完整路径) + const FString TextureName = Texture->GetFullName(); + JsonRoot->SetStringField(JsonFields::NAME, TextureName); // 写入名称 + JsonRoot->SetStringField(JsonFields::TYPE, TextureType); // 写入类型 + + // 计算名称的 MD5, 便于在导出数据中做唯一标识/校验 + const FString NameMD5 = FMD5::HashAnsiString(*TextureName); + JsonRoot->SetStringField(JsonFields::NAME_MD5, NameMD5); + + // 将纹理加入共享缓存, 供外部复用 (避免重复处理同一纹理) + SharedTextureMap.Add(TextureName, Texture); +} + +// 写入 Sprite 专有数据: Sprite 名称及其 MD5 +void FLQATextureUtil::WriteSpriteData(const TSharedPtr& JsonRoot, const FString& SpriteName) +{ + // 入参校验: JSON 根对象无效则直接返回 + if (!JsonRoot.IsValid()) + { + return; + } + + JsonRoot->SetStringField(JsonFields::SPRITE_NAME, SpriteName); // 写入 Sprite 名称 + + // 计算 Sprite 名称的 MD5 并写入 + const FString SpriteNameMD5 = FMD5::HashAnsiString(*SpriteName); + JsonRoot->SetStringField(JsonFields::SPRITE_NAME_MD5, SpriteNameMD5); +} + +bool FLQATextureUtil::GetTexture2DData(UTexture2D* Texture2D, TArray& OutData) +{ + OutData.Reset(); + + // Missing texture, or no mip data available to read from + if (!Texture2D) + { + return false; + } + + // UE 5.0+ made PlatformData private, must go through GetPlatformData() +#if ENGINE_MAJOR_VERSION >= 5 + FTexturePlatformData* PlatformData = Texture2D->GetPlatformData(); +#else + FTexturePlatformData* PlatformData = Texture2D->PlatformData; +#endif + if (!PlatformData || PlatformData->Mips.Num() == 0) + { + return false; + } + + const int32 Width = Texture2D->GetSizeX(); + const int32 Height = Texture2D->GetSizeY(); + if (Width <= 0 || Height <= 0) + { + return false; + } + + // Back up compression/sRGB settings so they can be restored after reading + const TextureCompressionSettings OldCompressionSettings = Texture2D->CompressionSettings; + const bool OldSRGB = Texture2D->SRGB; + // Disable compression and sRGB to get untouched raw pixels + Texture2D->CompressionSettings = TextureCompressionSettings::TC_VectorDisplacementmap; + Texture2D->SRGB = false; + Texture2D->UpdateResource(); + + const int64 PixelCount = static_cast(Width) * Height; + TArray Colors; + Colors.SetNumUninitialized(static_cast(PixelCount)); + + // Read mip 0 pixels + FTexture2DMipMap& TextureMip = PlatformData->Mips[0]; + void* TextureData = TextureMip.BulkData.Lock(LOCK_READ_WRITE); + if (TextureData) + { + FMemory::Memcpy(Colors.GetData(), TextureData, static_cast(PixelCount * sizeof(FColor))); + } + TextureMip.BulkData.Unlock(); + + // Restore original settings + Texture2D->CompressionSettings = OldCompressionSettings; + Texture2D->SRGB = OldSRGB; + Texture2D->UpdateResource(); + + if (!TextureData) + { + return false; + } + + // Compress raw pixels to PNG + // UE 5.1+ deprecated CompressImageArray in favour of PNGCompressImageArray (requires TArray64) +#if ENGINE_MAJOR_VERSION >= 5 + TArray64 PngData; + FImageUtils::PNGCompressImageArray(Width, Height, Colors, PngData); + if (PngData.Num() == 0) + { + return false; + } + OutData.Append(PngData.GetData(), static_cast(PngData.Num())); +#else + FImageUtils::CompressImageArray(Width, Height, Colors, OutData); +#endif + + return OutData.Num() > 0; +} + +// =================== 材质处理函数 =================== + +// 提取材质实例的标量、向量、纹理三类参数, 整合为一个 JSON 对象 +TSharedPtr FLQATextureUtil::ExtractMaterialParametersToJsonObject(UMaterialInstance* MaterialInstance) +{ + // 入参校验: 材质实例为空则记录警告并返回 nullptr + if (!MaterialInstance) + { + UE_LOG(LogLQATool, Warning, + TEXT("FLQATextureUtil::ExtractMaterialParametersToJsonObject - MaterialInstance is null")); + return nullptr; + } + + TSharedPtr RootObject = MakeShared(); + + // --- 提取标量参数 --- + TSharedPtr ScalarParamsObject = MakeShared(); + TArray ScalarInfos; // 标量参数信息列表 + TArray ScalarGuids; // 对应的 GUID 列表 (此处未使用) + MaterialInstance->GetAllScalarParameterInfo(ScalarInfos, ScalarGuids); + + // 遍历每个标量参数, 取值后写入 JSON (参数名 -> 值) + for (const auto& Info : ScalarInfos) + { + float Value; + if (MaterialInstance->GetScalarParameterValue(Info, Value)) + { + ScalarParamsObject->SetNumberField(Info.Name.ToString(), Value); + } + } + RootObject->SetObjectField(JsonFields::SCALAR_PARAMS, ScalarParamsObject); + + // --- 提取向量参数 --- + TSharedPtr VectorParamsObject = MakeShared(); + TArray VectorInfos; + TArray VectorGuids; + MaterialInstance->GetAllVectorParameterInfo(VectorInfos, VectorGuids); + + // 遍历每个向量参数, 取 FLinearColor 后转为 JSON 子对象写入 + for (const auto& Info : VectorInfos) + { + FLinearColor Value; + if (MaterialInstance->GetVectorParameterValue(Info, Value)) + { + VectorParamsObject->SetObjectField(Info.Name.ToString(), LinearColorToJson(Value)); + } + } + RootObject->SetObjectField(JsonFields::VECTOR_PARAMS, VectorParamsObject); + + // --- 提取纹理参数 --- + TSharedPtr TextureParamsObject = MakeShared(); + TArray TextureInfos; + TArray TextureGuids; + MaterialInstance->GetAllTextureParameterInfo(TextureInfos, TextureGuids); + + // 遍历每个纹理参数, 取纹理资源路径后写入 (参数名 -> 路径) + for (const auto& Info : TextureInfos) + { + UTexture* Texture = nullptr; + if (MaterialInstance->GetTextureParameterValue(Info, Texture) && Texture) + { + const FString Path = Texture->GetPathName(); + TextureParamsObject->SetStringField(Info.Name.ToString(), Path); + } + } + RootObject->SetObjectField(JsonFields::TEXTURE_PARAMS, TextureParamsObject); + + return RootObject; +} + +// 处理材质实例: 在参数 JSON 基础上, 追加基础 (父) 材质的路径 +TSharedPtr FLQATextureUtil::HandleMaterialInstance(UMaterialInstance* MaterialInstance) +{ + // 先提取参数; 若失败则直接返回 nullptr + TSharedPtr ResultObject = ExtractMaterialParametersToJsonObject(MaterialInstance); + if (!ResultObject.IsValid()) + { + return nullptr; + } + + // 获取基础材质 (材质实例最终继承的母材质) + UMaterialInterface* BaseMaterialInterface = MaterialInstance->GetBaseMaterial(); + if (BaseMaterialInterface) + { + const FString MaterialPath = BaseMaterialInterface->GetPathName(); + ResultObject->SetStringField(JsonFields::MATERIAL_PATH, MaterialPath); // 写入基础材质路径 + } + else + { + // 未找到基础材质时记录警告 (不影响已提取的参数) + UE_LOG(LogLQATool, Warning, + TEXT("FLQATextureUtil::HandleMaterialInstance - BaseMaterialInterface not found for %s"), + *MaterialInstance->GetName()); + } + + return ResultObject; +} + +// =================== 纹理处理函数 (按相似逻辑分组) =================== + +// 处理 Paper 精灵: 使用其烘焙纹理写入元数据, 再补充 Sprite 专有数据 +TSharedPtr FLQATextureUtil::HandlePaperSprite( + UPaperSprite* Sprite, TMap& SharedTextureMap) +{ + if (!Sprite) + { + return nullptr; + } + + TSharedPtr JsonObject = MakeShared(); + UTexture* BakedTexture = Sprite->GetBakedTexture(); // 获取精灵烘焙后的纹理 + + // 以 PaperSprite 类型写入纹理公共元数据 + WriteTextureMetadata(BakedTexture, JsonObject, TextureTypes::PAPER_SPRITE, SharedTextureMap); + + // 追加 Sprite 专有数据 (名称及其 MD5) + WriteSpriteData(JsonObject, Sprite->GetName()); + + return JsonObject; +} + +// 处理标准纹理 (Texture2D / RenderTarget2D): 写入纹理公共元数据 +TSharedPtr FLQATextureUtil::HandleStandardTexture( + UTexture* Texture, TMap& SharedTextureMap) +{ + if (!Texture) + { + return nullptr; + } + + TSharedPtr JsonObject = MakeShared(); + WriteTextureMetadata(Texture, JsonObject, TextureTypes::TEXTURE_2D, SharedTextureMap); + return JsonObject; +} + +// 处理立方体贴图: 写入纹理公共元数据 +TSharedPtr FLQATextureUtil::HandleTextureCube(UTextureCube* TextureCube) +{ + if (!TextureCube) + { + return nullptr; + } + + TSharedPtr JsonObject = MakeShared(); + + // 立方体贴图不参与共享纹理缓存, 这里传入一个临时的空 Map 占位 + TMap DummyMap; + WriteTextureMetadata(TextureCube, JsonObject, TextureTypes::TEXTURE_CUBE, DummyMap); + + return JsonObject; +} + +// =================== 主入口 =================== + +// 根据传入对象的实际类型, 分发到对应的处理函数, 返回其 JSON 表示 +TSharedPtr FLQATextureUtil::GetTextureJsonObj( + UObject* TextureObject, TMap& SharedTextureMap) +{ + // 入参校验: 对象为空则记录警告并返回空 JSON 对象 + if (!TextureObject) + { + UE_LOG(LogLQATool, Warning, TEXT("FLQATextureUtil::GetTextureJsonObj - TextureObject is null")); + return MakeShared(); + } + + // 处理材质实例 (动态与常量实例均继承自 UMaterialInstance, 逻辑一致) + if (UMaterialInstance* MaterialInstance = Cast(TextureObject)) + { + return HandleMaterialInstance(MaterialInstance); + } + + // 处理 Paper 精灵 + if (UPaperSprite* Sprite = Cast(TextureObject)) + { + return HandlePaperSprite(Sprite, SharedTextureMap); + } + + // 处理标准纹理 (Texture2D 与 TextureRenderTarget2D 使用相同逻辑) + if (UTexture2D* Texture2D = Cast(TextureObject)) + { + return HandleStandardTexture(Texture2D, SharedTextureMap); + } + + if (UTextureRenderTarget2D* TextureRT = Cast(TextureObject)) + { + return HandleStandardTexture(TextureRT, SharedTextureMap); + } + + // 处理立方体贴图 + if (UTextureCube* TextureCube = Cast(TextureObject)) + { + return HandleTextureCube(TextureCube); + } + + // 未知纹理类型: 记录错误并返回空 JSON 对象 + UE_LOG(LogLQATool, Error, TEXT("FLQATextureUtil::GetTextureJsonObj - Unknown texture type: %s"), + *TextureObject->GetClass()->GetName()); + + return MakeShared(); +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryCommands.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryCommands.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac532aca106d53978bf519952083fd6b9f3dca54 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryCommands.cpp @@ -0,0 +1,114 @@ +// ============================================================================ +// LQAGalleryCommands.cpp +// 功能: 注册并实现控制台命令 "LQA.BuildGallery", 用于在运行时 (PIE/Game) +// 快速构造 LQA 验证画廊控件, 并将其添加到视口, 便于做本地化质量 +// 验证 (LQA, Localization Quality Assurance) +// ============================================================================ + +#include "CoreMinimal.h" // UE 核心基础类型 (FString、TArray 等) +#include "LQABase.h" // 本插件基础定义, 包含日志分类 LogLQATool +#include "Blueprint/UserWidget.h" // UUserWidget 及 CreateWidget 模板 +#include "Engine/World.h" // UWorld 定义, 控件创建需要世界上下文 +#include "HAL/IConsoleManager.h" // 控制台命令管理器与自动注册类 + +// ---------------------------------------------------------------------------- +// 根据引擎版本选择不同的画廊控件实现, 并统一别名为 FLQAGalleryClass, +// 使下方逻辑无需关心具体版本差异 +// ---------------------------------------------------------------------------- +#if ENGINE_MAJOR_VERSION >= 5 +#include "Validation/LQAGalleryWidget_UE5.h" +using FLQAGalleryClass = ULQAGalleryWidget_UE5; // UE5 及以上使用 UE5 版本控件 +#else +#include "Validation/LQAGalleryWidget_UE4.h" +using FLQAGalleryClass = ULQAGalleryWidget_UE4; // UE4 使用 UE4 版本控件 +#endif + +// 使用匿名命名空间, 将回调函数限制在当前编译单元内, 避免符号污染全局 +namespace +{ +/** + * 控制台命令回调: 构造验证画廊并加入视口 + * + * 可选参数 (Args[0], 大小写不敏感): + * (无) 控件区 + 布局区 + * Widgets 仅构造控件区 (文本 / 输入 / 展示 / 动态) + * Layout 仅构造布局区 (也接受 Layouts) + * Bug 仅构造显示性质 BUG 示例区 (也接受 Bugs) + * Composite 全部内容 (画廊为纯 C++ 构建, 无独立 WBP 资产) + * All 全部内容 + * + * @param Args 控制台传入的参数列表 + * @param World 命令执行时的世界上下文 (PIE/Game 下有效) + */ +void BuildGalleryCommand(const TArray& Args, UWorld* World) +{ + // 控件创建依赖有效的 World, 若在编辑器非运行态调用则直接返回并提示 + if (!World) + { + UE_LOG(LogLQATool, Warning, TEXT("[LQA.BuildGallery] Invalid World, run in PIE/Game.")); + return; + } + + // 默认构造控件区与布局区 + bool bWidgets = true; + bool bLayouts = true; + bool bBugs = false; + + // 若带有参数, 则根据第一个参数决定构造范围 + if (Args.Num() > 0) + { + const FString Mode = Args[0].ToLower(); // 统一转小写, 做大小写不敏感匹配 + if (Mode == TEXT("widgets")) + { + bLayouts = false; // 仅控件: 关闭布局 + } + else if (Mode == TEXT("layout") || Mode == TEXT("layouts")) + { + bWidgets = false; // 仅布局: 关闭控件 + } + else if (Mode == TEXT("bug") || Mode == TEXT("bugs")) + { + bWidgets = false; + bLayouts = false; + bBugs = true; + } + else if (Mode == TEXT("composite") || Mode == TEXT("all")) + { + // 画廊为纯 C++ 构建, Composite 与 All 等价 (无独立 WBP 资产) + bWidgets = true; + bLayouts = true; + bBugs = true; + } + } + + // 创建画廊控件实例, 使用 World 作为外部对象 (Outer) 与上下文 + FLQAGalleryClass* Gallery = CreateWidget(World, FLQAGalleryClass::StaticClass()); + if (!Gallery) + { + // 创建失败一般是类未正确加载或内存异常, 记录错误并返回 + UE_LOG(LogLQATool, Error, TEXT("[LQA.BuildGallery] Failed to create gallery widget.")); + return; + } + + // 按照参数标志构建对应内容, 然后以较高的 ZOrder(10000) 添加到视口, + // 确保画廊显示在大多数其他 UI 之上 + Gallery->BuildAll(bWidgets, bLayouts, bBugs); + Gallery->AddToViewport(10000); + + // 输出构建结果日志, 便于确认实际构造了哪些部分 + UE_LOG(LogLQATool, Log, TEXT("[LQA.BuildGallery] Gallery added to viewport (Widgets=%d, Layouts=%d, Bugs=%d)."), + bWidgets ? 1 : 0, bLayouts ? 1 : 0, bBugs ? 1 : 0); +} +} + +// ---------------------------------------------------------------------------- +// 静态全局对象: 在模块加载时自动向控制台注册 "LQA.BuildGallery" 命令, +// 在模块卸载 (对象析构) 时自动注销, 无需手动管理生命周期 +// - 第一个参数: 命令名称 +// - 第二个参数: 帮助说明 (在控制台中可查看) +// - 第三个参数: 绑定到上面的静态回调函数的委托 +// ---------------------------------------------------------------------------- +static FAutoConsoleCommandWithWorldAndArgs GLQABuildGalleryCommand( + TEXT("LQA.BuildGallery"), + TEXT("构造 LQA 验证画廊 (全部常用控件与布局, 纯 C++), 可选参数: Widgets | Layout | Bug | Composite | All"), + FConsoleCommandWithWorldAndArgsDelegate::CreateStatic(&BuildGalleryCommand)); \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidgetItem.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidgetItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f5afd6ae1d5cd2ca003e62bb292456444e9e276 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidgetItem.cpp @@ -0,0 +1,251 @@ +#include "Validation/LQAGalleryWidgetItem.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/HorizontalBox.h" +#include "Components/HorizontalBoxSlot.h" +#include "Components/SizeBox.h" +#include "Components/TextBlock.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Runtime/Launch/Resources/Version.h" +#include "Validation/LQAGalleryWidgetText.h" +#include "Validation/LQAGalleryWidget_UE5.h" + +#if ENGINE_MAJOR_VERSION < 5 && WITH_EDITOR +#include "Engine/Blueprint.h" +#endif + +namespace +{ +void MarkEntryClassCooked() +{ + UClass* EntryClass = ULQAGalleryEntryWidget::StaticClass(); + EntryClass->bCooked = true; + +#if ENGINE_MAJOR_VERSION < 5 && WITH_EDITOR + if (!EntryClass->ClassGeneratedBy) + { + EntryClass->ClassGeneratedBy = NewObject(GetTransientPackage(), NAME_None, RF_Transient); + } +#endif +} +} + +// =========================================================================== +// 列表派生类:构造期指定 EntryWidgetClass(该成员为 protected,无 setter) +// =========================================================================== + +ULQAGalleryListView::ULQAGalleryListView(const FObjectInitializer& ObjectInitializer) + : Super(ObjectInitializer) +{ + MarkEntryClassCooked(); + EntryWidgetClass = ULQAGalleryEntryWidget::StaticClass(); +} + +ULQAGalleryTileView::ULQAGalleryTileView(const FObjectInitializer& ObjectInitializer) + : Super(ObjectInitializer) +{ + MarkEntryClassCooked(); + EntryWidgetClass = ULQAGalleryEntryWidget::StaticClass(); + + // 瓷砖尺寸:宽度需容纳条目文本,避免相邻 tile 内容溢出重叠 + SetEntryWidth(200.f); + SetEntryHeight(28.f); +} + +ULQAGalleryTreeView::ULQAGalleryTreeView(const FObjectInitializer& ObjectInitializer) + : Super(ObjectInitializer) +{ + MarkEntryClassCooked(); + EntryWidgetClass = ULQAGalleryEntryWidget::StaticClass(); +} + +// =========================================================================== +// 列表条目 +// =========================================================================== + +TSharedRef ULQAGalleryEntryWidget::RebuildWidget() +{ + // 纯 C++ 构造条目内容:单个 TextBlock + if (WidgetTree && !WidgetTree->RootWidget) + { + EntryLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Entry_Label")); + EntryLabel->SetText(LQAGalleryWidgetText::ContentTextBlock()); + WidgetTree->RootWidget = EntryLabel; + } + + return Super::RebuildWidget(); +} + +void ULQAGalleryEntryWidget::NativeOnListItemObjectSet(UObject* ListItemObject) +{ + IUserObjectListEntry::NativeOnListItemObjectSet(ListItemObject); + + if (!EntryLabel) + { + return; + } + + // 文本来源:列表项数据(由画廊构造时用 LQAGalleryText 常量填充) + const ULQAGalleryListItem* ListItem = Cast(ListItemObject); + EntryLabel->SetText(ListItem ? ListItem->Label : LQAGalleryWidgetText::ContentTextBlock()); + EntryLabel->SetAutoWrapText(ListItem ? ListItem->bAutoWrapText : true); + EntryLabel->SetColorAndOpacity(FSlateColor(ListItem ? ListItem->TextColor : FLinearColor::White)); +} + +// =========================================================================== +// 动态条目框条目 +// =========================================================================== + +TSharedRef ULQAGalleryDynamicEntryWidget::RebuildWidget() +{ + // 纯 C++ 构造条目内容:单个 TextBlock + if (WidgetTree && !WidgetTree->RootWidget) + { + EntryLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), + TEXT("Gallery_DynamicEntry_Label")); + EntryLabel->SetText(PendingText.IsEmpty() ? LQAGalleryWidgetText::DynamicEntryBoxText(1) : PendingText); + WidgetTree->RootWidget = EntryLabel; + } + + return Super::RebuildWidget(); +} + +void ULQAGalleryDynamicEntryWidget::SetEntryText(const FText& InText) +{ + PendingText = InText; + + if (EntryLabel) + { + EntryLabel->SetText(InText); + } +} + +// =========================================================================== +// 菜单内容 +// =========================================================================== + +UButton* ULQAGalleryMenuWidget::MakeMenuButton(UPanelWidget* Parent, const FText& Label, bool bFirst) +{ + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass()); + UTextBlock* ButtonText = WidgetTree->ConstructWidget(UTextBlock::StaticClass()); + ButtonText->SetText(Label); + ButtonText->SetColorAndOpacity(FSlateColor(FLQAGalleryTheme::ControlText())); + Button->AddChild(ButtonText); + + if (Parent) + { + if (UVerticalBoxSlot* ButtonSlot = Cast(Parent->AddChild(Button))) + { + ButtonSlot->SetPadding(FMargin(0.f, 2.f)); + } + } + + if (bFirst) + { + Button->OnClicked.AddDynamic(this, &ULQAGalleryMenuWidget::OnFirstButtonClicked); + FirstButton = Button; + } + else + { + Button->OnClicked.AddDynamic(this, &ULQAGalleryMenuWidget::OnSecondButtonClicked); + SecondButton = Button; + } + + return Button; +} + +TSharedRef ULQAGalleryMenuWidget::RebuildWidget() +{ + if (WidgetTree && !WidgetTree->RootWidget) + { + MenuBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("Gallery_Menu_Box")); + + MenuLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Menu_Label")); + MenuLabel->SetText(LQAGalleryWidgetText::ContentTextBlock()); + MenuLabel->SetColorAndOpacity(FSlateColor(FLQAGalleryTheme::Dark().TextOnPanel)); + if (UVerticalBoxSlot* LabelSlot = MenuBox->AddChildToVerticalBox(MenuLabel)) + { + LabelSlot->SetPadding(FMargin(4.f, 2.f)); + } + + MakeMenuButton(MenuBox, LQAGalleryWidgetText::ContentButton(), true); + MakeMenuButton(MenuBox, LQAGalleryWidgetText::ContentButton(), false); + + // 菜单弹层固定深色底,不随主题切换 + UBorder* PopupBorder = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Menu_Border")); + PopupBorder->SetBrushColor(FLQAGalleryTheme::Dark().BarBackground); + PopupBorder->SetPadding(FMargin(4.f)); + PopupBorder->SetContent(MenuBox); + + WidgetTree->RootWidget = PopupBorder; + } + + return Super::RebuildWidget(); +} + +void ULQAGalleryMenuWidget::OnFirstButtonClicked() +{ + UE_LOG(LogTemp, Verbose, TEXT("[LQAGallery] Menu button 1 clicked.")); +} + +void ULQAGalleryMenuWidget::OnSecondButtonClicked() +{ + UE_LOG(LogTemp, Verbose, TEXT("[LQAGallery] Menu button 2 clicked.")); +} + +// =========================================================================== +// 嵌套子 UserWidget +// =========================================================================== + +TSharedRef ULQAGalleryChildWidget::RebuildWidget() +{ + if (WidgetTree && !WidgetTree->RootWidget) + { + ChildBox = WidgetTree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("Gallery_Child_Box")); + + // 图标:纯色块(固定 24x24),避免引入贴图资产 + USizeBox* IconSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + IconSizeBox->SetMinDesiredWidth(24.f); + IconSizeBox->SetMinDesiredHeight(24.f); + ChildIcon = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Child_Icon")); + ChildIcon->SetBrushColor(IconColor); + IconSizeBox->AddChild(ChildIcon); + + if (UHorizontalBoxSlot* IconSlot = ChildBox->AddChildToHorizontalBox(IconSizeBox)) + { + IconSlot->SetPadding(FMargin(0.f, 0.f, 8.f, 0.f)); + IconSlot->SetVerticalAlignment(VAlign_Center); + } + + ChildLabel = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Child_Label")); + ChildLabel->SetText(LQAGalleryWidgetText::ContentTextBlock()); + ChildLabel->SetColorAndOpacity(FSlateColor(LabelColor)); + if (UHorizontalBoxSlot* LabelSlot = ChildBox->AddChildToHorizontalBox(ChildLabel)) + { + LabelSlot->SetVerticalAlignment(VAlign_Center); + } + + WidgetTree->RootWidget = ChildBox; + } + + return Super::RebuildWidget(); +} + +void ULQAGalleryChildWidget::SetThemeColors(const FLinearColor& InLabelColor, const FLinearColor& InIconColor) +{ + LabelColor = InLabelColor; + IconColor = InIconColor; + + if (ChildLabel) + { + ChildLabel->SetColorAndOpacity(FSlateColor(LabelColor)); + } + + if (ChildIcon) + { + ChildIcon->SetBrushColor(IconColor); + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE4.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52c044e1ab377b844f2f371c7575c61f232487ce --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE4.cpp @@ -0,0 +1,1408 @@ +#include "Validation/LQAGalleryWidget_UE4.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/BackgroundBlur.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/CheckBox.h" +#include "Components/CircularThrobber.h" +#include "Components/ComboBoxString.h" +#include "Components/DynamicEntryBox.h" +#include "Components/EditableText.h" +#include "Components/EditableTextBox.h" +#include "Components/ExpandableArea.h" +#include "Components/GridPanel.h" +#include "Components/GridSlot.h" +#include "Components/HorizontalBox.h" +#include "Components/HorizontalBoxSlot.h" +#include "Components/Image.h" +#include "Components/InputKeySelector.h" +#include "Components/InvalidationBox.h" +#include "Components/MenuAnchor.h" +#include "Components/MultiLineEditableText.h" +#include "Components/MultiLineEditableTextBox.h" +#include "Components/NamedSlot.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/ProgressBar.h" +#include "Components/RetainerBox.h" +#include "Components/RichTextBlock.h" +#include "Components/SafeZone.h" +#include "Components/ScaleBox.h" +#include "Components/ScrollBar.h" +#include "Components/ScrollBox.h" +#include "Components/SizeBox.h" +#include "Components/Slider.h" +#include "Components/Spacer.h" +#include "Components/SpinBox.h" +#include "Components/TextBlock.h" +#include "Components/Throbber.h" +#include "Components/UniformGridPanel.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Components/WidgetSwitcher.h" +#include "Components/WindowTitleBarArea.h" +#include "Components/WrapBox.h" +#include "Engine/DataTable.h" +#include "Engine/Font.h" +#include "Engine/Texture2D.h" +#include "Engine/World.h" +#include "Styling/CoreStyle.h" +#include "Styling/SlateTypes.h" +#include "TextureResource.h" +#include "UObject/UnrealType.h" + +#include "Validation/LQAGalleryWidgetItem.h" +#include "Validation/LQAGalleryWidgetText.h" + +namespace +{ + /** 画廊固定使用的引擎字体(不读项目默认字体配置) */ + FSlateFontInfo UE4GetRichTextFont(const TCHAR* Typeface, int32 Size = 24) + { + const FName TypefaceName(Typeface); + if (UFont* EngineFont = LoadObject(nullptr, TEXT("/Engine/EngineFonts/Roboto.Roboto"))) + { + return FSlateFontInfo(EngineFont, Size, TypefaceName); + } + + return FCoreStyle::GetDefaultFontStyle(TypefaceName, Size); + } + + FSlateFontInfo UE4GetEditableTextFont(const FSlateFontInfo& InSourceFont) + { + FSlateFontInfo FontInfo = UE4GetRichTextFont(TEXT("Regular")); + FontInfo.CompositeFont = InSourceFont.CompositeFont; + return FontInfo; + } + + /** 向富文本样式表追加一行样式 */ + void UE4AddRichTextStyleRow(UDataTable* Table, const FName& RowName, const FSlateFontInfo& Font, const FLinearColor& Color) + { + FRichTextStyleRow Row; + Row.TextStyle.Font = Font; + Row.TextStyle.ColorAndOpacity = FSlateColor(Color); + Table->AddRow(RowName, Row); + } +} + + +// =========================================================================== +// 生命周期与总装 +// =========================================================================== + +TSharedRef ULQAGalleryWidget_UE4::RebuildWidget() +{ + if (!RootPanel && WidgetTree) + { + BuildAll(true, true, false); + } + return Super::RebuildWidget(); +} + +void ULQAGalleryWidget_UE4::BuildAll(bool bIncludeWidgets, bool bIncludeLayouts, bool bIncludeBugs) +{ + if (!WidgetTree) + { + return; + } + + // ---- 根画布 ---- + UCanvasPanel* Canvas = WidgetTree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("GalleryRoot")); + WidgetTree->RootWidget = Canvas; + RootPanel = Canvas; + + // ---- 页面背景:全屏纯色,不参与命中测试 ---- + UBorder* Background = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Background")); + Background->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + Canvas->AddChild(Background); + if (UCanvasPanelSlot* BackgroundSlot = Cast(Background->Slot)) + { + BackgroundSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 1.f)); + BackgroundSlot->SetOffsets(FMargin(0.f)); + BackgroundSlot->SetZOrder(0); + } + BackgroundBorder = Background; + + // ---- 交互控制条:固定顶部,不随滚动 ---- + UWidget* ControlBar = BuildControlBar(); + if (ControlBar) + { + Canvas->AddChild(ControlBar); + if (UCanvasPanelSlot* ControlSlot = Cast(ControlBar->Slot)) + { + ControlSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 0.f)); + ControlSlot->SetOffsets(FMargin(8.f, 8.f, 8.f, 0.f)); + ControlSlot->SetAutoSize(true); + ControlSlot->SetZOrder(10); + } + } + + // ---- 滚动内容区(顶部避让控制条)---- + UScrollBox* Scroll = WidgetTree->ConstructWidget(UScrollBox::StaticClass(), TEXT("GalleryScroll")); + GalleryScroll = Scroll; + Canvas->AddChild(Scroll); + if (UCanvasPanelSlot* ScrollSlot = Cast(Scroll->Slot)) + { + ScrollSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 1.f)); + ScrollSlot->SetOffsets(FMargin(20.f, ControlBarHeight, 20.f, 20.f)); + ScrollSlot->SetZOrder(1); + } + + UVerticalBox* VBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("GalleryVBox")); + Scroll->AddChild(VBox); + ContentBox = VBox; + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::Title())); + + if (bIncludeWidgets) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionText())); + VBox->AddChildToVerticalBox(BuildTextSection()); + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionInput())); + VBox->AddChildToVerticalBox(BuildInputSection()); + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionPresent())); + VBox->AddChildToVerticalBox(BuildDisplaySection()); + } + + if (bIncludeLayouts) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionLayout())); + VBox->AddChildToVerticalBox(BuildLayoutSection()); + } + + if (bIncludeBugs) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionBug())); + VBox->AddChildToVerticalBox(BuildBugSection()); + } + + ApplyTheme(); +} + +// =========================================================================== +// 行 / 文本 / 纹理辅助 +// =========================================================================== + +UTextBlock* ULQAGalleryWidget_UE4::MakeTextBlock(const FText& Text, FName WidgetName, ELQAGalleryTextRole Role) +{ + UTextBlock* TextBlock = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), WidgetName); + TextBlock->SetText(Text); + RegisterThemedText(TextBlock, Role); + return TextBlock; +} + +void ULQAGalleryWidget_UE4::RegisterThemedText(UTextBlock* TextBlock, ELQAGalleryTextRole Role) +{ + if (!TextBlock) + { + return; + } + + switch (Role) + { + case ELQAGalleryTextRole::Secondary: SecondaryTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnAccent: OnAccentTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnPanel: OnPanelTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnControl: OnControlTexts.Add(TextBlock); break; + default: PrimaryTexts.Add(TextBlock); break; + } +} + +UWidget* ULQAGalleryWidget_UE4::MakeSectionHeader(const FText& Title) +{ + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetPadding(FMargin(8.f, 4.f)); + + Border->SetContent(MakeTextBlock(Title, NAME_None, ELQAGalleryTextRole::OnAccent)); + HeaderBorders.Add(Border); + return Border; +} + +UWidget* ULQAGalleryWidget_UE4::MakeSizedRow(const FText& Label, UWidget* Content, const FVector2D& Size) +{ + UHorizontalBox* Row = WidgetTree->ConstructWidget(UHorizontalBox::StaticClass()); + + // 标签列:固定宽度(以最长标签 MultiLineEditableTextBox 为准),保证各行内容起点一致; + USizeBox* LabelSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + LabelSizeBox->SetWidthOverride(LabelColumnWidth); + LabelSizeBox->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Secondary)); + + if (UHorizontalBoxSlot* LabelSlot = Row->AddChildToHorizontalBox(LabelSizeBox)) + { + LabelSlot->SetPadding(FMargin(0.f, 4.f, 16.f, 4.f)); + LabelSlot->SetVerticalAlignment(VAlign_Center); + } + + if (!Content) + { + return Row; + } + + // 内容列:用 MinDesired 约束(不用 Override,避免 EditableText / MultiLine 被裁剪) + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + SizeBox->SetMinDesiredWidth(static_cast(Size.X)); + SizeBox->SetMinDesiredHeight(static_cast(Size.Y)); + SizeBox->AddChild(Content); + + if (UHorizontalBoxSlot* ContentSlot = Row->AddChildToHorizontalBox(SizeBox)) + { + ContentSlot->SetPadding(FMargin(0.f, 4.f)); + ContentSlot->SetVerticalAlignment(VAlign_Center); + } + + return Row; +} + +UWidget* ULQAGalleryWidget_UE4::MakeFixedText( + const FText& Text, FName WidgetName, const FVector2D& Size, bool bWrap, float FontSize, UTextBlock** OutTextBlock) +{ + UTextBlock* TextBlock = MakeTextBlock(Text, WidgetName); + TextBlock->SetAutoWrapText(bWrap); + + if (FontSize > 0.f) + { +#if ENGINE_MAJOR_VERSION >= 5 + TextBlock->SetFontSize(FontSize); +#else + // UE4.27 无 SetFontSize,通过改写 FontInfo 达到同样字号效果 + FSlateFontInfo FontInfo = TextBlock->Font; + FontInfo.Size = static_cast(FontSize); + TextBlock->SetFont(FontInfo); +#endif + } + if (OutTextBlock) + { + *OutTextBlock = TextBlock; + } + + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + SizeBox->SetWidthOverride(Size.X); + SizeBox->SetHeightOverride(Size.Y); + SizeBox->AddChild(TextBlock); + return SizeBox; +} + +UWidget* ULQAGalleryWidget_UE4::MakeBugRow(const FText& Label, UWidget* StageContent, const FVector2D& StageSize, + bool bBottomReference, FLinearColor StageColor) +{ + UHorizontalBox* Row = WidgetTree->ConstructWidget(UHorizontalBox::StaticClass()); + + USizeBox* LabelBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + LabelBox->SetWidthOverride(400.f); + LabelBox->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Secondary)); + if (UHorizontalBoxSlot* LabelSlot = Row->AddChildToHorizontalBox(LabelBox)) + { + LabelSlot->SetPadding(FMargin(0.f, 4.f, 32.f, 4.f)); + LabelSlot->SetVerticalAlignment(VAlign_Center); + } + + USizeBox* StageBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + StageBox->SetWidthOverride(StageSize.X); + StageBox->SetHeightOverride(StageSize.Y); + + UBorder* Stage = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Stage->SetPadding(FMargin(0.f)); + + FSlateBrush StageBrush; + StageBrush.DrawAs = ESlateBrushDrawType::Box; + Stage->SetBrush(StageBrush); + Stage->SetBrushColor(StageColor.A > 0.f ? StageColor : Theme.BarBackground); + + UOverlay* StageOverlay = WidgetTree->ConstructWidget(UOverlay::StaticClass()); + if (StageContent) + { + if (UOverlaySlot* ContentSlot = StageOverlay->AddChildToOverlay(StageContent)) + { + ContentSlot->SetHorizontalAlignment(HAlign_Left); + ContentSlot->SetVerticalAlignment(VAlign_Top); + ContentSlot->SetPadding(FMargin(4.f)); + } + } + + auto CreateBottomReference = [this]() + { + UTextBlock* BottomReference = + WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Bug_BottomReference")); + BottomReference->SetText(LQAGalleryWidgetText::BugReferenceBottom()); + BottomReference->SetColorAndOpacity(FSlateColor(FLinearColor(0.62f, 0.64f, 0.69f, 1.f))); + return BottomReference; + }; + + Stage->SetContent(StageOverlay); + StageBox->AddChild(Stage); + + UWidget* StageColumn = StageBox; + if (bBottomReference) + { + UVerticalBox* Column = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + Column->AddChildToVerticalBox(StageBox); + + if (UVerticalBoxSlot* ReferenceSlot = Column->AddChildToVerticalBox(CreateBottomReference())) + { + ReferenceSlot->SetHorizontalAlignment(HAlign_Left); + ReferenceSlot->SetPadding(FMargin(4.f, 6.f, 0.f, 0.f)); + } + + StageColumn = Column; + } + + if (UHorizontalBoxSlot* StageSlot = Row->AddChildToHorizontalBox(StageColumn)) + { + StageSlot->SetPadding(FMargin(0.f, 4.f)); + StageSlot->SetVerticalAlignment(VAlign_Center); + } + + return Row; +} + +UButton* ULQAGalleryWidget_UE4::MakeControlButton(UPanelWidget* Parent, const FText& Label, FName WidgetName) +{ + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), WidgetName); + Button->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Primary)); + + if (Parent) + { + if (UHorizontalBoxSlot* ButtonSlot = Cast(Parent->AddChild(Button))) + { + ButtonSlot->SetPadding(FMargin(0.f, 0.f, 6.f, 0.f)); + } + } + + return Button; +} + +UTexture2D* ULQAGalleryWidget_UE4::CreateSolidTexture(int32 Size, const FColor& Color) +{ + UTexture2D* Texture = UTexture2D::CreateTransient(Size, Size, PF_B8G8R8A8); + if (!Texture) + { + return nullptr; + } + + // UE5 中 PlatformData 已私有化,必须用 GetPlatformData();UE4 保留字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + FTexturePlatformData* PlatformData = Texture->GetPlatformData(); +#else + FTexturePlatformData* PlatformData = Texture->PlatformData; +#endif + if (!PlatformData) + { + return nullptr; + } + + void* Data = PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FColor* Pixels = static_cast(Data); + for (int32 i = 0; i < Size * Size; ++i) + { + Pixels[i] = Color; + } + PlatformData->Mips[0].BulkData.Unlock(); + Texture->UpdateResource(); + return Texture; +} + +// =========================================================================== +// 交互控制条 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildControlBar() +{ + UBorder* Bar = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_ControlBar")); + Bar->SetPadding(FMargin(8.f, 6.f)); + ControlBarBorder = Bar; + + UHorizontalBox* Row = + WidgetTree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("Gallery_ControlBar_Row")); + + // 新增按钮时调用 MakeControlButton() 创建,再 AddDynamic 绑定到本类任一回调中; + // 按钮文本取自 LQAGalleryWidgetText 并需在 LQALocalization 登记。 + MakeControlButton(Row, LQAGalleryWidgetText::CtrlScrollTop(), TEXT("Gallery_Ctrl_ScrollTop")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE4::OnScrollTopClicked); + MakeControlButton(Row, LQAGalleryWidgetText::CtrlScrollBottom(), TEXT("Gallery_Ctrl_ScrollBottom")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE4::OnScrollBottomClicked); + MakeControlButton(Row, LQAGalleryWidgetText::CtrlToggleTheme(), TEXT("Gallery_Ctrl_ToggleTheme")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE4::OnToggleThemeClicked); + + Bar->SetContent(Row); + return Bar; +} + +void ULQAGalleryWidget_UE4::OnSwitchPageClicked() +{ + if (GallerySwitcher) + { + const int32 CurrentIndex = GallerySwitcher->GetActiveWidgetIndex(); + GallerySwitcher->SetActiveWidgetIndex(CurrentIndex == 0 ? 1 : 0); + } +} + +void ULQAGalleryWidget_UE4::OnToggleExpandClicked() +{ + if (GalleryExpandableArea) + { + GalleryExpandableArea->SetIsExpanded(!GalleryExpandableArea->GetIsExpanded()); + } +} + +void ULQAGalleryWidget_UE4::OnSwitchOptionClicked() +{ + const FString FirstOption = LQAGalleryWidgetText::ContentComboBoxString().ToString(); + const FString SecondOption = LQAGalleryWidgetText::ContentButton().ToString(); + + if (GalleryComboBoxString) + { + const FString Current = GalleryComboBoxString->GetSelectedOption(); + GalleryComboBoxString->SetSelectedOption(Current == FirstOption ? SecondOption : FirstOption); + } + + if (UComboBoxString* ComboBoxKeyFallback = Cast(GalleryComboBoxKey)) + { + const FString CurrentKey = ComboBoxKeyFallback->GetSelectedOption(); + ComboBoxKeyFallback->SetSelectedOption(CurrentKey == FirstOption ? SecondOption : FirstOption); + } +} + +void ULQAGalleryWidget_UE4::OnToggleMenuClicked() +{ + if (GalleryMenuAnchor) + { + GalleryMenuAnchor->ToggleOpen(true); + } +} + +void ULQAGalleryWidget_UE4::OnToggleCheckClicked() +{ + if (GalleryCheckBox) + { + GalleryCheckBox->SetIsChecked(!GalleryCheckBox->IsChecked()); + } +} + +void ULQAGalleryWidget_UE4::OnScrollTopClicked() +{ + if (GalleryScroll) + { + GalleryScroll->ScrollToStart(); + } +} + +void ULQAGalleryWidget_UE4::OnScrollBottomClicked() +{ + if (GalleryScroll) + { + GalleryScroll->ScrollToEnd(); + } +} + +void ULQAGalleryWidget_UE4::OnToggleThemeClicked() +{ + bDarkTheme = !bDarkTheme; + Theme = bDarkTheme ? FLQAGalleryTheme::Dark() : FLQAGalleryTheme::Light(); + ApplyTheme(); +} + +void ULQAGalleryWidget_UE4::ApplyTheme() +{ + if (BackgroundBorder) + { + BackgroundBorder->SetBrushColor(Theme.PageBackground); + } + + if (ControlBarBorder) + { + ControlBarBorder->SetBrushColor(Theme.BarBackground); + } + + for (UBorder* Header : HeaderBorders) + { + if (Header) + { + Header->SetBrushColor(Theme.HeaderBackground); + } + } + + for (UTextBlock* Text : PrimaryTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextPrimary)); + } + } + + for (UTextBlock* Text : SecondaryTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextSecondary)); + } + } + + for (UTextBlock* Text : OnAccentTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextOnAccent)); + } + } + + for (UTextBlock* Text : OnPanelTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextOnPanel)); + } + } + + for (UTextBlock* Text : OnControlTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(FLQAGalleryTheme::ControlText())); + } + } + + if (GalleryRichText) + { + GalleryRichText->SetDefaultColorAndOpacity(FSlateColor(Theme.TextPrimary)); + GalleryRichText->SetTextStyleSet(GetRichTextStyleSet()); + } + + if (GalleryEditableText) + { +#if ENGINE_MAJOR_VERSION >= 5 + FEditableTextStyle Style = GalleryEditableText->WidgetStyle; + Style.ColorAndOpacity = FSlateColor(Theme.TextPrimary); + GalleryEditableText->SetWidgetStyle(Style); +#else + GalleryEditableText->WidgetStyle.ColorAndOpacity = FSlateColor(Theme.TextPrimary); +#endif + } + + if (GalleryMultiLineEditableText) + { +#if ENGINE_MAJOR_VERSION >= 5 + FTextBlockStyle Style = GalleryMultiLineEditableText->WidgetStyle; + Style.ColorAndOpacity = FSlateColor(Theme.TextPrimary); + GalleryMultiLineEditableText->SetWidgetStyle(Style); +#else + GalleryMultiLineEditableText->WidgetStyle.ColorAndOpacity = FSlateColor(Theme.TextPrimary); +#endif + } + + if (GalleryEditableTextBox) + { +#if ENGINE_MAJOR_VERSION >= 5 + GalleryEditableTextBox->SetForegroundColor(FLQAGalleryTheme::ControlText()); +#else + GalleryEditableTextBox->WidgetStyle.ForegroundColor = FSlateColor(FLQAGalleryTheme::ControlText()); +#endif + } + + if (GalleryMultiLineEditableTextBox) + { +#if ENGINE_MAJOR_VERSION >= 5 + GalleryMultiLineEditableTextBox->SetForegroundColor(FLQAGalleryTheme::ControlText()); +#else + const FSlateColor MultiLineTextColor(FLQAGalleryTheme::ControlText()); + GalleryMultiLineEditableTextBox->WidgetStyle.SetForegroundColor(MultiLineTextColor); + GalleryMultiLineEditableTextBox->WidgetStyle.SetReadOnlyForegroundColor(MultiLineTextColor); + GalleryMultiLineEditableTextBox->TextStyle.SetColorAndOpacity(FSlateColor::UseForeground()); +#endif + } + + if (GallerySpinBox) + { + GallerySpinBox->SetForegroundColor(FSlateColor(FLQAGalleryTheme::ControlText())); + } + + if (GallerySlider) + { + GallerySlider->SetSliderBarColor(Theme.Divider); + GallerySlider->SetSliderHandleColor(Theme.Accent); + } + + if (GalleryProgressBar) + { + GalleryProgressBar->SetFillColorAndOpacity(Theme.Accent); + } + + for (UCheckBox* CheckBox : GalleryCheckBoxes) + { + if (!CheckBox) + { + continue; + } + +#if ENGINE_MAJOR_VERSION >= 5 + FCheckBoxStyle Style = CheckBox->GetWidgetStyle(); + Style.CheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + Style.UncheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + Style.UndeterminedImage.TintColor = FSlateColor(Theme.TextPrimary); + CheckBox->SetWidgetStyle(Style); +#else + CheckBox->WidgetStyle.CheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + CheckBox->WidgetStyle.UncheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + CheckBox->WidgetStyle.UndeterminedImage.TintColor = FSlateColor(Theme.TextPrimary); +#endif + } + + if (GalleryThrobber) + { +#if ENGINE_MAJOR_VERSION >= 5 + FSlateBrush Brush = GalleryThrobber->GetImage(); + Brush.TintColor = FSlateColor(Theme.TextPrimary); + GalleryThrobber->SetImage(Brush); +#else + GalleryThrobber->Image.TintColor = FSlateColor(Theme.TextPrimary); +#endif + } + + if (GalleryCircularThrobber) + { +#if ENGINE_MAJOR_VERSION >= 5 + FSlateBrush Brush = GalleryCircularThrobber->GetImage(); + Brush.TintColor = FSlateColor(Theme.TextPrimary); + GalleryCircularThrobber->SetImage(Brush); +#else + GalleryCircularThrobber->Image.TintColor = FSlateColor(Theme.TextPrimary); +#endif + } + + for (UListView* View : GalleryListViews) + { + if (!View) + { + continue; + } + + for (UObject* Item : View->GetListItems()) + { + if (ULQAGalleryListItem* ListItem = Cast(Item)) + { + ListItem->TextColor = Theme.TextPrimary; + } + } + + View->RegenerateAllEntries(); + } + + if (GalleryChildWidget) + { + GalleryChildWidget->SetThemeColors(Theme.TextPrimary, Theme.Accent); + } +} + +UDataTable* ULQAGalleryWidget_UE4::GetRichTextStyleSet() +{ + UDataTable*& CachedTable = bDarkTheme ? RichTextStyleDark : RichTextStyleLight; + if (CachedTable) + { + return CachedTable; + } + + UDataTable* Table = NewObject(this); + Table->RowStruct = FRichTextStyleRow::StaticStruct(); + + UE4AddRichTextStyleRow(Table, TEXT("Default"), UE4GetRichTextFont(TEXT("Regular")), Theme.TextPrimary); + UE4AddRichTextStyleRow(Table, TEXT("Name"), UE4GetRichTextFont(TEXT("Bold")), Theme.Highlight); + UE4AddRichTextStyleRow(Table, TEXT("Accent"), UE4GetRichTextFont(TEXT("Bold")), Theme.Accent); + + CachedTable = Table; + return Table; +} + +// =========================================================================== +// 一、文本类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildTextSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + UTextBlock* TextBlock = MakeTextBlock(LQAGalleryWidgetText::TextBlockSample(), TEXT("Gallery_TextBlock")); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTextBlock(), TextBlock, FVector2D(360.f, 24.f))); + + URichTextBlock* RichText = + WidgetTree->ConstructWidget(URichTextBlock::StaticClass(), TEXT("Gallery_RichTextBlock")); + RichText->SetText(LQAGalleryWidgetText::RichTextBlockSample()); + RichText->SetDefaultFont(UE4GetRichTextFont(TEXT("Regular"))); + GalleryRichText = RichText; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelRichTextBlock(), RichText, FVector2D(360.f, 32.f))); + + UEditableText* Editable = + WidgetTree->ConstructWidget(UEditableText::StaticClass(), TEXT("Gallery_EditableText")); + Editable->SetHintText(LQAGalleryWidgetText::HintEditableText()); + Editable->WidgetStyle.SetFont(UE4GetEditableTextFont(Editable->WidgetStyle.Font)); + GalleryEditableText = Editable; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelEditableText(), Editable, FVector2D(240.f, 28.f))); + + UEditableTextBox* EditableBox = + WidgetTree->ConstructWidget(UEditableTextBox::StaticClass(), TEXT("Gallery_EditableTextBox")); + EditableBox->SetHintText(LQAGalleryWidgetText::HintEditableTextBox()); +#if ENGINE_MAJOR_VERSION < 5 + EditableBox->WidgetStyle.SetFont(UE4GetEditableTextFont(EditableBox->WidgetStyle.Font)); +#endif + GalleryEditableTextBox = EditableBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelEditableTextBox(), EditableBox, FVector2D(240.f, 28.f))); + + UMultiLineEditableText* MultiText = WidgetTree->ConstructWidget( + UMultiLineEditableText::StaticClass(), TEXT("Gallery_MultiLineEditableText")); + MultiText->SetText(LQAGalleryWidgetText::MultiLineText()); + GalleryMultiLineEditableText = MultiText; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelMultiLineEditableText(), MultiText, FVector2D(260.f, 64.f))); + + UMultiLineEditableTextBox* MultiBox = WidgetTree->ConstructWidget( + UMultiLineEditableTextBox::StaticClass(), TEXT("Gallery_MultiLineEditableTextBox")); + MultiBox->SetText(LQAGalleryWidgetText::MultiLineTextBox()); + GalleryMultiLineEditableTextBox = MultiBox; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelMultiLineEditableTextBox(), MultiBox, FVector2D(260.f, 64.f))); + + return Box; +} + +// =========================================================================== +// 二、交互 / 输入类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildInputSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // Button + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("Gallery_Button")); + Button->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentButton(), NAME_None, ELQAGalleryTextRole::OnControl)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelButton(), Button, FVector2D(120.f, 28.f))); + + // CheckBox(选中态,供控制条切换) + UCheckBox* CheckBox = WidgetTree->ConstructWidget(UCheckBox::StaticClass(), TEXT("Gallery_CheckBox")); + CheckBox->SetIsChecked(true); + GalleryCheckBox = CheckBox; + GalleryCheckBoxes.Add(CheckBox); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCheckBox(), CheckBox, FVector2D(32.f, 32.f))); + + // CheckBox(未选中 + 禁用态) + UCheckBox* DisabledCheckBox = + WidgetTree->ConstructWidget(UCheckBox::StaticClass(), TEXT("Gallery_CheckBox_Disabled")); + DisabledCheckBox->SetIsChecked(false); + DisabledCheckBox->SetIsEnabled(false); + GalleryCheckBoxes.Add(DisabledCheckBox); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCheckBox(), DisabledCheckBox, FVector2D(32.f, 32.f))); + + // Slider + USlider* Slider = WidgetTree->ConstructWidget(USlider::StaticClass(), TEXT("Gallery_Slider")); + Slider->SetValue(0.5f); + GallerySlider = Slider; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSlider(), Slider, FVector2D(240.f, 20.f))); + + // ProgressBar + UProgressBar* Progress = + WidgetTree->ConstructWidget(UProgressBar::StaticClass(), TEXT("Gallery_ProgressBar")); + Progress->SetPercent(0.6f); + GalleryProgressBar = Progress; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelProgressBar(), Progress, FVector2D(240.f, 18.f))); + + // ComboBoxString + UComboBoxString* ComboBox = WidgetTree->ConstructWidget( + UComboBoxString::StaticClass(), TEXT("Gallery_ComboBoxString")); + ComboBox->AddOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + ComboBox->AddOption(LQAGalleryWidgetText::ContentButton().ToString()); + ComboBox->SetSelectedOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + GalleryComboBoxString = ComboBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelComboBoxString(), ComboBox, FVector2D(240.f, 28.f))); + + // UE4.27 无 UComboBoxKey,用 UComboBoxString 作为 ComboBoxKey 行的等价占位 + UComboBoxString* ComboBoxKeyFallback = WidgetTree->ConstructWidget( + UComboBoxString::StaticClass(), TEXT("Gallery_ComboBoxKey")); + ComboBoxKeyFallback->AddOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + ComboBoxKeyFallback->AddOption(LQAGalleryWidgetText::ContentButton().ToString()); + ComboBoxKeyFallback->SetSelectedOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + GalleryComboBoxKey = ComboBoxKeyFallback; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelComboBoxKey(), ComboBoxKeyFallback, FVector2D(240.f, 28.f))); + + // SpinBox + USpinBox* SpinBox = WidgetTree->ConstructWidget(USpinBox::StaticClass(), TEXT("Gallery_SpinBox")); + SpinBox->SetValue(42.f); + GallerySpinBox = SpinBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSpinBox(), SpinBox, FVector2D(140.f, 28.f))); + + // InputKeySelector + UInputKeySelector* KeySelector = WidgetTree->ConstructWidget( + UInputKeySelector::StaticClass(), TEXT("Gallery_InputKeySelector")); + KeySelector->SetKeySelectionText(LQAGalleryWidgetText::ContentKeySelection()); + KeySelector->SetNoKeySpecifiedText(LQAGalleryWidgetText::ContentNoKeySpecified()); + { + // UE5 起 TextStyle / WidgetStyle 的直接访问被弃用, 改用 getter/setter; + // UE4 仍只有公开成员, 这里按引擎版本分支, 保证两边都能编译且观感一致。 +#if ENGINE_MAJOR_VERSION >= 5 + // TextStyle 的类型是 FTextBlockStyle (不是 FSlateFontInfo); + // WidgetStyle 的 getter/setter 为 GetButtonStyle / SetButtonStyle。 + FTextBlockStyle KeyTextStyle = KeySelector->GetTextStyle(); + FSlateFontInfo KeyFont = UE4GetRichTextFont(TEXT("Bold")); + KeyFont.CompositeFont = KeyTextStyle.Font.CompositeFont; + KeyTextStyle.SetFont(KeyFont); + KeyTextStyle.SetColorAndOpacity(FSlateColor(FLinearColor(0.f, 1.f, 1.f))); + KeySelector->SetTextStyle(KeyTextStyle); + + FButtonStyle KeyStyle = KeySelector->GetButtonStyle(); + KeyStyle.SetNormalPadding(FMargin(12.f, 1.5f)); + KeyStyle.SetPressedPadding(FMargin(12.f, 1.5f)); + KeySelector->SetButtonStyle(KeyStyle); +#else + FSlateFontInfo KeyFont = UE4GetRichTextFont(TEXT("Bold")); + KeyFont.CompositeFont = KeySelector->TextStyle.Font.CompositeFont; + KeySelector->TextStyle.SetFont(KeyFont); + + FButtonStyle KeyStyle = KeySelector->WidgetStyle; + KeyStyle.SetNormalPadding(FMargin(12.f, 1.5f)); + KeyStyle.SetPressedPadding(FMargin(12.f, 1.5f)); + KeySelector->WidgetStyle = KeyStyle; + KeySelector->TextStyle.SetColorAndOpacity(FSlateColor(FLinearColor(0.f, 1.f, 1.f))); +#endif + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelInputKeySelector(), KeySelector, FVector2D(240.f, 28.f))); + + // MenuAnchor(菜单内容取自 ULQAGalleryMenuWidget) + UMenuAnchor* MenuAnchor = + WidgetTree->ConstructWidget(UMenuAnchor::StaticClass(), TEXT("Gallery_MenuAnchor")); + MenuAnchor->SetContent(MakeTextBlock(LQAGalleryWidgetText::ContentMenuAnchorAnchor())); + MenuAnchor->MenuClass = ULQAGalleryMenuWidget::StaticClass(); + MenuAnchor->SetPlacement(MenuPlacement_BelowAnchor); + GalleryMenuAnchor = MenuAnchor; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelMenuAnchor(), MenuAnchor, FVector2D(240.f, 28.f))); + + // ScrollBar(UMG 层不可指定方向,使用默认水平方向) + UScrollBar* ScrollBar = WidgetTree->ConstructWidget(UScrollBar::StaticClass(), TEXT("Gallery_ScrollBar")); + ScrollBar->SetState(0.3f, 0.4f); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelScrollBar(), ScrollBar, FVector2D(120.f, 16.f))); + + return Box; +} + +// =========================================================================== +// 三、展示类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildDisplaySection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // Image + UImage* Image = WidgetTree->ConstructWidget(UImage::StaticClass(), TEXT("Gallery_Image")); + if (UTexture2D* Texture = CreateSolidTexture(64, FColor(80, 160, 220, 255))) + { + FSlateBrush Brush; + Brush.SetResourceObject(Texture); + Brush.ImageSize = FVector2D(64.f, 64.f); + Image->SetBrush(Brush); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelImage(), Image, FVector2D(64.f, 64.f))); + + // Throbber / CircularThrobber + UThrobber* Throbber = WidgetTree->ConstructWidget(UThrobber::StaticClass(), TEXT("Gallery_Throbber")); + GalleryThrobber = Throbber; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelThrobber(), Throbber, FVector2D(48.f, 48.f))); + + UCircularThrobber* Circular = WidgetTree->ConstructWidget( + UCircularThrobber::StaticClass(), TEXT("Gallery_CircularThrobber")); + GalleryCircularThrobber = Circular; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCircularThrobber(), Circular, FVector2D(48.f, 48.f))); + + // Spacer(无视觉表现,仅占位) + USpacer* Spacer = WidgetTree->ConstructWidget(USpacer::StaticClass(), TEXT("Gallery_Spacer")); + Spacer->SetSize(FVector2D(40.f, 20.f)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSpacer(), Spacer, FVector2D(40.f, 20.f))); + + // Border + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Border")); + Border->SetBrushColor(FLinearColor(0.2f, 0.2f, 0.2f, 1.f)); + Border->SetPadding(FMargin(10.f)); + Border->SetContent(MakeTextBlock(LQAGalleryWidgetText::BorderContent(), NAME_None, ELQAGalleryTextRole::OnPanel)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelBorder(), Border, FVector2D(240.f, 40.f))); + + // BackgroundBlur + UBackgroundBlur* BackgroundBlur = WidgetTree->ConstructWidget( + UBackgroundBlur::StaticClass(), TEXT("Gallery_BackgroundBlur")); + { + UBorder* BlurContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + BlurContent->SetBrushColor(FLinearColor(0.3f, 0.3f, 0.3f, 1.f)); + BlurContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnPanel)); + BackgroundBlur->SetContent(BlurContent); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelBackgroundBlur(), BackgroundBlur, FVector2D(240.f, 80.f))); + + // RetainerBox + URetainerBox* RetainerBox = WidgetTree->ConstructWidget( + URetainerBox::StaticClass(), TEXT("Gallery_RetainerBox")); + { + UBorder* RetainerContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + RetainerContent->SetBrushColor(FLinearColor(0.25f, 0.25f, 0.35f, 1.f)); + RetainerContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnPanel)); + RetainerBox->SetContent(RetainerContent); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelRetainerBox(), RetainerBox, FVector2D(240.f, 80.f))); + + // ListView:3 条 + { + ULQAGalleryListView* ListView = WidgetTree->ConstructWidget( + ULQAGalleryListView::StaticClass(), TEXT("Gallery_ListView")); + GalleryListViews.Add(ListView); + for (int32 Index = 1; Index <= 3; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::ListViewText(Index); + ListView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelListView(), ListView, FVector2D(240.f, 120.f))); + } + + // TileView:2 条(tile 宽度已加大,条目过多会导致内容溢出重叠) + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_TileView")); + GalleryListViews.Add(TileView); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::TileViewText(Index); + TileView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTileView(), TileView, FVector2D(240.f, 80.f))); + } + + // TreeView:3 条 + { + ULQAGalleryTreeView* TreeView = WidgetTree->ConstructWidget( + ULQAGalleryTreeView::StaticClass(), TEXT("Gallery_TreeView")); + GalleryListViews.Add(TreeView); + for (int32 Index = 1; Index <= 3; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::TreeViewText(Index); + TreeView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTreeView(), TreeView, FVector2D(240.f, 120.f))); + } + + // DynamicEntryBox:3 条(条目为 C++ UserWidget,文本取自 LQAGalleryWidgetText) + { + ULQAGalleryDynamicEntryWidget::StaticClass()->bCooked = true; + + UDynamicEntryBox* DynamicEntryBox = WidgetTree->ConstructWidget( + UDynamicEntryBox::StaticClass(), TEXT("Gallery_DynamicEntryBox")); + for (int32 Index = 1; Index <= 3; ++Index) + { + if (ULQAGalleryDynamicEntryWidget* Entry = + DynamicEntryBox->CreateEntry(ULQAGalleryDynamicEntryWidget::StaticClass())) + { + Entry->SetEntryText(LQAGalleryWidgetText::DynamicEntryBoxText(Index)); + } + } + Box->AddChildToVerticalBox(MakeSizedRow( + LQAGalleryWidgetText::LabelDynamicEntryBox(), DynamicEntryBox, FVector2D(240.f, 90.f))); + } + + // 嵌套子 UserWidget(SObjectWidget) + { + USizeBox* ChildSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + ChildSizeBox->SetMinDesiredWidth(240.f); + ChildSizeBox->SetMinDesiredHeight(60.f); + + if (UWorld* World = GetWorld()) + { + if (ULQAGalleryChildWidget* Child = CreateWidget( + World, ULQAGalleryChildWidget::StaticClass(), TEXT("Gallery_ChildWidget"))) + { + GalleryChildWidget = Child; + ChildSizeBox->AddChild(Child); + } + } + + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelUserWidget(), ChildSizeBox, FVector2D(240.f, 60.f))); + } + + return Box; +} + +// =========================================================================== +// 四、布局容器 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildLayoutSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // CanvasPanel(独立示例行) + { + UCanvasPanel* Canvas = WidgetTree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("Gallery_CanvasPanel")); + UTextBlock* CanvasText = MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock()); + Canvas->AddChild(CanvasText); + if (UCanvasPanelSlot* CanvasItemSlot = Cast(CanvasText->Slot)) + { + CanvasItemSlot->SetAnchors(FAnchors(0.f, 0.f)); + CanvasItemSlot->SetOffsets(FMargin(0.f, 0.f, 120.f, 24.f)); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCanvasPanel(), Canvas, FVector2D(240.f, 60.f))); + } + + // ScrollBox(独立示例行) + { + UScrollBox* InnerScroll = + WidgetTree->ConstructWidget(UScrollBox::StaticClass(), TEXT("Gallery_ScrollBox")); + for (int32 Index = 0; Index < 3; ++Index) + { + InnerScroll->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentHorizontal(Index))); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelScrollBox(), InnerScroll, FVector2D(240.f, 60.f))); + } + + // VerticalBox(独立示例行) + { + UVerticalBox* InnerVertical = + WidgetTree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("Gallery_VerticalBox")); + InnerVertical->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock())); + InnerVertical->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelVerticalBox(), InnerVertical, FVector2D(240.f, 60.f))); + } + + // HorizontalBox + { + UHorizontalBox* HBox = + WidgetTree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("Gallery_HorizontalBox")); + for (int32 Index = 0; Index < 3; ++Index) + { + UTextBlock* Item = MakeTextBlock(LQAGalleryWidgetText::ContentHorizontal(Index)); + if (UHorizontalBoxSlot* ItemSlot = HBox->AddChildToHorizontalBox(Item)) + { + ItemSlot->SetPadding(FMargin(6.f, 0.f)); + } + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelHorizontalBox(), HBox, FVector2D(240.f, 60.f))); + } + + // GridPanel(补子项间距) + { + UGridPanel* Grid = WidgetTree->ConstructWidget(UGridPanel::StaticClass(), TEXT("Gallery_GridPanel")); + for (int32 RowIndex = 0; RowIndex < 2; ++RowIndex) + { + for (int32 ColumnIndex = 0; ColumnIndex < 2; ++ColumnIndex) + { + UTextBlock* Item = MakeTextBlock(LQAGalleryWidgetText::ContentGrid(RowIndex, ColumnIndex)); + if (UGridSlot* GridItemSlot = Grid->AddChildToGrid(Item, RowIndex, ColumnIndex)) + { + GridItemSlot->SetPadding(FMargin(4.f)); + } + } + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelGridPanel(), Grid, FVector2D(240.f, 60.f))); + } + + // UniformGridPanel(补槽位间距) + { + UUniformGridPanel* UniformGrid = WidgetTree->ConstructWidget( + UUniformGridPanel::StaticClass(), TEXT("Gallery_UniformGridPanel")); + UniformGrid->SetSlotPadding(FMargin(4.f)); + for (int32 Index = 0; Index < 4; ++Index) + { + UniformGrid->AddChildToUniformGrid( + MakeTextBlock(LQAGalleryWidgetText::ContentUniform(Index)), Index / 2, Index % 2); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelUniformGridPanel(), UniformGrid, FVector2D(240.f, 60.f))); + } + + // Overlay + { + UOverlay* Overlay = WidgetTree->ConstructWidget(UOverlay::StaticClass(), TEXT("Gallery_Overlay")); + UBorder* OverlayBackground = WidgetTree->ConstructWidget(UBorder::StaticClass()); + OverlayBackground->SetBrushColor(FLinearColor(0.3f, 0.3f, 0.3f, 1.f)); + if (UOverlaySlot* BackgroundSlot = Overlay->AddChildToOverlay(OverlayBackground)) + { + BackgroundSlot->SetPadding(FMargin(0.f)); + } + if (UOverlaySlot* ForegroundSlot = Overlay->AddChildToOverlay( + MakeTextBlock(LQAGalleryWidgetText::OverlayStack(), NAME_None, ELQAGalleryTextRole::OnPanel))) + { + ForegroundSlot->SetPadding(FMargin(6.f)); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelOverlay(), Overlay, FVector2D(240.f, 60.f))); + } + + // WrapBox(补内部间距) + { + UWrapBox* WrapBox = WidgetTree->ConstructWidget(UWrapBox::StaticClass(), TEXT("Gallery_WrapBox")); + WrapBox->SetInnerSlotPadding(FVector2D(6.f, 4.f)); + for (int32 Index = 0; Index < 6; ++Index) + { + WrapBox->AddChildToWrapBox(MakeTextBlock(LQAGalleryWidgetText::ContentWrap(Index))); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelWrapBox(), WrapBox, FVector2D(240.f, 60.f))); + } + + // SizeBox + { + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass(), TEXT("Gallery_SizeBox")); + SizeBox->SetWidthOverride(120.f); + SizeBox->SetHeightOverride(40.f); + UBorder* Inner = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Inner->SetBrushColor(FLinearColor(0.4f, 0.2f, 0.2f, 1.f)); + SizeBox->AddChild(Inner); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSizeBox(), SizeBox, FVector2D(120.f, 40.f))); + } + + // NamedSlot(Slate 层为 SBox,采集侧以 WidgetClass 细分) + { + USizeBox* NamedSlotSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + NamedSlotSizeBox->SetMinDesiredWidth(120.f); + NamedSlotSizeBox->SetMinDesiredHeight(40.f); + UNamedSlot* NamedSlot = + WidgetTree->ConstructWidget(UNamedSlot::StaticClass(), TEXT("Gallery_NamedSlot")); + NamedSlot->AddChild(MakeTextBlock(LQAGalleryWidgetText::LabelNamedSlot())); + NamedSlotSizeBox->AddChild(NamedSlot); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelNamedSlot(), NamedSlotSizeBox, FVector2D(120.f, 40.f))); + } + + // ScaleBox + { + UScaleBox* ScaleBox = WidgetTree->ConstructWidget(UScaleBox::StaticClass(), TEXT("Gallery_ScaleBox")); + ScaleBox->SetStretch(EStretch::ScaleToFit); + ScaleBox->AddChild(MakeTextBlock(LQAGalleryWidgetText::ScaleBoxContent())); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelScaleBox(), ScaleBox, FVector2D(240.f, 90.f))); + } + + // SafeZone + { + USafeZone* SafeZone = WidgetTree->ConstructWidget(USafeZone::StaticClass(), TEXT("Gallery_SafeZone")); + SafeZone->AddChild(MakeTextBlock(LQAGalleryWidgetText::SafeZoneContent())); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSafeZone(), SafeZone, FVector2D(240.f, 60.f))); + } + + // WidgetSwitcher(两页等高,供控制条切页) + { + UWidgetSwitcher* Switcher = WidgetTree->ConstructWidget( + UWidgetSwitcher::StaticClass(), TEXT("Gallery_WidgetSwitcher")); + Switcher->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentPage0())); + Switcher->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentPage1())); + Switcher->SetActiveWidgetIndex(0); + GallerySwitcher = Switcher; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelWidgetSwitcher(), Switcher, FVector2D(240.f, 60.f))); + } + + // InvalidationBox + { + UInvalidationBox* InvalidationBox = WidgetTree->ConstructWidget( + UInvalidationBox::StaticClass(), TEXT("Gallery_InvalidationBox")); + UBorder* InvalidationContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + InvalidationContent->SetBrushColor(FLinearColor(0.25f, 0.3f, 0.25f, 1.f)); + InvalidationContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentInvalidationBox(), NAME_None, ELQAGalleryTextRole::OnPanel)); + InvalidationBox->SetContent(InvalidationContent); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelInvalidationBox(), InvalidationBox, FVector2D(240.f, 60.f))); + } + + // WindowTitleBarArea + { + UWindowTitleBarArea* TitleBarArea = WidgetTree->ConstructWidget( + UWindowTitleBarArea::StaticClass(), TEXT("Gallery_WindowTitleBarArea")); + TitleBarArea->SetContent(MakeTextBlock(LQAGalleryWidgetText::ContentWindowTitleBarArea())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelWindowTitleBarArea(), TitleBarArea, FVector2D(240.f, 40.f))); + } + + // ExpandableArea(Header / Body 均用 C++ 构造;初始展开便于采集内容) + { + UExpandableArea* ExpandableArea = WidgetTree->ConstructWidget( + UExpandableArea::StaticClass(), TEXT("Gallery_ExpandableArea")); + ExpandableArea->SetContentForSlot( + FName(TEXT("Header")), MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnControl)); + + UVerticalBox* BodyBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + BodyBox->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock())); + BodyBox->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + ExpandableArea->SetContentForSlot(FName(TEXT("Body")), BodyBox); + ExpandableArea->SetIsExpanded(true); + GalleryExpandableArea = ExpandableArea; + + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelExpandableArea(), ExpandableArea, FVector2D(280.f, 120.f))); + } + + return Box; +} + +// =========================================================================== +// 五、显示性质 BUG 示例 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE4::BuildBugSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + auto AddBugRow = [Box](UWidget* Row, float ExtraSpacing = 0.f) + { + if (UVerticalBoxSlot* RowSlot = Box->AddChildToVerticalBox(Row)) + { + RowSlot->SetPadding(FMargin(0.f, 24.f + ExtraSpacing, 0.f, 24.f + ExtraSpacing)); + } + }; + + // BUG-01:不换行文本超出固定宽度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugOverflowSingleLine(), + TEXT("Gallery_Bug_01_Text"), FVector2D(160.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug01(), Stage, FVector2D(240.f, 32.f))); + } + + // BUG-02:自动换行后行数超出固定高度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugOverflowMultiLine(), + TEXT("Gallery_Bug_02_Text"), FVector2D(200.f, 40.f), true, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug02(), Stage, FVector2D(240.f, 64.f)), 16.f); + } + + // BUG-03:字号超过固定高度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugFontSize(), + TEXT("Gallery_Bug_03_Text"), FVector2D(120.f, 24.f), false, 36.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug03(), Stage, FVector2D(240.f, 40.f)), 16.f); + } + + // BUG-04:按钮内文本超出按钮宽度 + { + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("Gallery_Bug_04_Button")); + UTextBlock* ButtonText = MakeTextBlock( + LQAGalleryWidgetText::BugButtonOverflow(), TEXT("Gallery_Bug_04_Text"), ELQAGalleryTextRole::OnControl); + ButtonText->SetAutoWrapText(false); + Button->AddChild(ButtonText); + + USizeBox* ButtonBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + ButtonBox->SetWidthOverride(120.f); + ButtonBox->SetHeightOverride(28.f); + ButtonBox->AddChild(Button); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug04(), ButtonBox, FVector2D(160.f, 32.f))); + } + + // BUG-05:行高压缩导致同一文本节点内行间重叠 + { + UTextBlock* TextBlock = nullptr; + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugLineHeight(), + TEXT("Gallery_Bug_05_Text"), FVector2D(200.f, 40.f), true, 0.f, &TextBlock); + if (TextBlock) + { + if (FFloatProperty* LineHeightProperty = CastField( + UTextBlock::StaticClass()->FindPropertyByName(TEXT("LineHeightPercentage")))) + { + LineHeightProperty->SetPropertyValue_InContainer(TextBlock, 0.3f); + } + } + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug05(), Stage, FVector2D(240.f, 64.f))); + } + + // BUG-06:文本颜色与舞台底色相同 + { + const FLinearColor HiddenColor = FLQAGalleryTheme::Dark().BarBackground; + UTextBlock* HiddenText = + WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Bug_06_Text")); + HiddenText->SetText(LQAGalleryWidgetText::BugInvisible()); + HiddenText->SetAutoWrapText(false); + HiddenText->SetColorAndOpacity(FSlateColor(HiddenColor)); + + USizeBox* HiddenBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + HiddenBox->SetWidthOverride(200.f); + HiddenBox->SetHeightOverride(24.f); + HiddenBox->AddChild(HiddenText); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug06(), HiddenBox, FVector2D(240.f, 48.f), true, HiddenColor)); + } + + // BUG-07:文本超出控件边界后被硬截断 + { + UTextBlock* ClipText = nullptr; + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugTruncate(), + TEXT("Gallery_Bug_07_Text"), FVector2D(200.f, 24.f), false, 0.f, &ClipText); + if (ClipText) + { + ClipText->SetClipping(EWidgetClipping::ClipToBounds); + } + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug07(), Stage, FVector2D(240.f, 28.f))); + } + + // BUG-08:TileView 条目高度小于文本行高,相邻条目重叠 + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_Bug_08_TileView")); + TileView->SetEntryHeight(8.f); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::BugTileViewItem(Index); + TileView->AddItem(Item); + } + + USizeBox* TileViewBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + TileViewBox->SetWidthOverride(240.f); + TileViewBox->SetHeightOverride(80.f); + TileViewBox->AddChild(TileView); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug08(), TileViewBox, FVector2D(240.f, 80.f))); + } + + // BUG-09:TileView 条目文本不换行,跨条目溢出 + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_Bug_09_TileView")); + TileView->SetEntryWidth(120.f); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = Index == 1 ? LQAGalleryWidgetText::BugTileViewOverflow() + : LQAGalleryWidgetText::BugTileViewItem(2); + Item->bAutoWrapText = false; + TileView->AddItem(Item); + } + + USizeBox* TileViewBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + TileViewBox->SetWidthOverride(240.f); + TileViewBox->SetHeightOverride(80.f); + TileViewBox->AddChild(TileView); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug09(), TileViewBox, FVector2D(240.f, 80.f))); + } + + // BUG-10:无 Key 文本直接显示原始 Key + { + UWidget* Stage = MakeFixedText( + LQAGalleryWidgetText::BugNoKey(), TEXT("Gallery_Bug_10_Text"), FVector2D(400.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug10(), Stage, FVector2D(460.f, 40.f))); + } + + // BUG-11:文本有 Key 但没有译文 + { + UWidget* Stage = MakeFixedText( + LQAGalleryWidgetText::BugMissingTranslation(), TEXT("Gallery_Bug_11_Text"), FVector2D(300.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug11(), Stage, FVector2D(380.f, 40.f))); + } + + return Box; +} + + + diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE5.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE5.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fec3eb743544448866d5c0a0d69714dd822d72a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/Validation/LQAGalleryWidget_UE5.cpp @@ -0,0 +1,1388 @@ +#include "Validation/LQAGalleryWidget_UE5.h" + +#include "Blueprint/WidgetTree.h" +#include "Components/BackgroundBlur.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/CheckBox.h" +#include "Components/CircularThrobber.h" +#include "Components/ComboBoxString.h" +#include "Components/DynamicEntryBox.h" +#include "Components/EditableText.h" +#include "Components/EditableTextBox.h" +#include "Components/ExpandableArea.h" +#include "Components/GridPanel.h" +#include "Components/GridSlot.h" +#include "Components/HorizontalBox.h" +#include "Components/HorizontalBoxSlot.h" +#include "Components/Image.h" +#include "Components/InputKeySelector.h" +#include "Components/InvalidationBox.h" +#include "Components/MenuAnchor.h" +#include "Components/MultiLineEditableText.h" +#include "Components/MultiLineEditableTextBox.h" +#include "Components/NamedSlot.h" +#include "Components/Overlay.h" +#include "Components/OverlaySlot.h" +#include "Components/ProgressBar.h" +#include "Components/RetainerBox.h" +#include "Components/RichTextBlock.h" +#include "Components/SafeZone.h" +#include "Components/ScaleBox.h" +#include "Components/ScrollBar.h" +#include "Components/ScrollBox.h" +#include "Components/SizeBox.h" +#include "Components/Slider.h" +#include "Components/Spacer.h" +#include "Components/SpinBox.h" +#include "Components/TextBlock.h" +#include "Components/Throbber.h" +#include "Components/UniformGridPanel.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Components/WidgetSwitcher.h" +#include "Components/WindowTitleBarArea.h" +#include "Components/WrapBox.h" +#include "Engine/DataTable.h" +#include "Engine/Font.h" +#include "Engine/Texture2D.h" +#include "Engine/World.h" +#include "Styling/CoreStyle.h" +#include "Styling/SlateTypes.h" +#include "TextureResource.h" + +#include "Validation/LQAGalleryWidgetItem.h" +#include "Validation/LQAGalleryWidgetText.h" + +#if ENGINE_MAJOR_VERSION >= 5 +#include "Components/ComboBoxKey.h" +#include "Components/PostBufferUpdate.h" +#include "Components/StackBox.h" +#endif + +namespace +{ + /** 画廊 RichText 固定使用的引擎字体(不读项目默认字体配置) */ + FSlateFontInfo GetRichTextFont(const TCHAR* Typeface) + { + const FName TypefaceName(Typeface); + if (UFont* EngineFont = LoadObject(nullptr, TEXT("/Engine/EngineFonts/Roboto.Roboto"))) + { + return FSlateFontInfo(EngineFont, 24.f, TypefaceName); + } + + return FCoreStyle::GetDefaultFontStyle(TypefaceName, 24.f); + } + + /** 向富文本样式表追加一行样式 */ + void AddRichTextStyleRow(UDataTable* Table, const FName& RowName, const FSlateFontInfo& Font, const FLinearColor& Color) + { + FRichTextStyleRow Row; + Row.TextStyle.Font = Font; + Row.TextStyle.ColorAndOpacity = FSlateColor(Color); + Table->AddRow(RowName, Row); + } +} + +// =========================================================================== +// 生命周期与总装 +// =========================================================================== + +TSharedRef ULQAGalleryWidget_UE5::RebuildWidget() +{ + if (!RootPanel && WidgetTree) + { + BuildAll(true, true, false); + } + return Super::RebuildWidget(); +} + +void ULQAGalleryWidget_UE5::BuildAll(bool bIncludeWidgets, bool bIncludeLayouts, bool bIncludeBugs) +{ + if (!WidgetTree) + { + return; + } + + // ---- 根画布 ---- + UCanvasPanel* Canvas = WidgetTree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("GalleryRoot")); + WidgetTree->RootWidget = Canvas; + RootPanel = Canvas; + + // ---- 页面背景:全屏纯色,不参与命中测试 ---- + UBorder* Background = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Background")); + Background->SetVisibility(ESlateVisibility::SelfHitTestInvisible); + Canvas->AddChild(Background); + if (UCanvasPanelSlot* BackgroundSlot = Cast(Background->Slot)) + { + BackgroundSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 1.f)); + BackgroundSlot->SetOffsets(FMargin(0.f)); + BackgroundSlot->SetZOrder(0); + } + BackgroundBorder = Background; + + // ---- 交互控制条:固定顶部,不随滚动 ---- + UWidget* ControlBar = BuildControlBar(); + if (ControlBar) + { + Canvas->AddChild(ControlBar); + if (UCanvasPanelSlot* ControlSlot = Cast(ControlBar->Slot)) + { + ControlSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 0.f)); + ControlSlot->SetOffsets(FMargin(8.f, 8.f, 8.f, 0.f)); + ControlSlot->SetAutoSize(true); + ControlSlot->SetZOrder(10); + } + } + + // ---- 滚动内容区(顶部避让控制条)---- + UScrollBox* Scroll = WidgetTree->ConstructWidget(UScrollBox::StaticClass(), TEXT("GalleryScroll")); + GalleryScroll = Scroll; + Canvas->AddChild(Scroll); + if (UCanvasPanelSlot* ScrollSlot = Cast(Scroll->Slot)) + { + ScrollSlot->SetAnchors(FAnchors(0.f, 0.f, 1.f, 1.f)); + ScrollSlot->SetOffsets(FMargin(20.f, ControlBarHeight, 20.f, 20.f)); + ScrollSlot->SetZOrder(1); + } + + UVerticalBox* VBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("GalleryVBox")); + Scroll->AddChild(VBox); + ContentBox = VBox; + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::Title())); + + if (bIncludeWidgets) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionText())); + VBox->AddChildToVerticalBox(BuildTextSection()); + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionInput())); + VBox->AddChildToVerticalBox(BuildInputSection()); + + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionPresent())); + VBox->AddChildToVerticalBox(BuildDisplaySection()); + } + + if (bIncludeLayouts) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionLayout())); + VBox->AddChildToVerticalBox(BuildLayoutSection()); + } + + if (bIncludeBugs) + { + VBox->AddChildToVerticalBox(MakeSectionHeader(LQAGalleryWidgetText::SectionBug())); + VBox->AddChildToVerticalBox(BuildBugSection()); + } + + ApplyTheme(); +} + +// =========================================================================== +// 行 / 文本 / 纹理辅助 +// =========================================================================== + +UTextBlock* ULQAGalleryWidget_UE5::MakeTextBlock(const FText& Text, FName WidgetName, ELQAGalleryTextRole Role) +{ + UTextBlock* TextBlock = WidgetTree->ConstructWidget(UTextBlock::StaticClass(), WidgetName); + TextBlock->SetText(Text); + RegisterThemedText(TextBlock, Role); + return TextBlock; +} + +void ULQAGalleryWidget_UE5::RegisterThemedText(UTextBlock* TextBlock, ELQAGalleryTextRole Role) +{ + if (!TextBlock) + { + return; + } + + switch (Role) + { + case ELQAGalleryTextRole::Secondary: SecondaryTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnAccent: OnAccentTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnPanel: OnPanelTexts.Add(TextBlock); break; + case ELQAGalleryTextRole::OnControl: OnControlTexts.Add(TextBlock); break; + default: PrimaryTexts.Add(TextBlock); break; + } +} + +UWidget* ULQAGalleryWidget_UE5::MakeSectionHeader(const FText& Title) +{ + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Border->SetPadding(FMargin(8.f, 4.f)); + + Border->SetContent(MakeTextBlock(Title, NAME_None, ELQAGalleryTextRole::OnAccent)); + HeaderBorders.Add(Border); + return Border; +} + +UWidget* ULQAGalleryWidget_UE5::MakeSizedRow(const FText& Label, UWidget* Content, const FVector2D& Size) +{ + UHorizontalBox* Row = WidgetTree->ConstructWidget(UHorizontalBox::StaticClass()); + + // 标签列:固定宽度(以最长标签 MultiLineEditableTextBox 为准),保证各行内容起点一致; + USizeBox* LabelSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + LabelSizeBox->SetWidthOverride(LabelColumnWidth); + LabelSizeBox->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Secondary)); + + if (UHorizontalBoxSlot* LabelSlot = Row->AddChildToHorizontalBox(LabelSizeBox)) + { + LabelSlot->SetPadding(FMargin(0.f, 4.f, 16.f, 4.f)); + LabelSlot->SetVerticalAlignment(VAlign_Center); + } + + if (!Content) + { + return Row; + } + + // 内容列:用 MinDesired 约束(不用 Override,避免 EditableText / MultiLine 被裁剪) + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + SizeBox->SetMinDesiredWidth(static_cast(Size.X)); + SizeBox->SetMinDesiredHeight(static_cast(Size.Y)); + SizeBox->AddChild(Content); + + if (UHorizontalBoxSlot* ContentSlot = Row->AddChildToHorizontalBox(SizeBox)) + { + ContentSlot->SetPadding(FMargin(0.f, 4.f)); + ContentSlot->SetVerticalAlignment(VAlign_Center); + } + + return Row; +} + +UWidget* ULQAGalleryWidget_UE5::MakeFixedText( + const FText& Text, FName WidgetName, const FVector2D& Size, bool bWrap, float FontSize, UTextBlock** OutTextBlock) +{ + UTextBlock* TextBlock = MakeTextBlock(Text, WidgetName); + TextBlock->SetAutoWrapText(bWrap); +#if ENGINE_MAJOR_VERSION >= 5 + TextBlock->SetTextOverflowPolicy(ETextOverflowPolicy::Clip); + + if (bWrap) + { + TextBlock->SetWrapTextAt(Size.X); + } + + if (FontSize > 0.f) + { + TextBlock->SetFontSize(FontSize); + } +#endif + if (OutTextBlock) + { + *OutTextBlock = TextBlock; + } + + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + SizeBox->SetWidthOverride(Size.X); + SizeBox->SetHeightOverride(Size.Y); + SizeBox->AddChild(TextBlock); + return SizeBox; +} + +UWidget* ULQAGalleryWidget_UE5::MakeBugRow(const FText& Label, UWidget* StageContent, const FVector2D& StageSize, + bool bBottomReference, FLinearColor StageColor) +{ + UHorizontalBox* Row = WidgetTree->ConstructWidget(UHorizontalBox::StaticClass()); + + USizeBox* LabelBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + LabelBox->SetWidthOverride(400.f); + LabelBox->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Secondary)); + if (UHorizontalBoxSlot* LabelSlot = Row->AddChildToHorizontalBox(LabelBox)) + { + LabelSlot->SetPadding(FMargin(0.f, 4.f, 32.f, 4.f)); + LabelSlot->SetVerticalAlignment(VAlign_Center); + } + + USizeBox* StageBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + StageBox->SetWidthOverride(StageSize.X); + StageBox->SetHeightOverride(StageSize.Y); + + UBorder* Stage = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Stage->SetPadding(FMargin(0.f)); + + FSlateBrush StageBrush; + StageBrush.DrawAs = ESlateBrushDrawType::Box; +#if ENGINE_MAJOR_VERSION >= 5 + StageBrush.OutlineSettings.Width = 1.5f; + StageBrush.OutlineSettings.Color = FSlateColor(FLinearColor(0.55f, 0.58f, 0.63f, 1.f)); +#endif + Stage->SetBrush(StageBrush); + Stage->SetBrushColor(StageColor.A > 0.f ? StageColor : Theme.BarBackground); + + UOverlay* StageOverlay = WidgetTree->ConstructWidget(UOverlay::StaticClass()); + if (StageContent) + { + if (UOverlaySlot* ContentSlot = StageOverlay->AddChildToOverlay(StageContent)) + { + ContentSlot->SetHorizontalAlignment(HAlign_Left); + ContentSlot->SetVerticalAlignment(VAlign_Top); + ContentSlot->SetPadding(FMargin(4.f)); + } + } + + auto CreateBottomReference = [this]() + { + UTextBlock* BottomReference = + WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Bug_BottomReference")); + BottomReference->SetText(LQAGalleryWidgetText::BugReferenceBottom()); + BottomReference->SetColorAndOpacity(FSlateColor(FLinearColor(0.62f, 0.64f, 0.69f, 1.f))); + return BottomReference; + }; + + Stage->SetContent(StageOverlay); + StageBox->AddChild(Stage); + + UWidget* StageColumn = StageBox; + if (bBottomReference) + { + UVerticalBox* Column = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + Column->AddChildToVerticalBox(StageBox); + + if (UVerticalBoxSlot* ReferenceSlot = Column->AddChildToVerticalBox(CreateBottomReference())) + { + ReferenceSlot->SetHorizontalAlignment(HAlign_Left); + ReferenceSlot->SetPadding(FMargin(4.f, 6.f, 0.f, 0.f)); + } + + StageColumn = Column; + } + + if (UHorizontalBoxSlot* StageSlot = Row->AddChildToHorizontalBox(StageColumn)) + { + StageSlot->SetPadding(FMargin(0.f, 4.f)); + StageSlot->SetVerticalAlignment(VAlign_Center); + } + + return Row; +} + +UButton* ULQAGalleryWidget_UE5::MakeControlButton(UPanelWidget* Parent, const FText& Label, FName WidgetName) +{ + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), WidgetName); + Button->AddChild(MakeTextBlock(Label, NAME_None, ELQAGalleryTextRole::Primary)); + + if (Parent) + { + if (UHorizontalBoxSlot* ButtonSlot = Cast(Parent->AddChild(Button))) + { + ButtonSlot->SetPadding(FMargin(0.f, 0.f, 6.f, 0.f)); + } + } + + return Button; +} + +UTexture2D* ULQAGalleryWidget_UE5::CreateSolidTexture(int32 Size, const FColor& Color) +{ + UTexture2D* Texture = UTexture2D::CreateTransient(Size, Size, PF_B8G8R8A8); + if (!Texture) + { + return nullptr; + } + + // UE5 中 PlatformData 已私有化,必须用 GetPlatformData();UE4 保留字段访问 +#if ENGINE_MAJOR_VERSION >= 5 + FTexturePlatformData* PlatformData = Texture->GetPlatformData(); +#else + FTexturePlatformData* PlatformData = Texture->PlatformData; +#endif + if (!PlatformData) + { + return nullptr; + } + + void* Data = PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); + FColor* Pixels = static_cast(Data); + for (int32 i = 0; i < Size * Size; ++i) + { + Pixels[i] = Color; + } + PlatformData->Mips[0].BulkData.Unlock(); + Texture->UpdateResource(); + return Texture; +} + +// =========================================================================== +// 交互控制条 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildControlBar() +{ + UBorder* Bar = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_ControlBar")); + Bar->SetPadding(FMargin(8.f, 6.f)); + ControlBarBorder = Bar; + + UHorizontalBox* Row = + WidgetTree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("Gallery_ControlBar_Row")); + + // 新增按钮时调用 MakeControlButton() 创建,再 AddDynamic 绑定到本类任一回调中; + // 按钮文本取自 LQAGalleryWidgetText 并需在 LQALocalization 登记。 + MakeControlButton(Row, LQAGalleryWidgetText::CtrlScrollTop(), TEXT("Gallery_Ctrl_ScrollTop")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE5::OnScrollTopClicked); + MakeControlButton(Row, LQAGalleryWidgetText::CtrlScrollBottom(), TEXT("Gallery_Ctrl_ScrollBottom")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE5::OnScrollBottomClicked); + MakeControlButton(Row, LQAGalleryWidgetText::CtrlToggleTheme(), TEXT("Gallery_Ctrl_ToggleTheme")) + ->OnClicked.AddDynamic(this, &ULQAGalleryWidget_UE5::OnToggleThemeClicked); + + Bar->SetContent(Row); + return Bar; +} + +void ULQAGalleryWidget_UE5::OnSwitchPageClicked() +{ + if (GallerySwitcher) + { + const int32 CurrentIndex = GallerySwitcher->GetActiveWidgetIndex(); + GallerySwitcher->SetActiveWidgetIndex(CurrentIndex == 0 ? 1 : 0); + } +} + +void ULQAGalleryWidget_UE5::OnToggleExpandClicked() +{ + if (GalleryExpandableArea) + { + GalleryExpandableArea->SetIsExpanded(!GalleryExpandableArea->GetIsExpanded()); + } +} + +void ULQAGalleryWidget_UE5::OnSwitchOptionClicked() +{ + const FString FirstOption = LQAGalleryWidgetText::ContentComboBoxString().ToString(); + const FString SecondOption = LQAGalleryWidgetText::ContentButton().ToString(); + + if (GalleryComboBoxString) + { + const FString Current = GalleryComboBoxString->GetSelectedOption(); + GalleryComboBoxString->SetSelectedOption(Current == FirstOption ? SecondOption : FirstOption); + } + +#if ENGINE_MAJOR_VERSION >= 5 + if (UComboBoxKey* ComboBoxKey = Cast(GalleryComboBoxKey)) + { + const FName CurrentKey = ComboBoxKey->GetSelectedOption(); + ComboBoxKey->SetSelectedOption(CurrentKey == FName(*FirstOption) ? FName(*SecondOption) : FName(*FirstOption)); + } +#endif +} + +void ULQAGalleryWidget_UE5::OnToggleMenuClicked() +{ + if (GalleryMenuAnchor) + { + GalleryMenuAnchor->ToggleOpen(true); + } +} + +void ULQAGalleryWidget_UE5::OnToggleCheckClicked() +{ + if (GalleryCheckBox) + { + GalleryCheckBox->SetIsChecked(!GalleryCheckBox->IsChecked()); + } +} + +void ULQAGalleryWidget_UE5::OnScrollTopClicked() +{ + if (GalleryScroll) + { + GalleryScroll->ScrollToStart(); + } +} + +void ULQAGalleryWidget_UE5::OnScrollBottomClicked() +{ + if (GalleryScroll) + { + GalleryScroll->ScrollToEnd(); + } +} + +void ULQAGalleryWidget_UE5::OnToggleThemeClicked() +{ + bDarkTheme = !bDarkTheme; + Theme = bDarkTheme ? FLQAGalleryTheme::Dark() : FLQAGalleryTheme::Light(); + ApplyTheme(); +} + +void ULQAGalleryWidget_UE5::ApplyTheme() +{ +#if ENGINE_MAJOR_VERSION >= 5 + if (BackgroundBorder) + { + BackgroundBorder->SetBrushColor(Theme.PageBackground); + } + + if (ControlBarBorder) + { + ControlBarBorder->SetBrushColor(Theme.BarBackground); + } + + for (UBorder* Header : HeaderBorders) + { + if (Header) + { + Header->SetBrushColor(Theme.HeaderBackground); + } + } + + for (UTextBlock* Text : PrimaryTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextPrimary)); + } + } + + for (UTextBlock* Text : SecondaryTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextSecondary)); + } + } + + for (UTextBlock* Text : OnAccentTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextOnAccent)); + } + } + + for (UTextBlock* Text : OnPanelTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(Theme.TextOnPanel)); + } + } + + for (UTextBlock* Text : OnControlTexts) + { + if (Text) + { + Text->SetColorAndOpacity(FSlateColor(FLQAGalleryTheme::ControlText())); + } + } + + if (GalleryRichText) + { + GalleryRichText->SetDefaultColorAndOpacity(FSlateColor(Theme.TextPrimary)); + GalleryRichText->SetTextStyleSet(GetRichTextStyleSet()); + } + + if (GalleryEditableText) + { + FEditableTextStyle Style = GalleryEditableText->WidgetStyle; + Style.ColorAndOpacity = FSlateColor(Theme.TextPrimary); + GalleryEditableText->SetWidgetStyle(Style); + } + + if (GalleryMultiLineEditableText) + { + FTextBlockStyle Style = GalleryMultiLineEditableText->WidgetStyle; + Style.ColorAndOpacity = FSlateColor(Theme.TextPrimary); + GalleryMultiLineEditableText->SetWidgetStyle(Style); + } + + if (GalleryEditableTextBox) + { + GalleryEditableTextBox->SetForegroundColor(FLQAGalleryTheme::ControlText()); + } + + if (GalleryMultiLineEditableTextBox) + { + GalleryMultiLineEditableTextBox->SetForegroundColor(FLQAGalleryTheme::ControlText()); + } + + if (GallerySpinBox) + { + GallerySpinBox->SetForegroundColor(FSlateColor(FLQAGalleryTheme::ControlText())); + } + + if (GallerySlider) + { + GallerySlider->SetSliderBarColor(Theme.Divider); + GallerySlider->SetSliderHandleColor(Theme.Accent); + } + + if (GalleryProgressBar) + { + GalleryProgressBar->SetFillColorAndOpacity(Theme.Accent); + } + + for (UCheckBox* CheckBox : GalleryCheckBoxes) + { + if (!CheckBox) + { + continue; + } + + FCheckBoxStyle Style = CheckBox->GetWidgetStyle(); + Style.CheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + Style.UncheckedImage.TintColor = FSlateColor(Theme.TextPrimary); + Style.UndeterminedImage.TintColor = FSlateColor(Theme.TextPrimary); + CheckBox->SetWidgetStyle(Style); + } + + if (GalleryThrobber) + { + FSlateBrush Brush = GalleryThrobber->GetImage(); + Brush.TintColor = FSlateColor(Theme.TextPrimary); + GalleryThrobber->SetImage(Brush); + } + + if (GalleryCircularThrobber) + { + FSlateBrush Brush = GalleryCircularThrobber->GetImage(); + Brush.TintColor = FSlateColor(Theme.TextPrimary); + GalleryCircularThrobber->SetImage(Brush); + } + + for (UListView* View : GalleryListViews) + { + if (!View) + { + continue; + } + + for (UObject* Item : View->GetListItems()) + { + if (ULQAGalleryListItem* ListItem = Cast(Item)) + { + ListItem->TextColor = Theme.TextPrimary; + } + } + + View->RegenerateAllEntries(); + } + + if (GalleryChildWidget) + { + GalleryChildWidget->SetThemeColors(Theme.TextPrimary, Theme.Accent); + } +#endif +} + +UDataTable* ULQAGalleryWidget_UE5::GetRichTextStyleSet() +{ + UDataTable*& CachedTable = bDarkTheme ? RichTextStyleDark : RichTextStyleLight; + if (CachedTable) + { + return CachedTable; + } + + UDataTable* Table = NewObject(this); + Table->RowStruct = FRichTextStyleRow::StaticStruct(); + + AddRichTextStyleRow(Table, TEXT("Default"), GetRichTextFont(TEXT("Regular")), Theme.TextPrimary); + AddRichTextStyleRow(Table, TEXT("Name"), GetRichTextFont(TEXT("Bold")), Theme.Highlight); + AddRichTextStyleRow(Table, TEXT("Accent"), GetRichTextFont(TEXT("Bold")), Theme.Accent); + + CachedTable = Table; + return Table; +} + +UWidget* ULQAGalleryWidget_UE5::OnGenerateComboBoxKeyWidget(FName Item) +{ + // 选项文本取自选项名(选项名来自 LQAGalleryWidgetText) + UTextBlock* ItemText = WidgetTree->ConstructWidget(UTextBlock::StaticClass()); + ItemText->SetText(FText::FromName(Item)); + return ItemText; +} + +// =========================================================================== +// 一、文本类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildTextSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + UTextBlock* TextBlock = MakeTextBlock(LQAGalleryWidgetText::TextBlockSample(), TEXT("Gallery_TextBlock")); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTextBlock(), TextBlock, FVector2D(360.f, 24.f))); + + URichTextBlock* RichText = + WidgetTree->ConstructWidget(URichTextBlock::StaticClass(), TEXT("Gallery_RichTextBlock")); + RichText->SetText(LQAGalleryWidgetText::RichTextBlockSample()); + RichText->SetDefaultFont(GetRichTextFont(TEXT("Regular"))); + GalleryRichText = RichText; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelRichTextBlock(), RichText, FVector2D(360.f, 32.f))); + + UEditableText* Editable = + WidgetTree->ConstructWidget(UEditableText::StaticClass(), TEXT("Gallery_EditableText")); + Editable->SetHintText(LQAGalleryWidgetText::HintEditableText()); + GalleryEditableText = Editable; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelEditableText(), Editable, FVector2D(240.f, 28.f))); + + UEditableTextBox* EditableBox = + WidgetTree->ConstructWidget(UEditableTextBox::StaticClass(), TEXT("Gallery_EditableTextBox")); + EditableBox->SetHintText(LQAGalleryWidgetText::HintEditableTextBox()); + GalleryEditableTextBox = EditableBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelEditableTextBox(), EditableBox, FVector2D(240.f, 28.f))); + + UMultiLineEditableText* MultiText = WidgetTree->ConstructWidget( + UMultiLineEditableText::StaticClass(), TEXT("Gallery_MultiLineEditableText")); + MultiText->SetText(LQAGalleryWidgetText::MultiLineText()); + GalleryMultiLineEditableText = MultiText; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelMultiLineEditableText(), MultiText, FVector2D(260.f, 64.f))); + + UMultiLineEditableTextBox* MultiBox = WidgetTree->ConstructWidget( + UMultiLineEditableTextBox::StaticClass(), TEXT("Gallery_MultiLineEditableTextBox")); + MultiBox->SetText(LQAGalleryWidgetText::MultiLineTextBox()); + GalleryMultiLineEditableTextBox = MultiBox; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelMultiLineEditableTextBox(), MultiBox, FVector2D(260.f, 64.f))); + + return Box; +} + +// =========================================================================== +// 二、交互 / 输入类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildInputSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // Button + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("Gallery_Button")); + Button->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentButton(), NAME_None, ELQAGalleryTextRole::OnControl)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelButton(), Button, FVector2D(120.f, 28.f))); + + // CheckBox(选中态,供控制条切换) + UCheckBox* CheckBox = WidgetTree->ConstructWidget(UCheckBox::StaticClass(), TEXT("Gallery_CheckBox")); + CheckBox->SetIsChecked(true); + GalleryCheckBox = CheckBox; + GalleryCheckBoxes.Add(CheckBox); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCheckBox(), CheckBox, FVector2D(32.f, 32.f))); + + // CheckBox(未选中 + 禁用态) + UCheckBox* DisabledCheckBox = + WidgetTree->ConstructWidget(UCheckBox::StaticClass(), TEXT("Gallery_CheckBox_Disabled")); + DisabledCheckBox->SetIsChecked(false); + DisabledCheckBox->SetIsEnabled(false); + GalleryCheckBoxes.Add(DisabledCheckBox); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCheckBox(), DisabledCheckBox, FVector2D(32.f, 32.f))); + + // Slider + USlider* Slider = WidgetTree->ConstructWidget(USlider::StaticClass(), TEXT("Gallery_Slider")); + Slider->SetValue(0.5f); + GallerySlider = Slider; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSlider(), Slider, FVector2D(240.f, 20.f))); + + // ProgressBar + UProgressBar* Progress = + WidgetTree->ConstructWidget(UProgressBar::StaticClass(), TEXT("Gallery_ProgressBar")); + Progress->SetPercent(0.6f); + GalleryProgressBar = Progress; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelProgressBar(), Progress, FVector2D(240.f, 18.f))); + + // ComboBoxString + UComboBoxString* ComboBox = WidgetTree->ConstructWidget( + UComboBoxString::StaticClass(), TEXT("Gallery_ComboBoxString")); + ComboBox->AddOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + ComboBox->AddOption(LQAGalleryWidgetText::ContentButton().ToString()); + ComboBox->SetSelectedOption(LQAGalleryWidgetText::ContentComboBoxString().ToString()); + GalleryComboBoxString = ComboBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelComboBoxString(), ComboBox, FVector2D(240.f, 28.f))); + +#if ENGINE_MAJOR_VERSION >= 5 + // ComboBoxKey(Key 变体,对应 SComboBox) + UComboBoxKey* ComboBoxKey = WidgetTree->ConstructWidget( + UComboBoxKey::StaticClass(), TEXT("Gallery_ComboBoxKey")); + ComboBoxKey->AddOption(FName(*LQAGalleryWidgetText::ContentComboBoxString().ToString())); + ComboBoxKey->AddOption(FName(*LQAGalleryWidgetText::ContentButton().ToString())); + ComboBoxKey->SetSelectedOption(FName(*LQAGalleryWidgetText::ContentComboBoxString().ToString())); + ComboBoxKey->OnGenerateContentWidget.BindDynamic(this, &ULQAGalleryWidget_UE5::OnGenerateComboBoxKeyWidget); + ComboBoxKey->OnGenerateItemWidget.BindDynamic(this, &ULQAGalleryWidget_UE5::OnGenerateComboBoxKeyWidget); + GalleryComboBoxKey = ComboBoxKey; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelComboBoxKey(), ComboBoxKey, FVector2D(240.f, 28.f))); +#endif + + // SpinBox + USpinBox* SpinBox = WidgetTree->ConstructWidget(USpinBox::StaticClass(), TEXT("Gallery_SpinBox")); + SpinBox->SetValue(42.f); + GallerySpinBox = SpinBox; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSpinBox(), SpinBox, FVector2D(140.f, 28.f))); + + // InputKeySelector + UInputKeySelector* KeySelector = WidgetTree->ConstructWidget( + UInputKeySelector::StaticClass(), TEXT("Gallery_InputKeySelector")); + KeySelector->SetKeySelectionText(LQAGalleryWidgetText::ContentKeySelection()); + KeySelector->SetNoKeySpecifiedText(LQAGalleryWidgetText::ContentNoKeySpecified()); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelInputKeySelector(), KeySelector, FVector2D(240.f, 28.f))); + + // MenuAnchor(菜单内容取自 ULQAGalleryMenuWidget) + UMenuAnchor* MenuAnchor = + WidgetTree->ConstructWidget(UMenuAnchor::StaticClass(), TEXT("Gallery_MenuAnchor")); + MenuAnchor->SetContent(MakeTextBlock(LQAGalleryWidgetText::ContentMenuAnchorAnchor())); + MenuAnchor->MenuClass = ULQAGalleryMenuWidget::StaticClass(); + MenuAnchor->SetPlacement(MenuPlacement_BelowAnchor); + GalleryMenuAnchor = MenuAnchor; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelMenuAnchor(), MenuAnchor, FVector2D(240.f, 28.f))); + + // ScrollBar(UMG 层不可指定方向,使用默认水平方向) + UScrollBar* ScrollBar = WidgetTree->ConstructWidget(UScrollBar::StaticClass(), TEXT("Gallery_ScrollBar")); + ScrollBar->SetState(0.3f, 0.4f); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelScrollBar(), ScrollBar, FVector2D(120.f, 16.f))); + + return Box; +} + +// =========================================================================== +// 三、展示类控件 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildDisplaySection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // Image + UImage* Image = WidgetTree->ConstructWidget(UImage::StaticClass(), TEXT("Gallery_Image")); + if (UTexture2D* Texture = CreateSolidTexture(64, FColor(80, 160, 220, 255))) + { + FSlateBrush Brush; + Brush.SetResourceObject(Texture); + Brush.ImageSize = FVector2D(64.f, 64.f); + Image->SetBrush(Brush); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelImage(), Image, FVector2D(64.f, 64.f))); + + // Throbber / CircularThrobber + UThrobber* Throbber = WidgetTree->ConstructWidget(UThrobber::StaticClass(), TEXT("Gallery_Throbber")); + GalleryThrobber = Throbber; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelThrobber(), Throbber, FVector2D(48.f, 48.f))); + + UCircularThrobber* Circular = WidgetTree->ConstructWidget( + UCircularThrobber::StaticClass(), TEXT("Gallery_CircularThrobber")); + GalleryCircularThrobber = Circular; + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCircularThrobber(), Circular, FVector2D(48.f, 48.f))); + + // Spacer(无视觉表现,仅占位) + USpacer* Spacer = WidgetTree->ConstructWidget(USpacer::StaticClass(), TEXT("Gallery_Spacer")); + Spacer->SetSize(FVector2D(40.f, 20.f)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSpacer(), Spacer, FVector2D(40.f, 20.f))); + + // Border + UBorder* Border = WidgetTree->ConstructWidget(UBorder::StaticClass(), TEXT("Gallery_Border")); + Border->SetBrushColor(FLinearColor(0.2f, 0.2f, 0.2f, 1.f)); + Border->SetPadding(FMargin(10.f)); + Border->SetContent(MakeTextBlock(LQAGalleryWidgetText::BorderContent(), NAME_None, ELQAGalleryTextRole::OnPanel)); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelBorder(), Border, FVector2D(240.f, 40.f))); + + // BackgroundBlur + UBackgroundBlur* BackgroundBlur = WidgetTree->ConstructWidget( + UBackgroundBlur::StaticClass(), TEXT("Gallery_BackgroundBlur")); + { + UBorder* BlurContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + BlurContent->SetBrushColor(FLinearColor(0.3f, 0.3f, 0.3f, 1.f)); + BlurContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnPanel)); + BackgroundBlur->SetContent(BlurContent); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelBackgroundBlur(), BackgroundBlur, FVector2D(240.f, 80.f))); + + // RetainerBox + URetainerBox* RetainerBox = WidgetTree->ConstructWidget( + URetainerBox::StaticClass(), TEXT("Gallery_RetainerBox")); + { + UBorder* RetainerContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + RetainerContent->SetBrushColor(FLinearColor(0.25f, 0.25f, 0.35f, 1.f)); + RetainerContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnPanel)); + RetainerBox->SetContent(RetainerContent); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelRetainerBox(), RetainerBox, FVector2D(240.f, 80.f))); + +#if ENGINE_MAJOR_VERSION >= 5 + // PostBufferUpdate(无视觉表现,靠 SizeBox 占位) + USizeBox* PostBufferSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + UPostBufferUpdate* PostBufferUpdate = WidgetTree->ConstructWidget( + UPostBufferUpdate::StaticClass(), TEXT("Gallery_PostBufferUpdate")); + PostBufferSizeBox->SetMinDesiredWidth(120.f); + PostBufferSizeBox->SetMinDesiredHeight(40.f); + PostBufferSizeBox->AddChild(PostBufferUpdate); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelPostBufferUpdate(), PostBufferSizeBox, FVector2D(120.f, 40.f))); +#endif + + // ListView:3 条 + { + ULQAGalleryListView* ListView = WidgetTree->ConstructWidget( + ULQAGalleryListView::StaticClass(), TEXT("Gallery_ListView")); + GalleryListViews.Add(ListView); + for (int32 Index = 1; Index <= 3; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::ListViewText(Index); + ListView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelListView(), ListView, FVector2D(240.f, 120.f))); + } + + // TileView:2 条(tile 宽度已加大,条目过多会导致内容溢出重叠) + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_TileView")); + GalleryListViews.Add(TileView); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::TileViewText(Index); + TileView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTileView(), TileView, FVector2D(240.f, 80.f))); + } + + // TreeView:3 条 + { + ULQAGalleryTreeView* TreeView = WidgetTree->ConstructWidget( + ULQAGalleryTreeView::StaticClass(), TEXT("Gallery_TreeView")); + GalleryListViews.Add(TreeView); + for (int32 Index = 1; Index <= 3; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::TreeViewText(Index); + TreeView->AddItem(Item); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelTreeView(), TreeView, FVector2D(240.f, 120.f))); + } + + // DynamicEntryBox:3 条(条目为 C++ UserWidget,文本取自 LQAGalleryWidgetText) + { + ULQAGalleryDynamicEntryWidget::StaticClass()->bCooked = true; + + UDynamicEntryBox* DynamicEntryBox = WidgetTree->ConstructWidget( + UDynamicEntryBox::StaticClass(), TEXT("Gallery_DynamicEntryBox")); + for (int32 Index = 1; Index <= 3; ++Index) + { + if (ULQAGalleryDynamicEntryWidget* Entry = + DynamicEntryBox->CreateEntry(ULQAGalleryDynamicEntryWidget::StaticClass())) + { + Entry->SetEntryText(LQAGalleryWidgetText::DynamicEntryBoxText(Index)); + } + } + Box->AddChildToVerticalBox(MakeSizedRow( + LQAGalleryWidgetText::LabelDynamicEntryBox(), DynamicEntryBox, FVector2D(240.f, 90.f))); + } + + // 嵌套子 UserWidget(SObjectWidget) + { + USizeBox* ChildSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + ChildSizeBox->SetMinDesiredWidth(240.f); + ChildSizeBox->SetMinDesiredHeight(60.f); + + if (UWorld* World = GetWorld()) + { + if (ULQAGalleryChildWidget* Child = CreateWidget( + World, ULQAGalleryChildWidget::StaticClass(), TEXT("Gallery_ChildWidget"))) + { + GalleryChildWidget = Child; + ChildSizeBox->AddChild(Child); + } + } + + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelUserWidget(), ChildSizeBox, FVector2D(240.f, 60.f))); + } + + return Box; +} + +// =========================================================================== +// 四、布局容器 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildLayoutSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + // CanvasPanel(独立示例行) + { + UCanvasPanel* Canvas = WidgetTree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("Gallery_CanvasPanel")); + UTextBlock* CanvasText = MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock()); + Canvas->AddChild(CanvasText); + if (UCanvasPanelSlot* CanvasItemSlot = Cast(CanvasText->Slot)) + { + CanvasItemSlot->SetAnchors(FAnchors(0.f, 0.f)); + CanvasItemSlot->SetOffsets(FMargin(0.f, 0.f, 120.f, 24.f)); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelCanvasPanel(), Canvas, FVector2D(240.f, 60.f))); + } + + // ScrollBox(独立示例行) + { + UScrollBox* InnerScroll = + WidgetTree->ConstructWidget(UScrollBox::StaticClass(), TEXT("Gallery_ScrollBox")); + for (int32 Index = 0; Index < 3; ++Index) + { + InnerScroll->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentHorizontal(Index))); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelScrollBox(), InnerScroll, FVector2D(240.f, 60.f))); + } + + // VerticalBox(独立示例行) + { + UVerticalBox* InnerVertical = + WidgetTree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("Gallery_VerticalBox")); + InnerVertical->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock())); + InnerVertical->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelVerticalBox(), InnerVertical, FVector2D(240.f, 60.f))); + } + + // HorizontalBox + { + UHorizontalBox* HBox = + WidgetTree->ConstructWidget(UHorizontalBox::StaticClass(), TEXT("Gallery_HorizontalBox")); + for (int32 Index = 0; Index < 3; ++Index) + { + UTextBlock* Item = MakeTextBlock(LQAGalleryWidgetText::ContentHorizontal(Index)); + if (UHorizontalBoxSlot* ItemSlot = HBox->AddChildToHorizontalBox(Item)) + { + ItemSlot->SetPadding(FMargin(6.f, 0.f)); + } + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelHorizontalBox(), HBox, FVector2D(240.f, 60.f))); + } + + // GridPanel(补子项间距) + { + UGridPanel* Grid = WidgetTree->ConstructWidget(UGridPanel::StaticClass(), TEXT("Gallery_GridPanel")); + for (int32 RowIndex = 0; RowIndex < 2; ++RowIndex) + { + for (int32 ColumnIndex = 0; ColumnIndex < 2; ++ColumnIndex) + { + UTextBlock* Item = MakeTextBlock(LQAGalleryWidgetText::ContentGrid(RowIndex, ColumnIndex)); + if (UGridSlot* GridItemSlot = Grid->AddChildToGrid(Item, RowIndex, ColumnIndex)) + { + GridItemSlot->SetPadding(FMargin(4.f)); + } + } + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelGridPanel(), Grid, FVector2D(240.f, 60.f))); + } + + // UniformGridPanel(补槽位间距) + { + UUniformGridPanel* UniformGrid = WidgetTree->ConstructWidget( + UUniformGridPanel::StaticClass(), TEXT("Gallery_UniformGridPanel")); + UniformGrid->SetSlotPadding(FMargin(4.f)); + for (int32 Index = 0; Index < 4; ++Index) + { + UniformGrid->AddChildToUniformGrid( + MakeTextBlock(LQAGalleryWidgetText::ContentUniform(Index)), Index / 2, Index % 2); + } + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelUniformGridPanel(), UniformGrid, FVector2D(240.f, 60.f))); + } + + // Overlay + { + UOverlay* Overlay = WidgetTree->ConstructWidget(UOverlay::StaticClass(), TEXT("Gallery_Overlay")); + UBorder* OverlayBackground = WidgetTree->ConstructWidget(UBorder::StaticClass()); + OverlayBackground->SetBrushColor(FLinearColor(0.3f, 0.3f, 0.3f, 1.f)); + if (UOverlaySlot* BackgroundSlot = Overlay->AddChildToOverlay(OverlayBackground)) + { + BackgroundSlot->SetPadding(FMargin(0.f)); + } + if (UOverlaySlot* ForegroundSlot = Overlay->AddChildToOverlay( + MakeTextBlock(LQAGalleryWidgetText::OverlayStack(), NAME_None, ELQAGalleryTextRole::OnPanel))) + { + ForegroundSlot->SetPadding(FMargin(6.f)); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelOverlay(), Overlay, FVector2D(240.f, 60.f))); + } + + // WrapBox(补内部间距) + { + UWrapBox* WrapBox = WidgetTree->ConstructWidget(UWrapBox::StaticClass(), TEXT("Gallery_WrapBox")); + WrapBox->SetInnerSlotPadding(FVector2D(6.f, 4.f)); + for (int32 Index = 0; Index < 6; ++Index) + { + WrapBox->AddChildToWrapBox(MakeTextBlock(LQAGalleryWidgetText::ContentWrap(Index))); + } + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelWrapBox(), WrapBox, FVector2D(240.f, 60.f))); + } + + // SizeBox + { + USizeBox* SizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass(), TEXT("Gallery_SizeBox")); + SizeBox->SetWidthOverride(120.f); + SizeBox->SetHeightOverride(40.f); + UBorder* Inner = WidgetTree->ConstructWidget(UBorder::StaticClass()); + Inner->SetBrushColor(FLinearColor(0.4f, 0.2f, 0.2f, 1.f)); + SizeBox->AddChild(Inner); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSizeBox(), SizeBox, FVector2D(120.f, 40.f))); + } + + // NamedSlot(Slate 层为 SBox,采集侧以 WidgetClass 细分) + { + USizeBox* NamedSlotSizeBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + NamedSlotSizeBox->SetMinDesiredWidth(120.f); + NamedSlotSizeBox->SetMinDesiredHeight(40.f); + UNamedSlot* NamedSlot = + WidgetTree->ConstructWidget(UNamedSlot::StaticClass(), TEXT("Gallery_NamedSlot")); + NamedSlot->AddChild(MakeTextBlock(LQAGalleryWidgetText::LabelNamedSlot())); + NamedSlotSizeBox->AddChild(NamedSlot); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelNamedSlot(), NamedSlotSizeBox, FVector2D(120.f, 40.f))); + } + + // ScaleBox + { + UScaleBox* ScaleBox = WidgetTree->ConstructWidget(UScaleBox::StaticClass(), TEXT("Gallery_ScaleBox")); + ScaleBox->SetStretch(EStretch::ScaleToFit); + ScaleBox->AddChild(MakeTextBlock(LQAGalleryWidgetText::ScaleBoxContent())); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelScaleBox(), ScaleBox, FVector2D(240.f, 90.f))); + } + + // SafeZone + { + USafeZone* SafeZone = WidgetTree->ConstructWidget(USafeZone::StaticClass(), TEXT("Gallery_SafeZone")); + SafeZone->AddChild(MakeTextBlock(LQAGalleryWidgetText::SafeZoneContent())); + Box->AddChildToVerticalBox(MakeSizedRow(LQAGalleryWidgetText::LabelSafeZone(), SafeZone, FVector2D(240.f, 60.f))); + } + + // WidgetSwitcher(两页等高,供控制条切页) + { + UWidgetSwitcher* Switcher = WidgetTree->ConstructWidget( + UWidgetSwitcher::StaticClass(), TEXT("Gallery_WidgetSwitcher")); + Switcher->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentPage0())); + Switcher->AddChild(MakeTextBlock(LQAGalleryWidgetText::ContentPage1())); + Switcher->SetActiveWidgetIndex(0); + GallerySwitcher = Switcher; + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelWidgetSwitcher(), Switcher, FVector2D(240.f, 60.f))); + } + +#if ENGINE_MAJOR_VERSION >= 5 + // StackBox(水平 / 垂直各一例) + { + UStackBox* HorizontalStack = WidgetTree->ConstructWidget( + UStackBox::StaticClass(), TEXT("Gallery_StackBox_Horizontal")); + HorizontalStack->SetOrientation(Orient_Horizontal); + HorizontalStack->AddChildToStackBox(MakeTextBlock(LQAGalleryWidgetText::ContentButton())); + HorizontalStack->AddChildToStackBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelStackBox(), HorizontalStack, FVector2D(240.f, 60.f))); + + UStackBox* VerticalStack = WidgetTree->ConstructWidget( + UStackBox::StaticClass(), TEXT("Gallery_StackBox_Vertical")); + VerticalStack->SetOrientation(Orient_Vertical); + VerticalStack->AddChildToStackBox(MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock())); + VerticalStack->AddChildToStackBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelStackBox(), VerticalStack, FVector2D(240.f, 60.f))); + } +#endif + + // InvalidationBox + { + UInvalidationBox* InvalidationBox = WidgetTree->ConstructWidget( + UInvalidationBox::StaticClass(), TEXT("Gallery_InvalidationBox")); + UBorder* InvalidationContent = WidgetTree->ConstructWidget(UBorder::StaticClass()); + InvalidationContent->SetBrushColor(FLinearColor(0.25f, 0.3f, 0.25f, 1.f)); + InvalidationContent->SetContent( + MakeTextBlock(LQAGalleryWidgetText::ContentInvalidationBox(), NAME_None, ELQAGalleryTextRole::OnPanel)); + InvalidationBox->SetContent(InvalidationContent); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelInvalidationBox(), InvalidationBox, FVector2D(240.f, 60.f))); + } + + // WindowTitleBarArea + { + UWindowTitleBarArea* TitleBarArea = WidgetTree->ConstructWidget( + UWindowTitleBarArea::StaticClass(), TEXT("Gallery_WindowTitleBarArea")); + TitleBarArea->SetContent(MakeTextBlock(LQAGalleryWidgetText::ContentWindowTitleBarArea())); + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelWindowTitleBarArea(), TitleBarArea, FVector2D(240.f, 40.f))); + } + + // ExpandableArea(Header / Body 均用 C++ 构造;初始展开便于采集内容) + { + UExpandableArea* ExpandableArea = WidgetTree->ConstructWidget( + UExpandableArea::StaticClass(), TEXT("Gallery_ExpandableArea")); + ExpandableArea->SetContentForSlot( + FName(TEXT("Header")), MakeTextBlock(LQAGalleryWidgetText::ContentBorder(), NAME_None, ELQAGalleryTextRole::OnControl)); + + UVerticalBox* BodyBox = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + BodyBox->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentTextBlock())); + BodyBox->AddChildToVerticalBox(MakeTextBlock(LQAGalleryWidgetText::ContentBorder())); + ExpandableArea->SetContentForSlot(FName(TEXT("Body")), BodyBox); + ExpandableArea->SetIsExpanded(true); + GalleryExpandableArea = ExpandableArea; + + Box->AddChildToVerticalBox( + MakeSizedRow(LQAGalleryWidgetText::LabelExpandableArea(), ExpandableArea, FVector2D(280.f, 120.f))); + } + + return Box; +} + +// =========================================================================== +// 五、显示性质 BUG 示例 +// =========================================================================== + +UPanelWidget* ULQAGalleryWidget_UE5::BuildBugSection() +{ + UVerticalBox* Box = WidgetTree->ConstructWidget(UVerticalBox::StaticClass()); + + auto AddBugRow = [Box](UWidget* Row, float ExtraSpacing = 0.f) + { + if (UVerticalBoxSlot* RowSlot = Box->AddChildToVerticalBox(Row)) + { + RowSlot->SetPadding(FMargin(0.f, 24.f + ExtraSpacing, 0.f, 24.f + ExtraSpacing)); + } + }; + + // BUG-01:不换行文本超出固定宽度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugOverflowSingleLine(), + TEXT("Gallery_Bug_01_Text"), FVector2D(160.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug01(), Stage, FVector2D(240.f, 32.f))); + } + + // BUG-02:自动换行后行数超出固定高度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugOverflowMultiLine(), + TEXT("Gallery_Bug_02_Text"), FVector2D(200.f, 40.f), true, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug02(), Stage, FVector2D(240.f, 64.f)), 16.f); + } + + // BUG-03:字号超过固定高度 + { + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugFontSize(), + TEXT("Gallery_Bug_03_Text"), FVector2D(120.f, 24.f), false, 36.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug03(), Stage, FVector2D(240.f, 40.f)), 16.f); + } + + // BUG-04:按钮内文本超出按钮宽度 + { + UButton* Button = WidgetTree->ConstructWidget(UButton::StaticClass(), TEXT("Gallery_Bug_04_Button")); + UTextBlock* ButtonText = MakeTextBlock( + LQAGalleryWidgetText::BugButtonOverflow(), TEXT("Gallery_Bug_04_Text"), ELQAGalleryTextRole::OnControl); + ButtonText->SetAutoWrapText(false); + Button->AddChild(ButtonText); + + USizeBox* ButtonBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + ButtonBox->SetWidthOverride(120.f); + ButtonBox->SetHeightOverride(28.f); + ButtonBox->AddChild(Button); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug04(), ButtonBox, FVector2D(160.f, 32.f))); + } + + // BUG-05:行高压缩导致同一文本节点内行间重叠 + { + UTextBlock* TextBlock = nullptr; + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugLineHeight(), + TEXT("Gallery_Bug_05_Text"), FVector2D(200.f, 40.f), true, 0.f, &TextBlock); + if (TextBlock) + { +#if ENGINE_MAJOR_VERSION >= 5 + TextBlock->SetLineHeightPercentage(0.3f); +#endif + } + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug05(), Stage, FVector2D(240.f, 64.f))); + } + + // BUG-06:文本颜色与舞台底色相同 + { + const FLinearColor HiddenColor = FLQAGalleryTheme::Dark().BarBackground; + UTextBlock* HiddenText = + WidgetTree->ConstructWidget(UTextBlock::StaticClass(), TEXT("Gallery_Bug_06_Text")); + HiddenText->SetText(LQAGalleryWidgetText::BugInvisible()); + HiddenText->SetAutoWrapText(false); + HiddenText->SetColorAndOpacity(FSlateColor(HiddenColor)); + + USizeBox* HiddenBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + HiddenBox->SetWidthOverride(200.f); + HiddenBox->SetHeightOverride(24.f); + HiddenBox->AddChild(HiddenText); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug06(), HiddenBox, FVector2D(240.f, 48.f), true, HiddenColor)); + } + + // BUG-07:文本超出控件边界后被硬截断 + { + UTextBlock* ClipText = nullptr; + UWidget* Stage = MakeFixedText(LQAGalleryWidgetText::BugTruncate(), + TEXT("Gallery_Bug_07_Text"), FVector2D(200.f, 24.f), false, 0.f, &ClipText); + if (ClipText) + { + ClipText->SetClipping(EWidgetClipping::ClipToBounds); + } + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug07(), Stage, FVector2D(240.f, 28.f))); + } + + // BUG-08:TileView 条目高度小于文本行高,相邻条目重叠 + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_Bug_08_TileView")); + TileView->SetEntryHeight(8.f); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = LQAGalleryWidgetText::BugTileViewItem(Index); + TileView->AddItem(Item); + } + + USizeBox* TileViewBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + TileViewBox->SetWidthOverride(240.f); + TileViewBox->SetHeightOverride(80.f); + TileViewBox->AddChild(TileView); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug08(), TileViewBox, FVector2D(240.f, 80.f))); + } + + // BUG-09:TileView 条目文本不换行,跨条目溢出 + { + ULQAGalleryTileView* TileView = WidgetTree->ConstructWidget( + ULQAGalleryTileView::StaticClass(), TEXT("Gallery_Bug_09_TileView")); + TileView->SetEntryWidth(120.f); + for (int32 Index = 1; Index <= 2; ++Index) + { + ULQAGalleryListItem* Item = NewObject(this); + Item->Label = Index == 1 ? LQAGalleryWidgetText::BugTileViewOverflow() + : LQAGalleryWidgetText::BugTileViewItem(2); + Item->bAutoWrapText = false; + TileView->AddItem(Item); + } + + USizeBox* TileViewBox = WidgetTree->ConstructWidget(USizeBox::StaticClass()); + TileViewBox->SetWidthOverride(240.f); + TileViewBox->SetHeightOverride(80.f); + TileViewBox->AddChild(TileView); + + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug09(), TileViewBox, FVector2D(240.f, 80.f))); + } + + // BUG-10:无 Key 文本直接显示原始 Key + { + UWidget* Stage = MakeFixedText( + LQAGalleryWidgetText::BugNoKey(), TEXT("Gallery_Bug_10_Text"), FVector2D(400.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug10(), Stage, FVector2D(460.f, 40.f))); + } + + // BUG-11:文本有 Key 但没有译文 + { + UWidget* Stage = MakeFixedText( + LQAGalleryWidgetText::BugMissingTranslation(), TEXT("Gallery_Bug_11_Text"), FVector2D(300.f, 24.f), false, 0.f); + AddBugRow(MakeBugRow(LQAGalleryWidgetText::LabelBug11(), Stage, FVector2D(380.f, 40.f))); + } + + return Box; +} + diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/LQAWidgetTypeRegistry.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/LQAWidgetTypeRegistry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cbd77fcb3ef2f9b66855d5f31dc2b1636efa3f6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/LQAWidgetTypeRegistry.cpp @@ -0,0 +1,258 @@ +#include "WidgetSlots/LQAWidgetTypeRegistry.h" + +// 以下 UMG 控件头文件用于 StaticClass() 取类指针, 填入登记表的 WidgetClass 约束 +#include "Components/ComboBox.h" +#if ENGINE_MAJOR_VERSION >= 5 +#include "Components/ComboBoxKey.h" +#endif +#include "Components/ComboBoxString.h" +#include "Components/DynamicEntryBox.h" +#include "Components/EditableText.h" +#include "Components/EditableTextBox.h" +#include "Components/Image.h" +#include "Components/MultiLineEditableText.h" +#include "Components/MultiLineEditableTextBox.h" +#include "Components/NamedSlot.h" +#include "Components/NativeWidgetHost.h" +#include "Components/RichTextBlock.h" +#include "Components/SizeBox.h" +#include "Components/Button.h" +#include "Components/TextBlock.h" +#include "Components/Widget.h" +#include "WidgetSlots/WidgetDefines.h" // LQAWidgetNames 命名空间下的 Slate 名常量 + +// ================== 内部辅助函数 ================== + +// 匿名命名空间: 将辅助函数限定在本编译单元内, 不对外暴露符号 +namespace +{ +/** + * 判断某条登记项的 Slate 名是否与运行时 Slate 名命中 + * 支持两种模式: 精确同名, 或 (bPrefixMatch 为真时) 前缀匹配 + * + * @param Entry 待比对的登记项 + * @param SlateTypeName 运行时取得的 Slate 类型名 + * @return 命中返回 true, 否则 false + */ +bool IsSlateNameMatched(const FLQAWidgetTypeDesc& Entry, const FName& SlateTypeName) +{ + // 优先尝试完全同名: 这是最常见也最廉价的判断 + if (Entry.SlateTypeName == SlateTypeName) + { + return true; + } + + // 不要求前缀匹配时, 同名未命中即判定失败 + if (!Entry.bPrefixMatch) + { + return false; + } + + // 前缀匹配 (大小写敏感): 覆盖 SComboBox、SSpinBox 等 + // 运行时携带模板实参、名字不固定的 Slate 类型 + return SlateTypeName.ToString().StartsWith(Entry.SlateTypeName.ToString(), ESearchCase::CaseSensitive); +} +} + +// ================== 控件类型登记表 ================== + +// 获取控件类型登记表 +// 采用 "函数内 static" 惯用法: 首次调用时构建数组并常驻内存, +// 之后每次调用都返回同一份只读数据, 线程安全且无重复构建开销 +const TArray& FLQAWidgetTypeRegistry::GetEntries() +{ + // 引入 Slate 名常量所在命名空间, 下方可直接写 LQA_SizeBox 等短名 + using namespace LQAWidgetNames; + + // 登记项字段顺序: {Slate 类型名, UMG 类约束, LQA 类型枚举, WidgetClass 标签, 是否前缀匹配} + static const TArray Entries = { + // ===== Slate 根类型复用组: 同一 Slate 名对应多个 UMG 控件, 必须带 WidgetClass ===== + + // SizeBox 组: 这些控件的 Slate 根都是 SBox, 仅靠 Slate 名无法区分, 故各带 UMG 类约束 + {LQA_SizeBox, USizeBox::StaticClass(), ELQAWidgetType::LQA_SizeBox, TEXT("SizeBox")}, + {LQA_NamedSlot, UNamedSlot::StaticClass(), ELQAWidgetType::LQA_NamedSlot, TEXT("NamedSlot")}, + {LQA_NativeWidgetHost, UNativeWidgetHost::StaticClass(), ELQAWidgetType::LQA_NativeWidgetHost, + TEXT("NativeWidgetHost")}, + // CommonUI 按钮内部根容器 InternalRootButtonBase: Slate 根为 SBox, UMG 侧 UCommonButtonInternalBase + // 继承 UButton (非 USizeBox), 故补一条以 UButton 作类约束的 SBox 映射, 使其归入 SizeBox。 + {LQA_SizeBox, UButton::StaticClass(), ELQAWidgetType::LQA_SizeBox}, + + // ComboBox 组: Slate 名带模板实参 (SComboBox<...>) 故按前缀匹配; + // 三者归为同一 LQA 类型, 仅 WidgetClass 标签不同以便在 JSON 中区分 + {LQA_ComboBox, UComboBox::StaticClass(), ELQAWidgetType::LQA_ComboBoxStringText, TEXT("ComboBox"), true}, + {LQA_ComboBox, UComboBoxString::StaticClass(), ELQAWidgetType::LQA_ComboBoxStringText, TEXT("ComboBoxString"), + true}, +#if ENGINE_MAJOR_VERSION >= 5 + {LQA_ComboBox, UComboBoxKey::StaticClass(), ELQAWidgetType::LQA_ComboBoxStringText, TEXT("ComboBoxKey"), true}, +#endif + + // 动态条目框组: Slate 根按 EntryBoxType 为 SHorizontalBox / SVerticalBox / SWrapBox, + {LQA_HorizontalBox, UDynamicEntryBox::StaticClass(), ELQAWidgetType::LQA_DynamicEntryBox, + TEXT("DynamicEntryBox")}, + {LQA_VerticalBox, UDynamicEntryBox::StaticClass(), ELQAWidgetType::LQA_DynamicEntryBox, + TEXT("DynamicEntryBox")}, + {LQA_WrapBox, UDynamicEntryBox::StaticClass(), ELQAWidgetType::LQA_DynamicEntryBox, + TEXT("DynamicEntryBox")}, + + // ===== 1:1 类型: Slate 名与 LQA 类型一一对应, WidgetClass 留空, 仅按 Slate 名匹配 ===== + + // 文本类 + {LQA_TextBlock, nullptr, ELQAWidgetType::LQA_TextBlock}, + {LQA_RichTextBlock, nullptr, ELQAWidgetType::LQA_RichText}, + {LQA_EditableText, nullptr, ELQAWidgetType::LQA_EditableText}, + {LQA_EditableTextBox, nullptr, ELQAWidgetType::LQA_EditableTextBox}, + {LQA_MultilineEditableText, nullptr, ELQAWidgetType::LQA_MultilineEditableText}, + {LQA_MultilineEditableTextBox, nullptr, ELQAWidgetType::LQA_MultilineEditableTextBox}, + {LQA_TextScroller, nullptr, ELQAWidgetType::LQA_TextScroller}, + {LQA_LEDRichTextBlock, nullptr, ELQAWidgetType::LQA_LEDRichText}, + {LQA_InputKeySelector, nullptr, ELQAWidgetType::LQA_InputKeySelector}, + + // 可视化类 + {LQA_Image, nullptr, ELQAWidgetType::LQA_Image}, + {LQA_Button, nullptr, ELQAWidgetType::LQA_Button}, + {LQA_CheckBox, nullptr, ELQAWidgetType::LQA_CheckBox}, + + // 容器类 + {LQA_UserWidget, nullptr, ELQAWidgetType::LQA_UserWidget}, + {LQA_Canvas, nullptr, ELQAWidgetType::LQA_Canvas}, + {LQA_RetainerBox, nullptr, ELQAWidgetType::LQA_RetainerBox}, + {LQA_ScrollBox, nullptr, ELQAWidgetType::LQA_ScrollBox}, + // CommonUI 分层滚动框: Slate 根 SCommonHierarchicalScrollBox 继承 SScrollBox, 归入 ScrollBox 采集/还原 + {LQA_CommonHierarchicalScrollBox, nullptr, ELQAWidgetType::LQA_ScrollBox}, + {LQA_VerticalBox, nullptr, ELQAWidgetType::LQA_VerticalBox}, + {LQA_HorizontalBox, nullptr, ELQAWidgetType::LQA_HorizontalBox}, + {LQA_ScaleBox, nullptr, ELQAWidgetType::LQA_ScaleBox}, + {LQA_SafeZone, nullptr, ELQAWidgetType::LQA_SafeZone}, + {LQA_WrapBox, nullptr, ELQAWidgetType::LQA_WrapBox}, + {LQA_GridPanel, nullptr, ELQAWidgetType::LQA_GridPanel}, + {LQA_UniformGridPanel, nullptr, ELQAWidgetType::LQA_UniformGridPanel}, + {LQA_Overlay, nullptr, ELQAWidgetType::LQA_Overlay}, + {LQA_Border, nullptr, ELQAWidgetType::LQA_Border}, + {LQA_BackgroundBlur, nullptr, ELQAWidgetType::LQA_BackgroundBlur}, + {LQA_WidgetSwitcher, nullptr, ELQAWidgetType::LQA_WidgetSwitcher}, + {LQA_StackBox, nullptr, ELQAWidgetType::LQA_StackBox}, + {LQA_WindowTitleBarArea, nullptr, ELQAWidgetType::LQA_WindowTitleBarArea}, + {LQA_MenuAnchor, nullptr, ELQAWidgetType::LQA_MenuAnchor}, + {LQA_InvalidationBox, nullptr, ELQAWidgetType::LQA_InvalidationBox}, + {LQA_ScrollBar, nullptr, ELQAWidgetType::LQA_ScrollBar}, + {LQA_PostBufferUpdate, nullptr, ELQAWidgetType::LQA_PostBufferUpdate}, + {LQA_ObjectTableRow, nullptr, ELQAWidgetType::LQA_UserWidget}, // 列表行控件: Slate 根为 ObjectTableRowT, 按 UserWidget 采集以保留类型与子树 + {LQA_ListView, nullptr, ELQAWidgetType::LQA_ListView}, + {LQA_TileView, nullptr, ELQAWidgetType::LQA_TileView}, + {LQA_TreeView, nullptr, ELQAWidgetType::LQA_TreeView}, + {LQA_ExpandableArea, nullptr, ELQAWidgetType::LQA_ExpandableArea}, + + // 输入类 + {LQA_ProgressBar, nullptr, ELQAWidgetType::LQA_ProgressBar}, + {LQA_Slider, nullptr, ELQAWidgetType::LQA_Slider}, + // Slider 的 Slate 名固定; 而 SpinBox 运行时名为 SSpinBox, 故需前缀匹配 + {LQA_SpinBox, nullptr, ELQAWidgetType::LQA_SpinBox, NAME_None, true}, + + // 展示类 + {LQA_Throbber, nullptr, ELQAWidgetType::LQA_Throbber}, + {LQA_CircularThrobber, nullptr, ELQAWidgetType::LQA_CircularThrobber}, + {LQA_Spacer, nullptr, ELQAWidgetType::LQA_Spacer}, + + // 项目自定义控件类型可在此处追加新条目 + }; + + return Entries; +} + +namespace +{ +struct FWrappedWidgetClassDesc +{ + UClass* WidgetClass; + ELQAWidgetType WidgetType; +}; + +ELQAWidgetType ResolveWrappedWidgetType(const UWidget* SourceWidget) +{ + static const TArray WrappedClasses = { + {UTextBlock::StaticClass(), ELQAWidgetType::LQA_TextBlock}, + {URichTextBlock::StaticClass(), ELQAWidgetType::LQA_RichText}, + {UEditableText::StaticClass(), ELQAWidgetType::LQA_EditableText}, + {UEditableTextBox::StaticClass(), ELQAWidgetType::LQA_EditableTextBox}, + {UMultiLineEditableText::StaticClass(), ELQAWidgetType::LQA_MultilineEditableText}, + {UMultiLineEditableTextBox::StaticClass(), ELQAWidgetType::LQA_MultilineEditableTextBox}, + {UImage::StaticClass(), ELQAWidgetType::LQA_Image}, + }; + + for (const FWrappedWidgetClassDesc& Desc : WrappedClasses) + { + if (SourceWidget->IsA(Desc.WidgetClass)) + { + return Desc.WidgetType; + } + } + return ELQAWidgetType::LQA_Undefined; +} +} // namespace + +// 判定控件类型: 依次按 "精确类 → IsA → 无约束" 三轮扫描登记表 +// 分三轮而非一轮的原因: 保证高优先级规则先命中, +// 避免父类条目 (如 UComboBox) 抢走本应属于子类 (如 UComboBoxKey) 的匹配 +const FLQAWidgetTypeDesc* FLQAWidgetTypeRegistry::TryGetWidgetTypeDesc( + const FName& SlateTypeName, const UObject* SourceObject) +{ + const TArray& Entries = GetEntries(); + + // 来源对象可能并非 UWidget (或为空), Cast 失败时 SourceWidget 为 nullptr, + // 届时跳过前两轮类约束匹配, 仅走第 3 轮无约束匹配 + const UWidget* SourceWidget = Cast(SourceObject); + + // SInvalidationPanel 也用作 TextBlock 的包装层, 此时按 UMG 类判定 + if (SourceWidget && SlateTypeName == LQAWidgetNames::LQA_InvalidationBox) + { + const ELQAWidgetType WrappedType = ResolveWrappedWidgetType(SourceWidget); + if (WrappedType != ELQAWidgetType::LQA_Undefined) + { + for (const FLQAWidgetTypeDesc& Entry : Entries) + { + if (Entry.WidgetType == WrappedType && Entry.WidgetClass == nullptr) + { + return &Entry; + } + } + } + } + + if (SourceWidget) + { + const UClass* SourceClass = SourceWidget->GetClass(); + + // 第 1 轮: 精确类匹配 (类完全相等) + // 优先级最高, 确保 UComboBoxKey 不会被父类 UComboBox 的条目先命中 + for (const FLQAWidgetTypeDesc& Entry : Entries) + { + if (Entry.WidgetClass && SourceClass == Entry.WidgetClass && IsSlateNameMatched(Entry, SlateTypeName)) + { + return &Entry; + } + } + + // 第 2 轮: IsA 匹配 (是某登记类的子类) + // 覆盖蓝图继承场景, 例如一个 WBP 继承自 USizeBox, 其精确类不在表中, + // 但 IsA(USizeBox) 为真, 可归入 SizeBox 类型 + for (const FLQAWidgetTypeDesc& Entry : Entries) + { + if (Entry.WidgetClass && SourceWidget->IsA(Entry.WidgetClass) && IsSlateNameMatched(Entry, SlateTypeName)) + { + return &Entry; + } + } + } + + // 第 3 轮: 无 UMG 类约束的条目 (1:1 类型), 仅凭 Slate 名判定 + for (const FLQAWidgetTypeDesc& Entry : Entries) + { + if (!Entry.WidgetClass && IsSlateNameMatched(Entry, SlateTypeName)) + { + return &Entry; + } + } + + // 三轮均未命中: 通常是未登记的 Slate 内部控件 (无需作为 LQA 节点处理) + return nullptr; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b719fea71a344198e83dec548b76f3116dc5b80f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/BackgroundBlurSlot.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_BackgroundBlurSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UBackgroundBlurSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UBackgroundBlurSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BorderSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BorderSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e80a68c21a7310a1a456eca2f340bf9c738600c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_BorderSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_BorderSlot2Json.h" + +#include "Components/BorderSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_BorderSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UBorderSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UBorderSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ButtonSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ButtonSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e02208b8ed782068c3fd23aecd10e6e6aaa8121f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ButtonSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_ButtonSlot2Json.h" + +#include "Components/ButtonSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_ButtonSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UButtonSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UButtonSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd0d7b7017c2c86519471239efab940782380d47 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.h" + +#include "Components/CanvasPanelSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_CanvasPanelSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UCanvasPanelSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UCanvasPanelSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_GridSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_GridSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ae766005ab1965501f636022c338c751ec24440 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_GridSlot2Json.cpp @@ -0,0 +1,33 @@ +#include "WidgetSlots/Slot/LQA_GridSlot2Json.h" + +#include "Components/GridSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_GridSlot2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UGridSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UGridSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a71f5fef87654869b4df40b3fd1d38e73c54c523 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.h" + +#include "Components/HorizontalBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_HorizontalBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UHorizontalBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UHorizontalBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_OverlaySlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_OverlaySlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b013c4d031d1ba5652dd3e1ad5248a92755c9c50 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_OverlaySlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_OverlaySlot2Json.h" + +#include "Components/OverlaySlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_OverlaySlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UOverlaySlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UOverlaySlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_PanelSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_PanelSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7466b3dc5bf6b7a6938c1abc72967615fa0904a6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_PanelSlot2Json.cpp @@ -0,0 +1,38 @@ +#include "WidgetSlots/Slot/LQA_PanelSlot2Json.h" + +#include "Components/PanelSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +// 输出单子容器内容槽: UPanelSlot 基类无可序列化的布局属性时仍写入空 Slot 对象与槽类型 +void FLQA_PanelSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (!InWidget->SourceObject.IsValid()) + { + return; + } + + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UPanelSlot* Slot = Cast(SourceUwg->Slot); + if (!Slot) + { + return; + } + + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot); + + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UPanelSlot")); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b8160dbf0bf4d4463b9c23eb5598093573383e5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_SafeZoneSlot2Json.h" + +#include "Components/SafeZoneSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_SafeZoneSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + USafeZoneSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("USafeZoneSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c70a6f4ca9cfc8f0c2a72043ec6f14c698ea28a1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.h" + +#include "Components/ScaleBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_ScaleBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UScaleBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UScaleBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92f973c090b7babdc6b4425c30c2ee2e30ab30d0 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.h" + +#include "Components/ScrollBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_ScrollBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UScrollBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UScrollBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..793823771fba1e6caa0bdcde1d4f5157789620a3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_SizeBoxSlot2Json.h" + +#include "Components/SizeBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_SizeBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + USizeBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("USizeBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_StackBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_StackBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61d08540df06596fa45ba0e9600695858eea138a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_StackBoxSlot2Json.cpp @@ -0,0 +1,45 @@ +#include "WidgetSlots/Slot/LQA_StackBoxSlot2Json.h" + +#if ENGINE_MAJOR_VERSION >= 5 + +#include "Components/Widget.h" +#include "Components/StackBoxSlot.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_StackBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UStackBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UStackBoxSlot")); + } + } + } +} + +#else + +void FLQA_StackBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ +} + +#endif // ENGINE_MAJOR_VERSION >= 5 diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_UniformGridSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_UniformGridSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0904a35d3d394bcae06d4610530d3f10dea2cf7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_UniformGridSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_UniformGridSlot2Json.h" + +#include "Components/UniformGridSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_UniformGridSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UUniformGridSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UUniformGridSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fdc4dd7f3c7362498808781052a24ce37837573a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.h" + +#include "Components/VerticalBoxSlot.h" +#include "Components/Widget.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_VerticalBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UVerticalBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UVerticalBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0a43a3da69abe8fdeff0c7b2c31d85f96f775ee --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WidgetSwitcherSlot.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_WidgetSwitcherSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UWidgetSwitcherSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UWidgetSwitcherSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..438adef087c05a8f67f69f960d0dc7bef423efdc --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WindowTitleBarAreaSlot.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_WindowTitleBarAreaSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UWindowTitleBarAreaSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UWindowTitleBarAreaSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa798d510730193b48f5fe2b5b558c5d72126d33 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Slot/LQA_WrapBoxSlot2Json.h" + +#include "Components/Widget.h" +#include "Components/WrapBoxSlot.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_WrapBoxSlot2Json::ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid()) + { + return; + } + + if (InWidget->SourceObject.IsValid()) + { + UWidget* SourceUwg = Cast(InWidget->SourceObject); + if (!SourceUwg) + { + return; + } + + UWrapBoxSlot* Slot = Cast(SourceUwg->Slot); + if (Slot) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UWrapBoxSlot")); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonFactory.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ee8d90ca0ba17764fdd8801f817c766267b4c2d --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonFactory.cpp @@ -0,0 +1,113 @@ +#include "WidgetSlots/Slot2JsonFactory.h" + +#include "Snapshot/LQAWidgetNode.h" +// 以下为各种具体 Slot 类型对应的序列化处理器头文件 +// 每个 Slot 类型都对应 UMG 中的一种布局容器 (如 CanvasPanel、VerticalBox 等) +#include "WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.h" +#include "WidgetSlots/Slot/LQA_BorderSlot2Json.h" +#include "WidgetSlots/Slot/LQA_ButtonSlot2Json.h" +#include "WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.h" +#include "WidgetSlots/Slot/LQA_GridSlot2Json.h" +#include "WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_OverlaySlot2Json.h" +#include "WidgetSlots/Slot/LQA_PanelSlot2Json.h" +#include "WidgetSlots/Slot/LQA_SafeZoneSlot2Json.h" +#include "WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_SizeBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_StackBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_UniformGridSlot2Json.h" +#include "WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.h" +#include "WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.h" +#include "WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.h" +#include "WidgetSlots/Slot2JsonInterface.h" +#include "WidgetSlots/Slot/LQA_WrapBoxSlot2Json.h" + +/** + * 根据控件节点的 Slot 类型创建对应的序列化处理器 + * 核心逻辑: 通过 switch 分发, 将枚举类型映射到具体的处理器实例 + */ +TSharedPtr FSlot2JsonFactory::MakeSlotData(const TSharedPtr WidgetNode) +{ + // 入参校验: 节点无效时打印警告并返回空指针 + if (!WidgetNode.IsValid()) + { + UE_LOG(LogLQAToolSlot2Json, Warning, TEXT("MakeSlotData: Invalid WidgetNode passed.")); + return nullptr; + } + + // 根据节点的 Slot 类型, 创建并返回对应的序列化处理器 + // MakeShareable: 将 new 出来的裸指针包装为 TSharedPtr, 由智能指针托管生命周期 + switch (WidgetNode->GetSlotType()) + { + case ELQASlotType::LQA_ButtonSlot: // 按钮槽 + return MakeShareable(new FLQA_ButtonSlot2Json()); + case ELQASlotType::LQA_CanvasPanelSlot: // 画布面板槽 (绝对定位) + return MakeShareable(new FLQA_CanvasPanelSlot2Json()); + case ELQASlotType::LQA_ScrollBoxSlot: // 滚动框槽 + return MakeShareable(new FLQA_ScrollBoxSlot2Json()); + case ELQASlotType::LQA_VerticalBoxSlot: // 垂直布局框槽 + return MakeShareable(new FLQA_VerticalBoxSlot2Json()); + case ELQASlotType::LQA_HorizontalBoxSlot: // 水平布局框槽 + return MakeShareable(new FLQA_HorizontalBoxSlot2Json()); + case ELQASlotType::LQA_ScaleBoxSlot: // 缩放框槽 + return MakeShareable(new FLQA_ScaleBoxSlot2Json()); + case ELQASlotType::LQA_SafeZoneSlot: // 安全区域槽 (适配刘海屏等) + return MakeShareable(new FLQA_SafeZoneSlot2Json()); + case ELQASlotType::LQA_WrapBoxSlot: // 自动换行框槽 + return MakeShareable(new FLQA_WrapBoxSlot2Json()); + case ELQASlotType::LQA_SizeBoxSlot: // 固定尺寸框槽 + return MakeShareable(new FLQA_SizeBoxSlot2Json()); + case ELQASlotType::LQA_GridSlot: // 网格槽 + return MakeShareable(new FLQA_GridSlot2Json()); + case ELQASlotType::LQA_UniformGridSlot: // 均匀网格槽 + return MakeShareable(new FLQA_UniformGridSlot2Json()); + case ELQASlotType::LQA_OverlaySlot: // 叠加层槽 + return MakeShareable(new FLQA_OverlaySlot2Json()); + case ELQASlotType::LQA_BorderSlot: // 边框槽 + return MakeShareable(new FLQA_BorderSlot2Json()); + case ELQASlotType::LQA_WidgetSwitcherSlot: // 控件切换器槽 + return MakeShareable(new FLQA_WidgetSwitcherSlot2Json()); + case ELQASlotType::LQA_BackgroundBlurSlot: // 背景模糊槽 + return MakeShareable(new FLQA_BackgroundBlurSlot2Json()); + case ELQASlotType::LQA_StackBoxSlot: // 堆叠框槽 + return MakeShareable(new FLQA_StackBoxSlot2Json()); + case ELQASlotType::LQA_WindowTitleBarAreaSlot:// 窗口标题栏区域槽 + return MakeShareable(new FLQA_WindowTitleBarAreaSlot2Json()); + case ELQASlotType::LQA_PanelSlot: // 单子容器内容槽 + return MakeShareable(new FLQA_PanelSlot2Json()); + default: + // 未知/不支持的 Slot 类型, 不做处理 + break; + } + + // 未匹配到任何已知类型时返回空指针 + return nullptr; +} + +/** + * 对外统一入口: 将指定控件节点的 Slot 数据序列化为 JSON 对象 + */ +TSharedPtr FSlot2JsonFactory::Slot2Json(const TSharedPtr& Widget) +{ + // 创建一个空的 JSON 对象作为返回结果的容器 + TSharedPtr NewObject = MakeShared(); + + // 入参校验: 节点无效时打印警告并返回空 JSON 对象 (而非 nullptr, 便于调用方直接使用) + if (!Widget.IsValid()) + { + UE_LOG(LogLQAToolSlot2Json, Warning, TEXT("Slot2Json: Invalid WidgetNode passed.")); + return NewObject; + } + + // 通过工厂方法获取与该节点 Slot 类型匹配的序列化处理器 + const TSharedPtr Interface = MakeSlotData(Widget); + if (Interface.IsValid()) + { + // 调用处理器的 ToJson, 将 Slot 数据写入 NewObject + Interface->ToJson(Widget, NewObject); + } + + // 返回最终的 JSON 对象 (即使没有匹配到处理器, 也返回空对象) + return NewObject; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonInterface.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a1a1d8738cc7ac25e56bcaf73fabe62168d7b7a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Slot2JsonInterface.cpp @@ -0,0 +1,8 @@ +#include "WidgetSlots/Slot2JsonInterface.h" // 本接口对应的头文件 + +#include "Snapshot/LQAWidgetNode.h" // 控件节点定义 (ToJson 中会用到) +#include "Styling/SlateColor.h" // Slate 颜色类型, Slot 序列化时可能涉及 + +// 定义 (实例化) 在头文件中声明的日志分类 LogLQAToolSlot2Json +// DECLARE_LOG_CATEGORY_EXTERN 负责声明, DEFINE_LOG_CATEGORY 负责在某个 .cpp 中定义, 二者需配对 +DEFINE_LOG_CATEGORY(LogLQAToolSlot2Json); \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_BackgroundBlur2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_BackgroundBlur2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f357e64e5ca97a4c92b8a85b4f7a34ddd96dca1c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_BackgroundBlur2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_BackgroundBlur2Json.h" + +#include "Components/BackgroundBlur.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_BackgroundBlur2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_BackgroundBlur.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Border2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Border2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52bb3ba675266d323c5672ce3eb683e8522a5ebd --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Border2Json.cpp @@ -0,0 +1,30 @@ +#include "WidgetSlots/Widget/LQA_Border2Json.h" + +#include "Components/Border.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_Border2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Border.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UBorder* Border = Cast(InWidget->SourceObject); + if (Border) + { + UObject* ResourceObject = Border->Background.GetResourceObject(); + if (ResourceObject) + { + OutJsonObject->SetObjectField( + TEXT("TextureData"), FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap)); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Button2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Button2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..234332bbf6459b5f33660d304986cec09af565ff --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Button2Json.cpp @@ -0,0 +1,39 @@ +#include "WidgetSlots/Widget/LQA_Button2Json.h" + +#include "Components/Button.h" +#include "Engine/Texture2D.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQAJsonUtils.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_Button2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Button.ToString()); + if (InWidget->SourceObject.IsValid()) + { + const UButton* Button = Cast(InWidget->SourceObject); + if (Button) + { + // 记录Brush +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = Button->GetStyle().Normal.GetResourceObject(); + FVector2D ImageSize = Button->GetStyle().Normal.ImageSize; +#else + UObject* ResourceObject = Button->WidgetStyle.Normal.GetResourceObject(); + FVector2D ImageSize = Button->WidgetStyle.Normal.ImageSize; +#endif + if (ResourceObject) + { + const TSharedPtr TextureObj = + FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap); + OutJsonObject->SetObjectField(TEXT("TextureData"), TextureObj); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CanvasPanel2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CanvasPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a5ea9ef00f1d4b6818e26a33943ad6365c40093 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CanvasPanel2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_CanvasPanel2Json.h" + +#include "Components/CanvasPanel.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQAJsonUtils.h" + +void FLQA_CanvasPanel2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Canvas.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CheckBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CheckBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fff28055e62b02bf4f7e05578b317d5d33ea670 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CheckBox2Json.cpp @@ -0,0 +1,35 @@ +#include "WidgetSlots/Widget/LQA_CheckBox2Json.h" + +#include "Components/CheckBox.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQAJsonUtils.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_CheckBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_CheckBox.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UCheckBox* CheckBox = Cast(InWidget->SourceObject); + if (CheckBox) + { +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = CheckBox->GetWidgetStyle().UncheckedImage.GetResourceObject(); +#else + UObject* ResourceObject = CheckBox->WidgetStyle.UncheckedImage.GetResourceObject(); +#endif + if (ResourceObject) + { + OutJsonObject->SetObjectField( + TEXT("TextureData"), FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap)); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CircularThrobber2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CircularThrobber2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..600fe3c16b80b39239ec5b03de06fc020b01e5ce --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_CircularThrobber2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Widget/LQA_CircularThrobber2Json.h" + +#include "Components/CircularThrobber.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_CircularThrobber2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_CircularThrobber.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + if (const UCircularThrobber* CircularThrobberIns = Cast(InWidget->SourceObject.Get())) + { +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = CircularThrobberIns->GetImage().GetResourceObject(); +#else + UObject* ResourceObject = CircularThrobberIns->Image.GetResourceObject(); +#endif + if (ResourceObject) + { + const TSharedPtr TextureObj = + FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap); + OutJsonObject->SetObjectField(TEXT("TextureData"), TextureObj); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ComboBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ComboBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..493792a295b99a830549d4bd9e518d9798e32aff --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ComboBox2Json.cpp @@ -0,0 +1,44 @@ +#include "WidgetSlots/Widget/LQA_ComboBox2Json.h" + +#include "Components/ComboBoxString.h" +#include "Snapshot/LQAWidgetNode.h" +#include "WidgetSlots/WidgetDefines.h" + +void FLQA_ComboBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ComboBox.ToString()); + + if (!InWidget->SourceObject.IsValid()) + { + return; + } + + UObject* SourceObj = InWidget->SourceObject.Get(); + + const UComboBoxString* ComboBoxStringIns = Cast(SourceObj); + if (!ComboBoxStringIns) + { + return; + } + + TArray> OptionJsonArray; + const int32 OptionCount = ComboBoxStringIns->GetOptionCount(); + OptionJsonArray.Reserve(OptionCount); + for (int32 Index = 0; Index < OptionCount; ++Index) + { + OptionJsonArray.Emplace(MakeShared(ComboBoxStringIns->GetOptionAtIndex(Index))); + } + OutJsonObject->SetArrayField(TEXT("OptionStrings"), OptionJsonArray); + + const FString SelectedOption = ComboBoxStringIns->GetSelectedOption(); + if (!SelectedOption.IsEmpty()) + { + OutJsonObject->SetStringField(*CommonStrKey, SelectedOption); + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae53daa9b6c94b5e3c995f4ddfa64dbfba3075e3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.cpp @@ -0,0 +1,16 @@ +#include "WidgetSlots/Widget/LQA_DynamicEntryBox2Json.h" + +#include "Snapshot/LQAWidgetNode.h" +#include "WidgetSlots/WidgetDefines.h" + +// 输出动态条目框: WidgetType 取实际 Slate 根类型名, 由 WidgetClass 标识动态条目框 +void FLQA_DynamicEntryBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), InWidget->BaseWidgetType); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8312d00be09cb77b4093464dddc076ff2e6ffb2f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBlock2Json.cpp @@ -0,0 +1,30 @@ +#include "WidgetSlots/Widget/LQA_EditableTextBlock2Json.h" + +#include "Components/EditableText.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_EditableTextBlock2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_EditableText.ToString()); + if (InWidget->SourceObject.IsValid()) + { + const UEditableText* EditableText = Cast(InWidget->SourceObject); + if (EditableText) + { + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetText()); +#if ENGINE_MAJOR_VERSION >= 5 + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetHintText(), TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); +#else + WriteTextEntry_ToJson(OutJsonObject, EditableText->HintText, TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); +#endif + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBox2json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBox2json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a9b5633743f77814e6b06597bd986b6baa146cd --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_EditableTextBox2json.cpp @@ -0,0 +1,30 @@ +#include "WidgetSlots/Widget/LQA_EditableTextBox2Json.h" + +#include "Components/EditableTextBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_EditableTextBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_EditableTextBox.ToString()); + if (InWidget->SourceObject.IsValid()) + { + const UEditableTextBox* EditableText = Cast(InWidget->SourceObject); + if (EditableText) + { + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetText()); +#if ENGINE_MAJOR_VERSION >= 5 + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetHintText(), TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); +#else + WriteTextEntry_ToJson(OutJsonObject, EditableText->HintText, TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); +#endif + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ExpandableArea2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ExpandableArea2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22d942ba4912d95fa551156135ccff7025b69b32 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ExpandableArea2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_ExpandableArea2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_ExpandableArea2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ExpandableArea.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_GridPanel2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_GridPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0376ad1d09e496086018ee741aeb8866b186334e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_GridPanel2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_GridPanel2Json.h" + +#include "Components/GridPanel.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_GridPanel2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_GridPanel.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_HorizontalBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_HorizontalBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e442a3af390387180dea9d04ad641cbe9c3aed8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_HorizontalBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_HorizontalBox2Json.h" + +#include "Components/HorizontalBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_HorizontalBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_HorizontalBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Image2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Image2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce4b359a196016b96a44ec381e3521354cf08c39 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Image2Json.cpp @@ -0,0 +1,39 @@ +#include "WidgetSlots/Widget/LQA_Image2Json.h" + +#include "Components/Image.h" +#include "Engine/Texture2D.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQAJsonUtils.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_Image2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Image.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + UImage* Image = Cast(InWidget->SourceObject); + if (Image) + { +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = Image->GetBrush().GetResourceObject(); + FVector2D ImageSize = Image->GetBrush().ImageSize; +#else + UObject* ResourceObject = Image->Brush.GetResourceObject(); + FVector2D ImageSize = Image->Brush.ImageSize; +#endif + if (ResourceObject) + { + const TSharedPtr TextureObj = + FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap); + OutJsonObject->SetObjectField(TEXT("TextureData"), TextureObj); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InputKeySelector2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InputKeySelector2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b874a38103da6400370b26a878f6369817d25ca --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InputKeySelector2Json.cpp @@ -0,0 +1,32 @@ +#include "WidgetSlots/Widget/LQA_InputKeySelector2Json.h" + +#include "Components/InputKeySelector.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_InputKeySelector2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_InputKeySelector.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UInputKeySelector* InputKeySelectorIns = Cast(InWidget->SourceObject); + if (InputKeySelectorIns) + { +#if ENGINE_MAJOR_VERSION >= 5 + const FText KeySelectionText = InputKeySelectorIns->GetKeySelectionText(); + const FText NoKeySpecifiedText = InputKeySelectorIns->GetNoKeySpecifiedText(); +#else + const FText KeySelectionText = InputKeySelectorIns->KeySelectionText; + const FText NoKeySpecifiedText = InputKeySelectorIns->NoKeySpecifiedText; +#endif + + WriteTextEntry_ToJson(OutJsonObject, KeySelectionText.IsEmpty() ? NoKeySpecifiedText : KeySelectionText); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InvalidationBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InvalidationBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ce4593b99eb86b3feec9c6435173261d2b61004 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_InvalidationBox2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_InvalidationBox2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_InvalidationBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_InvalidationBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ListView2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ListView2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddb862bce89921304a03470bc11159a07a2162aa --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ListView2Json.cpp @@ -0,0 +1,21 @@ +#include "WidgetSlots/Widget/LQA_ListView2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_ListView2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ListView.ToString()); + + TArray> ListItems; + CollectListEntryTexts(InWidget, ListItems); + if (ListItems.Num() > 0) + { + OutJsonObject->SetArrayField(TEXT("ListItems"), ListItems); + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MenuAnchor2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MenuAnchor2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..522c1445e90fe62e930142cefe18b267074c560d --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MenuAnchor2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_MenuAnchor2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_MenuAnchor2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_MenuAnchor.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0bef91c17cb8274160df6a9e1df2118c97c27173 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.cpp @@ -0,0 +1,26 @@ +#include "WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.h" + +#include "Components/MultiLineEditableText.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_MultilineEditableTextBlock2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_MultilineEditableText.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UMultiLineEditableText* EditableText = Cast(InWidget->SourceObject); + if (EditableText) + { + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetText()); + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetHintText(), TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6f9c8907abffcb81c669603ddf529af95869fab --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.cpp @@ -0,0 +1,26 @@ +#include "WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.h" + +#include "Components/MultiLineEditableTextBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_MultilineEditableTextBox::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_MultilineEditableTextBox.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UMultiLineEditableTextBox* EditableText = Cast(InWidget->SourceObject); + if (EditableText) + { + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetText()); + WriteTextEntry_ToJson(OutJsonObject, EditableText->GetHintText(), TEXT("hinttextStr"), TEXT("HintTextKey"), + TEXT("HintTextSourceStr")); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NamedSlot2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NamedSlot2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0f1c02a48c825e4f4080ca64b180c281ceae179 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NamedSlot2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_NamedSlot2Json.h" + +#include "Snapshot/LQAWidgetNode.h" +#include "WidgetSlots/WidgetDefines.h" + +void FLQA_NamedSlot2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_NamedSlot.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c6d66fa7c9171f59ecfd1136cf31fdc632c3aef --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_NativeWidgetHost2Json.h" + +#include "Snapshot/LQAWidgetNode.h" +#include "WidgetSlots/WidgetDefines.h" + +void FLQA_NativeWidgetHost2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_NativeWidgetHost.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Overlay2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Overlay2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba0305c16102d870ad53de87845a3fbef3fe75b6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Overlay2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_Overlay2Json.h" + +#include "Components/Overlay.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_Overlay2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Overlay.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96523061a8fb71b81f91bd58000a3642d0136091 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_PostBufferUpdate2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_PostBufferUpdate2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_PostBufferUpdate.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ProgressBar2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ProgressBar2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f0a73772765f821796385b0074a5ca6c2e7ee7d --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ProgressBar2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Widget/LQA_ProgressBar2Json.h" + +#include "Components/ProgressBar.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_ProgressBar2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ProgressBar.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + if (const UProgressBar* ProgressBar = Cast(InWidget->SourceObject.Get())) + { +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = ProgressBar->GetWidgetStyle().FillImage.GetResourceObject(); +#else + UObject* ResourceObject = ProgressBar->WidgetStyle.FillImage.GetResourceObject(); +#endif + if (ResourceObject) + { + const TSharedPtr TextureObj = + FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap); + OutJsonObject->SetObjectField(TEXT("TextureData"), TextureObj); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RetainerBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RetainerBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eaf2c99b936160f079f585a400ec87495a7e3952 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RetainerBox2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_RetainerBox2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_RetainerBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_RetainerBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RichTextBlock2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RichTextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00727914e0f23661e053e8bc452d30909c3de0dd --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_RichTextBlock2Json.cpp @@ -0,0 +1,79 @@ +#include "WidgetSlots/Widget/LQA_RichTextBlock2Json.h" + +#include "Engine/DataTable.h" +#include "Snapshot/LQAWidgetNode.h" +#include "UObject/UnrealType.h" + +namespace +{ +void SerializeRichTextStyleSet(const URichTextBlock* RichTextBlock, const TSharedPtr& OutJsonObject) +{ + if (!RichTextBlock || !OutJsonObject.IsValid()) + { + return; + } + +#if ENGINE_MAJOR_VERSION >= 5 + const UDataTable* StyleSet = RichTextBlock->GetTextStyleSet(); +#else + const UDataTable* StyleSet = nullptr; + const FObjectProperty* TextStyleSetProp = + FindFProperty(URichTextBlock::StaticClass(), TEXT("TextStyleSet")); + if (TextStyleSetProp) + { + StyleSet = Cast(TextStyleSetProp->GetObjectPropertyValue_InContainer(RichTextBlock)); + } +#endif + if (!StyleSet || StyleSet->GetRowStruct() != FRichTextStyleRow::StaticStruct()) + { + return; + } + + TSharedPtr StyleSetObject = MakeShared(); + for (const TPair& RowPair : StyleSet->GetRowMap()) + { + const auto* Row = reinterpret_cast(RowPair.Value); + if (!Row) + { + continue; + } + + TSharedRef RowObject = MakeShared(); + if (FJsonObjectConverter::UStructToJsonObject(FRichTextStyleRow::StaticStruct(), Row, RowObject, 0, 0)) + { + StyleSetObject->SetObjectField(RowPair.Key.ToString(), RowObject); + } + } + + if (StyleSetObject->Values.Num() > 0) + { + OutJsonObject->SetObjectField(TEXT("RichTextStyleSetData"), StyleSetObject); + } +} +} // namespace + +void FLQA_RichTextBlock2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_RichTextBlock.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const URichTextBlock* TextBlockIns = Cast(InWidget->SourceObject); + if (TextBlockIns) + { + const FText Text = TextBlockIns->GetText(); + + UE_LOG(LogLQAToolWidget2Json, Verbose, TEXT("Find Text Block Content = %s"), *Text.ToString()); + WriteTextEntry_ToJson(OutJsonObject, Text); + + // 样式表是运行时 Transient 对象, 序列化其行内容供还原端重建 + SerializeRichTextStyleSet(TextBlockIns, OutJsonObject); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SafeZone2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SafeZone2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eeb0a5a64fe7c1f08a1e3a4dde7de55e0f09d1fa --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SafeZone2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_SafeZone2Json.h" + +#include "Components/SafeZone.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_SafeZone2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_SafeZone.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScaleBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScaleBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bda0b45e0e79792c8535dda7339c372a4b53ee8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScaleBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_ScaleBox2Json.h" + +#include "Components/ScaleBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_ScaleBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ScaleBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBar2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBar2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfe48bb7e04e03019ee810da478b9f45f7846135 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBar2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_ScrollBar2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_ScrollBar2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ScrollBar.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c60190b8394ae8a86c8b7e0f730d13792e19c57f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_ScrollBox2Json.cpp @@ -0,0 +1,24 @@ +#include "WidgetSlots/Widget/LQA_ScrollBox2Json.h" + +#include "Components/ScrollBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_ScrollBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_ScrollBox.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UScrollBox* ScrollBoxIns = Cast(InWidget->SourceObject.Get()); + if (ScrollBoxIns) + { + OutJsonObject->SetNumberField(TEXT("ScrollOffset"), ScrollBoxIns->GetScrollOffset()); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SizeBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SizeBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e14220f7d324ffb68b88cae0a84ef28b3efea4e2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SizeBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_SizeBox2Json.h" + +#include "Snapshot/LQAWidgetNode.h" +#include "WidgetSlots/WidgetDefines.h" + +void FLQA_SizeBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_SizeBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Slider2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Slider2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6da1fe2559a8957ff43ec24783cf343705ea4fea --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Slider2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_Slider2Json.h" + +#include "Components/Slider.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_Slider2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Slider.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Spacer2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Spacer2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2dcae2b9a583157949af15ed29ed43b983061a2e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Spacer2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_Spacer2Json.h" + +#include "Components/Spacer.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_Spacer2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Spacer.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SpinBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SpinBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34c7cbde271ca6a5f9c98657e9b5236c03d2d54a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_SpinBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_SpinBox2Json.h" + +#include "Components/SpinBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_SpinBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_SpinBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_StackBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_StackBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f4d33994dec1fa0aa1935611dcd0cd0e139382e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_StackBox2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_StackBox2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_StackBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_StackBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextBlock2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextBlock2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1cefd3bb8f55b7e17f44daa0a8e0134f09b4d2f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextBlock2Json.cpp @@ -0,0 +1,25 @@ +#include "WidgetSlots/Widget/LQA_TextBlock2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_TextBlock2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_TextBlock.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + const UTextBlock* TextBlockIns = Cast(InWidget->SourceObject); + if (TextBlockIns) + { + const FText Text = TextBlockIns->GetText(); + UE_LOG(LogLQAToolWidget2Json, Verbose, TEXT("Find Text Block Content = %s"), *Text.ToString()); + WriteTextEntry_ToJson(OutJsonObject, Text); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextScroller2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextScroller2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d74432fdf5c7ca3caa7436dab955e3390c456f14 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TextScroller2Json.cpp @@ -0,0 +1,26 @@ +#include "WidgetSlots/Widget/LQA_TextScroller2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_TextScroller2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_TextScroller.ToString()); + + // 滚动文本控件的文本来源与其 UObject (TextBlock 或其派生类) 一致 + if (InWidget->SourceObject.IsValid()) + { + const UTextBlock* TextScrollerIns = Cast(InWidget->SourceObject); + if (TextScrollerIns) + { + const FText Text = TextScrollerIns->GetText(); + UE_LOG(LogLQAToolWidget2Json, Verbose, TEXT("Find Text Scroller Content = %s"), *Text.ToString()); + WriteTextEntry_ToJson(OutJsonObject, Text); + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Throbber2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Throbber2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f90dab78e22fd1a9632d09747eb6fd5d41a3ec39 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_Throbber2Json.cpp @@ -0,0 +1,34 @@ +#include "WidgetSlots/Widget/LQA_Throbber2Json.h" + +#include "Components/Throbber.h" +#include "Snapshot/LQAWidgetNode.h" +#include "Utils/LQATextureUtil.h" + +void FLQA_Throbber2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_Throbber.ToString()); + + if (InWidget->SourceObject.IsValid()) + { + if (const UThrobber* ThrobberIns = Cast(InWidget->SourceObject.Get())) + { +#if ENGINE_MAJOR_VERSION >= 5 + UObject* ResourceObject = ThrobberIns->GetImage().GetResourceObject(); +#else + UObject* ResourceObject = ThrobberIns->Image.GetResourceObject(); +#endif + if (ResourceObject) + { + const TSharedPtr TextureObj = + FLQATextureUtil::GetTextureJsonObj(ResourceObject, SharedTextureMap); + OutJsonObject->SetObjectField(TEXT("TextureData"), TextureObj); + } + } + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TileView2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TileView2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c97d88500225c51fd0ba527819750130343bfe45 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TileView2Json.cpp @@ -0,0 +1,21 @@ +#include "WidgetSlots/Widget/LQA_TileView2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_TileView2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_TileView.ToString()); + + TArray> ListItems; + CollectListEntryTexts(InWidget, ListItems); + if (ListItems.Num() > 0) + { + OutJsonObject->SetArrayField(TEXT("ListItems"), ListItems); + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TreeView2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TreeView2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf7970b8a7f02750a471c613c6ec48a4495d86b5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_TreeView2Json.cpp @@ -0,0 +1,21 @@ +#include "WidgetSlots/Widget/LQA_TreeView2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_TreeView2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_TreeView.ToString()); + + TArray> ListItems; + CollectListEntryTexts(InWidget, ListItems); + if (ListItems.Num() > 0) + { + OutJsonObject->SetArrayField(TEXT("ListItems"), ListItems); + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UniformGridPanel2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UniformGridPanel2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8223594184d49d78bd8cdcd23378f94f6452f6d9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UniformGridPanel2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_UniformGridPanel2Json.h" + +#include "Components/UniformGridPanel.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_UniformGridPanel2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_UniformGridPanel.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UserWidget2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UserWidget2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c5d1b7e662f8cbfcaa0589e0f80ac3fa7576ecc --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_UserWidget2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_UserWidget2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_UserWidget2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_UserWidget.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_VerticalBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_VerticalBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93b63eb91e7be918a515b2391e3859ef51132cb6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_VerticalBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_VerticalBox2Json.h" + +#include "Components/VerticalBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_VerticalBox2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_VerticalBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..761eb339da865c4cfcac9c1ef0c3f9c2cc6e41f5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_WidgetSwitcher2Json.h" + +#include "Components/WidgetSwitcher.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_WidgetSwitcher2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_WidgetSwitcher.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99ef3da57d7f0c6547eb8e41c999add17bcdd527 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.cpp @@ -0,0 +1,14 @@ +#include "WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.h" + +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_WindowTitleBarArea2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_WindowTitleBarArea.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WrapBox2Json.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WrapBox2Json.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24cb777351bfe5df239ea412e5ddf503bb688cf8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget/LQA_WrapBox2Json.cpp @@ -0,0 +1,15 @@ +#include "WidgetSlots/Widget/LQA_WrapBox2Json.h" + +#include "Components/WrapBox.h" +#include "Snapshot/LQAWidgetNode.h" + +void FLQA_WrapBox2Json::ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) + { + return; + } + + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_WrapBox.ToString()); +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonFactory.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..854161eb48251555ea1975f68a2e13b4671c25d6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonFactory.cpp @@ -0,0 +1,371 @@ +#include "WidgetSlots/Widget2JsonFactory.h" + +#include "Snapshot/LQAWidgetNode.h" // 控件节点定义 +#include "WidgetSlots/Widget2JsonInterface.h" // 控件转 JSON 的通用接口 +#include "WidgetSlots/WidgetDefines.h" // 控件类型枚举、日志分类等公共定义 + +// ========== 控件转换器头文件: 各具体控件类型对应的 JSON 转换实现 ========== +// 基础控件 +#include "WidgetSlots/Widget/LQA_BackgroundBlur2Json.h" +#include "WidgetSlots/Widget/LQA_Border2Json.h" +#include "WidgetSlots/Widget/LQA_Button2Json.h" +#include "WidgetSlots/Widget/LQA_CanvasPanel2Json.h" +#include "WidgetSlots/Widget/LQA_CheckBox2Json.h" +#include "WidgetSlots/Widget/LQA_CircularThrobber2Json.h" +#include "WidgetSlots/Widget/LQA_ComboBox2Json.h" +#include "WidgetSlots/Widget/LQA_DynamicEntryBox2Json.h" +#include "WidgetSlots/Widget/LQA_EditableTextBlock2Json.h" +#include "WidgetSlots/Widget/LQA_EditableTextBox2Json.h" +#include "WidgetSlots/Widget/LQA_GridPanel2Json.h" +#include "WidgetSlots/Widget/LQA_HorizontalBox2Json.h" +#include "WidgetSlots/Widget/LQA_Image2Json.h" +#include "WidgetSlots/Widget/LQA_InvalidationBox2Json.h" +#include "WidgetSlots/Widget/LQA_InputKeySelector2Json.h" +#include "WidgetSlots/Widget/LQA_MenuAnchor2Json.h" +#include "WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.h" +#include "WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.h" +#include "WidgetSlots/Widget/LQA_NamedSlot2Json.h" +#include "WidgetSlots/Widget/LQA_NativeWidgetHost2Json.h" +#include "WidgetSlots/Widget/LQA_TextScroller2Json.h" +#include "WidgetSlots/Widget/LQA_Overlay2Json.h" +#include "WidgetSlots/Widget/LQA_PostBufferUpdate2Json.h" +#include "WidgetSlots/Widget/LQA_ProgressBar2Json.h" +#include "WidgetSlots/Widget/LQA_RetainerBox2Json.h" +#include "WidgetSlots/Widget/LQA_RichTextBlock2Json.h" +#include "WidgetSlots/Widget/LQA_SafeZone2Json.h" +#include "WidgetSlots/Widget/LQA_ScaleBox2Json.h" +#include "WidgetSlots/Widget/LQA_ScrollBar2Json.h" +#include "WidgetSlots/Widget/LQA_ScrollBox2Json.h" +#include "WidgetSlots/Widget/LQA_SizeBox2Json.h" +#include "WidgetSlots/Widget/LQA_Slider2Json.h" +#include "WidgetSlots/Widget/LQA_Spacer2Json.h" +#include "WidgetSlots/Widget/LQA_SpinBox2Json.h" +#include "WidgetSlots/Widget/LQA_StackBox2Json.h" +#include "WidgetSlots/Widget/LQA_TextBlock2Json.h" +#include "WidgetSlots/Widget/LQA_Throbber2Json.h" +#include "WidgetSlots/Widget/LQA_UniformGridPanel2Json.h" +#include "WidgetSlots/Widget/LQA_UserWidget2Json.h" +#include "WidgetSlots/Widget/LQA_VerticalBox2Json.h" +#include "WidgetSlots/Widget/LQA_WidgetSwitcher2Json.h" +#include "WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.h" +#include "WidgetSlots/Widget/LQA_WrapBox2Json.h" +#include "WidgetSlots/Widget/LQA_ExpandableArea2Json.h" +#include "WidgetSlots/Widget/LQA_ListView2Json.h" +#include "WidgetSlots/Widget/LQA_TileView2Json.h" +#include "WidgetSlots/Widget/LQA_TreeView2Json.h" + +/** + * 根据控件节点的类型, 创建并返回对应的「控件 -> JSON」转换器 + * 采用工厂模式 + switch 分发: 每种控件类型映射到一个具体的转换器实现 + */ +TSharedPtr FWidget2JsonFactory::MakeWidgetData(const TSharedPtr InWidgetNode) +{ + // 入参有效性校验: 空指针直接告警并返回 + if (!InWidgetNode.IsValid()) + { + UE_LOG(LogLQAToolWidget, Warning, TEXT("MakeWidgetData: Invalid WidgetNode pointer.")); + return nullptr; + } + + // 取出控件的 LQA 类型枚举 + const ELQAWidgetType WidgetType = InWidgetNode->GetNodeType(); + + // 根据控件类型创建相应的转换器 + switch (WidgetType) + { + // ========== 基础文本类控件 ========== + case ELQAWidgetType::LQA_TextBlock: + return MakeShareable(new FLQA_TextBlock2Json()); + case ELQAWidgetType::LQA_RichText: + return MakeShareable(new FLQA_RichTextBlock2Json()); + case ELQAWidgetType::LQA_EditableText: + return MakeShareable(new FLQA_EditableTextBlock2Json()); + case ELQAWidgetType::LQA_EditableTextBox: + return MakeShareable(new FLQA_EditableTextBox2Json()); + case ELQAWidgetType::LQA_MultilineEditableText: + return MakeShareable(new FLQA_MultilineEditableTextBlock2Json()); + case ELQAWidgetType::LQA_MultilineEditableTextBox: + return MakeShareable(new FLQA_MultilineEditableTextBox()); + case ELQAWidgetType::LQA_TextScroller: + return MakeShareable(new FLQA_TextScroller2Json()); + + // ========== 输入类控件 ========== + case ELQAWidgetType::LQA_ComboBoxStringText: + return MakeShareable(new FLQA_ComboBox2Json()); + case ELQAWidgetType::LQA_InputKeySelector: + return MakeShareable(new FLQA_InputKeySelector2Json()); + case ELQAWidgetType::LQA_CheckBox: + return MakeShareable(new FLQA_CheckBox2Json()); + case ELQAWidgetType::LQA_Button: + return MakeShareable(new FLQA_Button2Json()); + case ELQAWidgetType::LQA_ProgressBar: + return MakeShareable(new FLQA_ProgressBar2Json()); + case ELQAWidgetType::LQA_Slider: + return MakeShareable(new FLQA_Slider2Json()); + case ELQAWidgetType::LQA_SpinBox: + return MakeShareable(new FLQA_SpinBox2Json()); + + // ========== 展示类控件 ========== + case ELQAWidgetType::LQA_Image: + return MakeShareable(new FLQA_Image2Json()); + case ELQAWidgetType::LQA_Throbber: + return MakeShareable(new FLQA_Throbber2Json()); + case ELQAWidgetType::LQA_CircularThrobber: + return MakeShareable(new FLQA_CircularThrobber2Json()); + case ELQAWidgetType::LQA_Spacer: + return MakeShareable(new FLQA_Spacer2Json()); + case ELQAWidgetType::LQA_BackgroundBlur: + return MakeShareable(new FLQA_BackgroundBlur2Json()); + case ELQAWidgetType::LQA_Border: + return MakeShareable(new FLQA_Border2Json()); + + // ========== 容器类控件 ========== + case ELQAWidgetType::LQA_UserWidget: + return MakeShareable(new FLQA_UserWidget2Json()); + case ELQAWidgetType::LQA_Canvas: + return MakeShareable(new FLQA_CanvasPanel2Json()); + case ELQAWidgetType::LQA_RetainerBox: + return MakeShareable(new FLQA_RetainerBox2Json()); + case ELQAWidgetType::LQA_Overlay: + return MakeShareable(new FLQA_Overlay2Json()); + case ELQAWidgetType::LQA_WidgetSwitcher: + return MakeShareable(new FLQA_WidgetSwitcher2Json()); + case ELQAWidgetType::LQA_StackBox: + return MakeShareable(new FLQA_StackBox2Json()); + case ELQAWidgetType::LQA_WindowTitleBarArea: + return MakeShareable(new FLQA_WindowTitleBarArea2Json()); + case ELQAWidgetType::LQA_MenuAnchor: + return MakeShareable(new FLQA_MenuAnchor2Json()); + case ELQAWidgetType::LQA_InvalidationBox: + return MakeShareable(new FLQA_InvalidationBox2Json()); + case ELQAWidgetType::LQA_ScrollBar: + return MakeShareable(new FLQA_ScrollBar2Json()); + case ELQAWidgetType::LQA_PostBufferUpdate: + return MakeShareable(new FLQA_PostBufferUpdate2Json()); + case ELQAWidgetType::LQA_DynamicEntryBox: + return MakeShareable(new FLQA_DynamicEntryBox2Json()); + case ELQAWidgetType::LQA_ListView: + return MakeShareable(new FLQA_ListView2Json()); + case ELQAWidgetType::LQA_TileView: + return MakeShareable(new FLQA_TileView2Json()); + case ELQAWidgetType::LQA_TreeView: + return MakeShareable(new FLQA_TreeView2Json()); + case ELQAWidgetType::LQA_ExpandableArea: + return MakeShareable(new FLQA_ExpandableArea2Json()); + + // ========== 布局类控件 ========== + case ELQAWidgetType::LQA_VerticalBox: + return MakeShareable(new FLQA_VerticalBox2Json()); + case ELQAWidgetType::LQA_HorizontalBox: + return MakeShareable(new FLQA_HorizontalBox2Json()); + case ELQAWidgetType::LQA_GridPanel: + return MakeShareable(new FLQA_GridPanel2Json()); + case ELQAWidgetType::LQA_UniformGridPanel: + return MakeShareable(new FLQA_UniformGridPanel2Json()); + case ELQAWidgetType::LQA_WrapBox: + return MakeShareable(new FLQA_WrapBox2Json()); + + // ========== 滚动类控件 ========== + case ELQAWidgetType::LQA_ScrollBox: + return MakeShareable(new FLQA_ScrollBox2Json()); + + // ========== 尺寸约束类控件 ========== + case ELQAWidgetType::LQA_ScaleBox: + return MakeShareable(new FLQA_ScaleBox2Json()); + case ELQAWidgetType::LQA_SafeZone: + return MakeShareable(new FLQA_SafeZone2Json()); + // Slate 根类型复用: Slate 根均为 SBox, 具体类型由注册表按 UMG 类区分 + case ELQAWidgetType::LQA_SizeBox: + return MakeShareable(new FLQA_SizeBox2Json()); + case ELQAWidgetType::LQA_NamedSlot: + return MakeShareable(new FLQA_NamedSlot2Json()); + case ELQAWidgetType::LQA_NativeWidgetHost: + return MakeShareable(new FLQA_NativeWidgetHost2Json()); + + // ========== 未支持的控件类型 ========== + default: + // 记录告警并输出具体的类型枚举值, 便于后续排查/扩展 + UE_LOG(LogLQAToolWidget, Warning, TEXT("MakeWidgetData: Unsupported widget type: %d"), + static_cast(WidgetType)); + break; + } + + return nullptr; +} + +/** + * 将「未定义(不支持的)」控件转换为 JSON + * 仅写入 WidgetType="UNDEFINE" 标记, 并填充未定义控件所需的通用数据 + */ +TSharedPtr FWidget2JsonFactory::UndefineWidget2Json(const TSharedPtr& InWidget) +{ + // 新建一个空的 JSON 对象 + TSharedPtr NewObject = MakeShareable(new FJsonObject()); + // 标记该控件类型为未定义 + NewObject->SetStringField(TEXT("WidgetType"), TEXT("UNDEFINE")); + + // 节点有效时, 填充未定义控件的通用数据 + if (InWidget.IsValid()) + { + InWidget->FillCommonDataForUndefinedWidget(NewObject); + } + + return NewObject; +} + +/** + * 将控件转换为 JSON 的核心入口 + * 流程: 填充通用数据 -> 按类型做差异化序列化 -> 写入 Slate 根类型复用标识 + */ +TSharedPtr FWidget2JsonFactory::Widget2Json( + const TSharedPtr& InWidget, TMap& SharedTextureMap, const bool bNeedObjectData) +{ + // 新建承载结果的 JSON 对象 + TSharedPtr NewObject = MakeShareable(new FJsonObject()); + + // 先填充控件的通用数据 (名称、坐标、尺寸、图层、插槽类型等) + if (InWidget.IsValid()) + { + InWidget->FillCommonData(NewObject, bNeedObjectData); + } + + // 按控件类型选取对应转换器并执行类型差异化序列化 + const TSharedPtr Interface = MakeWidgetData(InWidget); + if (Interface.IsValid()) + { + // 调用具体转换器的 ToJson, 将该类型特有的字段写入 NewObject + Interface->ToJson(InWidget, NewObject, SharedTextureMap); + } + else + { + // 未能创建转换器 (类型不支持或节点无效), 记录告警 + UE_LOG(LogLQAToolWidget, Warning, TEXT("Widget2Json: Failed to create interface for widget conversion")); + } + + // Slate 根类型复用: 由注册表判定的 UMG 侧标识统一写入 WidgetClass 字段 (1:1 类型不写) + if (InWidget.IsValid() && InWidget->WidgetClassTag != NAME_None) + { + NewObject->SetStringField(TEXT("WidgetClass"), InWidget->WidgetClassTag.ToString()); + } + + return NewObject; +} + +/** + * 从控件 JSON 数据中解析控件的位置 + * 优先使用 corners (四角点) 数组的左上角点; 若无则回退到 ViewportPos 字段 + */ +FVector2D FWidget2JsonFactory::GetWidgetPos(const TSharedPtr InWidgetData, const FVector2D& InWindowSize) +{ + // 优先尝试从 corners 四角点数组中获取位置 + if (InWidgetData->HasField(TEXT("corners"))) + { + const TArray> SizePoint = InWidgetData->GetArrayField(TEXT("corners")); + // 四角点结构应恰好包含 4 个点, 索引 [1] 约定为左上角点 + if (SizePoint.Num() == 4) + { + return DeserializePoint(SizePoint[1]->AsObject(), InWindowSize); + } + } + + // 回退方案: 使用 ViewportPos 字段 (视口坐标) + if (InWidgetData->HasField(TEXT("ViewportPos"))) + { + const TSharedPtr ViewportPosObj = InWidgetData->GetObjectField(TEXT("ViewportPos")); + FVector2D Point = FVector2D::ZeroVector; + + // 分别读取 x、y 分量 (字段可能缺失, 故逐个判断) + if (ViewportPosObj->HasField(TEXT("x"))) + { + Point.X = ViewportPosObj->GetNumberField(TEXT("x")); + } + + if (ViewportPosObj->HasField(TEXT("y"))) + { + Point.Y = ViewportPosObj->GetNumberField(TEXT("y")); + } + + return Point; + } + + // 两种来源都没有时, 返回零向量 + return FVector2D::ZeroVector; +} + +/** + * 从控件 JSON 数据中解析控件的尺寸 + * @param bUseAbsoluteSize 为 true 时由四角点计算绝对尺寸; 为 false 时使用 LocalSize 本地尺寸 + */ +FVector2D FWidget2JsonFactory::GetWidgetSize( + const TSharedPtr InWidgetData, const FVector2D& InWindowSize, bool bUseAbsoluteSize) +{ + if (bUseAbsoluteSize) + { + // 由 corners 四角点计算尺寸: 右下角 - 左上角 + if (InWidgetData->HasField(TEXT("corners"))) + { + const TArray> SizePoint = InWidgetData->GetArrayField(TEXT("corners")); + if (SizePoint.Num() == 4) + { + // 索引 [1] 为左上角, [3] 为右下角 + const FVector2D LeftUpper = DeserializePoint(SizePoint[1]->AsObject(), InWindowSize); + const FVector2D RightBottom = DeserializePoint(SizePoint[3]->AsObject(), InWindowSize); + return RightBottom - LeftUpper; + } + } + + return FVector2D::ZeroVector; + } + + // 非绝对尺寸: 若存在 LocalSize 则使用本地尺寸 + if (InWidgetData->HasField(TEXT("LocalSize"))) + { + const TSharedPtr LocalSizeObj = InWidgetData->GetObjectField(TEXT("LocalSize")); + FVector2D Point = FVector2D::ZeroVector; + + // 逐个读取宽(x)、高(y) + if (LocalSizeObj->HasField(TEXT("x"))) + { + Point.X = LocalSizeObj->GetNumberField(TEXT("x")); + } + + if (LocalSizeObj->HasField(TEXT("y"))) + { + Point.Y = LocalSizeObj->GetNumberField(TEXT("y")); + } + + return Point; + } + + return FVector2D::ZeroVector; +} + +/** + * 从 JSON 数据反序列化出一个二维坐标点, 并进行坐标系换算 + * 注意: 原始坐标系与目标坐标系的 Y 轴方向相反, 这里会以窗口高度为基准翻转 Y + */ +FVector2D FWidget2JsonFactory::DeserializePoint(const TSharedPtr InPosData, const FVector2D& InWindowSize) +{ + FVector2D Point = FVector2D::ZeroVector; + + // 读取 x 分量 + if (InPosData->HasField(TEXT("x"))) + { + Point.X = InPosData->GetNumberField(TEXT("x")); + } + + // 读取 y 分量 + if (InPosData->HasField(TEXT("y"))) + { + Point.Y = InPosData->GetNumberField(TEXT("y")); + } + + // 坐标系换算 (翻转 Y 轴): 以窗口高度减去原始 Y 值 + // 仅当点非零时执行, 避免对零向量做无意义的翻转 + if (!Point.IsZero()) + { + Point.Y = InWindowSize.Y - Point.Y; + } + + return Point; +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonInterface.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..607a45a47022d5ee0dd9f07260f013b6d9bc214f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/Widget2JsonInterface.cpp @@ -0,0 +1,239 @@ +#include "WidgetSlots/Widget2JsonInterface.h" + +#include "Components/EditableText.h" // 单行可编辑文本 +#include "Components/EditableTextBox.h" // 单行可编辑文本框 +#include "Components/MultiLineEditableText.h" // 多行可编辑文本 +#include "Components/MultiLineEditableTextBox.h" // 多行可编辑文本框 +#include "Components/RichTextBlock.h" // 富文本块 +#include "Components/TextBlock.h" // 普通文本块 +#include "Slate/SObjectTableRow.h" // 列表条目 Slate 根 (GetIndentLevel 层级深度) +#include "Snapshot/LQAWidgetNode.h" // 控件节点定义 +#include "Styling/SlateColor.h" // Slate 颜色类型 +#include "WidgetSlots/WidgetDefines.h" // 公共字段名/常量定义 + +// 定义 (实现) 头文件中声明的日志分类 +DEFINE_LOG_CATEGORY(LogLQAToolWidget2Json); + +// 将文本及其本地化信息写入 JSON 对象 +void FWidget2JsonInterface::WriteTextEntry_ToJson(const TSharedPtr& JsonObj, const FText& Text, + const FString& TextEntryName, const FString& TextKeyName, const FString& SourceStringKeyName) +{ + // 校验入参: JSON 对象无效则记录警告并提前返回 + if (!JsonObj.IsValid()) + { + UE_LOG(LogLQAToolWidget2Json, Warning, TEXT("WriteTextEntry_ToJson: Invalid JsonObj pointer")); + return; + } + + // 写入显示文本 (当前语言下实际呈现的字符串) + JsonObj->SetStringField(*TextEntryName, *Text.ToString()); + + // 如果文本非空, 则尝试写入其源字符串 (本地化前的原始文本) + if (!Text.IsEmpty()) + { + const FString* SourceString = FTextInspector::GetSourceString(Text); + if (SourceString && !SourceString->IsEmpty()) + { + JsonObj->SetStringField(SourceStringKeyName, *SourceString); + } + } + + // 写入本地化键信息 (命名空间 + 键) + if (!Text.IsEmpty()) + { + FString Namespace, Key; + GetTextNamespaceAndKey(Text, Namespace, Key); + + // 命名空间与键都有效时, 以 "Namespace,Key" 的格式写入 + if (!Namespace.IsEmpty() && !Key.IsEmpty()) + { + JsonObj->SetStringField(*TextKeyName, FString::Printf(TEXT("%s,%s"), *Namespace, *Key)); + } + else + { + // 否则写入预定义的无效键标记 + JsonObj->SetStringField(*TextKeyName, InvalidTextKey); + } + } +} + +// 从本地化文本中提取命名空间与键 +void FWidget2JsonInterface::GetTextNamespaceAndKey(const FText& Text, FString& OutNamespace, FString& OutKey) +{ + // 通过文本检查器获取命名空间, 取不到时默认为空字符串 + OutNamespace = FTextInspector::GetNamespace(Text).Get(TEXT("")); + +#if WITH_EDITOR + // 仅在编辑器构建下执行: + // 编辑器中命名空间可能带有尾部附加信息 (如 " <包路径>"), + // 这里从末尾按空格切分, 仅保留前半段作为 “干净” 的命名空间 + FString NamespaceLeft, NamespaceRight; + if (OutNamespace.Split(TEXT(" "), &NamespaceLeft, &NamespaceRight, ESearchCase::IgnoreCase, ESearchDir::FromEnd)) + { + if (!NamespaceLeft.IsEmpty()) + { + OutNamespace = NamespaceLeft; + } + } +#endif + + // 通过文本检查器获取键, 取不到时默认为 "INVALIDKEY" + OutKey = FTextInspector::GetKey(Text).Get(TEXT("INVALIDKEY")); +} + +// ============================================================================ +// 列表条目文本收集 (ListView / TileView / TreeView 通用) +// ============================================================================ + +namespace +{ +/** + * 从文本类控件节点读取显示文本 + * 覆盖常见的文本控件类型 (条目文本不仅限于 TextBlock) + */ +FText GetNodeText(const TSharedRef& Node) +{ + UObject* Source = Node->SourceObject.Get(); + if (!Source) + { + return FText::GetEmpty(); + } + + switch (Node->GetNodeType()) + { + case ELQAWidgetType::LQA_TextBlock: + if (const UTextBlock* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + case ELQAWidgetType::LQA_RichText: + if (const URichTextBlock* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + case ELQAWidgetType::LQA_EditableText: + if (const UEditableText* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + case ELQAWidgetType::LQA_EditableTextBox: + if (const UEditableTextBox* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + case ELQAWidgetType::LQA_MultilineEditableText: + if (const UMultiLineEditableText* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + case ELQAWidgetType::LQA_MultilineEditableTextBox: + if (const UMultiLineEditableTextBox* Widget = Cast(Source)) + { + return Widget->GetText(); + } + break; + default: + break; + } + return FText::GetEmpty(); +} + +/** + * 在节点子树中深度优先查找第一个文本节点, 并把其文本写入 OutJson + * @return 找到并写入返回 true + */ +bool WriteFirstTextEntry(const TSharedRef& Node, const TSharedPtr& OutJson) +{ + const FText Text = GetNodeText(Node); + if (!Text.IsEmpty()) + { + FWidget2JsonInterface::WriteTextEntry_ToJson(OutJson, Text); + return true; + } + + // 递归查找子节点 + for (const TSharedRef& Child : Node->GetChildNodes()) + { + if (WriteFirstTextEntry(Child, OutJson)) + { + return true; + } + } + return false; +} + +/** + * 读取条目的层级深度 (TreeView 使用; ListView/TileView 无嵌套, 恒为 0) + * 条目的 Slate 根为 SObjectTableRow, 其 GetIndentLevel 返回在树中的嵌套深度。 + */ +int32 GetNodeDepth(const TSharedRef& Node) +{ + if (Node->CachedWidget.IsValid()) + { + if (const TSharedPtr> Row = + StaticCastSharedPtr>(Node->CachedWidget)) + { + return Row->GetIndentLevel(); + } + } + return 0; +} +} // namespace + +void FWidget2JsonInterface::CollectListEntryTexts( + const TSharedPtr& InWidget, TArray>& OutListItems) +{ + if (!InWidget.IsValid()) + { + return; + } + + // 下钻 Slate 内部包装层 (UNDEFINE 且无名字), 定位条目层 + TSharedPtr Cursor = InWidget; + while (Cursor.IsValid()) + { + const TArray>& Children = Cursor->GetChildNodes(); + if (Children.Num() == 0) + { + return; + } + + // 出现多个子节点: 当前层级即条目层 + if (Children.Num() > 1) + { + for (const TSharedRef& Entry : Children) + { + TSharedPtr ItemJson = MakeShared(); + if (WriteFirstTextEntry(Entry, ItemJson)) + { + // 附带层级深度, 供还原端重建 TreeView 父子结构 + ItemJson->SetNumberField(TEXT("Depth"), GetNodeDepth(Entry)); + OutListItems.Add(MakeShared(ItemJson)); + } + } + return; + } + + // 单子节点: 是内部包装节点则继续下钻, 否则它就是唯一条目 + const TSharedRef& OnlyChild = Children[0]; + const bool bInternalWrapper = + OnlyChild->GetNodeType() == ELQAWidgetType::LQA_Undefined && OnlyChild->WidgetName == NAME_None; + if (!bInternalWrapper) + { + TSharedPtr ItemJson = MakeShared(); + if (WriteFirstTextEntry(OnlyChild, ItemJson)) + { + ItemJson->SetNumberField(TEXT("Depth"), GetNodeDepth(OnlyChild)); + OutListItems.Add(MakeShared(ItemJson)); + } + return; + } + + Cursor = OnlyChild; + } +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/WidgetDefines.cpp b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/WidgetDefines.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffc325ffe425a8c6ebc43c9bc8c5df5094a30535 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Private/WidgetSlots/WidgetDefines.cpp @@ -0,0 +1,10 @@ +// WidgetDefines.cpp +// 该文件负责提供 WidgetDefines.h 中声明的日志分类的实际定义 +// 注意: 各 Widget 类型的 FName 常量 (LQAWidgetNames 命名空间) +// 并不在此定义, 而是在 LQAWidgetNode.cpp 中集中定义 + +#include "WidgetSlots/WidgetDefines.h" + +// 定义日志分类 LogLQAToolWidget, 与头文件中的 DECLARE_LOG_CATEGORY_EXTERN 相对应 +// 整个工程中该宏只能出现一次, 否则会导致重复定义的链接错误 +DEFINE_LOG_CATEGORY(LogLQAToolWidget); \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQABase.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQABase.h new file mode 100644 index 0000000000000000000000000000000000000000..37c7a2a8ad5a06a0fc3ea3e8ae70db1d1279f941 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQABase.h @@ -0,0 +1,21 @@ +// LQABase.h +// LQA (Localization Quality Assurance, 本地化质量保证) 工具插件的基础定义头文件 +// 本文件集中声明插件中通用的日志类别, 供插件内其他模块引用 + +#pragma once + +// 引入虚幻引擎最核心的基础头文件, +// 提供基础类型、宏、容器、日志系统等最常用的核心功能 +#include "CoreMinimal.h" + +/** + * LQA 基础定义 (LQA Base Definitions) + * 包含 LQA 工具插件所需的通用日志功能及基础功能定义 + */ + +// 声明一个外部 (extern) 日志类别, 供插件内多个 .cpp 文件共享使用 +// - LogLQATool: 日志类别名称, 使用时通过 UE_LOG(LogLQATool, ...) 输出日志 +// - Log : 默认日志级别 (编译期), 低于该级别的日志将被编译器剔除 +// - All : 运行时允许输出的最高详细级别 (即不做额外限制, 全部可输出) +// 该宏只做 “声明”, 真正的 “定义” 需在对应的 .cpp 中使用 DEFINE_LOG_CATEGORY +DECLARE_LOG_CATEGORY_EXTERN(LogLQATool, Log, All); \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAInputProcessor.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAInputProcessor.h new file mode 100644 index 0000000000000000000000000000000000000000..2c1a3fbd4eb13e7bf78a29a04b33e5a458d0a504 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAInputProcessor.h @@ -0,0 +1,39 @@ +#pragma once + +// UE 核心最小头文件集, 提供基础类型 (如 float、TSharedRef 等) +#include "CoreMinimal.h" +// Slate 输入处理器接口, 自定义输入处理器必须继承该接口 +#include "Framework/Application/IInputProcessor.h" +// LQA 导出工具类, 鼠标事件最终会转发给它处理 +#include "Utils/LQAExportUtil.h" + +/** + * LQA 按键捕获功能的输入处理器 + * + * 该类继承自 Slate 的 IInputProcessor 接口, 被注册到 FSlateApplication 后, + * 能够在应用程序级别 (优先于普通控件) 拦截并处理输入事件 + * 主要用于捕获鼠标事件, 从而检测并上报用户与控件 (Widget) 的交互 + */ +class FLQAInputProcessor : public IInputProcessor +{ +public: + // 使用默认虚析构函数, 确保通过基类指针释放时能正确析构派生类 + virtual ~FLQAInputProcessor() = default; + + /** + * 每帧调用一次, 用于更新输入处理器的状态 + * @param DeltaTime 距离上一帧经过的时间 (秒) + * @param SlateApp Slate 应用程序引用, 可用于访问应用级输入状态 + * @param Cursor 光标接口引用, 可用于查询或控制鼠标光标 + */ + virtual void Tick(const float DeltaTime, FSlateApplication& SlateApp, TSharedRef Cursor) override; + + /** + * 处理鼠标按键按下事件 + * 在 Slate 将事件分发给普通控件之前被调用, 可用于全局拦截鼠标按下操作 + * @param SlateApp Slate 应用程序引用 + * @param MouseEvent 鼠标事件数据, 包含按下的按键、屏幕坐标等信息 + * @return 返回 true 表示事件已被本处理器消费 (不再向下传递); 返回 false 表示继续传递该事件 + */ + virtual bool HandleMouseButtonDownEvent(FSlateApplication& SlateApp, const FPointerEvent& MouseEvent) override; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAManager.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAManager.h new file mode 100644 index 0000000000000000000000000000000000000000..31e5dc49736e1e0e9a5b104079b52e723ad1337f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQAManager.h @@ -0,0 +1,82 @@ +#pragma once + +#include "CoreMinimal.h" +#include "LQABase.h" +#include "Subsystems/GameInstanceSubsystem.h" +#include "ToolPanel/LQABaseView.h" + +#include "LQAManager.generated.h" + +/** + * ULQAManager —— LQA (本地化质量保证 / Localization Quality Assurance) 工具的核心管理类 + * + * 继承自 UGameInstanceSubsystem (游戏实例子系统), 其生命周期与 GameInstance 绑定: + * 游戏实例创建时自动创建, 游戏实例销毁时自动销毁, 全局唯一 + * 主要职责: 管理 LQA 工具面板 UI 的创建/移除, 以及对外提供视图数据导出 (Dump) 功能 + */ +UCLASS() +class LQATOOL_API ULQAManager : public UGameInstanceSubsystem +{ + GENERATED_BODY() + +public: + /** + * 初始化 LQA 管理器子系统 (由引擎在子系统创建时自动调用) + * @param Collection 子系统集合, 用于声明子系统之间的依赖关系 + */ + virtual void Initialize(FSubsystemCollectionBase& Collection) override; + + /** + * 反初始化 LQA 管理器子系统 (由引擎在子系统销毁时自动调用), 用于释放资源 + */ + virtual void Deinitialize() override; + + /** + * 获取 LQA 管理器单例实例 + * @param GameIns 游戏实例对象 (可选); 传入时优先从该实例获取子系统 + * @return ULQAManager 实例指针; 若未找到则返回 nullptr + */ + UFUNCTION(BlueprintCallable, Category = "LQA") + static ULQAManager* GetLQAManager(UObject* GameIns = nullptr); + + /** + * 初始化所有 LQA 组件 (主要是创建并显示 LQA 工具面板) + */ + UFUNCTION(BlueprintCallable, Category = "LQA") + void InitAll(); + + /** + * 反初始化所有 LQA 组件 (主要是移除 LQA 工具面板) + */ + UFUNCTION(BlueprintCallable, Category = "LQA") + void DeInitAll(); + + /** + * 导出 (Dump) 当前视图数据, 并支持高级选项 + * @param bContainsTextures 是否一并导出纹理 (贴图) 数据 + * @param bNeedObjectData 是否导出对象的元数据 (Object Metadata) + */ + UFUNCTION(BlueprintCallable, Category = "LQA") + void LQADumpViewAdvanced(bool bContainsTextures = false, bool bNeedObjectData = false) const; + +private: + /** + * 创建 LQA 控件 (Widget) 并添加到视口 (Viewport) 中 + */ + void InitLQAWidget(); + + /** + * 从视口中移除 LQA 控件 (Widget) + */ + void RemoveLQAWidget(); + + /** LQA 主控件 (面板 UI) 实例, 使用 UPROPERTY 标记以纳入 GC 管理, 防止被垃圾回收 */ + UPROPERTY() + ULQABaseView* LQAWidget = nullptr; + + /** LQA 系统是否已就绪的标志位; 仅当为 true 时才允许创建面板 */ + bool bIsLQAReady = false; + + /** 单例实例指针, 便于通过静态方法 GetLQAManager 全局访问 */ + static ULQAManager* Instance; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQATool.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQATool.h new file mode 100644 index 0000000000000000000000000000000000000000..9233b131da0474f17cada4fd2f5b228f069942bb --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/LQATool.h @@ -0,0 +1,47 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Modules/ModuleInterface.h" + +/** + * LQA 工具模块 (Language Quality Assurance, 语言质量保证) + * + * 该模块为虚幻引擎 (Unreal Engine) 项目提供语言质量保证相关功能, + * 继承自 IModuleInterface, 是一个标准的 UE 插件模块入口类 + * 主要职责: + * - 在模块启动时注册控制台命令 (Console Command); + * - 维护一个全局的 “Dump 延迟时间” 配置, 供外部读写 + */ +class FLQAToolModule : public IModuleInterface +{ +public: + /** ===== IModuleInterface 接口实现 ===== */ + + /** 模块启动时调用: 用于执行初始化逻辑 (此处注册控制台命令) */ + virtual void StartupModule() override; + + /** 模块关闭时调用: 用于执行清理逻辑 (如注销命令、释放资源等) */ + virtual void ShutdownModule() override; + + /** + * 获取当前 LQA 的 Dump (数据导出) 延迟时间 + * @return 当前延迟时间, 单位: 秒 + */ + static float GetLQADumpDelay(); + + /** + * 设置 LQA 的 Dump (数据导出) 延迟时间 + * @param InDelay 延迟时间, 单位: 秒 (内部会被限制为 >= 0.0f, 负值会被钳制到 0) + */ + static void SetLQADumpDelay(float InDelay); + +private: + /** + * 注册 LQA 功能相关的控制台命令 + * 声明为 const, 表示该函数不会修改当前对象的成员状态 + */ + void RegisterConsoleCommands() const; + + /** 静态成员变量: 保存 Dump 延迟时间, 单位: 秒 (整个模块共享一份) */ + static float LQADumpDelay; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNode.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNode.h new file mode 100644 index 0000000000000000000000000000000000000000..f15c19e145e1c26d2600de775caf6150e49bf590 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNode.h @@ -0,0 +1,312 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Fonts/SlateFontInfo.h" +#include "Json.h" +#include "Layout/ArrangedWidget.h" +#include "Layout/Geometry.h" +#include "Templates/SharedPointer.h" + +/** + * LQA 支持的控件 (Widget) 类型枚举 + * 作用:把 Slate 底层各种控件类型, 归一映射为 LQA 工具内部统一识别的类型, + * 便于后续按类型做差异化的数据采集 / JSON 序列化处理 + */ +enum class ELQAWidgetType : uint8 +{ + // ===== 文本类控件 ===== + LQA_TextBlock, // 普通文本块 + LQA_RichText, // 富文本 + LQA_EditableText, // 单行可编辑文本 + LQA_EditableTextBox, // 单行可编辑文本框 + LQA_MultilineEditableText, // 多行可编辑文本 + LQA_MultilineEditableTextBox, // 多行可编辑文本框 + LQA_TextScroller, // 文本滚动控件 + LQA_ComboBoxStringText, // 字符串下拉框 (内含文本) + LQA_LEDRichText, // LED 风格富文本 + LQA_InputKeySelector, // 按键选择器 + + // ===== 输入类控件 ===== + LQA_ProgressBar, // 进度条 + LQA_Slider, // 滑动条 + LQA_SpinBox, // 数值微调框 + + // ===== 视觉类控件 ===== + LQA_Image, // 图片 + LQA_Button, // 按钮 + LQA_CheckBox, // 复选框 + LQA_Throbber, // 线性加载指示器 + LQA_CircularThrobber, // 环形加载指示器 + LQA_Spacer, // 占位空白 + + // ===== 容器类控件 ===== + LQA_UserWidget, // 用户自定义控件 (蓝图 UserWidget) + LQA_Canvas, // 画布面板 + LQA_RetainerBox, // 渲染缓存盒 + LQA_ScrollBox, // 滚动盒 + LQA_VerticalBox, // 垂直布局盒 + LQA_HorizontalBox, // 水平布局盒 + LQA_ScaleBox, // 缩放盒 + LQA_SafeZone, // 安全区 + LQA_WrapBox, // 自动换行盒 + LQA_SizeBox, // 尺寸约束盒 + LQA_GridPanel, // 网格面板 + LQA_UniformGridPanel, // 均匀网格面板 + LQA_Overlay, // 叠加层 + LQA_Border, // 边框容器 + LQA_BackgroundBlur, // 背景模糊 + LQA_WidgetSwitcher, // 控件切换器 + LQA_StackBox, // 堆叠盒 + LQA_WindowTitleBarArea, // 窗口标题栏区域 + LQA_MenuAnchor, // 菜单锚点 + LQA_InvalidationBox, // 失效缓存面板 + LQA_ScrollBar, // 滚动条 + LQA_PostBufferUpdate, // 后处理缓冲更新 + LQA_DynamicEntryBox, // 动态条目框 + LQA_ListView, // 列表视图 + LQA_TileView, // 平铺视图 + LQA_TreeView, // 树形视图 + LQA_ExpandableArea, // 可展开区域 + + // ===== Slate 根类型复用 (多个 UMG 控件共用同一个 Slate 实现根, 按 UMG 类区分) ===== + LQA_NamedSlot, // 命名插槽 (Slate 根为 SBox) + LQA_NativeWidgetHost, // 原生控件宿主 (Slate 根为 SBox) + LQA_Viewport, // 视口控件 (Slate 根为 SBox, 暂未登记) + + // 项目自定义控件类型可在此处追加 + + // 未定义 / 未知控件类型 (默认值) + LQA_Undefined +}; + +/** + * LQA 支持的插槽 (Slot) 类型枚举 + * 插槽描述子控件在父容器中的布局方式; 此枚举把 Slate/UMG 的插槽类型 + * 归一为内部统一类型,便于识别并在数据中排除/标记特定插槽 + */ +enum class ELQASlotType : uint8 +{ + // ===== 标准插槽 ===== + LQA_ButtonSlot, // 按钮插槽 + LQA_CanvasPanelSlot, // 画布面板插槽 + LQA_ScrollBoxSlot, // 滚动盒插槽 + LQA_VerticalBoxSlot, // 垂直盒插槽 + LQA_HorizontalBoxSlot, // 水平盒插槽 + LQA_ScaleBoxSlot, // 缩放盒插槽 + LQA_SafeZoneSlot, // 安全区插槽 + LQA_WrapBoxSlot, // 换行盒插槽 + LQA_SizeBoxSlot, // 尺寸盒插槽 + LQA_GridSlot, // 网格插槽 + LQA_UniformGridSlot, // 均匀网格插槽 + LQA_OverlaySlot, // 叠加层插槽 + LQA_BorderSlot, // 边框插槽 + LQA_WidgetSwitcherSlot, // 控件切换器插槽 + LQA_BackgroundBlurSlot, // 背景模糊插槽 + LQA_StackBoxSlot, // 堆叠盒插槽 + LQA_WindowTitleBarAreaSlot, // 窗口标题栏区域插槽 + LQA_PanelSlot, // 单子容器内容插槽 (UPanelSlot 基类) + + // 项目自定义插槽类型可在此处追加 + + // 未定义 / 未知插槽类型 (默认值) + LQA_UndefinedSlot +}; + +/** + * LQA 系统中的控件节点 + * 以树形结构表示 UI 控件层级, 携带控件的位置 (屏幕坐标)、类型、 + * 插槽类型以及源对象等信息, 是快照 (Snapshot) 数据采集的核心数据结构 + */ +class LQATOOL_API FLQAWidgetNode +{ +public: + /** + * 构造函数: 从 "已排布的控件(ArrangedWidget)" 构建节点 + * @param InWidgetGeometry 包含几何信息 (Geometry) 与控件引用 (Widget) 的已排布控件 + */ + explicit FLQAWidgetNode(const FArrangedWidget& InWidgetGeometry); + + /** + * 添加一个子节点 + * @param InChildNode 待添加的子节点 + */ + void AddChildNode(TSharedRef InChildNode); + + /** + * 清空所有子节点 + */ + void ClearChildNodes(); + + /** + * 获取所有子节点 + * @return 子节点数组 (常量引用) + */ + const TArray>& GetChildNodes() const; + + /** + * 获取控件类型。 + * @return 控件类型枚举 + */ + ELQAWidgetType GetNodeType() const + { + return NodeType; + } + + /** + * 获取插槽类型 + * @return 插槽类型枚举 + */ + ELQASlotType GetSlotType() const + { + return SlotType; + } + + /** + * 为 "未定义类型" 控件填充通用 JSON 数据 + * @param InObject 待填充的 JSON 对象 + */ + void FillCommonDataForUndefinedWidget(TSharedPtr InObject) const; + + /** + * 填充控件的通用 JSON 数据 + * @param InObject 待填充的 JSON 对象 + * @param bNeedObjectData 是否需要附加源对象 (UObject) 的元数据 + */ + void FillCommonData(TSharedPtr InObject, bool bNeedObjectData) const; + + /** + * 计算并设置 UI 的屏幕位置数据 (四角坐标、视口坐标、本地尺寸、包围盒等) + * @return 计算成功返回 true, 失败 (如 World 无效) 返回 false + */ + bool SetUIPosition(); + + /** + * 设置节点唯一标识 (ID) + * @param Id 节点 ID + */ + void SetNodeId(int32 Id); + + /** + * 递归地为当前节点及其子节点设置包围盒 (BoxSize) 尺寸 + */ + void SetBoxSize(); + +public: + // ===== 控件与几何数据 ===== + /** 缓存的 Slate 控件引用 */ + TSharedPtr CachedWidget; + + /** 节点唯一标识 */ + int32 NodeId = -1; + + /** 控件名称 */ + FName WidgetName; + + /** 源 UObject 的弱引用 (通常为对应的 UWidget) */ + TWeakObjectPtr SourceObject; + + /** Slate 根类型复用组内的 UMG 侧类标识 (如 "NamedSlot"), 1:1 类型为 None */ + FName WidgetClassTag; + + /** 缓存的几何信息 */ + FGeometry CachedGeometry; + + /** 图层 ID */ + int32 LayerId = -1; + + // ===== 位置数据 (屏幕坐标系) ===== + /** 左下角坐标 */ + FVector2D LeftBottomPos = FVector2D::ZeroVector; + + /** 左上角坐标 */ + FVector2D LeftUpperPos = FVector2D::ZeroVector; + + /** 右上角坐标 */ + FVector2D RightUpperPos = FVector2D::ZeroVector; + + /** 右下角坐标 */ + FVector2D RightBottomPos = FVector2D::ZeroVector; + + /** 视口坐标 */ + FVector2D ViewportPos = FVector2D::ZeroVector; + + /** 本地尺寸 */ + FVector2D LocalSize = FVector2D::ZeroVector; + + /** 包围盒 (2D) */ + FBox2D BoxSize = FBox2D(FVector2D::ZeroVector, FVector2D::ZeroVector); + + /** 包围盒是否有效 */ + bool bBoxIsValid = false; + + /** 基础插槽类型 (原始类名字符串) */ + FString BaseSlotType; + + /** 命名插槽名称 */ + FName SlotName; + + /** 基础控件类型 (原始类名字符串) */ + FString BaseWidgetType; + +private: + /** + * 处理控件类型识别与元数据提取 (构造时调用的核心逻辑) + * @param InWidget 待处理的 Slate 控件 + */ + void HandleWidget(const TSharedRef& InWidget); + + + /** + * 将插槽类型名 (字符串) 转换为枚举 + * @param SlotTypeName 插槽类型名 + * @return 插槽类型枚举(未匹配则返回 LQA_UndefinedSlot) + */ + static ELQASlotType GetSlotType(const FName& SlotTypeName); + + /** + * 获取四个角点坐标组成的 JSON 数组 + * @return 角点坐标 JSON 数组 + */ + TArray> GetCornerPosition() const; + + /** + * 获取包围盒尺寸组成的 JSON 数组 + * @return 包围盒 JSON 数组 + */ + TArray> GetBoxSizePosition() const; + + /** + * 将视口坐标转换为 JSON 对象 + * @return 包含视口坐标的 JSON 对象 + */ + TSharedPtr ConvertViewportPos2Json() const; + + /** + * 将本地尺寸转换为 JSON 对象 + * @return 包含本地尺寸的 JSON 对象 + */ + TSharedPtr ConvertLocalSize2Json() const; + + /** + * 将二维坐标转换为 JSON 对象 + * @param InPos 待转换的坐标 + * @return 包含坐标数据的 JSON 对象 + */ + TSharedPtr ConvertPos2Json(const FVector2D& InPos) const; + + /** + * 判断当前节点是否为用户自定义控件 (UserWidget) + * @return 是则返回 true + */ + bool CheckNodeIsUserWidget() const; + +private: + /** 子控件节点数组 */ + TArray> ChildNodes; + + /** 控件类型 (枚举) */ + ELQAWidgetType NodeType = ELQAWidgetType::LQA_Undefined; + + /** 插槽类型 (枚举) */ + ELQASlotType SlotType = ELQASlotType::LQA_UndefinedSlot; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNodeUtil.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNodeUtil.h new file mode 100644 index 0000000000000000000000000000000000000000..260e020b58bde9985eb1aed3e66e4c5e4607ce2f --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Snapshot/LQAWidgetNodeUtil.h @@ -0,0 +1,33 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Layout/ArrangedWidget.h" // 提供 FArrangedWidget (控件 + 其布局几何信息的组合) +#include "Snapshot/LQAWidgetNode.h" // 控件节点类型 FLQAWidgetNode 的定义 + +/** + * 控件节点 (idget Node) 操作工具类 + * + * 该类用于在 LQA (本地化质量保证) 快照流程中, + * 根据 Slate 控件的布局结果构建一棵 “控件节点树”, + * 便于后续对界面控件进行遍历、分析与截图标注等操作 + * + * 说明: 这是一个纯静态工具类, 不需要实例化 + */ +class LQATOOL_API FLQAWidgetNodeUtil +{ +public: + /** + * 根据已排布的控件几何递归构建控件节点树。 + * + * 子控件几何取自布局排布结果, 因此视口外 (被 ScrollBox 等裁剪) 的子树同样会被采集; + * 从未参与排布的子树 (Collapsed 控件、WidgetSwitcher 非活动页) 不采集。 + * + * 从未参与绘制的控件会先按其排布几何补一次 Tick, 使其在 Tick 中构建的内容 + * (虚拟化列表行、按需创建的子控件) 就位; 控件自身视口内从未构建的内容不采集。 + * + * @param InWidgetGeometry 已排布的控件 (含控件引用与几何信息) + * @param Index 节点序号计数器 (构建过程中持续自增) + * @return 构建好的控件节点树 + */ + static TSharedRef GetNodeFromTree(const FArrangedWidget& InWidgetGeometry, int32& Index); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/ToolPanel/LQABaseView.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/ToolPanel/LQABaseView.h new file mode 100644 index 0000000000000000000000000000000000000000..063e9239a457d4fd26ded3d6973bcdfe9c47e401 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/ToolPanel/LQABaseView.h @@ -0,0 +1,162 @@ +#pragma once + +#include "Blueprint/UserWidget.h" // UUserWidget 基类 +#include "Components/Button.h" // UButton 按钮控件 +#include "Components/CanvasPanel.h" // UCanvasPanel 画布面板控件 +#include "Components/TextBlock.h" // UTextBlock 文本控件 +#include "CoreMinimal.h" // UE 核心基础类型 +#include "Runtime/Launch/Resources/Version.h" // 引擎版本宏 (ENGINE_MAJOR_VERSION 等) + +#include "LQABaseView.generated.h" // UHT 自动生成的反射代码, 必须放在最后 + +// 前向声明: 输入预处理器类, 用于捕获键盘输入 (头文件中仅声明, 减少编译依赖) +class FLQAInputProcessor; + +/** + * LQA 工具面板 —— LQA 工具的主 UI 控件 + * 以悬浮调试面板的形式, 提供 Dump (界面转储) 与 GetKey (按键捕获) 两大功能 + */ +UCLASS() +class LQATOOL_API ULQABaseView : public UUserWidget +{ + GENERATED_BODY() + +public: + /** + * 构造函数 + * @param ObjectInitializer UE 对象初始化器 + */ + explicit ULQABaseView(const FObjectInitializer& ObjectInitializer); + + /** + * 析构函数 —— 确保对象销毁时正确清理 (注销输入预处理器) + */ + virtual ~ULQABaseView(); + + /** + * 控件构造完成时调用 + * 在此为按钮绑定点击事件、注册关卡移除委托 + */ + virtual void NativeConstruct() override; + + /** + * 以代码方式重建控件结构 + * 创建根画布面板以及各个按钮 + * @return 根控件引用 + */ + virtual TSharedRef RebuildWidget() override; + +#if ENGINE_MAJOR_VERSION < 5 + /** + * [UE4] 当关卡从世界中被移除时调用 (虚函数重写) + * 用于在关卡卸载时清理输入预处理器, 防止悬空引用 + * @param InLevel 被移除的关卡 + * @param InWorld 包含该关卡的世界 + */ + virtual void OnLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld) override; +#else + /** + * [UE5] 绑定到 FWorldDelegates::LevelRemovedFromWorld 的处理函数 + * UE5 中该通知改为委托形式, 故需手动注册/注销 + * @param InLevel 被移除的关卡 + * @param InWorld 包含该关卡的世界 + */ + void HandleLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld); + + /** + * [UE5] 对象销毁时注销关卡移除委托, 避免委托回调访问已失效对象 + */ + virtual void BeginDestroy() override; +#endif + +protected: + /** + * Dump View 按钮的点击事件处理函数 + * 需用 UFUNCTION() 标记, 才能绑定到 OnClicked 动态委托 + */ + UFUNCTION() + void OnDumpViewClicked(); + + /** + * Get Key 按钮的点击事件处理函数 + * 需用 UFUNCTION() 标记, 才能绑定到 OnClicked 动态委托 + */ + UFUNCTION() + void OnGetKeyClicked(); + + /** + * 执行实际的界面转储 (Dump) 操作 + * 声明为 const, 表示不修改对象自身状态 + */ + void HandleDumpViewClicked() const; + +private: + // ===== UI 布局常量 ===== + static constexpr float BUTTON_WIDTH = 120.0f; // 普通按钮宽度 + static constexpr float BUTTON_HEIGHT = 120.0f; // 按钮高度 + static constexpr float GETKEY_BUTTON_WIDTH = 150.0f; // GetKey 按钮宽度 (略宽以容纳文本) + static constexpr float BUTTON_ANCHOR_Y = 0.45f; // 按钮在画布上的 Y 轴锚点 (屏幕中部偏上) + static constexpr float GETKEY_BUTTON_OFFSET_X = 120.0f;// GetKey 按钮相对 X 偏移 (排在 Dump 按钮右侧) + + /** + * 创建并配置 Dump View 按钮 + * @return 创建成功返回 true, 否则返回 false + */ + bool CreateDumpViewButton(); + + /** + * 创建并配置 Get Key 按钮 + * @return 创建成功返回 true, 否则返回 false + */ + bool CreateGetKeyButton(); + + /** + * 根据当前状态更新 Get Key 按钮上的文本 (On / Off) + * @param bIsKeyEnabled 按键捕获当前是否已启用 + */ + void UpdateGetKeyButtonText(bool bIsKeyEnabled); + + /** + * 启用或禁用按键捕获 + * 启用时向 Slate 注册输入预处理器, 禁用时注销 + * @param bEnable 是否启用按键捕获 + */ + void SetKeyCapture(bool bEnable); + + /** + * 清理输入预处理器: 从 Slate 注销并释放, 重置状态标志 + */ + void CleanupInputProcessor(); + +protected: + /** 根画布面板, 所有子控件都挂载在其上 */ + UPROPERTY() + UCanvasPanel* RootCanvasPanel; + + /** Dump View 按钮 */ + UPROPERTY() + UButton* DumpViewBtn; + + /** Dump View 按钮上的文本 */ + UPROPERTY() + UTextBlock* DumpViewBtnText; + + /** Get Key 按钮 */ + UPROPERTY() + UButton* GetKeyBtn; + + /** Get Key 按钮上的文本 */ + UPROPERTY() + UTextBlock* GetKeyBtnText; + + /** 用于按键捕获的输入预处理器 (共享指针, 非 UObject) */ + TSharedPtr InputProcessor; + + /** 按键转储 (捕获) 功能是否启用的状态标志 */ + bool bLQAEnableKeyDump = false; + +#if ENGINE_MAJOR_VERSION >= 5 + /** [UE5] FWorldDelegates::LevelRemovedFromWorld 的委托句柄, 用于后续注销 */ + FDelegateHandle LevelRemovedFromWorldHandle; +#endif +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQACommonUtil.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQACommonUtil.h new file mode 100644 index 0000000000000000000000000000000000000000..79c0b677b42d03869ccdd48bf066fef4370e6470 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQACommonUtil.h @@ -0,0 +1,49 @@ +#pragma once + +#include "CoreMinimal.h" + +// 声明一个名为 LogLQAToolCommonUtil 的外部日志分类 (供本类的 .cpp 及其他模块使用) +// 第二个参数 Log 为默认日志级别, 第三个参数 All 表示编译期允许输出的最高级别 +DECLARE_LOG_CATEGORY_EXTERN(LogLQAToolCommonUtil, Log, All); + +/** + * LQA 工具通用工具类 + * 提供系统信息获取、路径处理、配置读取以及字符串编码等静态辅助方法 + * 本类为纯静态工具类, 无需实例化即可使用 + */ +class LQATOOL_API FLQACommonUtil +{ +public: + /** 获取游戏的 Saved 存档目录的绝对路径 (会根据不同平台做差异化处理) */ + static FString GetGameSavedPath(); + + /** 获取系统信息 (平台、操作系统版本、设备型号、CPU 信息), 并拼接为 URL 查询参数字符串 */ + static FString GetSystemInfo(); + + /** 从项目配置文件中读取客户端版本号 */ + static FString GetClientVersion(); + + /** 对字符串进行 URL 编码, 转义其中的特殊字符 */ + static FString UrlEncodeString(const FString& InputString); + +private: + // ---------- 常量定义 ---------- + + /** 默认版本号: 当无法从配置中读取到版本时返回此值 */ + static constexpr const TCHAR* DEFAULT_VERSION = TEXT("0.0.0.0"); + + /** 未知值占位符: 当某项系统信息为空时使用 */ + static constexpr const TCHAR* UNKNOWN_VALUE = TEXT("Unknown"); + + /** 有效路径的最小长度 (用于路径合法性校验) */ + static constexpr int32 MIN_PATH_LENGTH = 1; + + /** 返回安全的字符串值: 若原值为空则返回默认值 (默认为 UNKNOWN_VALUE) */ + static FString GetSafeStringValue(const FString& Value, const FString& DefaultValue = UNKNOWN_VALUE); + + /** 校验路径字符串是否合法 (非空且长度大于最小长度) */ + static bool IsValidPath(const FString& Path); + + /** 获取当前运行平台的名称字符串 (如 Windows、Android、iOS 等) */ + static FString GetCurrentPlatformName(); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAExportUtil.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAExportUtil.h new file mode 100644 index 0000000000000000000000000000000000000000..ccb725e971b1403cf7defd170130107e98103c81 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAExportUtil.h @@ -0,0 +1,223 @@ +#pragma once + +#include "CoreMinimal.h" + +// 前置声明, 避免在头文件中引入完整定义, 减少编译依赖 +class FJsonObject; // JSON 对象类, 用于序列化控件数据 +class FLQAWidgetNode; // LQA 控件树节点, 描述 UI 控件层级结构 +class SWindow; // Slate 窗口类 +class UTexture; // 纹理资源类 +class UTexture2D; + +/** + * 控件数据与截图导出工具类 + * 提供控件树分析、JSON 序列化以及屏幕截图捕获等功能 + * 整个类均为静态方法 (无需实例化), 作为纯工具集合使用 + */ +class FLQAExportUtil +{ +public: + // ======================================== + // 公共接口 —— 主要导出函数 + // ======================================== + + /** + * 将当前激活窗口的控件视图以 “高级模式” 导出为 JSON + * @param CurDate 时间戳, 用于生成文件名 (保证唯一性) + * @param bContainsTextures 是否在导出数据中包含纹理数据 + * @param bNeedObjectData 是否包含控件的对象元数据 (额外信息) + * @return 控件蓝图 (WidgetBlueprint) 名称 + */ + static FString DumpViewAdvanced(const FDateTime& CurDate, bool bContainsTextures, bool bNeedObjectData); + + /** + * 提取当前视图中所有的文本类控件 + * @return 文本控件对应的 JSON 对象数组 + */ + static TArray> DumpText(); + + /** + * 捕获屏幕截图 + * @param CurDate 时间戳, 用于生成文件名 + * @param WBPName 控件蓝图名称, 用于组织截图保存路径 + */ + static void ScreenShot(const FDateTime& CurDate, const FString& WBPName); + + // ======================================== + // 公共接口 —— 交互相关函数 + // ======================================== + + /** 处理鼠标按下事件 (根据点击位置查找对应的文本控件) */ + static void OnPointerDown(const FPointerEvent& MouseEvent); + + /** + * 查找所有包含指定屏幕坐标点的控件 + * @param ClickPosition 屏幕坐标位置 (点击点) + * @param TextWidgets 待搜索的文本控件集合 + * @param OutWidgets 输出参数, 命中的控件集合 + * @return 若找到任意匹配控件则返回 true + */ + static bool FindAllWidgetsContainingPoint(const FVector2D& ClickPosition, + const TArray>& TextWidgets, TArray>& OutWidgets); + + // ======================================== + // 公共接口 —— 通用工具函数 + // ======================================== + + /** 获取系统当前的区域/语言 (Culture) 设置 */ + static FString GetCurrentCulture(); + + /** + * 向 JSON 对象中追加系统元数据 (版本、设备、视口尺寸等) + * @param JsonObject 目标 JSON 对象 + */ + static void AddSystemData(const TSharedPtr& JsonObject); + + /** + * 将快照数据保存到磁盘 + * @param InJsonData 待保存的 JSON 字符串 + * @param WBPName 控件蓝图名称, 用于生成保存路径与文件名 + * @param CurDate 时间戳, 用于生成文件名 + * @return 保存成功返回 true + */ + static bool SaveSnapshotData(const FString& InJsonData, const FString& WBPName, const FDateTime& CurDate); + +private: + // ======================================== + // 私有 —— 核心快照函数 + // ======================================== + + /** + * 从指定窗口创建 “高级模式” 快照 + * @param VisibleWindow 目标窗口 + * @param CurDate 时间戳 + * @param bContainsTextures 是否包含纹理数据 + * @param bNeedObjectData 是否包含对象元数据 + * @return 控件蓝图名称 + */ + static FString CreateSnapshotAdvanced(const TSharedPtr& VisibleWindow, const FDateTime& CurDate, + bool bContainsTextures, bool bNeedObjectData); + + /** + * 从名称列表中解析出控件蓝图名称 + * @param NameList 待处理的控件名称列表 + * @return 解析得到的蓝图名称 + */ + static FString FindWBPName(TArray& NameList); + + /** + * Build the session directory that holds every artifact of one dump. + * @param CurDate Timestamp for directory naming + * @param WBPName Widget blueprint name + * @return Absolute path to the session directory + */ + static FString GetSnapshotDirectory(const FDateTime& CurDate, const FString& WBPName); + + /** + * Check whether a texture only exists in memory, i.e. it cannot be loaded back by path. + * @param Texture2D Texture to test + * @return true if the texture has no asset on disk backing it + */ + static bool IsRuntimeGeneratedTexture(const UTexture2D* Texture2D); + + /** + * Persist runtime-generated textures to disk as PNG, so they can be restored later. + * Textures already backed by an asset on disk are skipped, since those can be loaded by path. + * Files are named after the texture's nameMD5 and written to /Textures. + * @param SharedTextureMap Texture cache collected during the dump + * @param CurDate Timestamp for directory naming + * @param WBPName Widget blueprint name + */ + static void ExportSharedTextures( + const TMap& SharedTextureMap, const FDateTime& CurDate, const FString& WBPName); + + // ======================================== + // 私有 —— 控件树遍历处理 + // ======================================== + + /** + * 递归收集控件树中所有有效节点 (UserWidget 类型且未被排除) + * @param Node 根节点 (遍历起点) + * @param OutValidNodes 输出参数, 收集到的有效节点 + */ + static void GetAllValidNodes( + const TSharedPtr& Node, TArray>& OutValidNodes); + + /** + * 递归收集控件树中所有文本节点, 并转换为 JSON + * @param Node 根节点 (遍历起点) + * @param OutValidTextNodes 输出参数, 文本节点对应的 JSON 对象 + */ + static void GetAllTextNodes( + const TSharedPtr& Node, TArray>& OutValidTextNodes); + + // ======================================== + // 私有 —— 节点序列化 + // ======================================== + + /** + * 将单个控件节点序列化为 JSON (根据节点类型分发到不同处理函数) + * @param Node 控件节点 + * @param SharedTextureMap 纹理缓存 (去重复用纹理) + * @param NameList 名称跟踪列表 + * @param bNeedObjectData 是否包含对象元数据 + * @param ParentName 父控件名称 + * @return 序列化得到的 JSON 对象 + */ + static TSharedPtr DumpNodeInfo(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, + const FName ParentName = FName()); + + /** 处理 UserWidget (用户控件) 类型节点的序列化 */ + static TSharedPtr HandleUserWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, + const FName ParentName = FName()); + + /** 处理 Undefined (未定义) 类型节点的序列化 */ + static TSharedPtr HandleUndefinedWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, + const FName ParentName = FName()); + + /** 处理其他 (普通) 类型节点的序列化 */ + static TSharedPtr HandleOtherWidget(const TSharedPtr& Node, + TMap& SharedTextureMap, TArray& NameList, bool bNeedObjectData, + const FName ParentName = FName()); + + /** + * 处理子节点并将其序列化结果追加到父 JSON 对象中 + * @param Node 父节点 + * @param ParentJsonObject 父 JSON 对象 + * @param SharedTextureMap 纹理缓存 + * @param NameList 名称跟踪列表 + * @param bNeedObjectData 是否包含对象元数据 + * @param ParentName 父控件名称 + */ + static void ProcessChildNodes(const TSharedPtr& Node, + const TSharedPtr& ParentJsonObject, TMap& SharedTextureMap, + TArray& NameList, bool bNeedObjectData, const FName ParentName = FName()); + + // ======================================== + // 私有 —— 截图相关函数 + // ======================================== + + /** + * 生成截图文件的完整保存路径 + * @param CurDate 时间戳 + * @param WBPName 控件蓝图名称 + * @return 完整文件路径 + */ + static FString GetScreenShotFileName(const FDateTime& CurDate, const FString& WBPName); + + /** + * 发起截图捕获流程 (先截前景图, 延迟后再截背景图) + * @param InScreenshotPath 目标文件路径 + */ + static void StartScreenshotSequence(const FString& InScreenshotPath); + +private: + /** 前景截图文件路径 (静态成员, 供截图回调使用) */ + static FString ScreenshotPath; + + /** 背景截图文件路径 (静态成员, 供延迟截图回调使用) */ + static FString BgScreenshotPath; +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAJsonUtils.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAJsonUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..46baccbd9ee3314e4372d983f6f598555cb40df1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQAJsonUtils.h @@ -0,0 +1,68 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" + +// 声明本模块专用的日志分类 LogLQAToolJsonUtils +// 参数含义: 分类名、默认日志级别 (Log)、编译期允许的最高级别 (All) +// 用于在 .cpp 中通过 UE_LOG(LogLQAToolJsonUtils, ...) 输出 JSON 相关日志 +DECLARE_LOG_CATEGORY_EXTERN(LogLQAToolJsonUtils, Log, All); + +/** + * JSON 序列化 / 反序列化工具类 + * 全部成员均为静态方法, 无需实例化即可调用, 作为纯工具集合使用 + * 封装了基础类型与 UObject 的 JSON 读写, 统一做了空指针/有效性校验 + */ +class LQATOOL_API FLQAJsonUtils +{ +public: + // ========== 序列化 (对象/数据 -> JSON) ========== + + /** 通过 UE 反射机制, 将 UObject 的属性序列化写入 JSON 对象 */ + static bool SerializeObjectToJson(const TSharedPtr& JsonObject, UObject* Object); + + /** 将基础类型以指定 Key 写入 JSON 对象 (函数重载, 支持常用类型) */ + // FVector2D: 会写成 { "X": .., "Y": .. } 的子对象 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, const FVector2D& Value); + // 布尔值 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, bool Value); + // 32 位整型 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, int32 Value); + // 单精度浮点 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, float Value); + // 双精度浮点 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, double Value); + // 字符串 + static bool SerializeToJson(const TSharedPtr& JsonObject, const FString& Key, const FString& Value); + + // ========== 反序列化 (JSON -> 数据) ========== + + /** 从 JSON 中按 Key 读取基础类型; 字段不存在或无效时返回传入的默认值 */ + // 读取 FVector2D (期望值是包含 X/Y 的子对象) + static FVector2D DeserializeVector2D(const TSharedPtr& JsonObject, const FString& Key, + const FVector2D& DefaultValue = FVector2D::ZeroVector); + // 读取布尔值 + static bool DeserializeBool( + const TSharedPtr& JsonObject, const FString& Key, bool DefaultValue = false); + // 读取 32 位整型 + static int32 DeserializeInt32( + const TSharedPtr& JsonObject, const FString& Key, int32 DefaultValue = 0); + // 读取单精度浮点 + static float DeserializeFloat( + const TSharedPtr& JsonObject, const FString& Key, float DefaultValue = 0.0f); + // 读取字符串 + static FString DeserializeString( + const TSharedPtr& JsonObject, const FString& Key, const FString& DefaultValue = TEXT("")); + + // ========== 通用工具方法 ========== + + /** 递归移除 JSON 中所有「键名为空」的字段 (含嵌套对象与数组内的对象) */ + static void RemoveEmptyKeysRecursively(TSharedPtr JsonObject); + + /** 判断 JSON 对象是否有效且包含指定字段 Key */ + static bool HasValidField(const TSharedPtr& JsonObject, const FString& Key); + +private: + /** 校验 JSON 对象指针是否有效 (内部统一校验入口, 无效时打警告日志) */ + static bool IsValidJsonObject(const TSharedPtr& JsonObject); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQATextureUtil.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQATextureUtil.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c6c5db9c15f9768fcb150ccf8bfa3e9451f5c7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Utils/LQATextureUtil.h @@ -0,0 +1,177 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" // UE 的 JSON 核心库, 提供 FJsonObject 等类型 +#include "JsonObjectConverter.h" // 结构体与 JSON 之间互转的工具 +#include "Math/Vector2D.h" // 二维向量 FVector2D + +#include "LQATextureUtil.generated.h" // UE 反射系统生成的代码 (必须放在最后一个 include) + +// 前向声明: 仅声明指针/引用用到的类型, 减少头文件依赖、加快编译 +class UTexture; +class UMaterialInstance; +class UMaterialInstanceDynamic; +class UMaterialInstanceConstant; +class UPaperSprite; +class UTexture2D; +class UTextureRenderTarget2D; +class UTextureCube; + +/** + * 纹理元数据结构 (内部使用,未暴露给蓝图) + * 记录纹理在图集/序列中的索引、UV 坐标与尺寸 + */ +struct FLQATextureMeta +{ + int32 Index; // 纹理索引 + FVector2D UV; // 纹理的 UV 坐标 + FVector2D Size; // 纹理尺寸 (宽、高) +}; + +/** + * 材质参数数据结构, 可在蓝图中使用 (BlueprintType) + * 用于聚合材质实例中的三类参数, 便于序列化 + */ +USTRUCT(BlueprintType) +struct FMaterialParameterData +{ + GENERATED_BODY() + + // 标量参数: 参数名 -> 浮点值 + UPROPERTY() + TMap ScalarParameters; + + // 向量参数: 参数名 -> 线性颜色 (RGBA) + UPROPERTY() + TMap VectorParameters; + + // 纹理参数: 参数名 -> 纹理资源路径 + UPROPERTY() + TMap TextureParameters; +}; + +/** + * 纹理与材质数据提取工具类 + * 负责把 UE 的纹理 / 材质对象转换为 JSON 表示, 供 LQA 工具导出使用 + * 全部为静态方法, 无需实例化 + */ +class FLQATextureUtil +{ +public: + /** + * 提取材质实例的全部参数并转换为 JSON 对象 + * @param MaterialInstance 要提取参数的材质实例 + * @return 包含材质参数的 JSON 对象; 若入参无效则返回 nullptr + */ + static TSharedPtr ExtractMaterialParametersToJsonObject(UMaterialInstance* MaterialInstance); + + /** + * 将纹理对象转换为 JSON 表示 (对外主入口) + * 内部会根据对象实际类型分发到对应的处理函数 + * @param TextureObject 要转换的纹理/材质对象 + * @param SharedTextureMap 共享纹理缓存 (避免重复处理同一纹理) + * @return 表示该纹理的 JSON 对象 + */ + static TSharedPtr GetTextureJsonObj( + UObject* TextureObject, TMap& SharedTextureMap); + + /** + * Read a Texture2D's pixels and compress them to PNG bytes. + * Used to persist runtime-generated textures (e.g. /Engine/Transient ones) that have no asset on disk. + * @param Texture2D Texture to read + * @param OutData Compressed PNG bytes + * @return true if PNG data was produced + */ + static bool GetTexture2DData(UTexture2D* Texture2D, TArray& OutData); + +private: + // JSON 字段名常量, 使用 “命名空间式” 的嵌套结构体来组织, 避免魔法字符串散落各处 + struct JsonFields + { + static const FString NAME; // 纹理名称字段 + static const FString NAME_MD5; // 纹理名称的 MD5 值字段 + static const FString TYPE; // 纹理类型字段 + static const FString SPRITE_NAME; // Sprite 名称字段 + static const FString SPRITE_NAME_MD5; // Sprite 名称的 MD5 值字段 + static const FString MATERIAL_PATH; // 基础材质路径字段 + static const FString SCALAR_PARAMS; // 标量参数集合字段 + static const FString VECTOR_PARAMS; // 向量参数集合字段 + static const FString TEXTURE_PARAMS; // 纹理参数集合字段 + + // 颜色分量字段名 (R/G/B/A) + struct ColorFields + { + static const FString R; // 红色分量 + static const FString G; // 绿色分量 + static const FString B; // 蓝色分量 + static const FString A; // 透明度分量 + }; + }; + + // 纹理类型名称常量 + struct TextureTypes + { + static const FString PAPER_SPRITE; // Paper2D 精灵类型 + static const FString TEXTURE_2D; // 2D 纹理类型 + static const FString TEXTURE_CUBE; // 立方体贴图类型 + }; + + // 以下为按功能分组的核心工具函数 + + // === JSON 转换工具 === + /** + * 将线性颜色转换为 JSON 对象 + * @param Color 要转换的颜色 + * @return 表示该颜色的 JSON 对象 (含 R/G/B/A 字段) + */ + static TSharedPtr LinearColorToJson(const FLinearColor& Color); + + /** + * 写入纹理的公共元数据 (名称、类型、名称 MD5) 到 JSON + * @param Texture 要提取数据的纹理 + * @param JsonRoot 写入目标 JSON 对象 + * @param TextureType 纹理类型字符串 + * @param SharedTextureMap 共享纹理缓存 + */ + static void WriteTextureMetadata(UTexture* Texture, const TSharedPtr& JsonRoot, + const FString& TextureType, TMap& SharedTextureMap); + + /** + * 写入 Sprite 专有数据 (Sprite 名称及其 MD5) 到 JSON + * @param JsonRoot 写入目标 JSON 对象 + * @param SpriteName Sprite 名称 + */ + static void WriteSpriteData(const TSharedPtr& JsonRoot, const FString& SpriteName); + + // === 材质处理函数 === + /** + * 处理材质实例并转换为 JSON (在参数基础上追加基础材质路径) + * @param MaterialInstance 要转换的材质实例 + * @return 表示该材质的 JSON 对象 + */ + static TSharedPtr HandleMaterialInstance(UMaterialInstance* MaterialInstance); + + // === 纹理处理函数 (按相似逻辑分组) === + /** + * 处理 Paper 精灵并转换为 JSON + * @param Sprite 要转换的精灵 + * @param SharedTextureMap 共享纹理缓存 + * @return 表示该精灵的 JSON 对象 + */ + static TSharedPtr HandlePaperSprite(UPaperSprite* Sprite, TMap& SharedTextureMap); + + /** + * 处理标准纹理 (Texture2D / RenderTarget2D) 并转换为 JSON + * @param Texture 要转换的纹理 + * @param SharedTextureMap 共享纹理缓存 + * @return 表示该纹理的 JSON 对象 + */ + static TSharedPtr HandleStandardTexture(UTexture* Texture, TMap& SharedTextureMap); + + /** + * 处理立方体贴图并转换为 JSON + * @param TextureCube 要转换的立方体贴图 + * @return 表示该立方体贴图的 JSON 对象 + */ + static TSharedPtr HandleTextureCube(UTextureCube* TextureCube); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetItem.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetItem.h new file mode 100644 index 0000000000000000000000000000000000000000..73dd4fb69b8a4837446e58712d3492a7742d369a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetItem.h @@ -0,0 +1,193 @@ +#pragma once + +#include "Blueprint/IUserObjectListEntry.h" +#include "Blueprint/UserWidget.h" +#include "Components/ListView.h" +#include "Components/TileView.h" +#include "Components/TreeView.h" +#include "CoreMinimal.h" + +#include "LQAGalleryWidgetItem.generated.h" + +class UBorder; +class UButton; +class UHorizontalBox; +class UPanelWidget; +class UTextBlock; +class UVerticalBox; + +/** + * LQA 验证画廊的子控件集合(UE5 版本),与 ULQAGalleryWidget_UE5 配套使用。 + * + * 约束:纯 C++ 构造,不新增资产;文本只能取自 LQAGalleryText。 + */ + +// =========================================================================== +// 1. 列表项数据 +// =========================================================================== + +/** 列表项数据对象:承载条目文本与配色 */ +UCLASS() +class ULQAGalleryListItem : public UObject +{ + GENERATED_BODY() + +public: + UPROPERTY() + FText Label; + + /** 条目文本是否自动换行(默认 true;BUG 示例置 false 制造溢出) */ + UPROPERTY() + bool bAutoWrapText = true; + + /** 条目文本颜色(由画廊按当前主题写入) */ + UPROPERTY() + FLinearColor TextColor = FLinearColor::White; +}; + +// =========================================================================== +// 2. 列表派生类 +// =========================================================================== + +/** 画廊 ListView:构造期指定 EntryWidgetClass(引擎中该成员为 protected,无 setter) */ +UCLASS() +class ULQAGalleryListView : public UListView +{ + GENERATED_BODY() + +public: + ULQAGalleryListView(const FObjectInitializer& ObjectInitializer); +}; + +/** 画廊 TileView:同 ULQAGalleryListView,用于设置 EntryWidgetClass */ +UCLASS() +class ULQAGalleryTileView : public UTileView +{ + GENERATED_BODY() + +public: + ULQAGalleryTileView(const FObjectInitializer& ObjectInitializer); +}; + +/** 画廊 TreeView:同 ULQAGalleryListView,用于设置 EntryWidgetClass */ +UCLASS() +class ULQAGalleryTreeView : public UTreeView +{ + GENERATED_BODY() + +public: + ULQAGalleryTreeView(const FObjectInitializer& ObjectInitializer); +}; + +// =========================================================================== +// 3. 列表条目 +// =========================================================================== + +/** 画廊列表条目,作为列表三件套的 EntryWidgetClass */ +UCLASS() +class ULQAGalleryEntryWidget : public UUserWidget, public IUserObjectListEntry +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + +protected: + /** 绑定所属列表项数据(ULQAGalleryListItem::Label) */ + virtual void NativeOnListItemObjectSet(UObject* ListItemObject) override; + + UPROPERTY(Transient) + UTextBlock* EntryLabel = nullptr; +}; + +/** 画廊动态条目框条目,由 UDynamicEntryBox::CreateEntry 创建 */ +UCLASS() +class ULQAGalleryDynamicEntryWidget : public UUserWidget +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + + /** 设置条目文本;控件尚未构建时先缓存,构建后应用 */ + void SetEntryText(const FText& InText); + +protected: + UPROPERTY(Transient) + UTextBlock* EntryLabel = nullptr; + + /** 待应用文本(控件未构建时缓存) */ + FText PendingText; +}; + +// =========================================================================== +// 4. 菜单内容 +// =========================================================================== + +/** 画廊菜单内容,由 UMenuAnchor::MenuClass 引用 */ +UCLASS() +class ULQAGalleryMenuWidget : public UUserWidget +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + +protected: + /** 按钮 1 点击(仅用于构成可交互控件,不做业务处理) */ + UFUNCTION() + void OnFirstButtonClicked(); + + /** 按钮 2 点击(仅用于构成可交互控件,不做业务处理) */ + UFUNCTION() + void OnSecondButtonClicked(); + + /** 使用已登记文本构造一个按钮 */ + UButton* MakeMenuButton(UPanelWidget* Parent, const FText& Label, bool bFirst); + + UPROPERTY(Transient) + UVerticalBox* MenuBox = nullptr; + + UPROPERTY(Transient) + UTextBlock* MenuLabel = nullptr; + + UPROPERTY(Transient) + UButton* FirstButton = nullptr; + + UPROPERTY(Transient) + UButton* SecondButton = nullptr; +}; + +// =========================================================================== +// 5. 嵌套子 UserWidget +// =========================================================================== + +/** 画廊嵌套子 UserWidget,由画廊 CreateWidget 动态创建 */ +UCLASS() +class ULQAGalleryChildWidget : public UUserWidget +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + + /** 按主题设置标签与图标颜色 */ + void SetThemeColors(const FLinearColor& InLabelColor, const FLinearColor& InIconColor); + +protected: + UPROPERTY(Transient) + UHorizontalBox* ChildBox = nullptr; + + /** 图标位(纯色块,避免依赖任何贴图资产) */ + UPROPERTY(Transient) + UBorder* ChildIcon = nullptr; + + UPROPERTY(Transient) + UTextBlock* ChildLabel = nullptr; + + /** 标签颜色(子控件未构建时先缓存) */ + FLinearColor LabelColor = FLinearColor::White; + + /** 图标颜色(子控件未构建时先缓存) */ + FLinearColor IconColor = FLinearColor(0.20f, 0.60f, 0.90f, 1.f); +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetText.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetText.h new file mode 100644 index 0000000000000000000000000000000000000000..835674cc07f641eea11d93db5e4d47bcf6f305ea --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidgetText.h @@ -0,0 +1,300 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Internationalization/Text.h" +#include "Runtime/Launch/Resources/Version.h" + +/** + * 画廊控件文本定义:为画廊示例 UI 提供显示文本(画廊唯一文本出口)。 + * + * 使用规范: + * 1. 示例文本只允许在本文件定义,控件侧不得硬编码; + * 2. 新增文本必须同步登记到 LQALocalization 两个 JSON,否则还原侧取不到译文。 + */ +namespace LQAGalleryWidgetText +{ +/** 统一 Namespace,与 GameLocalizationExport_en.json 的键前缀保持一致 */ +#define LQA_GALLERY_TEXT(Key, SourceStr) NSLOCTEXT("ST_Gallery", Key, SourceStr) +/** 画廊行标签 / 编号等次级文本(源文在 Text_Translations_en.json 中登记) */ +#define LQA_GALLERY_LABEL(Name, SourceStr) NSLOCTEXT("ST_Gallery", "ST_Gallery_Label_" #Name, SourceStr) + +// =========================================================================== +// L1:内容文本(Key 与源文对齐 GameLocalizationExport_en.json) +// =========================================================================== + +#if ENGINE_MAJOR_VERSION >= 5 +inline FText Title() { return LQA_GALLERY_TEXT("ST_Gallery_Title", "LQA 验证画廊 (UE5)"); } +#else +inline FText Title() { return LQA_GALLERY_TEXT("ST_Gallery_Title_UE4", "LQA 验证画廊 (UE4)"); } +#endif +inline FText SectionText() { return LQA_GALLERY_TEXT("ST_Gallery_Section_Text", "一、文本类控件"); } +inline FText SectionInput() { return LQA_GALLERY_TEXT("ST_Gallery_Section_Input", "二、交互/输入类控件"); } +inline FText SectionPresent() { return LQA_GALLERY_TEXT("ST_Gallery_Section_Present", "三、展示类控件"); } +inline FText SectionLayout() { return LQA_GALLERY_TEXT("ST_Gallery_Section_Layout", "四、布局容器"); } + +inline FText TextBlockSample() { return LQA_GALLERY_TEXT("ST_Gallery_TextBlockSample", "这是 TextBlock 示例"); } +inline FText RichTextBlockSample() +{ + return LQA_GALLERY_TEXT("ST_Gallery_RichTextBlockSample", "这是 RichTextBlock 富文本 示例"); +} +inline FText MultiLineText() { return LQA_GALLERY_TEXT("ST_Gallery_MultiLineText", "MultiLineEditableText\n多行文本"); } +inline FText MultiLineTextBox() +{ + return LQA_GALLERY_TEXT("ST_Gallery_MultiLineTextBox", "MultiLineEditableTextBox\n多行文本框"); +} +inline FText HintEditableText() { return LQA_GALLERY_TEXT("ST_Gallery_Hint_EditableText", "EditableText 单行输入"); } +inline FText HintEditableTextBox() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Hint_EditableTextBox", "EditableTextBox 单行输入框"); +} +inline FText BorderContent() { return LQA_GALLERY_TEXT("ST_Gallery_BorderContent", "Border 内容"); } +inline FText OverlayStack() { return LQA_GALLERY_TEXT("ST_Gallery_OverlayStack", "Overlay 叠加"); } +inline FText ScaleBoxContent() { return LQA_GALLERY_TEXT("ST_Gallery_ScaleBoxContent", "ScaleBox 缩放内容"); } +inline FText SafeZoneContent() { return LQA_GALLERY_TEXT("ST_Gallery_SafeZoneContent", "SafeZone 内容"); } + +// =========================================================================== +// L2:行标签(源文在 Text_Translations_en.json 中登记,译文与源文一致) +// =========================================================================== + +inline FText LabelTextBlock() { return LQA_GALLERY_LABEL(TextBlock, "TextBlock"); } +inline FText LabelRichTextBlock() { return LQA_GALLERY_LABEL(RichTextBlock, "RichTextBlock"); } +inline FText LabelEditableText() { return LQA_GALLERY_LABEL(EditableText, "EditableText"); } +inline FText LabelEditableTextBox() { return LQA_GALLERY_LABEL(EditableTextBox, "EditableTextBox"); } +inline FText LabelMultiLineEditableText() +{ + return LQA_GALLERY_LABEL(MultiLineEditableText, "MultiLineEditableText"); +} +inline FText LabelMultiLineEditableTextBox() +{ + return LQA_GALLERY_LABEL(MultiLineEditableTextBox, "MultiLineEditableTextBox"); +} +inline FText LabelButton() { return LQA_GALLERY_LABEL(Button, "Button"); } +inline FText LabelCheckBox() { return LQA_GALLERY_LABEL(CheckBox, "CheckBox"); } +inline FText LabelSlider() { return LQA_GALLERY_LABEL(Slider, "Slider"); } +inline FText LabelProgressBar() { return LQA_GALLERY_LABEL(ProgressBar, "ProgressBar"); } +inline FText LabelComboBoxString() { return LQA_GALLERY_LABEL(ComboBoxString, "ComboBoxString"); } +inline FText LabelComboBoxKey() { return LQA_GALLERY_LABEL(ComboBoxKey, "ComboBoxKey"); } +inline FText LabelSpinBox() { return LQA_GALLERY_LABEL(SpinBox, "SpinBox"); } +inline FText LabelInputKeySelector() { return LQA_GALLERY_LABEL(InputKeySelector, "InputKeySelector"); } +inline FText LabelImage() { return LQA_GALLERY_LABEL(Image, "Image"); } +inline FText LabelThrobber() { return LQA_GALLERY_LABEL(Throbber, "Throbber"); } +inline FText LabelCircularThrobber() { return LQA_GALLERY_LABEL(CircularThrobber, "CircularThrobber"); } +inline FText LabelSpacer() { return LQA_GALLERY_LABEL(Spacer, "Spacer (40x20)"); } +inline FText LabelBorder() { return LQA_GALLERY_LABEL(Border, "Border"); } +inline FText LabelBackgroundBlur() { return LQA_GALLERY_LABEL(BackgroundBlur, "BackgroundBlur"); } +inline FText LabelRetainerBox() { return LQA_GALLERY_LABEL(RetainerBox, "RetainerBox"); } +inline FText LabelPostBufferUpdate() { return LQA_GALLERY_LABEL(PostBufferUpdate, "PostBufferUpdate"); } +inline FText LabelUserWidget() { return LQA_GALLERY_LABEL(UserWidget, "UserWidget"); } +inline FText LabelCanvasPanel() { return LQA_GALLERY_LABEL(CanvasPanel, "CanvasPanel"); } +inline FText LabelScrollBox() { return LQA_GALLERY_LABEL(ScrollBox, "ScrollBox"); } +inline FText LabelVerticalBox() { return LQA_GALLERY_LABEL(VerticalBox, "VerticalBox"); } +inline FText LabelHorizontalBox() { return LQA_GALLERY_LABEL(HorizontalBox, "HorizontalBox"); } +inline FText LabelScaleBox() { return LQA_GALLERY_LABEL(ScaleBox, "ScaleBox"); } +inline FText LabelSafeZone() { return LQA_GALLERY_LABEL(SafeZone, "SafeZone"); } +inline FText LabelWrapBox() { return LQA_GALLERY_LABEL(WrapBox, "WrapBox"); } +inline FText LabelSizeBox() { return LQA_GALLERY_LABEL(SizeBox, "SizeBox (120x40)"); } +inline FText LabelNamedSlot() { return LQA_GALLERY_LABEL(NamedSlot, "NamedSlot"); } +inline FText LabelGridPanel() { return LQA_GALLERY_LABEL(GridPanel, "GridPanel"); } +inline FText LabelUniformGridPanel() { return LQA_GALLERY_LABEL(UniformGridPanel, "UniformGridPanel"); } +inline FText LabelOverlay() { return LQA_GALLERY_LABEL(Overlay, "Overlay"); } +inline FText LabelWidgetSwitcher() { return LQA_GALLERY_LABEL(WidgetSwitcher, "WidgetSwitcher"); } +inline FText LabelStackBox() { return LQA_GALLERY_LABEL(StackBox, "StackBox"); } +inline FText LabelInvalidationBox() { return LQA_GALLERY_LABEL(InvalidationBox, "InvalidationBox"); } +inline FText LabelWindowTitleBarArea() +{ + return LQA_GALLERY_LABEL(WindowTitleBarArea, "WindowTitleBarArea"); +} +inline FText LabelScrollBar() { return LQA_GALLERY_LABEL(ScrollBar, "ScrollBar"); } +inline FText LabelMenuAnchor() { return LQA_GALLERY_LABEL(MenuAnchor, "MenuAnchor"); } +inline FText LabelExpandableArea() { return LQA_GALLERY_LABEL(ExpandableArea, "ExpandableArea"); } +inline FText LabelDynamicEntryBox() { return LQA_GALLERY_LABEL(DynamicEntryBox, "DynamicEntryBox"); } +inline FText LabelListView() { return LQA_GALLERY_LABEL(ListView, "ListView"); } +inline FText LabelTileView() { return LQA_GALLERY_LABEL(TileView, "TileView"); } +inline FText LabelTreeView() { return LQA_GALLERY_LABEL(TreeView, "TreeView"); } + +// =========================================================================== +// L2:示例内容 / 辅助文本 +// =========================================================================== + +inline FText ContentTextBlock() { return LQA_GALLERY_LABEL(ContentTextBlock, "TextBlock"); } +inline FText ContentBorder() { return LQA_GALLERY_LABEL(ContentBorder, "Border"); } +inline FText ContentButton() { return LQA_GALLERY_LABEL(ContentButton, "Button"); } +inline FText ContentComboBoxString() { return LQA_GALLERY_LABEL(ContentComboBoxString, "ComboBoxString"); } +inline FText ContentEditableText() { return LQA_GALLERY_LABEL(ContentEditableText, "EditableText"); } +inline FText ContentScrollBox() { return LQA_GALLERY_LABEL(ContentScrollBox, "ScrollBox"); } +inline FText ContentPage0() { return LQA_GALLERY_LABEL(Page0, "Page 0"); } +inline FText ContentPage1() { return LQA_GALLERY_LABEL(Page1, "Page 1"); } +inline FText ContentKeySelection() { return LQA_GALLERY_LABEL(KeySelection, "KeySelection"); } +inline FText ContentNoKeySpecified() { return LQA_GALLERY_LABEL(NoKeySpecified, "NoKeySpecified"); } +inline FText ContentMenuAnchorAnchor() { return LQA_GALLERY_LABEL(MenuAnchorAnchor, "MenuAnchor Anchor"); } +inline FText ContentInvalidationBox() { return LQA_GALLERY_LABEL(InvalidationBoxContent, "InvalidationBox Content"); } +inline FText ContentWindowTitleBarArea() +{ + return LQA_GALLERY_LABEL(WindowTitleBarAreaContent, "WindowTitleBarArea Content"); +} +inline FText ContentHorizontal(int32 Index) +{ + switch (Index) + { + case 0: return LQA_GALLERY_LABEL(H0, "[H0]"); + case 1: return LQA_GALLERY_LABEL(H1, "[H1]"); + default: return LQA_GALLERY_LABEL(H2, "[H2]"); + } +} +inline FText ContentGrid(int32 Row, int32 Column) +{ + if (Row == 0 && Column == 0) { return LQA_GALLERY_LABEL(R0C0, "(0,0)"); } + if (Row == 0 && Column == 1) { return LQA_GALLERY_LABEL(R0C1, "(0,1)"); } + if (Row == 1 && Column == 0) { return LQA_GALLERY_LABEL(R1C0, "(1,0)"); } + return LQA_GALLERY_LABEL(R1C1, "(1,1)"); +} +inline FText ContentUniform(int32 Index) +{ + switch (Index) + { + case 0: return LQA_GALLERY_LABEL(U0, "U0"); + case 1: return LQA_GALLERY_LABEL(U1, "U1"); + case 2: return LQA_GALLERY_LABEL(U2, "U2"); + default: return LQA_GALLERY_LABEL(U3, "U3"); + } +} +inline FText ContentWrap(int32 Index) +{ + switch (Index) + { + case 0: return LQA_GALLERY_LABEL(W0, "Wrap0"); + case 1: return LQA_GALLERY_LABEL(W1, "Wrap1"); + case 2: return LQA_GALLERY_LABEL(W2, "Wrap2"); + case 3: return LQA_GALLERY_LABEL(W3, "Wrap3"); + case 4: return LQA_GALLERY_LABEL(W4, "Wrap4"); + default: return LQA_GALLERY_LABEL(W5, "Wrap5"); + } +} + +// =========================================================================== +// L2:交互控制条按钮文本 +// =========================================================================== + +inline FText CtrlScrollTop() { return LQA_GALLERY_LABEL(CtrlScrollTop, "滚动到顶"); } +inline FText CtrlScrollBottom() { return LQA_GALLERY_LABEL(CtrlScrollBottom, "滚动到底"); } +inline FText CtrlToggleTheme() { return LQA_GALLERY_LABEL(CtrlToggleTheme, "切换背景"); } + +// =========================================================================== +// L2:列表示例条目文本(Text<序号>,便于采集时核对条目来源) +// =========================================================================== + +inline FText DynamicEntryBoxText(int32 Index) +{ + switch (Index) + { + case 1: return LQA_GALLERY_LABEL(DynamicEntryBoxText1, "DynamicEntryBoxText1"); + case 2: return LQA_GALLERY_LABEL(DynamicEntryBoxText2, "DynamicEntryBoxText2"); + default: return LQA_GALLERY_LABEL(DynamicEntryBoxText3, "DynamicEntryBoxText3"); + } +} + +inline FText ListViewText(int32 Index) +{ + switch (Index) + { + case 1: return LQA_GALLERY_LABEL(ListViewText1, "ListViewText1"); + case 2: return LQA_GALLERY_LABEL(ListViewText2, "ListViewText2"); + default: return LQA_GALLERY_LABEL(ListViewText3, "ListViewText3"); + } +} + +inline FText TileViewText(int32 Index) +{ + return Index == 1 ? LQA_GALLERY_LABEL(TileViewText1, "TileViewText1") + : LQA_GALLERY_LABEL(TileViewText2, "TileViewText2"); +} + +inline FText TreeViewText(int32 Index) +{ + switch (Index) + { + case 1: return LQA_GALLERY_LABEL(TreeViewText1, "TreeViewText1"); + case 2: return LQA_GALLERY_LABEL(TreeViewText2, "TreeViewText2"); + default: return LQA_GALLERY_LABEL(TreeViewText3, "TreeViewText3"); + } +} + +// =========================================================================== +// L1:显示性质 BUG 示例文本(故意缺陷,供插件识别能力验证;文本需登记本地化) +// =========================================================================== + +inline FText SectionBug() { return LQA_GALLERY_TEXT("ST_Gallery_Section_Bug", "五、显示性质 BUG"); } + +inline FText BugOverflowSingleLine() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_OverflowSingleLine", + "这段文本故意不换行,会冲出左侧固定区域并超出舞台边界,用于检测文本溢出与重叠"); +} +inline FText BugOverflowMultiLine() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_OverflowMultiLine", "换行后行数超出高度,越出舞台底部"); +} +inline FText BugFontSize() { return LQA_GALLERY_TEXT("ST_Gallery_Bug_FontSize", "字号 36 的文本"); } +inline FText BugButtonOverflow() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_ButtonOverflow", "Confirm and Continue With All Changes"); +} +inline FText BugLineHeight() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_LineHeight", + "行高被压缩到 30%,两行文本会互相叠压,用于检测单个文本节点内部的重叠"); +} +inline FText BugInvisible() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_Invisible", "这段文本与底色同色,应完全不可见"); +} +inline FText BugTileViewOverflow() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_TileViewOverflow", "OverflowingTileViewItemTextWithoutAnySpaces"); +} + +inline FText BugTruncate() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_Truncate", + "这段文本超出固定宽度后被硬截断,末尾没有省略号,用于检测截断识别"); +} + +/** BUG 示例:无本地化 Key 的文本(不登记 LQALocalization,采集应输出 INVALIDKEY) */ +inline FText BugNoKey() +{ + return FText::FromString(TEXT("Invalid/IDC_Gameltem_30005")); +} + +/** BUG 示例:有 Key 但无译文的文本(不登记 LQALocalization,英文下应显示中文源文) */ +inline FText BugMissingTranslation() +{ + return LQA_GALLERY_TEXT("ST_Gallery_Bug_MissingTranslation", "漏译:有 Key 无译文"); +} + +// =========================================================================== +// L2:显示性质 BUG 行标签与参照文本 +// =========================================================================== + +inline FText LabelBug01() { return LQA_GALLERY_LABEL(Bug01, "[BUG-01] 单行超长溢出"); } +inline FText LabelBug02() { return LQA_GALLERY_LABEL(Bug02, "[BUG-02] 换行纵向溢出"); } +inline FText LabelBug03() { return LQA_GALLERY_LABEL(Bug03, "[BUG-03] 字号过大溢出"); } +inline FText LabelBug04() { return LQA_GALLERY_LABEL(Bug04, "[BUG-04] 按钮文本被截断"); } +inline FText LabelBug05() { return LQA_GALLERY_LABEL(Bug05, "[BUG-05] 行高压缩叠字"); } +inline FText LabelBug06() { return LQA_GALLERY_LABEL(Bug06, "[BUG-06] 文本同色不可见"); } +inline FText LabelBug07() { return LQA_GALLERY_LABEL(Bug07Truncate, "[BUG-07] 文本被硬截断"); } +inline FText LabelBug08() { return LQA_GALLERY_LABEL(Bug08, "[BUG-08] TileView 容器重叠"); } +inline FText LabelBug09() { return LQA_GALLERY_LABEL(Bug09, "[BUG-09] TileView 条目截断"); } +inline FText LabelBug10() { return LQA_GALLERY_LABEL(Bug10MissingKey, "[BUG-10] 漏 Key 显示原始 Key"); } +inline FText LabelBug11() { return LQA_GALLERY_LABEL(Bug11, "[BUG-11] 有 Key 但漏译"); } + +inline FText BugReferenceBottom() { return LQA_GALLERY_LABEL(BugReferenceBottom, "↑ 底部参照行"); } + +inline FText BugTileViewItem(int32 Index) +{ + return Index == 1 ? LQA_GALLERY_LABEL(BugTileViewItem1, "BugTile1") + : LQA_GALLERY_LABEL(BugTileViewItem2, "BugTile2"); +} + +#undef LQA_GALLERY_LABEL +#undef LQA_GALLERY_TEXT +} diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE4.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE4.h new file mode 100644 index 0000000000000000000000000000000000000000..9b3ec9b40baf8962b4ef3f109f18975be0086aee --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE4.h @@ -0,0 +1,286 @@ +#pragma once + +#include "Blueprint/UserWidget.h" +#include "CoreMinimal.h" +#include "Validation/LQAGalleryWidget_UE5.h" + +#include "LQAGalleryWidget_UE4.generated.h" + +class UBorder; +class UButton; +class UCheckBox; +class UCircularThrobber; +class UComboBoxKey; +class UComboBoxString; +class UDataTable; +class UEditableText; +class UEditableTextBox; +class UExpandableArea; +class UListView; +class UMenuAnchor; +class UMultiLineEditableText; +class UMultiLineEditableTextBox; +class UPanelWidget; +class UProgressBar; +class URichTextBlock; +class UScrollBox; +class USlider; +class USpinBox; +class UTextBlock; +class UTexture2D; +class UThrobber; +class UVerticalBox; +class UWidget; +class UWidgetSwitcher; +class ULQAGalleryChildWidget; + + +/** + * LQA 快速验证画廊(UE4 版本):一次性构造全部示例控件与布局容器。 + * + * 使用方式:运行 `LQA.BuildGallery [Widgets|Layout|Composite|All]` 自动挂载到视口; + * 顶部控制条“切换背景”按钮在深色 / 浅色主题间切换。 + * 约束:纯 C++ 构建,不新增任何资产;示例文本只能取自 LQAGalleryText; + * 新增文本控件须经 MakeTextBlock 登记配色角色; + * RichText 字体固定取引擎字体,不读项目默认字体配置。 + */ +UCLASS() +class ULQAGalleryWidget_UE4 : public UUserWidget +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + + /** + * 构建画廊 + * @param bIncludeWidgets 文本 / 输入 / 展示 / 动态 四区 + * @param bIncludeLayouts 布局容器区 + * @param bIncludeBugs 显示性质 BUG 示例区 + */ + void BuildAll(bool bIncludeWidgets = true, bool bIncludeLayouts = true, bool bIncludeBugs = false); + + /** 按当前主题刷新背景、标题条、控制条与全部已登记控件 */ + void ApplyTheme(); + +private: + // ======================================================================= + // 分区构造 + // ======================================================================= + UPanelWidget* BuildTextSection(); + UPanelWidget* BuildInputSection(); + UPanelWidget* BuildDisplaySection(); + UPanelWidget* BuildLayoutSection(); + UPanelWidget* BuildBugSection(); + + /** 顶部固定交互控制条(滚动定位 / 主题切换) */ + UPanelWidget* BuildControlBar(); + + // ======================================================================= + // 行 / 文本 / 纹理辅助 + // ======================================================================= + + /** 分区标题(蓝底白字) */ + UWidget* MakeSectionHeader(const FText& Title); + + /** 统一示例行:左标签(统一列宽)+ 右内容(SizeBox 约束最小尺寸) */ + UWidget* MakeSizedRow(const FText& Label, UWidget* Content, const FVector2D& Size); + + /** + * BUG 示例用固定尺寸文本(SizeBox 强制宽高,允许内容绘制越界) + * @param OutTextBlock 非空时返回内部 TextBlock + */ + UWidget* MakeFixedText(const FText& Text, FName WidgetName, const FVector2D& Size, bool bWrap, float FontSize, + UTextBlock** OutTextBlock = nullptr); + + /** + * BUG 示例行:左标签 + 固定尺寸舞台(1px 描边) + * @param bBottomReference 是否在舞台下方显示参照行 + * @param StageColor 舞台底色,透明时取当前主题控制条底色 + */ + UWidget* MakeBugRow(const FText& Label, UWidget* StageContent, const FVector2D& StageSize, + bool bBottomReference = false, FLinearColor StageColor = FLinearColor::Transparent); + + /** 使用已登记文本构造 TextBlock,并按角色登记主题配色 */ + UTextBlock* MakeTextBlock(const FText& Text, FName WidgetName = NAME_None, + ELQAGalleryTextRole Role = ELQAGalleryTextRole::Primary); + + /** 按角色登记文本控件,供 ApplyTheme 统一改色 */ + void RegisterThemedText(UTextBlock* TextBlock, ELQAGalleryTextRole Role); + + /** 取当前主题的 RichText 样式表(缺失时按主题构建并缓存) */ + UDataTable* GetRichTextStyleSet(); + + /** 构造控制条按钮(对象名需唯一,避免同名对象被复用) */ + UButton* MakeControlButton(UPanelWidget* Parent, const FText& Label, FName WidgetName); + + /** 构造纯色 texture(供 Image 示例使用) */ + UTexture2D* CreateSolidTexture(int32 Size, const FColor& Color); + + // ======================================================================= + // 交互回调(供控制条按钮 AddDynamic 绑定;默认仅 SwitchPage 被使用,其余供扩展) + // ======================================================================= + UFUNCTION() + void OnSwitchPageClicked(); + + UFUNCTION() + void OnToggleExpandClicked(); + + UFUNCTION() + void OnSwitchOptionClicked(); + + UFUNCTION() + void OnToggleMenuClicked(); + + UFUNCTION() + void OnToggleCheckClicked(); + + UFUNCTION() + void OnScrollTopClicked(); + + UFUNCTION() + void OnScrollBottomClicked(); + + /** 深色 / 浅色主题切换 */ + UFUNCTION() + void OnToggleThemeClicked(); + + // ======================================================================= + // 成员(动态态回调需要访问,Transient 避免被序列化) + // ======================================================================= + UPROPERTY(Transient) + UPanelWidget* RootPanel = nullptr; + + UPROPERTY(Transient) + UPanelWidget* ContentBox = nullptr; + + UPROPERTY(Transient) + UScrollBox* GalleryScroll = nullptr; + + UPROPERTY(Transient) + UWidgetSwitcher* GallerySwitcher = nullptr; + + UPROPERTY(Transient) + UExpandableArea* GalleryExpandableArea = nullptr; + + UPROPERTY(Transient) + UComboBoxString* GalleryComboBoxString = nullptr; + + UPROPERTY(Transient) + UWidget* GalleryComboBoxKey = nullptr; + + UPROPERTY(Transient) + UMenuAnchor* GalleryMenuAnchor = nullptr; + + UPROPERTY(Transient) + UCheckBox* GalleryCheckBox = nullptr; + + // ======================================================================= + // 主题 + // ======================================================================= + + /** 当前主题色板 */ + FLQAGalleryTheme Theme = FLQAGalleryTheme::Dark(); + + /** 当前是否为深色主题 */ + bool bDarkTheme = true; + + /** 当前主题下的页面背景层 */ + UPROPERTY(Transient) + UBorder* BackgroundBorder = nullptr; + + /** 顶部控制条底色容器 */ + UPROPERTY(Transient) + UBorder* ControlBarBorder = nullptr; + + /** 分区标题条(随主题换底色) */ + UPROPERTY(Transient) + TArray HeaderBorders; + + /** 页面正文文本 */ + UPROPERTY(Transient) + TArray PrimaryTexts; + + /** 行标签文本 */ + UPROPERTY(Transient) + TArray SecondaryTexts; + + /** 标题条文本 */ + UPROPERTY(Transient) + TArray OnAccentTexts; + + /** 示例面板内文本 */ + UPROPERTY(Transient) + TArray OnPanelTexts; + + /** 引擎默认浅色控件上的文本 */ + UPROPERTY(Transient) + TArray OnControlTexts; + + /** RichTextBlock 示例 */ + UPROPERTY(Transient) + URichTextBlock* GalleryRichText = nullptr; + + /** 深色主题的 RichText 样式表(运行时构建,不依赖资产) */ + UPROPERTY(Transient) + UDataTable* RichTextStyleDark = nullptr; + + /** 浅色主题的 RichText 样式表(运行时构建,不依赖资产) */ + UPROPERTY(Transient) + UDataTable* RichTextStyleLight = nullptr; + + /** EditableText 示例 */ + UPROPERTY(Transient) + UEditableText* GalleryEditableText = nullptr; + + /** MultiLineEditableText 示例 */ + UPROPERTY(Transient) + UMultiLineEditableText* GalleryMultiLineEditableText = nullptr; + + /** EditableTextBox 示例 */ + UPROPERTY(Transient) + UEditableTextBox* GalleryEditableTextBox = nullptr; + + /** MultiLineEditableTextBox 示例 */ + UPROPERTY(Transient) + UMultiLineEditableTextBox* GalleryMultiLineEditableTextBox = nullptr; + + /** SpinBox 示例 */ + UPROPERTY(Transient) + USpinBox* GallerySpinBox = nullptr; + + /** Slider 示例 */ + UPROPERTY(Transient) + USlider* GallerySlider = nullptr; + + /** ProgressBar 示例 */ + UPROPERTY(Transient) + UProgressBar* GalleryProgressBar = nullptr; + + /** CheckBox 示例集合 */ + UPROPERTY(Transient) + TArray GalleryCheckBoxes; + + /** Throbber 示例 */ + UPROPERTY(Transient) + UThrobber* GalleryThrobber = nullptr; + + /** CircularThrobber 示例 */ + UPROPERTY(Transient) + UCircularThrobber* GalleryCircularThrobber = nullptr; + + /** 列表类示例(ListView / TileView / TreeView) */ + UPROPERTY(Transient) + TArray GalleryListViews; + + /** 嵌套子 UserWidget 示例 */ + UPROPERTY(Transient) + ULQAGalleryChildWidget* GalleryChildWidget = nullptr; + + /** 标签列固定宽度:以最长标签(MultiLineEditableTextBox)为准,保证各行内容起点一致 */ + float LabelColumnWidth = 350.f; + + /** 控制条高度:滚动区避让量 */ + float ControlBarHeight = 64.f; +}; + diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE5.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE5.h new file mode 100644 index 0000000000000000000000000000000000000000..6c04a3aa81411c0df9554c4e706065a82bc83e83 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/Validation/LQAGalleryWidget_UE5.h @@ -0,0 +1,393 @@ +#pragma once + +#include "Blueprint/UserWidget.h" +#include "CoreMinimal.h" + +#include "LQAGalleryWidget_UE5.generated.h" + +class UBorder; +class UButton; +class UCheckBox; +class UCircularThrobber; +class UComboBoxKey; +class UComboBoxString; +class UDataTable; +class UEditableText; +class UEditableTextBox; +class UExpandableArea; +class UListView; +class UMenuAnchor; +class UMultiLineEditableText; +class UMultiLineEditableTextBox; +class UPanelWidget; +class UProgressBar; +class URichTextBlock; +class UScrollBox; +class USlider; +class USpinBox; +class UTextBlock; +class UTexture2D; +class UThrobber; +class UVerticalBox; +class UWidget; +class UWidgetSwitcher; +class ULQAGalleryChildWidget; + +/** 画廊文本配色角色(决定文本随主题取哪一种语义色) */ +enum class ELQAGalleryTextRole : uint8 +{ + /** 页面正文 */ + Primary, + /** 行标签 */ + Secondary, + /** 分区标题条上的文字 */ + OnAccent, + /** 深色示例面板内的文字 */ + OnPanel, + /** 引擎默认浅色控件上的文字 */ + OnControl +}; + +/** + * 画廊配色主题:深色 / 浅色两套色板。 + * + * 使用规范: + * 1. 颜色以 #RRGGBB 书写并经 FromHex() 转换,不直接写 FLinearColor 分量; + * 2. 新增语义色时两套主题必须同时给出取值; + * 3. 引擎默认浅色控件(Button / 菜单按钮)上的文字使用 ControlText(),不随主题变化。 + */ +struct FLQAGalleryTheme +{ + /** 页面底色 */ + FLinearColor PageBackground; + + /** 顶部控制条底色 */ + FLinearColor BarBackground; + + /** 分区标题条底色 */ + FLinearColor HeaderBackground; + + /** 分隔线与控件轨道色 */ + FLinearColor Divider; + + /** 页面正文色 */ + FLinearColor TextPrimary; + + /** 行标签色 */ + FLinearColor TextSecondary; + + /** 强调底(分区标题条)上的文字色 */ + FLinearColor TextOnAccent; + + /** 深色示例面板内的文字色 */ + FLinearColor TextOnPanel; + + /** 强调色(Slider 手柄 / ProgressBar 填充 / 富文本强调段) */ + FLinearColor Accent; + + /** 富文本标记名强调色(与 Accent 区分) */ + FLinearColor Highlight; + + /** 深色主题色板 */ + static FLQAGalleryTheme Dark(); + + /** 浅色主题色板 */ + static FLQAGalleryTheme Light(); + + /** #RRGGBB / #RRGGBBAA 转线性色 */ + static FLinearColor FromHex(const TCHAR* Hex) + { + return FLinearColor::FromSRGBColor(FColor::FromHex(FString(Hex))); + } + + /** 引擎默认浅色控件上的文字颜色 */ + static FLinearColor ControlText() + { + return FromHex(TEXT("#1F2937")); + } +}; + +inline FLQAGalleryTheme FLQAGalleryTheme::Dark() +{ + FLQAGalleryTheme Theme; + Theme.PageBackground = FromHex(TEXT("#1F2937")); + Theme.BarBackground = FromHex(TEXT("#111827")); + Theme.HeaderBackground = FromHex(TEXT("#1D4ED8")); + Theme.Divider = FromHex(TEXT("#374151")); + Theme.TextPrimary = FromHex(TEXT("#E5E7EB")); + Theme.TextSecondary = FromHex(TEXT("#9CA3AF")); + Theme.TextOnAccent = FromHex(TEXT("#F8FAFC")); + Theme.TextOnPanel = FromHex(TEXT("#F8FAFC")); + Theme.Accent = FromHex(TEXT("#60A5FA")); + Theme.Highlight = FromHex(TEXT("#FBBF24")); + return Theme; +} + +inline FLQAGalleryTheme FLQAGalleryTheme::Light() +{ + FLQAGalleryTheme Theme; + Theme.PageBackground = FromHex(TEXT("#E2E8F0")); + Theme.BarBackground = FromHex(TEXT("#CBD5E1")); + Theme.HeaderBackground = FromHex(TEXT("#2563EB")); + Theme.Divider = FromHex(TEXT("#94A3B8")); + Theme.TextPrimary = FromHex(TEXT("#1F2937")); + Theme.TextSecondary = FromHex(TEXT("#475569")); + Theme.TextOnAccent = FromHex(TEXT("#F8FAFC")); + Theme.TextOnPanel = FromHex(TEXT("#F8FAFC")); + Theme.Accent = FromHex(TEXT("#1D4ED8")); + Theme.Highlight = FromHex(TEXT("#B45309")); + return Theme; +} + +/** + * LQA 快速验证画廊(UE5 版本):一次性构造全部示例控件与布局容器。 + * + * 使用方式:运行 `LQA.BuildGallery [Widgets|Layout|Composite|All]` 自动挂载到视口; + * 顶部控制条“切换背景”按钮在深色 / 浅色主题间切换。 + * 约束:纯 C++ 构建,不新增任何资产;示例文本只能取自 LQAGalleryText; + * 新增文本控件须经 MakeTextBlock 登记配色角色; + * RichText 字体固定取引擎字体,不读项目默认字体配置。 + */ +UCLASS() +class ULQAGalleryWidget_UE5 : public UUserWidget +{ + GENERATED_BODY() + +public: + virtual TSharedRef RebuildWidget() override; + + /** + * 构建画廊 + * @param bIncludeWidgets 文本 / 输入 / 展示 / 动态 四区 + * @param bIncludeLayouts 布局容器区 + * @param bIncludeBugs 显示性质 BUG 示例区 + */ + void BuildAll(bool bIncludeWidgets = true, bool bIncludeLayouts = true, bool bIncludeBugs = false); + + /** 按当前主题刷新背景、标题条、控制条与全部已登记控件 */ + void ApplyTheme(); + +private: + // ======================================================================= + // 分区构造 + // ======================================================================= + UPanelWidget* BuildTextSection(); + UPanelWidget* BuildInputSection(); + UPanelWidget* BuildDisplaySection(); + UPanelWidget* BuildLayoutSection(); + UPanelWidget* BuildBugSection(); + + /** 顶部固定交互控制条(滚动定位 / 主题切换) */ + UPanelWidget* BuildControlBar(); + + // ======================================================================= + // 行 / 文本 / 纹理辅助 + // ======================================================================= + + /** 分区标题(蓝底白字) */ + UWidget* MakeSectionHeader(const FText& Title); + + /** 统一示例行:左标签(统一列宽)+ 右内容(SizeBox 约束最小尺寸) */ + UWidget* MakeSizedRow(const FText& Label, UWidget* Content, const FVector2D& Size); + + /** + * BUG 示例用固定尺寸文本(SizeBox 强制宽高,允许内容绘制越界) + * @param OutTextBlock 非空时返回内部 TextBlock + */ + UWidget* MakeFixedText(const FText& Text, FName WidgetName, const FVector2D& Size, bool bWrap, float FontSize, + UTextBlock** OutTextBlock = nullptr); + + /** + * BUG 示例行:左标签 + 固定尺寸舞台(1px 描边) + * @param bBottomReference 是否在舞台下方显示参照行 + * @param StageColor 舞台底色,透明时取当前主题控制条底色 + */ + UWidget* MakeBugRow(const FText& Label, UWidget* StageContent, const FVector2D& StageSize, + bool bBottomReference = false, FLinearColor StageColor = FLinearColor::Transparent); + + /** 使用已登记文本构造 TextBlock,并按角色登记主题配色 */ + UTextBlock* MakeTextBlock(const FText& Text, FName WidgetName = NAME_None, + ELQAGalleryTextRole Role = ELQAGalleryTextRole::Primary); + + /** 按角色登记文本控件,供 ApplyTheme 统一改色 */ + void RegisterThemedText(UTextBlock* TextBlock, ELQAGalleryTextRole Role); + + /** 取当前主题的 RichText 样式表(缺失时按主题构建并缓存) */ + UDataTable* GetRichTextStyleSet(); + + /** 构造控制条按钮(对象名需唯一,避免同名对象被复用) */ + UButton* MakeControlButton(UPanelWidget* Parent, const FText& Label, FName WidgetName); + + /** 构造纯色 texture(供 Image 示例使用) */ + UTexture2D* CreateSolidTexture(int32 Size, const FColor& Color); + + // ======================================================================= + // 交互回调(供控制条按钮 AddDynamic 绑定;默认仅 SwitchPage 被使用,其余供扩展) + // ======================================================================= + UFUNCTION() + void OnSwitchPageClicked(); + + UFUNCTION() + void OnToggleExpandClicked(); + + UFUNCTION() + void OnSwitchOptionClicked(); + + UFUNCTION() + void OnToggleMenuClicked(); + + UFUNCTION() + void OnToggleCheckClicked(); + + UFUNCTION() + void OnScrollTopClicked(); + + UFUNCTION() + void OnScrollBottomClicked(); + + /** 深色 / 浅色主题切换 */ + UFUNCTION() + void OnToggleThemeClicked(); + + /** 为 ComboBoxKey 生成内容/选项控件(未绑定时引擎会显示默认缺省提示文本) */ + UFUNCTION() + UWidget* OnGenerateComboBoxKeyWidget(FName Item); + + // ======================================================================= + // 成员(动态态回调需要访问,Transient 避免被序列化) + // ======================================================================= + UPROPERTY(Transient) + UPanelWidget* RootPanel = nullptr; + + UPROPERTY(Transient) + UPanelWidget* ContentBox = nullptr; + + UPROPERTY(Transient) + UScrollBox* GalleryScroll = nullptr; + + UPROPERTY(Transient) + UWidgetSwitcher* GallerySwitcher = nullptr; + + UPROPERTY(Transient) + UExpandableArea* GalleryExpandableArea = nullptr; + + UPROPERTY(Transient) + UComboBoxString* GalleryComboBoxString = nullptr; + + UPROPERTY(Transient) + UWidget* GalleryComboBoxKey = nullptr; + + UPROPERTY(Transient) + UMenuAnchor* GalleryMenuAnchor = nullptr; + + UPROPERTY(Transient) + UCheckBox* GalleryCheckBox = nullptr; + + // ======================================================================= + // 主题 + // ======================================================================= + + /** 当前主题色板 */ + FLQAGalleryTheme Theme = FLQAGalleryTheme::Dark(); + + /** 当前是否为深色主题 */ + bool bDarkTheme = true; + + /** 当前主题下的页面背景层 */ + UPROPERTY(Transient) + UBorder* BackgroundBorder = nullptr; + + /** 顶部控制条底色容器 */ + UPROPERTY(Transient) + UBorder* ControlBarBorder = nullptr; + + /** 分区标题条(随主题换底色) */ + UPROPERTY(Transient) + TArray HeaderBorders; + + /** 页面正文文本 */ + UPROPERTY(Transient) + TArray PrimaryTexts; + + /** 行标签文本 */ + UPROPERTY(Transient) + TArray SecondaryTexts; + + /** 标题条文本 */ + UPROPERTY(Transient) + TArray OnAccentTexts; + + /** 示例面板内文本 */ + UPROPERTY(Transient) + TArray OnPanelTexts; + + /** 引擎默认浅色控件上的文本 */ + UPROPERTY(Transient) + TArray OnControlTexts; + + /** RichTextBlock 示例 */ + UPROPERTY(Transient) + URichTextBlock* GalleryRichText = nullptr; + + /** 深色主题的 RichText 样式表(运行时构建,不依赖资产) */ + UPROPERTY(Transient) + UDataTable* RichTextStyleDark = nullptr; + + /** 浅色主题的 RichText 样式表(运行时构建,不依赖资产) */ + UPROPERTY(Transient) + UDataTable* RichTextStyleLight = nullptr; + + /** EditableText 示例 */ + UPROPERTY(Transient) + UEditableText* GalleryEditableText = nullptr; + + /** MultiLineEditableText 示例 */ + UPROPERTY(Transient) + UMultiLineEditableText* GalleryMultiLineEditableText = nullptr; + + /** EditableTextBox 示例 */ + UPROPERTY(Transient) + UEditableTextBox* GalleryEditableTextBox = nullptr; + + /** MultiLineEditableTextBox 示例 */ + UPROPERTY(Transient) + UMultiLineEditableTextBox* GalleryMultiLineEditableTextBox = nullptr; + + /** SpinBox 示例 */ + UPROPERTY(Transient) + USpinBox* GallerySpinBox = nullptr; + + /** Slider 示例 */ + UPROPERTY(Transient) + USlider* GallerySlider = nullptr; + + /** ProgressBar 示例 */ + UPROPERTY(Transient) + UProgressBar* GalleryProgressBar = nullptr; + + /** CheckBox 示例集合 */ + UPROPERTY(Transient) + TArray GalleryCheckBoxes; + + /** Throbber 示例 */ + UPROPERTY(Transient) + UThrobber* GalleryThrobber = nullptr; + + /** CircularThrobber 示例 */ + UPROPERTY(Transient) + UCircularThrobber* GalleryCircularThrobber = nullptr; + + /** 列表类示例(ListView / TileView / TreeView) */ + UPROPERTY(Transient) + TArray GalleryListViews; + + /** 嵌套子 UserWidget 示例 */ + UPROPERTY(Transient) + ULQAGalleryChildWidget* GalleryChildWidget = nullptr; + + /** 标签列固定宽度:以最长标签(MultiLineEditableTextBox)为准,保证各行内容起点一致 */ + float LabelColumnWidth = 350.f; + + /** 控制条高度:滚动区避让量 */ + float ControlBarHeight = 64.f; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/LQAWidgetTypeRegistry.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/LQAWidgetTypeRegistry.h new file mode 100644 index 0000000000000000000000000000000000000000..53f9e603264b8aec91d66cb5759322c6ffb78b3c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/LQAWidgetTypeRegistry.h @@ -0,0 +1,97 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Snapshot/LQAWidgetNode.h" // ELQAWidgetType 枚举定义所在 +#include "Templates/SubclassOf.h" // TSubclassOf<> 智能类指针 + +// 前置声明: 此处只需用到 UWidget 作为类型约束的基类, 无需包含其完整定义 +class UWidget; + +/** + * 控件类型登记项 (单条映射规则) + * + * 作用: + * 描述一条 "Slate 类型名 + UMG 类约束 → LQA 控件类型枚举" 的映射规则 + * 采集端在遍历控件树时, 拿到运行时的 Slate 类型名与来源 UObject, + * 逐条比对本结构体, 命中后即可得到对应的 LQA 控件类型 + * + * 为什么需要 UMG 类约束 (WidgetClass): + * 部分 UMG 控件在 Slate 层共用同一个实现根 (例如 USizeBox / UNamedSlot / + * UNativeWidgetHost 的 Slate 根都是 SBox), 此时仅凭 Slate 名无法区分, + * 必须额外用 UMG 类做二次约束, 这类场景称为 "Slate 根类型复用", + * 每个 UMG 类各登记一条并填写 WidgetClass; 一对一 (1:1) 的类型则留空 + */ +struct FLQAWidgetTypeDesc +{ + /** + * Slate 层类型名, 即 SWidget::GetType() 的返回值 + * 例如 "SBox"、"STextBlock", 带模板参数的类型配合 bPrefixMatch 使用 + */ + FName SlateTypeName; + + /** + * UMG 类约束 + * - 为空 (nullptr): 仅按 Slate 名匹配, 用于 1:1 类型; + * - 非空: 参与精确类 / IsA 匹配, 用于区分共用 Slate 根的多个控件 + */ + TSubclassOf WidgetClass; + + /** 命中本条规则后对外返回的 LQA 控件类型枚举 (默认未定义) */ + ELQAWidgetType WidgetType = ELQAWidgetType::LQA_Undefined; + + /** + * 写入 JSON 的 UMG 侧标识 (对应 JSON 的 WidgetClass 字段) + * 仅在 "Slate 根类型复用" 时填写, 用于在导出数据中区分同根的不同控件; + * 1:1 类型无需填写, 保持 NAME_None + */ + FName WidgetClassTag; + + /** + * Slate 名是否按 "前缀" 匹配 (默认精确匹配) + * 用于带模板实参的 Slate 类型, 其运行时名字不固定, + * 例如 "SComboBox"、"SSpinBox" + * 置 true 后, 只要运行时 Slate 名以 SlateTypeName 为前缀即视为命中 + */ + bool bPrefixMatch = false; +}; + +/** + * LQA 控件类型注册表 (全局唯一登记处) + * + * 作用: + * 作为 "Slate 类型名 + UMG 类 → LQA 控件类型" 的唯一数据源, + * 供采集端在识别控件类型时统一查询, 避免映射规则散落各处 + * + * 使用规范: + * 1. 新增控件类型只需修改 GetEntries() 中的登记表, 不要再另建映射表; + * 2. "Slate 根类型复用" 的同名条目必须全部填写 WidgetClass, + * 禁止保留一条无约束的同名兜底条目 (否则会被它抢先命中); + * 3. 同一 Slate 名存在继承关系时, 依赖匹配算法 "精确类优先" 的特性保证正确性, + * 因此条目之间的书写顺序不敏感; + * 4. Slate 类型名带模板参数时 (如 SComboBox), 登记其前缀并置 + * bPrefixMatch = true + */ +class LQATOOL_API FLQAWidgetTypeRegistry +{ +public: + /** + * 获取全部登记项 + * 内部使用函数内 static 数组, 首次调用时构建一次并常驻, 后续直接复用 + * @return 登记项数组的常量引用 (只读) + */ + static const TArray& GetEntries(); + + /** + * 尝试为给定控件查找对应的类型登记项 + * + * 匹配顺序 (优先级由高到低): + * 1) 精确类匹配: SourceObject 的类与 WidgetClass 完全相等; + * 2) IsA 匹配: SourceObject 是 WidgetClass 的子类 (覆盖蓝图 WBP 子类); + * 3) 无约束条目: WidgetClass 为空, 仅按 Slate 名匹配 (1:1 类型) + * + * @param SlateTypeName Slate 层类型名 (SWidget::GetType()) + * @param SourceObject 反射元数据中的来源对象 (通常是 UWidget), 可为空 + * @return 命中的登记项指针; 未命中返回 nullptr + */ + static const FLQAWidgetTypeDesc* TryGetWidgetTypeDesc(const FName& SlateTypeName, const UObject* SourceObject); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..bcbb8e76329a269ceff0f5573be4cce9c9d8a688 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BackgroundBlurSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_BackgroundBlurSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BorderSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BorderSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..216f4c98162c9ea938dd815bcdb39b37cd791767 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_BorderSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_BorderSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ButtonSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ButtonSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..59864a5b2154c86cedc55e4575e31bba038e4622 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ButtonSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_ButtonSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..aaa1285b3332d9c6d4363bfbe357f02391e10ee2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_CanvasPanelSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_CanvasPanelSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_GridSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_GridSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..215e8b49fe6fa358f960e759522b3d7a9b59af5a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_GridSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_GridSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..d12ee2cd8c1357954d489aaed01f6eb1c02da26c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_HorizontalBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_HorizontalBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_OverlaySlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_OverlaySlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..669b5befbffd4b2c168190b964d53c83be453fb9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_OverlaySlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_OverlaySlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_PanelSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_PanelSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..26662db4343fd370e97e33da567d6aed028d2cf8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_PanelSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_PanelSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..10248cd0c148f9073f741128b852e399b2242042 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SafeZoneSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_SafeZoneSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..50bf4b9778afb04fc3d3ab1410a676569d63fafb --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScaleBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_ScaleBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..c2ce2fb263cef8c290a9455b0725d55353fd8e48 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_ScrollBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_ScrollBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..31fc3d94862618555194987b3eea353d2cbb702d --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_SizeBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_SizeBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_StackBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_StackBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..6e5d3ef93e0a95ff15246b45bf5872f1a26e7aa9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_StackBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_StackBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_UniformGridSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_UniformGridSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ba4b67cfe4e2a10f8e01d70eff22da5fc76cb16c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_UniformGridSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_UniformGridSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..016a897b5329988588b77b212d67b727bcfabbf5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_VerticalBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_VerticalBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ea94a77051cce461f9879e33e71f9a2834ac946e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WidgetSwitcherSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_WidgetSwitcherSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..f74af3390e04a50c77990f7f2eea87e957cc8a5b --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WindowTitleBarAreaSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_WindowTitleBarAreaSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..75188df44ce2a1b8cbb6d305bc88fa39309e6169 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot/LQA_WrapBoxSlot2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "JsonUtilities.h" +#include "WidgetSlots/Slot2JsonInterface.h" + +class FLQA_WrapBoxSlot2Json : public FSlot2JsonInterface +{ +public: + virtual void ToJson( + const TSharedPtr InWidget, const TSharedPtr OutJsonObject) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonFactory.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..b4afc3dfecb3ca8586bc7d0e353404f6debdb4f1 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonFactory.h @@ -0,0 +1,40 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "Snapshot/LQAWidgetNode.h" + +// 前向声明: Slot 转 Json 的接口类 +// 这里只用到了它的指针类型, 无需包含完整头文件, 可减少编译依赖 +class FSlot2JsonInterface; + +/** + * FSlot2JsonFactory —— Slot 转 Json 的工厂类 + * + * 职责: + * 根据 UI 控件节点 (FLQAWidgetNode) 所携带的 Slot 类型, + * 选择并创建对应的序列化处理器, 再把该控件的 Slot (布局槽) 数据 + * 序列化为 JSON 对象 + * + * 设计模式: 工厂模式 (Factory Pattern) + * - 将 “创建具体 Slot 处理器” 的逻辑集中在一处, + * 调用方无需关心具体类型, 只需拿到最终的 JSON 结果 + */ +class FSlot2JsonFactory +{ +public: + /** + * 将指定控件节点的 Slot 数据序列化为 JSON 对象 (对外统一入口) + * @param Widget 待序列化的控件节点 (共享指针) + * @return 序列化后的 JSON 对象; 若节点无效则返回空 JSON 对象 + */ + static TSharedPtr Slot2Json(const TSharedPtr& Widget); + +private: + /** + * 根据控件节点的 Slot 类型创建对应的序列化处理器 + * @param WidgetNode 控件节点 (共享指针) + * @return 对应类型的 Slot2Json 处理器; 若类型不支持或节点无效则返回 nullptr + */ + static TSharedPtr MakeSlotData(const TSharedPtr WidgetNode); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonInterface.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..041984d54c5ed93167c646641467dedb995069a4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Slot2JsonInterface.h @@ -0,0 +1,76 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" // UE 的 JSON 核心类型 (FJsonObject、FJsonValue 等) +#include "JsonObjectConverter.h" // 提供 JSON 与 UStruct/UObject 相互转换的工具类 +#include "Snapshot/LQAWidgetNode.h" // LQA 控件节点定义, 承载控件及其 Slot 布局信息 + +// 声明一个日志分类 LogLQAToolSlot2Json, 供本模块的 Slot 转 JSON 流程输出日志 +// 参数依次为: 日志分类名、默认日志级别(Log)、编译期允许的最高日志级别(All) +DECLARE_LOG_CATEGORY_EXTERN(LogLQAToolSlot2Json, Log, All); + +/** + * 控件 Slot 转 JSON 的接口 (抽象基类) + * + * 作用: 将控件的布局与定位信息 (即 Slot 数据) 序列化为 JSON, + * 以便做快照存储、数据传输或后续反序列化还原 + * 说明: 这是一个纯虚接口, 不同类型的 Slot (如 CanvasSlot、HorizontalBoxSlot 等) + * 应派生此类并实现各自的 ToJson 逻辑 + */ +class FSlot2JsonInterface +{ +public: + /** 默认构造函数 (使用编译器生成的默认实现) */ + FSlot2JsonInterface() = default; + + /** 虚析构函数: 保证通过基类指针删除派生对象时能正确释放资源 */ + virtual ~FSlot2JsonInterface() = default; + + /** + * 将控件的 Slot 信息转换为 JSON + * @param InWidget 包含 Slot 信息的控件节点 (输入) + * @param OutJsonObject 用于接收转换结果的目标 JSON 对象 (输出) + * 注意: 纯虚函数, 必须由派生类实现具体的序列化逻辑 + */ + virtual void ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject) = 0; + + /** + * 将 JSON 数据反序列化为指定类型的 UObject 实例 + * @tparam T 要创建的目标对象类型 (需为 UObject 派生类) + * @param InJsonData 作为数据来源的 JSON 对象 + * @param InStructData 描述目标类型字段布局的 UStruct 定义 + * @return 转换成功返回新建对象指针; 失败返回 nullptr + */ + template + T* GetAsObject(const TSharedPtr& InJsonData, const UStruct* InStructData) + { + // 先创建一个目标类型的空实例, 后续把 JSON 字段填充进去 + T* ObjIns = NewObject(); + + // 仅当 JSON 数据有效且结构定义存在时才执行转换 + if (InJsonData.IsValid() && InStructData) + { + // 转换标志位: 指定在 JSON -> UStruct 转换过程中需要一并处理的属性类别 + // - CPF_BlueprintAssignable : 可在蓝图中绑定的 (多播委托) 属性 + // - CPF_BlueprintCallable : 可在蓝图中调用的属性 + // - CPF_BlueprintAuthorityOnly : 仅在网络权威端有效的属性 + // - CPF_TextExportTransient : 文本导出时视为瞬态 (不导出) 的属性 + // - CPF_InstancedReference : 实例化引用 (子对象) 属性 + constexpr int64 ConversionFlags = CPF_BlueprintAssignable | CPF_BlueprintCallable | + CPF_BlueprintAuthorityOnly | CPF_TextExportTransient | + CPF_InstancedReference; + + // 执行实际的 JSON -> UStruct(UObject) 转换 + // 参数: 源 JSON 的共享引用、结构定义、目标对象指针、CheckFlags(0)、SkipFlags(ConversionFlags) + if (FJsonObjectConverter::JsonObjectToUStruct( + InJsonData.ToSharedRef(), InStructData, ObjIns, 0, ConversionFlags)) + { + // 转换成功, 返回填充好的对象 + return ObjIns; + } + } + + // 数据无效或转换失败, 返回空指针 + return nullptr; + } +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_BackgroundBlur2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_BackgroundBlur2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..482208a6b50ad1a8293e4087634c92d7d3b154ef --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_BackgroundBlur2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UBackgroundBlur; + +// For BackgroundBlur +class FLQA_BackgroundBlur2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Border2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Border2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..e3b4f9f74e3abd422226bc4f67f01792fd9fac15 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Border2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UBorder; + +// For Border +class FLQA_Border2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Button2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Button2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..895f4f9ead7612098d4b817c4056286a303ad3b3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Button2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UButton; + +// For Button +class FLQA_Button2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CanvasPanel2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CanvasPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..1b5a942bb750bd4f7e1d86d24273e10e90a287d3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CanvasPanel2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UCanvasPanel; + +// For CanvasPanel +class FLQA_CanvasPanel2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CheckBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CheckBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a367de703d47c9d74e0148ef3e19a89d65cb5163 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CheckBox2Json.h @@ -0,0 +1,12 @@ +#pragma once +#include "WidgetSlots/Widget2JsonInterface.h" + +class UCheckBox; + +// For CheckBox +class FLQA_CheckBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CircularThrobber2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CircularThrobber2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..3be00c8b0747c3bce10606415a3b6bd239eeb509 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_CircularThrobber2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UCircularThrobber; + +// For CircularThrobber (collects Image texture) +class FLQA_CircularThrobber2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ComboBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ComboBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..086c2dc87fd3ee957fee15b704567b70c91e754b --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ComboBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UComboBox; + +// For ComboBox +class FLQA_ComboBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..aca6a2800f3f7853571229c5d20ed7af85176fc5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_DynamicEntryBox2Json.h @@ -0,0 +1,12 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Json.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class FLQA_DynamicEntryBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBlock2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..fc6ff41c35c2a263e24bfab6a5d4622b595f8dc3 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBlock2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UEditableTextBlock; + +// For EditableTextBlock +class FLQA_EditableTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBox2json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBox2json.h new file mode 100644 index 0000000000000000000000000000000000000000..c38068275ea29592cdd7aa4ddb305b49e93641e7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_EditableTextBox2json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UEditableTextBox; + +// For EditableTextBox +class FLQA_EditableTextBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ExpandableArea2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ExpandableArea2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..aee569a56e30327ec0d7ea797713017e5d7845a9 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ExpandableArea2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For ExpandableArea +class FLQA_ExpandableArea2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_GridPanel2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_GridPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..305bdd5fb837f1c4b87b5572d4599572681debd5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_GridPanel2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UGridPanel; + +// For CanvasPanel +class FLQA_GridPanel2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_HorizontalBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_HorizontalBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..5a9e950b9b2c9e15135458e3c545c676138a4c5b --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_HorizontalBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UHorizontalBox; + +// For HorizontalBox +class FLQA_HorizontalBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Image2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Image2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..c8b665ec7c17696e4e7d31b2c00fd0f510da1182 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Image2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UImage; + +// For Image +class FLQA_Image2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InputKeySelector2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InputKeySelector2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..bbca1836afe0cc8178b3d214776b937a3441e43c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InputKeySelector2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Components/InputKeySelector.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class UInputKeySelector; + +// For InputKeySelector +class FLQA_InputKeySelector2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InvalidationBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InvalidationBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..3d810161b12733cd1b3ac03c66731861bbaa561e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_InvalidationBox2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For InvalidationBox +class FLQA_InvalidationBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ListView2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ListView2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..e3674bf153db6de12750b35c183140b7e0ddd8bf --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ListView2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For ListView +class FLQA_ListView2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MenuAnchor2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MenuAnchor2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7976f5e6d8ec598ed0bdede2845c2e678f8d80e4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MenuAnchor2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For MenuAnchor +class FLQA_MenuAnchor2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..5bec11f2328ad4bc37b2f8665184a0e00fa4b78a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBlock2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UMultilineEditableTextBlock; + +// For MultilineEditableTextBlock +class FLQA_MultilineEditableTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..de4d54f28fe36a5c8a701d7aba3fdf5a407ab793 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_MultilineEditableTextBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UMultilineEditableTextBox; + +// For MultilineEditableTextBox +class FLQA_MultilineEditableTextBox : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NamedSlot2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NamedSlot2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..3f4398d7aa303ff756d539b06385d88383d7bfb8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NamedSlot2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For NamedSlot (Slate 层根为 SBox, 类型由注册表按 UNamedSlot 判定) +class FLQA_NamedSlot2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..3ddd43e08fc4b4974a3e2019c055072b07afece4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_NativeWidgetHost2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For NativeWidgetHost (Slate 层根为 SBox, 类型由注册表按 UNativeWidgetHost 判定) +class FLQA_NativeWidgetHost2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Overlay2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Overlay2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..8b398d49223ec2073c1b0d7332a716180d1ebec5 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Overlay2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UOverlay; + +// For Overlay +class FLQA_Overlay2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..efb7a2503264124b0f78bb67b256389d1b59b133 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_PostBufferUpdate2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For PostBufferUpdate +class FLQA_PostBufferUpdate2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ProgressBar2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ProgressBar2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..8570433213685c14642fa54a90bcc681a8d17932 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ProgressBar2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UProgressBar; + +// For ProgressBar (collects FillImage texture) +class FLQA_ProgressBar2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RetainerBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RetainerBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..d009c4d78e8b2c920e51bf7d68a593b18a7ffdb4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RetainerBox2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Components/RetainerBox.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class URetainerBox; + +// For RetainerBox +class FLQA_RetainerBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RichTextBlock2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RichTextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..9c6a944cca3fa75e52b9616ddf787021a0e302a4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_RichTextBlock2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Components/RichTextBlock.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class URichTextBlock; + +// For RichTextBlock +class FLQA_RichTextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SafeZone2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SafeZone2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..4b6cda520d7013e81c669c7097ae9032ffb64408 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SafeZone2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class USafeZone; + +// For SafeZone +class FLQA_SafeZone2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScaleBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScaleBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..748b5a1a37556c62a315242d2043d5ab5b80b5d2 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScaleBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UScaleBox; + +// For ScaleBox +class FLQA_ScaleBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBar2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBar2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..12c0c16a5235d39baef78c677fe0b97ab8e58efa --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBar2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For ScrollBar +class FLQA_ScrollBar2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..fa5cf4c0b869b08c4e116edb31dfdc1598447ac7 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_ScrollBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UScrollBox; + +// For ScrollBox +class FLQA_ScrollBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SizeBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SizeBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..7774f7c84bd370e831ef8c4d87f10d9d843e3bf4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SizeBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class USizeBox; + +// For SizeBox +class FLQA_SizeBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Slider2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Slider2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..44bcc9e42ac3971283ee9262760b2e814807f9ba --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Slider2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For Slider (shell: no text/texture collection) +class FLQA_Slider2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Spacer2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Spacer2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..a8fa9822132e7bd83b7d615a94036d945f66491b --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Spacer2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For Spacer (shell: no text/texture collection) +class FLQA_Spacer2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SpinBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SpinBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..f899783e6a79bc7a7db501ae7433e7f28069d8ae --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_SpinBox2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For SpinBox (shell: no text/texture collection) +class FLQA_SpinBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_StackBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_StackBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..8ef35498eef73ec1ba7367a12d09a047dd8f9088 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_StackBox2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For StackBox +class FLQA_StackBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextBlock2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextBlock2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..174d2294615f8ba30c9d87d48bf20d85cc9f276a --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextBlock2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Components/TextBlock.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class UTextBlock; + +// For TextBlock +class FLQA_TextBlock2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextScroller2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextScroller2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..d815c5b3b76895f87a60affed77ce70f25d0ee4d --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TextScroller2Json.h @@ -0,0 +1,14 @@ +#pragma once + +#include "Components/TextBlock.h" +#include "WidgetSlots/Widget2JsonInterface.h" + +class UTextBlock; + +// For TextScroller +class FLQA_TextScroller2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Throbber2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Throbber2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..78885ae60c722742efc2a3caceff85dd37f75a76 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_Throbber2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UThrobber; + +// For Throbber (collects Image texture) +class FLQA_Throbber2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TileView2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TileView2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..db719fb17f0311b7fcf5d2367607149e076ee7b4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TileView2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For TileView +class FLQA_TileView2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TreeView2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TreeView2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..f731a27b202281518d383b7c936b8fce992a6b24 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_TreeView2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For TreeView +class FLQA_TreeView2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UniformGridPanel2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UniformGridPanel2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..2b69edd365a197e8111ca8447a1ca1203951b55c --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UniformGridPanel2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UUniformGridPanel; + +// For UniformGridPanel +class FLQA_UniformGridPanel2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UserWidget2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UserWidget2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..ea9ec6eb63d32b382702da99d3675a2389e53f35 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_UserWidget2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UUserWidget; + +// For UserWidget +class FLQA_UserWidget2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_VerticalBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_VerticalBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..9dd013e7bb90ddf082563c0ec423ff141cb85079 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_VerticalBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UVerticalBox; + +// For VerticalBox +class FLQA_VerticalBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..46ddf90944dc3dd399078fa8f22e725fe63f03c8 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WidgetSwitcher2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For WidgetSwitcher +class FLQA_WidgetSwitcher2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..2cdce31f28ac4e6fd7e8b10adbb98ece7e0f9ea4 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WindowTitleBarArea2Json.h @@ -0,0 +1,11 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +// For WindowTitleBarArea +class FLQA_WindowTitleBarArea2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WrapBox2Json.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WrapBox2Json.h new file mode 100644 index 0000000000000000000000000000000000000000..25f1188407a8b00fb97534583d31321a0ce7b107 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget/LQA_WrapBox2Json.h @@ -0,0 +1,13 @@ +#pragma once + +#include "WidgetSlots/Widget2JsonInterface.h" + +class UWrapBox; + +// For WrapBox +class FLQA_WrapBox2Json : public FWidget2JsonInterface +{ +public: + virtual void ToJson(TSharedPtr InWidget, TSharedPtr OutJsonObject, + TMap& SharedTextureMap) override; +}; diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonFactory.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..2eebd9d6bb988bdb6db6b825756f8637359d7eea --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonFactory.h @@ -0,0 +1,102 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Engine/Texture.h" +#include "Json.h" + +// UHT (虚幻头文件工具) 自动生成的反射代码, 必须作为最后一个 include +#include "Widget2JsonFactory.generated.h" + +// 前向声明: 仅用到指针/引用, 无需包含完整头文件, 可减少编译依赖、加快编译 +class FWidget2JsonInterface; // 控件 -> JSON 转换器的通用接口 +class UWidget; // UMG 控件基类 +class FLQAWidgetNode; // LQA 快照系统中的控件节点 (封装了控件及其附加信息) +class UTexture2D; // 2D 纹理 +class URestoreWindowProxy; // 还原窗口的代理对象 + +/** + * @brief 控件元数据结构体, 用于存储单个控件的核心信息 + * + * 包含控件实例、位置、尺寸以及 Z 层级 (Z-order), + * 便于正确处理控件的层级关系与布局排版 + */ +USTRUCT() +struct FWidgetMeta +{ + GENERATED_BODY() + +public: + /** 控件实例引用 (由 UPROPERTY 标记, 纳入 GC 管理, 避免被意外回收) */ + UPROPERTY() + UWidget* WidgetIns = nullptr; + + /** 控件在二维空间中的位置 (默认零向量) */ + FVector2D WidgetPos = FVector2D::ZeroVector; + + /** 控件的尺寸 (宽、高,默认零向量) */ + FVector2D WidgetSize = FVector2D::ZeroVector; + + /** Z 层级, 用于深度排序 (数值越大越靠前显示) */ + int32 ZOrder = 0; +}; + +/** + * @brief 控件转 JSON 的工厂类 + * + * 该工厂提供一系列静态方法, 用于把各种类型的控件转换为对应的 JSON 表示, + * 同时处理「已定义(支持的)」与「未定义(不支持的)」两类控件 + */ +class FWidget2JsonFactory +{ +public: + /** + * @brief 将「未定义(不支持的)」控件转换为 JSON + * @param InWidget 待转换的控件节点 + * @return 表示该未定义控件的 JSON 对象 (WidgetType 标记为 "UNDEFINE") + */ + static TSharedPtr UndefineWidget2Json(const TSharedPtr& InWidget); + + /** + * @brief 将控件转换为 JSON, 可选择是否附带对象数据 + * @param InWidget 待转换的控件节点 + * @param SharedTextureMap 共享纹理映射表, 用于复用纹理、减少冗余 (按引用传入以便回写) + * @param bNeedObjectData 是否在转换结果中包含对象数据 + * @return 表示该控件的 JSON 对象 + */ + static TSharedPtr Widget2Json(const TSharedPtr& InWidget, + TMap& SharedTextureMap, const bool bNeedObjectData); + +private: + /** + * @brief 根据控件类型创建对应的控件数据转换接口 + * @param InWidgetNode 待分析的控件节点 + * @return 指向相应控件转换器的共享指针; 若类型不支持则返回 nullptr + */ + static TSharedPtr MakeWidgetData(const TSharedPtr InWidgetNode); + + /** + * @brief 从 JSON 数据中提取控件位置 + * @param InWidgetData 源 JSON 控件数据 + * @param InWindowSize 参考窗口尺寸, 用于坐标计算/换算 + * @return 控件位置 (二维向量) + */ + static FVector2D GetWidgetPos(const TSharedPtr InWidgetData, const FVector2D& InWindowSize); + + /** + * @brief 从 JSON 数据中提取控件尺寸 + * @param InWidgetData 源 JSON 控件数据 + * @param InWindowSize 参考窗口尺寸, 用于计算 + * @param bUseAbsoluteSize 是否使用绝对尺寸 (true: 由四角点计算; false: 使用本地尺寸 LocalSize) + * @return 控件尺寸 (二维向量) + */ + static FVector2D GetWidgetSize( + const TSharedPtr InWidgetData, const FVector2D& InWindowSize, bool bUseAbsoluteSize); + + /** + * @brief 从 JSON 数据反序列化出一个坐标点, 并进行坐标系换算 + * @param InPosData 包含位置数据的 JSON 对象 + * @param InWindowSize 参考窗口尺寸, 用于坐标系换算 (Y 轴翻转) + * @return 反序列化后的坐标点 (二维向量) + */ + static FVector2D DeserializePoint(const TSharedPtr InPosData, const FVector2D& InWindowSize); +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonInterface.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..0592489ede1b9531f345a33cb21a189e71d3adca --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/Widget2JsonInterface.h @@ -0,0 +1,108 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Internationalization/TextLocalizationManager.h" // 文本本地化管理器, 用于获取命名空间/键等本地化信息 +#include "Json.h" // UE 的 JSON 基础类型 (FJsonObject 等) +#include "JsonObjectConverter.h" // JSON 与 UStruct/UObject 互转的工具类 +#include "Snapshot/LQAWidgetNode.h" // LQA 控件节点定义 (FLQAWidgetNode) +#include "WidgetDefines.h" // 公共常量定义 (如 CommonStrKey、CommonTextKey 等字段名) + +// 声明本模块专用的日志分类: LogLQAToolWidget2Json +// 用于在 Widget 转 JSON 过程中输出日志, 便于调试与问题定位 +DECLARE_LOG_CATEGORY_EXTERN(LogLQAToolWidget2Json, Log, All); + +// 前向声明: 仅在接口中以指针/引用形式使用这些类型, 无需包含完整头文件, 可降低编译依赖 +class UWidget; // UMG 控件基类 +class SWidget; // Slate 控件基类 +class FLQAWidgetNode; // LQA 控件节点 +struct FSlateColor; // Slate 颜色结构 +class UTexture; // 纹理资源 +class URestoreWindowProxy; // 窗口还原代理 + +/** + * 将控件 (Widget) 转换为 JSON 的接口基类 + * 提供文本本地化处理与对象转换等通用能力, 供各类具体控件转换器继承实现 + */ +class FWidget2JsonInterface +{ +public: + /** 默认构造函数 */ + FWidget2JsonInterface() = default; + + /** 虚析构函数, 保证通过基类指针删除派生类对象时能正确释放资源 */ + virtual ~FWidget2JsonInterface() = default; + + /** + * 将一段文本 (FText) 写入 JSON, 并附带本地化信息 (源字符串与本地化键) + * @param JsonObj 目标 JSON 对象 + * @param Text 源文本 + * @param TextEntryName 显示文本的字段名 (默认: CommonStrKey) + * @param TextKeyName 本地化键的字段名 (默认: CommonTextKey) + * @param SourceStringKeyName 源字符串的字段名 (默认: SourceStringKey) + */ + static void WriteTextEntry_ToJson(const TSharedPtr& JsonObj, const FText& Text, + const FString& TextEntryName = CommonStrKey, const FString& TextKeyName = CommonTextKey, + const FString& SourceStringKeyName = SourceStringKey); + + /** + * 收集列表控件 (ListView/TileView/TreeView) 的条目文本 + * 列表条目是运行时动态生成的 UserWidget, 其数据层 (ListItems 为 Transient) 不会随对象反射导出, + * 因此只能从已生成的条目控件树里抽取。这里剥掉 Slate 内部包装层 (SHorizontalBox/SVerticalBox/SListPanel), + * 逐条目提取第一个文本节点, 作为 ListItems 数组元素 (字段与普通文本节点一致: textStr/TextKey/SourceString)。 + * + * @param InWidget 列表控件节点 + * @param OutListItems 输出: 每个条目文本对应的 JSON 对象 + */ + static void CollectListEntryTexts( + const TSharedPtr& InWidget, TArray>& OutListItems); + + /** + * 从本地化文本中提取命名空间 (Namespace) 与键 (Key) + * @param Text 源文本 + * @param OutNamespace 输出参数: 命名空间 + * @param OutKey 输出参数: 键 + */ + static void GetTextNamespaceAndKey(const FText& Text, FString& OutNamespace, FString& OutKey); + + /** + * 将控件节点转换为 JSON (纯虚函数, 必须由派生类实现) + * @param InWidget 待转换的控件节点 + * @param OutJsonObject 输出的目标 JSON 对象 + * @param SharedTextureMap 共享纹理缓存, 用于复用已处理过的纹理, 避免重复转换 + */ + virtual void ToJson(const TSharedPtr InWidget, const TSharedPtr OutJsonObject, + TMap& SharedTextureMap) = 0; + + /** + * 将 JSON 数据反序列化为一个 UObject 实例 + * @tparam T 要创建的对象类型 + * @param JsonData 源 JSON 数据 + * @param StructData 目标类型对应的 UStruct 定义 + * @return 创建成功返回对象指针; 失败返回 nullptr + */ + template + T* GetAsObject(const TSharedPtr& JsonData, const UStruct* StructData) + { + // 入参校验: JSON 数据无效或缺少类型定义时直接返回空 + if (!JsonData.IsValid() || !StructData) + { + return nullptr; + } + + // 在临时包 (Transient Package) 中创建对象, 表示该对象不会被保存到磁盘 + T* ObjIns = NewObject(GetTransientPackage()); + + // 转换时需要跳过/特殊处理的属性标志位 (这些属性在 JSON<->UObject 转换中需被忽略) + constexpr int64 ConversionFlags = CPF_BlueprintAssignable | CPF_BlueprintCallable | CPF_BlueprintAuthorityOnly | + CPF_TextExportTransient | CPF_InstancedReference; + + // 执行 JSON -> UStruct 的填充, 成功则返回已填充的对象 + if (FJsonObjectConverter::JsonObjectToUStruct(JsonData.ToSharedRef(), StructData, ObjIns, 0, ConversionFlags)) + { + return ObjIns; + } + + // 转换失败返回空指针 + return nullptr; + } +}; \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/WidgetDefines.h b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/WidgetDefines.h new file mode 100644 index 0000000000000000000000000000000000000000..5ed0df7ef01a1c51dbebf9689223f195d7e4fc63 --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/Plugins/LQATool/Source/LQATool/Public/WidgetSlots/WidgetDefines.h @@ -0,0 +1,107 @@ +#pragma once + +#include "CoreMinimal.h" + +// 声明一个外部日志分类 LogLQAToolWidget, 供整个 LQA Widget 模块使用 +// - 第二个参数 Log: 默认的日志详细级别 (Verbosity) +// - 第三个参数 All: 编译期允许的最高日志级别 +// 真正的定义 (DEFINE_LOG_CATEGORY) 位于 WidgetDefines.cpp 中 +DECLARE_LOG_CATEGORY_EXTERN(LogLQAToolWidget, Log, All); + +// ============================================================ +// Widget 序列化时使用的通用 JSON 字段名 (Key) +// 统一在此定义, 避免在各处硬编码字符串、减少拼写错误 +// ============================================================ + +// 源字符串字段: 存放控件原始 (未翻译) 的文本内容 +static FString SourceStringKey = TEXT("SourceString"); +// 通用文本字段: 存放当前显示的文本字符串 +static FString CommonStrKey = TEXT("textStr"); +// 文本键字段: 存放本地化 Key (用于定位该文本在本地化表中的条目) +static FString CommonTextKey = TEXT("TextKey"); +// 对象数据字段: 存放控件对应的对象/节点数据块 +static FString CommonObjectKey = TEXT("ObjectData"); + +// 无效文本键常量: 当某个节点缺少有效的 TextKey 时, 使用该占位值标记为无效 +static const TCHAR* InvalidTextKey = TEXT(",INVALIDKEY"); + +// ============================================================ +// Widget 类型的 FName 常量声明 +// 说明: +// - 这些常量的实际定义位于 LQAWidgetNode.cpp 中的 LQAWidgetNames 命名空间 +// - 在此以 extern 方式声明, 使得所有翻译单元 (每个 LQA_*2Json.cpp) +// 都能引用到同一份常量, 避免重复定义导致的链接错误 +// - 使用 FName 而非字符串, 可获得更快的比较性能 (基于名字索引) +// ============================================================ +namespace LQAWidgetNames +{ +// ---- 文本类控件 ---- +extern const FName LQA_TextBlock; // 普通文本块 +extern const FName LQA_RichTextBlock; // 富文本块 (支持内嵌标记) +extern const FName LQA_EditableText; // 单行可编辑文本 +extern const FName LQA_EditableTextBox; // 带边框的单行可编辑文本框 +extern const FName LQA_MultilineEditableText; // 多行可编辑文本 +extern const FName LQA_MultilineEditableTextBox; // 带边框的多行可编辑文本框 +extern const FName LQA_TextScroller; // 滚动文本 (跑马灯) +extern const FName LQA_InputKeySelector; // 输入按键选择器 + +// ---- 下拉选择类控件 ---- +extern const FName LQA_ComboBox; // 下拉框 (通用) +extern const FName LQA_ComboBoxString; // 字符串下拉框 +extern const FName LQA_ComboBoxKey; // 按键下拉框 +extern const FName LQA_LEDRichTextBlock; // LED 风格富文本块 (自定义控件) + +// ---- 基础显示/交互控件 ---- +extern const FName LQA_Image; // 图片 +extern const FName LQA_Button; // 按钮 +extern const FName LQA_UserWidget; // 用户自定义控件 (UserWidget) + +// ---- 布局/容器类控件 ---- +extern const FName LQA_Canvas; // 画布面板 (绝对定位) +extern const FName LQA_RetainerBox; // 渲染缓存容器 +extern const FName LQA_ScrollBox; // 滚动容器 +extern const FName LQA_CommonHierarchicalScrollBox; // 分层滚动框 (CommonUI, Slate 根 SCommonHierarchicalScrollBox) +extern const FName LQA_VerticalBox; // 垂直排列容器 +extern const FName LQA_HorizontalBox; // 水平排列容器 +extern const FName LQA_ScaleBox; // 缩放容器 +extern const FName LQA_SafeZone; // 安全区容器 (适配不同屏幕边距) +extern const FName LQA_WrapBox; // 自动换行容器 +extern const FName LQA_SizeBox; // 固定尺寸容器 +extern const FName LQA_NamedSlot; // 具名插槽 +extern const FName LQA_NativeWidgetHost; // 原生 Slate 控件宿主 + +// ---- 勾选/网格类控件 ---- +extern const FName LQA_CheckBox; // 复选框 +extern const FName LQA_GridPanel; // 网格面板 +extern const FName LQA_UniformGridPanel; // 均匀网格面板 +extern const FName LQA_Overlay; // 层叠面板 (控件重叠) +extern const FName LQA_Border; // 边框容器 +extern const FName LQA_BackgroundBlur; // 背景模糊 + +// ---- 进度/加载提示类控件 ---- +extern const FName LQA_ProgressBar; // 进度条 +extern const FName LQA_Throbber; // 加载指示器 (点状) +extern const FName LQA_CircularThrobber; // 环形加载指示器 + +// ---- 数值输入类控件 ---- +extern const FName LQA_Slider; // 滑块 +extern const FName LQA_SpinBox; // 数值微调框 +extern const FName LQA_SpinBoxFloat; // 浮点数值微调框 +extern const FName LQA_Spacer; // 占位空白控件 + +// ---- 切换/特殊功能类控件 ---- +extern const FName LQA_WidgetSwitcher; // 控件切换器 (多页切换) +extern const FName LQA_StackBox; // 堆叠容器 +extern const FName LQA_WindowTitleBarArea; // 窗口标题栏区域 +extern const FName LQA_MenuAnchor; // 菜单锚点 (弹出菜单) +extern const FName LQA_InvalidationBox; // 失效缓存容器 (性能优化) +extern const FName LQA_ScrollBar; // 滚动条 +extern const FName LQA_PostBufferUpdate; // 后处理缓冲更新控件 + +// ---- 列表/视图类控件 ---- +extern const FName LQA_ObjectTableRow; // 列表行控件的 Slate 根 (按 UserWidget 采集) +extern const FName LQA_ListView; // 列表视图 +extern const FName LQA_TileView; // 平铺视图 +extern const FName LQA_TreeView; // 树状视图 +extern const FName LQA_ExpandableArea; // 可展开/折叠区域 +} \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQATool_Plugin/README.md b/timi_hok_game_translator/UE_LQATool_Plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..669a7451ff4efe07eeafa565813b678dea91115e --- /dev/null +++ b/timi_hok_game_translator/UE_LQATool_Plugin/README.md @@ -0,0 +1,397 @@ +# LQATool 插件 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +## 插件简介 + +**LQATool** 是一个运行时 Unreal Engine 插件, 面向本地化团队提供语言质量与界面布局的可视化检测能力 + +### 核心功能 + +- **Dump**: 导出控件树快照 (JSON), 包含层级、坐标尺寸、样式、文本与本地化 Key, 同时生成前景与背景截图 +- **Get Key**: 开启捕获后用鼠标右键点击界面文本, 屏幕提示该文本的内容、源字符串与本地化 Key + +> **采集端不翻译**: Dump 记录的是 **游戏当前实际显示的文本** (`textStr`) 和本地化 Key (`TextKey`), 不做任何语言转换, 译文替换发生在还原端 (LQARestore) —— 它按运行时 `-Language` / `-RestoreDirection` 查翻译表后重新渲染, 因此采集一次中文基线, 就能在还原端切换任意目标语言 + +### 使用方式 + +- 通过控制台命令 `r.EnableLQATool <0/1> [DelayInSeconds]` 启用或关闭调试面板 +- 可选参数 `DelayInSeconds` 用于设置截图与导出流程的延迟执行秒数 (默认为 0, 即立即执行) + +### 技术架构 + +- `ULQAManager` 子系统 (Game Instance Subsystem) 负责初始化调试面板 (`ULQABaseView`)、输入捕获器 (`FLQAInputProcessor`) 以及 Widget 导出功能 +- 暴露 `LQADumpViewAdvanced` 等 Blueprint 可调用接口, 便于在编辑器或运行时生成 Widget 快照 + +### 平台支持 + +- 支持 Win64、Mac、iOS、Android 平台 +- 面向非 Shipping 构建的测试场景 + +### 插件结构 + +```text +LQATool/ +├── .clang-format # UE C++ 代码风格配置 +├── LQATool.uplugin # 插件清单, 声明模块、版本、平台 +├── Resources/ # 图标与分发资源 +└── Source/LQATool/ + ├── LQATool.Build.cs # 构建脚本 + ├── Public/ + │ ├── LQABase.h # 公共宏、日志定义 + │ ├── LQAManager.h # GameInstanceSubsystem, 对外入口 + │ ├── LQAInputProcessor.h # GetKey 的右键输入捕获 + │ ├── ToolPanel/LQABaseView.h # 调试面板 (Dump / GetKey 按钮) + │ ├── Snapshot/ # Widget 树节点抽象与构建工具 + │ ├── Utils/ # 导出、JSON、贴图、通用工具 + │ ├── Validation/ # 纯 C++ 测试画廊与 LQA.BuildGallery 命令 + │ └── WidgetSlots/ + │ ├── LQAWidgetTypeRegistry.h # Slate 名 + UMG 类 → 控件类型的登记表 + │ ├── WidgetDefines.h # JSON 字段名与 Slate 类型名常量 + │ ├── Widget2JsonFactory.h # Widget 转换工厂 + │ ├── Slot2JsonFactory.h # Slot 转换工厂 + │ ├── Widget/ # 所有的控件转换实现 + │ └── Slot/ # 所有的槽转换实现 + └── Private/ # 对应 Public/ 的实现文件 (.cpp) +``` + +### 扩展说明 + +- 插件具备基础控件采集能力, 接入游戏项目中, 需要按需增加自定义控件和 Slot 类型到 `WidgetSlots` 目录下 + +--- + +## 接入插件 + +### 1. 拷贝插件到工程 + +将 `Plugins/LQATool` 整个目录复制到目标 UE 工程的 `Plugins/` 目录下 (没有则新建): + +```text +YourProject/ +├── YourProject.uproject +└── Plugins/ + └── LQATool/ + ├── LQATool.uplugin + ├── Resources/ + └── Source/ +``` + +### 2. 在 .uproject 中启用插件 + +在 `YourProject.uproject` 的 `Plugins` 数组中声明: + +```json +"Plugins": [ + { + "Name": "LQATool", + "Enabled": true + } +] +``` + +也可以在编辑器中通过 `Edit > Plugins` 搜索 `LQATool` (分类为 Testing) 勾选启用, 然后重启编辑器 + +### 3. 添加模块依赖 (C++ 调用时) + +插件模块为 `Runtime` 类型, 加载阶段 `PostConfigInit`, 会自动随游戏启动, 若需要在项目 C++ 中直接调用 `ULQAManager` 接口, 需在 `YourProject.Build.cs` 中加入模块依赖: + +```csharp +PublicDependencyModuleNames.AddRange(new string[] +{ + "Core", + "CoreUObject", + "Engine", + "LQATool" +}); +``` + +### 4. 生成工程并编译 + +右键 `.uproject` → **Generate Project Files** (Rider 中 Reload/Regenerate 亦可), 编译 `Development Editor` / `Development` 配置, 平台白名单为 `Win64 / Mac / IOS / Android`, 其他平台不会加载 + +### 5. 运行时打开调试面板 + +在 Standalone 或打包产物中按 `~` 打开控制台: + +```text +r.EnableLQATool 1 // 打开面板 +r.EnableLQATool 1 3 // 打开面板, 并让 Dump 延迟 3 秒执行 +r.EnableLQATool 0 // 关闭面板 +``` + +也可通过蓝图或 C++ 调用子系统接口: + +```cpp +#include "LQAManager.h" + +if (ULQAManager* LQAManager = ULQAManager::GetLQAManager(GetGameInstance())) +{ + LQAManager->InitAll(); // 打开面板 + LQAManager->LQADumpViewAdvanced(true, true); // 导出快照 (含贴图与 Object 元数据) +} +``` + +> PIE 模式下 `GetLQAManager` 返回空并提示 `PIE mode is not recommended, please use Standalone mode`, 调试面板请用 **Standalone** 或真机运行 + +--- + +## 测试流程 (画廊) + +插件自带一个纯 C++ 构造的测试画廊, 覆盖常用 UMG 控件与布局容器, 不依赖任何 WBP 或美术资源, 按下面步骤可以完整走通 Dump 与 GetKey + +### 1. 启动运行时 + +编辑器 **Play → Standalone Game**, 或直接运行打包产物, 按 `~` 打开控制台 + +### 2. 构造画廊 + +```text +LQA.BuildGallery // 控件区 + 布局区 +LQA.BuildGallery Widgets // 仅控件区 +LQA.BuildGallery Layout // 仅布局区 +LQA.BuildGallery Bug // 仅显示性质 BUG 示例区 +LQA.BuildGallery All // 全部: 控件区 + 布局区 + BUG 示例区 +``` + +画廊以 ZOrder 10000 添加到视口并铺满屏幕, 执行后立即可见, BUG 示例区位于画廊最下方, 标题为 `五、显示性质 BUG`, 包含 11 条故意制造的文本溢出 / 截断 / 重叠 / 不可见 / 漏 Key 用例, 用于验证 Dump 与还原对异常 UI 的识别能力 + +### 3. 打开调试面板 + +```text +r.EnableLQATool 1 +``` + +屏幕左侧中部出现 `Dump` 与 `GetKey [Off]` 两个按钮, 面板层级高于画廊, 不会被遮挡 + +### 4. 采集快照 + +点击 `Dump`, 按钮固定按 `LQADumpViewAdvanced(true, true)` 导出, 完成后在 `/Saved/LQA/` 下生成一个按时间戳命名的目录: + +```text +Saved/LQA/2026_10_18_11_23_18_LQAGalleryWidget_UE5_2147482364/ +├── LQA_Snapshot__<时间戳>.json # 控件树快照 +├── LQA_ScreenShot__<时间戳>.png # 含全部 UI (含调试面板) +├── LQA_ScreenShot__<时间戳>_BG.png # 无 UI 的纯场景图 +└── Textures/ # 仅当存在运行时生成的贴图时创建 + └── .png +``` + +`` 取自运行时控件名, 画廊为 `LQAGalleryWidget_UE5` (UE4 为 `LQAGalleryWidget_UE4`), 末尾可能带 `_<数字>` 唯一化后缀。Android 的 `Saved` 目录位于 `PersistentDownloadDir` 下, iOS 位于应用沙盒的 `Saved` 目录 + +### 5. 取文本 Key + +1. 点击 `GetKey` 按钮, 按钮变为 `GetKey [On]` +2. 用 **鼠标右键** 点击画廊中的文本 (例如标题 `LQA 验证画廊 (UE5)`) +3. 屏幕上提示 `localization: <当前文本>`, 文本有有效 Key 时同时给出源字符串与本地化 Key +4. 再次点击按钮恢复 `[Off]`, 结束捕获 + +> 捕获期间右键事件会被插件消费, 不会传给下层控件 + +### 6. 核对结果 + +| 检查项 | 期望 | +| --- | --- | +| 顶层字段 | 只有 `uitree` 与 `meta`; `uitree` 只有一个根节点, 名称以 `LQAGalleryWidget_UE5` 开头 | +| `meta.sizeX` / `sizeY` | 与截图像素尺寸一致 (本次示例为 1536 × 864) | +| 文本节点 | `textStr` 为画廊当前文本, `TextKey` 形如 `ST_Gallery,ST_Gallery_TextBlockSample`; 没有 Key 的文本为 `,INVALIDKEY` | +| 控件类型 | 画廊中的 TextBlock、Button、ListView 等都有对应 `WidgetType`, 不应出现 `UNDEFINE` | +| 截图 | 前景含画廊与调试面板, `_BG.png` 只有场景背景 | +| GetKey | 右键点击的文本, 其屏幕提示的 Key 与 JSON 中的 `TextKey` 一致 | + +### 7. 还原验证 (可选) + +将 Dump 出的 JSON 交给 LQARestore 的本地模式即可查看还原效果, 它会递归扫描 `Saved/LQA/` 下的所有 JSON 文件 + +### 8. BUG 示例区 (显示性质) + +`LQA.BuildGallery Bug` 单独构建, 每行由左标签 + 固定尺寸舞台 (1px 描边) 组成, 行间已有固定上下间距, 画廊内按 BUG-01 ~ BUG-11 顺序显示, 其中 BUG-10 与 BUG-11 相邻, 便于对照漏 Key 与漏译 + +| 编号 | 缺陷 | 判定点 | +| --- | --- | --- | +| BUG-01 | 单行文本不换行, 横向溢出舞台右边界 | 截图文本越出舞台描边 | +| BUG-02 | 换行后行数超出固定高度, 越出舞台底部 | 截图文本越出舞台描边 | +| BUG-03 | 字号 36 超过舞台高度, 字形越出底边 | `ObjectData` 中 `Font.Size=36`, 截图字形溢出 | +| BUG-04 | 按钮内文本被按钮裁剪 | `textStr` 完整, 截图按钮内只显示前半段 | +| BUG-05 | 行高压缩到 30%, 同节点内行间叠字 | `LineHeightPercentage=0.3`, 截图可判定 | +| BUG-06 | 文本与底色同色 | 节点与 `textStr` 存在, 截图对应区域无字 | +| BUG-07 | 文本被 `ClipToBounds` 硬截断 | `textStr` 完整, 截图尾部缺失 | +| BUG-08 | TileView 条目高度小于行高, 条目重叠 | 相邻条目节点 `corners` 重叠 | +| BUG-09 | TileView 条目宽度小于文本宽度, 文本跨条目溢出 | `textStr` 完整, 截图条目内只显示前半段 | +| BUG-10 | 无 Key, 直接显示原始 Key | `TextKey` 为 `,INVALIDKEY` | +| BUG-11 | 有 Key 但未登记译文 | `F2C` 下 `textStr` 为中文源文 (中文守卫); `C2F` 下查表未命中会变成 `##UnMatched` | + +> BUG-10 的文本与 BUG-11 的 Key (`ST_Gallery_Bug_MissingTranslation`) 故意不登记 `LQALocalization`, 不要补录, 否则示例失效 + +> 采集前请先滚动到画廊底部, 否则 BUG-09~11 落在视口外, 快照中的坐标为负值, 还原图会缺这几条 + +> `corners` 表示控件分配区域, 不包含文本溢出绘制范围; 溢出、压字、截断等表现以截图为准 + +--- + +## 快照 JSON 说明 + +### 顶层字段 + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `uitree` | array | 顶层控件树, 每项为一个 UserWidget 根 (调试面板已被排除) | +| `meta` | object | `version` (取自 `ProjectVersion`, 缺省 `1.0.0.0`)、`device` (`Platform=...&OSVersion=...`)、`sizeX`/`sizeY` (视口像素尺寸, 与截图一致) | + +### 节点字段 + +| 字段 | 说明 | +| --- | --- | +| `WidgetName` | 控件名; `None` 表示无命名的 Slate 内部控件 | +| `WidgetType` | 控件类型标识 (Slate 名); 未登记类型为 `UNDEFINE` | +| `WidgetClass` | 仅 Slate 根类型复用组输出, 如 `SizeBox` / `NamedSlot` / `ComboBoxString` | +| `corners` | 4 个角点, 顺序为 左下 → 左上 → 右上 → 右下, 视口像素, Y 轴向上 | +| `ViewportPos` / `LocalSize` / `BoxSize` | 视口坐标 / Slate 逻辑尺寸 (非像素) / 像素包围盒 | +| `LayerId` | 图层 id, 当前实现恒为 `0`; 未识别节点为 `-1` | +| `Slot` / `SlotType` | 已识别槽的反射属性与槽类型名 (如 `UCanvasPanelSlot`) | +| `ExcludedSlotType` | 源控件的原始槽类名 (无 `U` 前缀), 与 `SlotType` 并存, 供对照排查 | +| `ExcludedWidgetType` | 仅 `UNDEFINE` 节点输出, 为 Slate 原始类型名 | +| `NewWidgetType` | 仅 `UNDEFINE` 且控件名含 `_C_` 时输出 `SObjectWidget` | +| `ParentWidget` | 父路径, 形如 `父##子`; `ChildNodes` 为子节点数组 | +| `ObjectData` | 源 UObject 的反射属性 (`LQADumpViewAdvanced` 第 2 个参数为 true 时输出) | +| `TextureData` | 图片控件的贴图元数据: `name` / `type` / `nameMD5` | +| `textStr` / `SourceString` / `TextKey` | 当前显示文本 / 源字符串 / 本地化键 (`Namespace,Key`; 无键时 `,INVALIDKEY`) | + +### 使用时注意 + +- **单位不同** — `corners`/`BoxSize` 为视口像素, `LocalSize` 为 Slate 逻辑单位, 核对或还原时按 `meta.sizeX / 根节点.LocalSize.x` 归一化, 不要直接混用 +- **包含视口外控件** — 采集范围是 Slate 中已排列的控件树, 被裁剪或位于视口外的控件仍会输出; 无子节点的 `UNDEFINE` 节点会被丢弃 +- **列表/树控件类型名带模板参数** — 输出为 `ListViewT` / `TileViewT` / `TreeViewT`, 消费端按前缀匹配 +- **截图包含调试面板** — `Dump` / `GetKey` 会遮挡左上角; 需要干净截图时以 `_BG.png` 为底, 但它比前景晚 1.2 秒, 动态场景下两者不完全同步 +- **JSON 不含时间戳** — 同一界面连续两次 Dump 的 JSON 可以字节级一致, 截图差异来自场景动态或面板状态 + +--- + +## 扩展自定义控件与槽 + +默认只识别引擎内置的 UMG 控件与 Panel Slot: 自定义控件会以 `UNDEFINE` 导出 (若有子节点), 自定义槽会记录在 `ExcludedSlotType` 中, 按下面步骤登记即可纳入 JSON + +### 先确认类型名 + +- **控件类型名** 取自 Slate 层 `SWidget::GetType()` (如 `STextBlock`, 不是 UMG 的 `UTextBlock`) +- **槽类型名** 取自 `UPanelSlot::GetClass()->GetName()` (如 `CanvasPanelSlot`) +- **名称带模板参数** (如 `SComboBox`) 时登记前缀, 并置 `bPrefixMatch = true`; 此类控件未登记时不会以 `UNDEFINE` 出现, 而是整体消失 +- 最省事的确认方式: 先 Dump 一次, 从 `ExcludedWidgetType` / `ExcludedSlotType` 中读取真实类型名 + +### 新增采集控件 (4 步) + +以新增 `SMyText` (对应 `UMyText`) 为例: + +1. **新增枚举** — `Public/Snapshot/LQAWidgetNode.h` 的 `ELQAWidgetType` (注释 `项目自定义控件类型可在此处追加` 处): + +```cpp +LQA_MyText, +``` + +2. **登记类型** — `Private/WidgetSlots/LQAWidgetTypeRegistry.cpp` 的 `GetEntries()`: + +```cpp +{LQAWidgetNames::LQA_MyText, nullptr, ELQAWidgetType::LQA_MyText}, +``` + +Slate 名常量统一在 `WidgetDefines.h` (声明) 与 `LQAWidgetNode.cpp` (定义) 的 `LQAWidgetNames` 中补一条, 值为 Slate 类型名, 若多个 UMG 控件共用同一个 Slate 根 (如 `SBox`), 每个 UMG 类各登记一条并填 `WidgetClass` 标签, 不保留无约束的同名兜底条目: + +```cpp +{LQAWidgetNames::LQA_MyText, UMyText::StaticClass(), ELQAWidgetType::LQA_MyText, TEXT("MyText")}, +``` + +3. **实现转换类** — 复制现有的 `LQA_TextBlock2Json.h/.cpp` 为 `WidgetSlots/Widget/LQA_MyText2Json.h/.cpp`, 改类名为 `FLQA_MyText2Json`, 并在 .cpp 中 include 自定义控件头文件后实现 `ToJson`: + +```cpp +void FLQA_MyText2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject, TMap& SharedTextureMap) +{ + if (!InWidget.IsValid()) { return; } + OutJsonObject->SetStringField(TEXT("WidgetType"), LQAWidgetNames::LQA_MyText.ToString()); + + if (const UMyText* MyText = Cast(InWidget->SourceObject.Get())) + { + WriteTextEntry_ToJson(OutJsonObject, MyText->GetText()); + } +} +``` + +4. **工厂注册** — `Private/WidgetSlots/Widget2JsonFactory.cpp` 中 include 新头文件, 并在 `MakeWidgetData()` 的 switch 新增 case: + +```cpp +case ELQAWidgetType::LQA_MyText: + return MakeShareable(new FLQA_MyText2Json()); +``` + +### 新增采集槽 (5 步) + +以新增 `UMyPanelSlot` 为例: + +1. **定义类型名** — `LQAWidgetNode.cpp` 的 `LQASlotNames` 命名空间, 值为 Slot 类名: + +```cpp +const FName LQA_MySlot(TEXT("MyPanelSlot")); +``` + +2. **新增枚举** — `LQAWidgetNode.h` 的 `ELQASlotType`: + +```cpp +LQA_MySlot, +``` + +3. **注册映射** — `GetSlotType()` 的 `SlotTypeMap`: + +```cpp +{LQA_MySlot, ELQASlotType::LQA_MySlot}, +``` + +4. **实现转换类** — 在 `WidgetSlots/Slot/` 下新增 `LQA_MySlot2Json.h/.cpp`, 继承 `FSlot2JsonInterface`: + +```cpp +void FLQA_MySlot2Json::ToJson(const TSharedPtr InWidget, + const TSharedPtr OutJsonObject) +{ + if (!InWidget.IsValid() || !InWidget->SourceObject.IsValid()) { return; } + UWidget* SourceUwg = Cast(InWidget->SourceObject.Get()); + if (!SourceUwg) { return; } + + if (UMyPanelSlot* Slot = Cast(SourceUwg->Slot)) + { + TSharedPtr JsonObject = MakeShareable(new FJsonObject); + if (FLQAJsonUtils::SerializeObjectToJson(JsonObject, Slot)) + { + OutJsonObject->SetObjectField(TEXT("Slot"), JsonObject); + OutJsonObject->SetStringField(TEXT("SlotType"), TEXT("UMyPanelSlot")); + } + } +} +``` + +5. **工厂注册** — `Private/WidgetSlots/Slot2JsonFactory.cpp` 中 include 新头文件, 并在 `MakeSlotData()` 的 switch 新增 case: + +```cpp +case ELQASlotType::LQA_MySlot: + return MakeShareable(new FLQA_MySlot2Json()); +``` + +完成后重新生成工程并编译, 漏改的步骤可以这样确认: 新控件仍出现在 `ExcludedWidgetType` 中, 新槽仍出现在 `ExcludedSlotType` 中 + +--- + +## 常见问题 + +| 现象 | 原因与处理 | +| --- | --- | +| `Invalid world for r.EnableLQATool.` | 命令需在有 World 的运行时执行, 不能在编辑器未运行时使用 | +| `Failed to get ULQAManager instance.` | GameInstance 尚未创建或处于 PIE, 改用 Standalone 运行 | +| 命令或按钮无响应 | 确认插件已启用并编译成功, 通过日志分类 `LogLQATool` 过滤排查 | +| `r.EnableLQATool 1` 后看不到按钮 | 按钮位于屏幕左侧中部, 窗口过小或被其他全屏 UI 覆盖时检查布局 | +| 快照节点数与截图可见控件数不一致 | 采集包含被裁剪/视口外的控件, 无子节点的 `UNDEFINE` 节点会被丢弃; 以 `ExcludedWidgetType` / `ExcludedSlotType` 对照排查 | + +--- + +## 代码规范 + +插件根目录的 `.clang-format` 定义了 UE C++ 代码风格规范 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQAUpload_Tool/.gitignore b/timi_hok_game_translator/UE_LQAUpload_Tool/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..adbb97d2d3137fe76f2d8e88a55e1c2b285a6cd6 --- /dev/null +++ b/timi_hok_game_translator/UE_LQAUpload_Tool/.gitignore @@ -0,0 +1 @@ +data/ \ No newline at end of file diff --git a/timi_hok_game_translator/UE_LQAUpload_Tool/LQAConfig.ini b/timi_hok_game_translator/UE_LQAUpload_Tool/LQAConfig.ini new file mode 100644 index 0000000000000000000000000000000000000000..2dd069c487e6c2b054ac2cbde333575e2aa225fe --- /dev/null +++ b/timi_hok_game_translator/UE_LQAUpload_Tool/LQAConfig.ini @@ -0,0 +1,32 @@ +[server] +; LQA 平台地址 (不要带结尾斜杠) +host = http://127.0.0.1:8080/api-pro +; 鉴权 Token, 留空时将尝试 dev 自动登录 (POST /api/user/login), 适合本地开发服务器 +token = + +[project] +; 项目 ID / 任务 ID (必填) +project_id = 1 +job_id = 1 +; 模块 ID (可选, 留空则不提交) +module_id = +; 资源版本 (可选, 留空则使用 dump 内 meta.version) +resource_version = + +[data] +; 待上传数据的根目录 +root_path = ./data +; 目录扫描模式: +; recursive = 递归遍历, 自动挑选所有含有效 dump 的目录 (兼容 xxx/LQA/... 嵌套结构) +; flat = 仅遍历 root_path 下的一级子目录 +scan_mode = recursive + +[options] +; 是否要求存在背景图 *_BG.png 才算有效记录 (true/false) +require_background = false +; 是否把背景图以 hex 写入 bg_data 字段上传 (true/false) +embed_background = false +; 是否要求存在 Texture_*.png 才算有效记录 (true/false) +require_texture = false +; 单条记录上传失败时的重试次数 +retry_times = 1 diff --git a/timi_hok_game_translator/UE_LQAUpload_Tool/README.md b/timi_hok_game_translator/UE_LQAUpload_Tool/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f43968bef8891b5335e5fa025cc7a08bf82bea19 --- /dev/null +++ b/timi_hok_game_translator/UE_LQAUpload_Tool/README.md @@ -0,0 +1,87 @@ +# UE LQA Dump 数据上传工具 + +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +通用、配置驱动的 LQA UI-dump 数据上传脚本, 扫描数据目录中由 LQA 采集工具产出的 dump 记录, 将快照 JSON 规整为平台所需结构后, 通过 HTTP API 逐条上传 + +## 目录结构 + +``` +UE_LQAUpload_Tool/ +├── ue_lqa_upload_tool.py # 主脚本 +├── LQAConfig.ini # 配置模板 +└── README.md +``` + +## 一条有效 dump 记录 + +脚本把一个「子目录」视为一条记录, 目录中需至少包含: + +| 文件 | 说明 | 是否必需 | +| --- | --- | --- | +| `*.json` (`upload.json` 除外) | UI 快照数据 | 必需 | +| `LQA_ScreenShot_*.png` | 截图 | 必需 | +| `*_BG.png` | 背景图 | 可选(`require_background` 控制) | +| `Texture_*.png` | 纹理图 | 可选 (`require_texture` 控制) | + +## 平台 API 契约 + +| 方法 | 路径 | 作用 | +| --- | --- | --- | +| POST | `/api/user/login` | dev 自动登录 (无 Token 时使用) | +| POST | `/api/data/entity` | 创建数据实体, 返回 `data_id` | +| POST | `/api/upload_file` | 上传文件, 返回远端 `file_path` | +| PATCH | `/api/data/entity` | 回填截图 / module_id / resource_version | + +有 Token 时, 所有请求携带请求头 `LQA-Authorization: ` + +## JSON 规整逻辑 + +对每个快照 JSON 做如下处理 (字段存在时才转换, 缺失则跳过): +1. 将 `nan` / `inf` 等非法 token 替换为 `0`, 保证严格 JSON 可解析; +2. `meta` → `gameData`; +3. `gameData.version` → `gameData.resourceVersion`; +4. `gameData.device` → `phoneType`; +5. 写入 `name` = JSON 文件名; +6. 若开启 `embed_background` 且存在背景图, 写入 `bg_data` (hex) + +## 使用 + +### 1. 安装依赖 + +```bash +pip install requests +``` + +### 2. 修改配置 + +编辑 `LQAConfig.ini`, 至少填写 `host`、`project_id`、`job_id`、`root_path` + +### 3. 运行 + +```bash +# 使用同目录下 LQAConfig.ini +python ue_lqa_upload_tool.py + +# 指定配置文件 +python ue_lqa_upload_tool.py -c /path/to/LQAConfig.ini + +# 临时覆盖数据根目录 +python ue_lqa_upload_tool.py --root /path/to/data + +# 输出调试日志 +python ue_lqa_upload_tool.py -v +``` + +## 输出 + +上传完成后,在 `root_path` 下生成 / 合并 `upload.json`,内容为 `data_id -> 源目录` 的映射, 便于后续反查与去重 + +## 配置项说明 + +见 `LQAConfig.ini` 内注释, 关键项: +- `server.token`: 留空则走 dev 自动登录; +- `data.scan_mode`: `recursive`(默认)或 `flat`; +- `options.require_background` / `require_texture`: 控制记录有效性判定; +- `options.embed_background`: 是否把背景图内嵌进上传数据; +- `options.retry_times`: 单条失败重试次数 diff --git a/timi_hok_game_translator/UE_LQAUpload_Tool/ue_lqa_upload_tool.py b/timi_hok_game_translator/UE_LQAUpload_Tool/ue_lqa_upload_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf987163a305c7fa11e93c0d8bc14121ec57007 --- /dev/null +++ b/timi_hok_game_translator/UE_LQAUpload_Tool/ue_lqa_upload_tool.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +UE LQA Dump 数据上传工具 +========================== + +一个通用的、由配置驱动的 LQA UI-dump 数据上传工具 + +它会扫描数据目录下的 dump 记录 (由 LQA 采集工具生成, 每条记录是一个子目录, +内含一份快照 JSON + 一张截图 PNG, 可选包含背景 PNG / 贴图 PNG), +把 JSON 规范化为 LQA 平台期望的结构, 然后通过平台 HTTP API 逐条上传 + +平台 API 约定 +------------- +- POST /api/user/login 仅用于开发环境的自动登录 (未配置 token 时使用) +- POST /api/data/entity 创建数据实体, 返回 data_id +- POST /api/upload_file 上传文件, 返回远端 file_path +- PATCH /api/data/entity 关联截图 / module_id / resource_version + +鉴权方式 +------------- +- 如果配置了 token, 则每个请求都会携带 ``LQA-Authorization`` 请求头 +- 如果未配置 token, 则回退到开发环境自动登录接口 + (``POST /api/user/login``), 方便对接本地开发服务器 + +所有行为均通过 ``LQAConfig.ini`` 控制 (参见随附的示例配置) +服务器地址、凭据和本地路径都不会硬编码在代码中 +""" + +import argparse +import configparser +import glob +import json +import logging +import os +import sys + +import requests + + +# --------------------------------------------------------------------------- # +# 配置 +# --------------------------------------------------------------------------- # +class Config: + """运行时配置, 从 INI 文件加载""" + + def __init__(self, ini_path): + self.ini_path = ini_path + parser = configparser.ConfigParser() + if not parser.read(ini_path, encoding="utf-8"): + raise FileNotFoundError(f"配置文件不存在或无法读取: {ini_path}") + + # [server] + self.host = parser.get("server", "host", fallback="").strip().rstrip("/") + self.token = parser.get("server", "token", fallback="").strip() + + # [project] + self.project_id = parser.getint("project", "project_id") + self.job_id = parser.getint("project", "job_id") + module_id = parser.get("project", "module_id", fallback="").strip() + self.module_id = int(module_id) if module_id else None + resource_version = parser.get("project", "resource_version", fallback="").strip() + self.resource_version = resource_version or None + + # [data] + self.root_path = parser.get("data", "root_path").strip() + # flat = 仅遍历一级子目录 + # recursive = 遍历整棵目录树, 并挑选出所有包含 dump 的目录 + self.scan_mode = parser.get("data", "scan_mode", fallback="recursive").strip().lower() + + # [options] + self.require_background = parser.getboolean("options", "require_background", fallback=False) + self.embed_background = parser.getboolean("options", "embed_background", fallback=False) + self.require_texture = parser.getboolean("options", "require_texture", fallback=False) + self.retry_times = parser.getint("options", "retry_times", fallback=1) + + if not self.host: + raise ValueError("配置项 [server].host 不能为空") + + +# --------------------------------------------------------------------------- # +# 平台客户端 +# --------------------------------------------------------------------------- # +class LQAClient: + """LQA 平台 HTTP API 的轻量封装""" + + def __init__(self, cfg): + self.cfg = cfg + self.session = requests.Session() + self._auth_header = {"LQA-Authorization": cfg.token} if cfg.token else {} + + def login_if_needed(self): + """未配置 token 时, 尝试调用开发环境自动登录接口""" + if self.cfg.token: + logging.info("使用 Token 鉴权, 跳过登录") + return True + url = self.cfg.host + "/api/user/login" + try: + resp = self.session.post(url, timeout=30) + logging.info("dev 自动登录: HTTP %s", resp.status_code) + return resp.status_code == 200 + except requests.RequestException as exc: + logging.error("dev 自动登录失败: %s", exc) + return False + + def upload_json(self, json_content): + """创建数据实体, 返回其 data_id (失败时返回 None)""" + url = self.cfg.host + "/api/data/entity" + payload = { + "project_id": self.cfg.project_id, + "job_id": self.cfg.job_id, + "data": json_content, + } + try: + resp = self.session.post(url, headers=self._auth_header, json=payload, timeout=120) + except requests.RequestException as exc: + logging.error("upload_json 请求异常: %s", exc) + return None + if resp.status_code != 200: + logging.error("upload_json HTTP %s: %s", resp.status_code, resp.text[:200]) + return None + body = resp.json() + if body.get("code") != 0: + logging.error("upload_json 业务错误: %s", body.get("msg")) + return None + return body["data"]["data"]["id"] + + def upload_file(self, file_path): + """上传文件, 返回远端 file_path (失败时返回 None)""" + url = self.cfg.host + "/api/upload_file" + try: + with open(file_path, "rb") as fp: + resp = self.session.post( + url, headers=self._auth_header, files={"file": fp}, timeout=120 + ) + except (requests.RequestException, OSError) as exc: + logging.error("upload_file 请求异常: %s", exc) + return None + if resp.status_code != 200: + logging.error("upload_file HTTP %s: %s", resp.status_code, resp.text[:200]) + return None + body = resp.json() + if body.get("code") != 0: + logging.error("upload_file 业务错误: %s", body.get("msg")) + return None + return body["data"]["file_path"] + + def update_data(self, data_id, shot_img_path): + """为一个数据实体关联截图, 以及可选的 module_id / resource_version""" + url = self.cfg.host + "/api/data/entity" + payload = {"id": int(data_id), "shot_img_path": shot_img_path} + if self.cfg.module_id is not None: + payload["module_id"] = self.cfg.module_id + if self.cfg.resource_version is not None: + payload["resource_version"] = self.cfg.resource_version + try: + resp = self.session.patch(url, headers=self._auth_header, json=payload, timeout=60) + except requests.RequestException as exc: + logging.error("update_data 请求异常: %s", exc) + return False + if resp.status_code != 200: + logging.error("update_data HTTP %s: %s", resp.status_code, resp.text[:200]) + return False + body = resp.json() + if body.get("code") != 0: + logging.error("update_data 业务错误: %s", body.get("msg")) + return False + return True + + +# --------------------------------------------------------------------------- # +# 工具函数 +# --------------------------------------------------------------------------- # +# 会破坏严格 JSON 解析器的非有限数值 token, 统一替换为 "0" +_NAN_INF_TOKENS = ("-nan(ind)", "nan(ind)", "-nan", "nan", "-inf", "inf") + + +def sanitize_json_text(text): + """把 nan/inf token (部分 C++ 序列化器会输出) 替换为 0""" + for token in _NAN_INF_TOKENS: + text = text.replace(token, "0") + return text + + +def normalise_content(content, json_name): + """ + 把原始 dump 字典重整为 LQA 平台期望的结构 + + 所有转换都是防御式的: 仅当某个键存在时才移动/重命名它, + 因此同一份代码对包含或不包含这些字段的 dump 都适用 + """ + if "meta" in content: + content["gameData"] = content.pop("meta") + game_data = content.setdefault("gameData", {}) + if "version" in game_data: + game_data["resourceVersion"] = game_data.pop("version") + if "device" in game_data: + content["phoneType"] = game_data.pop("device") + content["name"] = json_name + return content + + +def png_to_hex(png_path): + with open(png_path, "rb") as fp: + return fp.read().hex() + + +def find_record_assets(directory, cfg): + """ + 检查一个目录, 判断它是否是有效的 dump 记录 + + 返回 (json_file, screenshot_file, background_file), 其中 background_file + 可能为 None; 若该目录不是有效记录, 则返回 (None, None, None) + """ + if not os.path.isdir(directory): + return None, None, None + + json_files = glob.glob(os.path.join(directory, "*.json")) + screenshot_files = glob.glob(os.path.join(directory, "LQA_ScreenShot_*.png")) + background_files = glob.glob(os.path.join(directory, "*_BG.png")) + texture_files = glob.glob(os.path.join(directory, "Texture_*.png")) + + # 不要把我们自己的产物 (upload.json) 当作 dump 快照 + json_files = [f for f in json_files if os.path.basename(f).lower() != "upload.json"] + + if not json_files or not screenshot_files: + return None, None, None + if cfg.require_background and not background_files: + return None, None, None + if cfg.require_texture and not texture_files: + return None, None, None + + background = background_files[0] if background_files else None + return json_files[0], screenshot_files[0], background + + +def discover_records(cfg): + """逐个产出配置根目录下所有有效的记录目录""" + root = cfg.root_path + if not os.path.isdir(root): + logging.error("数据根目录不存在: %s", root) + return [] + + candidates = [] + if cfg.scan_mode == "flat": + for entry in sorted(os.listdir(root)): + abs_path = os.path.join(root, entry) + if os.path.isdir(abs_path): + candidates.append(abs_path) + else: # recursive + for current, dirs, _files in os.walk(root): + candidates.append(current) + + records = [] + for directory in candidates: + json_file, shot_file, bg_file = find_record_assets(directory, cfg) + if json_file: + records.append((directory, json_file, shot_file, bg_file)) + + # 按创建时间排序, 保证多次运行结果稳定可复现 + records.sort(key=lambda item: os.path.getctime(item[0])) + return records + + +def process_record(client, cfg, directory, json_file, shot_file, bg_file): + """上传单条记录, 成功则返回平台 data_id, 失败返回 None""" + json_name = os.path.basename(json_file) + try: + with open(json_file, "r", encoding="utf8") as fp: + raw = sanitize_json_text(fp.read()) + content = json.loads(raw) + except (OSError, ValueError) as exc: + logging.error("读取/解析 JSON 失败 %s: %s", json_file, exc) + return None + + content = normalise_content(content, json_name) + + if cfg.embed_background and bg_file: + try: + content["bg_data"] = png_to_hex(bg_file) + except OSError as exc: + logging.warning("背景图读取失败, 跳过 bg_data %s: %s", bg_file, exc) + + for attempt in range(1, cfg.retry_times + 1): + data_id = client.upload_json(content) + if not data_id: + logging.warning("创建数据实体失败 (第 %d/%d 次): %s", attempt, cfg.retry_times, directory) + continue + remote_shot = client.upload_file(shot_file) + if not remote_shot: + logging.warning("截图上传失败 (第 %d/%d 次): %s", attempt, cfg.retry_times, directory) + continue + if client.update_data(data_id, remote_shot): + logging.info("上传成功: data_id=%s %s", data_id, directory) + return data_id + logging.warning("更新数据实体失败 (第 %d/%d 次): %s", attempt, cfg.retry_times, directory) + return None + + +# --------------------------------------------------------------------------- # +# 入口 +# --------------------------------------------------------------------------- # +def parse_args(): + parser = argparse.ArgumentParser(description="LQA UI-dump 上传工具") + default_ini = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LQAConfig.ini") + parser.add_argument("-c", "--config", default=default_ini, + help="配置文件路径 (默认: 脚本同目录的 LQAConfig.ini)") + parser.add_argument("--root", default=None, + help="覆盖配置中的数据根目录 [data].root_path") + parser.add_argument("-v", "--verbose", action="store_true", help="输出调试日志") + return parser.parse_args() + + +def main(): + args = parse_args() + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format="%(asctime)s [%(levelname)s] %(message)s", + datefmt="%H:%M:%S", + ) + + try: + cfg = Config(args.config) + except (FileNotFoundError, ValueError, configparser.Error) as exc: + logging.error("配置加载失败: %s", exc) + return 2 + + if args.root: + cfg.root_path = args.root + + logging.info("平台地址: %s", cfg.host) + logging.info("数据根目录: %s (模式: %s)", cfg.root_path, cfg.scan_mode) + + client = LQAClient(cfg) + if not client.login_if_needed(): + logging.error("鉴权失败, 终止") + return 1 + + records = discover_records(cfg) + if not records: + logging.warning("未发现任何有效的 dump 记录目录") + return 0 + logging.info("发现 %d 条待上传记录", len(records)) + + results = {} + for directory, json_file, shot_file, bg_file in records: + data_id = process_record(client, cfg, directory, json_file, shot_file, bg_file) + if data_id: + results[str(data_id)] = directory + + # 持久化 data_id -> 源目录的映射 (与已有内容合并) + out_path = os.path.join(cfg.root_path, "upload.json") + existing = {} + if os.path.exists(out_path): + try: + with open(out_path, "r", encoding="utf-8") as fp: + existing = json.load(fp) + except (OSError, ValueError): + existing = {} + existing.update(results) + try: + with open(out_path, "w", encoding="utf-8") as fp: + json.dump(existing, fp, ensure_ascii=False, indent=4) + logging.info("结果映射已写入: %s", out_path) + except OSError as exc: + logging.error("写入结果映射失败: %s", exc) + + logging.info("完成: 成功 %d / 总计 %d", len(results), len(records)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitattributes b/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..f4d6982a3e6b1dd5c9577990ae0ef92874b728c1 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitattributes @@ -0,0 +1,2 @@ +# auto generated by UGit +*.png filter=lfs diff=lfs merge=binary -text diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitignore b/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f3e98d13582841197ee3b63fb8a5e3164b9ded5d --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/.gitignore @@ -0,0 +1,4 @@ +*.meta +!Font/**/*.meta +cache/ +__pycache__/ \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorFontResolver.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorFontResolver.cs new file mode 100644 index 0000000000000000000000000000000000000000..5aa6e777b7d24438842845bda7399dadcea785d9 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorFontResolver.cs @@ -0,0 +1,169 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\EditorFontResolver.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; +using LQARestore.Core; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 编辑器环境下的字体解析器, 实现 IFontResolver + /// 职责: + /// - 把 dump JSON 中的字体引用 (fontRef) 还原为工程内真实的 Font 资源; + /// - 兼容两种采集来源: 编辑器采集 (含 assetPath/guid) 与 Android 采集 (仅剩字体名); + /// 设计要点: + /// - 三级解析顺序: 先按精确路径/guid 加载, 失败再退化为按字体名在工程内反查; + /// - 对 Unity 内置字体 (unity_builtin_extra / 全零 guid) 做特殊处理, 走 Resources.GetBuiltinResource; + /// - 按名字反查代价较高, 用实例字典缓存结果 (含未找到的 null), 避免重复扫描 AssetDatabase; + /// + public class EditorFontResolver : IFontResolver + { + // ========================================== + // 缓存 + // ========================================== + + /// + /// 字体名 -> Font 的缓存 (实例字段, 每个 resolver 独立一份) + /// 缓存中允许存 null, 用于记住 "这个名字确实找不到", 避免对同一缺失字体反复扫描工程 + /// + private readonly Dictionary _fontCache = new Dictionary(); + + // ========================================== + // 公开 API: IFontResolver 实现 + // ========================================== + + /// + /// 把字体引用解析为工程内的 Font 资源, 解析不到时返回 null (由上层回退默认字体) + /// + /// dump JSON 中的字体引用字典, 可能含 name / assetPath / guid 字段 + /// 解析到的 Font, 找不到返回 null + public Font Resolve(Dictionary fontRef) + { + if (fontRef == null) return null; + + // 1) 编辑器采集的 dump: 有 assetPath/guid, 走原精确加载 + var byPath = LoadAssetSmart(fontRef); + if (byPath != null) return byPath; + + // 2) Android 采集: assetPath/guid 均为 null, 只剩字体名, 按名字在工程内反查 + string assetName = fontRef.Get("name"); + if (string.IsNullOrEmpty(assetName)) return null; + + // 命中缓存直接返回 (含 "曾经没找到" 的 null 结果) + if (_fontCache.TryGetValue(assetName, out var cached)) return cached; + + // 未缓存则扫描工程, 无论找到与否都写回缓存 + Font found = FindFontByNameInProject(assetName); + _fontCache[assetName] = found; + + if (found == null) + Debug.LogWarning($"[LQARestore][EditorFontResolver] 工程内未找到字体 '{assetName}', 回退默认字体, 中文可能显示为方块, 请确认该字体资源存在于当前工程的 Assets 下"); + return found; + } + + // ========================================== + // 内部辅助: 按名字反查 / 精确加载 / 内置资源判定 + // ========================================== + + /// + /// 按字体名在整个工程内反查对应的 Font 资源 (用于 Android 采集只剩名字的场景) + /// + /// 字体名, 可能带扩展名 (如 "xxx.ttf") + /// 名字精确匹配的 Font, 找不到返回 null + private Font FindFontByNameInProject(string fontName) + { + // 去掉可能带的扩展名 (如 "xxx.ttf" -> "xxx") + string bare = Path.GetFileNameWithoutExtension(fontName); + if (string.IsNullOrEmpty(bare)) return null; + + // FindAssets 为模糊匹配, 需再做一次精确名校验, 避免命中相似名 (如 ...Bold) + foreach (var g in AssetDatabase.FindAssets($"t:Font {bare}")) + { + string path = AssetDatabase.GUIDToAssetPath(g); + var f = AssetDatabase.LoadAssetAtPath(path); + // 资源名或文件名任一与 bare 忽略大小写相等才算命中, 排除模糊匹配的近似项 + if (f != null && + (string.Equals(f.name, bare, StringComparison.OrdinalIgnoreCase) || + string.Equals(Path.GetFileNameWithoutExtension(path), bare, StringComparison.OrdinalIgnoreCase))) + return f; + } + return null; + } + + /// + /// 按引用中的 assetPath/guid 精确加载资源, 并对 Unity 内置资源做特殊处理 + /// + /// 要加载的资源类型 (当前仅对 Font 做了内置资源分支) + /// 资源引用字典, 含 name / assetPath / guid 字段 + /// 加载到的资源, 失败返回 null + private T LoadAssetSmart(Dictionary assetRef) where T : UnityEngine.Object + { + if (assetRef == null) return null; + + string assetName = assetRef.Get("name"); + string assetPath = assetRef.Get("assetPath"); + string guid = assetRef.Get("guid"); + + // 内置资源无法用 AssetDatabase 按路径加载, 需走 Resources.GetBuiltinResource + if (IsBuiltinResource(assetPath, guid)) + { + if (string.IsNullOrEmpty(assetName)) return null; + + if (typeof(T) == typeof(Font)) + { + // 内置字体需带 .ttf 后缀才能被 GetBuiltinResource 识别, 缺失则补上 + string fontFile = assetName.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) ? assetName : assetName + ".ttf"; + var f = Resources.GetBuiltinResource(fontFile); + if (f != null) return f as T; + return null; + } + + // 目前仅支持内置 Font, 其它内置类型不处理 + return null; + } + + // 非内置资源: 必须有路径才能加载 + if (string.IsNullOrEmpty(assetPath)) return null; + return AssetDatabase.LoadAssetAtPath(assetPath); + } + + /// + /// 判定给定引用是否指向 Unity 内置资源 + /// 依据: 路径含 "unity_builtin_extra", 或 guid 全为 0/f (内置资源的特征 guid) + /// + /// 资源路径, 可能为 null + /// 资源 guid, 可能为 null + /// 是内置资源返回 true + private bool IsBuiltinResource(string assetPath, string guid) + { + // 路径命中内置资源文件名 + if (!string.IsNullOrEmpty(assetPath) + && assetPath.IndexOf("unity_builtin_extra", StringComparison.OrdinalIgnoreCase) >= 0) + return true; + + // guid 全部由 0 / f 组成 (大小写不限) 也视为内置资源的特征 guid + if (!string.IsNullOrEmpty(guid)) + { + bool allZeroOrF = true; + for (int i = 0; i < guid.Length; i++) + { + char c = guid[i]; + if (c != '0' && c != 'f' && c != 'F') { allZeroOrF = false; break; } + } + if (allZeroOrF) return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorSceneHost.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorSceneHost.cs new file mode 100644 index 0000000000000000000000000000000000000000..22a1a12576d8ab1797f0e86cee0b62fca89f789e --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/EditorSceneHost.cs @@ -0,0 +1,227 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\EditorSceneHost.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using LQARestore.Core; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 场景宿主的编辑器实现, 实现 ISceneHost + /// 职责: + /// - 新建承载还原对象的空场景; + /// - 反射设置 Game 视图分辨率, 使预览/截图与原始画面对齐; + /// - 用临时正交相机 + RenderTexture 把当前画面截图保存为 PNG; + /// - 把场景标记为脏, 让编辑器识别到内容变化; + /// 设计要点: + /// - 把 EditorSceneManager / GameView 反射 / 相机渲染等编辑器专属操作集中在此, + /// 使核心还原流程只依赖 ISceneHost 抽象而与平台解耦; + /// - GameView 相关 API 均为内部类型, 只能通过反射访问; + /// - 分辨率设置失败仅影响预览对齐, 做容错不中断还原; 截图涉及的临时对象在 finally 中彻底清理; + /// + public class EditorSceneHost : ISceneHost + { + /// + /// 当前由本宿主新建/持有的还原场景, 供 MarkDirty 标记使用 + /// + private UnityEngine.SceneManagement.Scene _scene; + + /// + /// 新建一个空的单场景 (含默认对象) 作为还原容器, 并命名后记录到 _scene + /// + /// 新场景名称 + public void NewRestoreScene(string sceneName) + { + _scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single); + _scene.name = sceneName; + } + + /// + /// 设置 Game 视图分辨率 (ISceneHost.SetResolution 的实现) + /// 通过反射操作内部类型 UnityEditor.GameViewSizes/GameViewSize: 先查找是否已有同尺寸, + /// 没有则新增一个 FixedResolution 自定义尺寸, 最后选中它 + /// 该操作仅为改善预览对齐, 失败会被捕获并降级为警告, 不影响截图导出 + /// + /// 目标宽度 (像素), 非正数时直接忽略 + /// 目标高度 (像素), 非正数时直接忽略 + /// 新尺寸在 GameView 列表中的显示标签 + public void SetResolution(int width, int height, string label) + { + if (width <= 0 || height <= 0) return; + + try + { + // GameView 相关类型均为编辑器程序集中的内部类型, 只能反射拿取 + var editorAsm = typeof(EditorWindow).Assembly; + var sizesType = editorAsm.GetType("UnityEditor.GameViewSizes"); + var gvSizeType = editorAsm.GetType("UnityEditor.GameViewSize"); + var gvSizeTypeEnum = editorAsm.GetType("UnityEditor.GameViewSizeType"); + + // GameViewSizes 是 ScriptableSingleton, 取其单例 + var singletonType = typeof(ScriptableSingleton<>).MakeGenericType(sizesType); + var instance = singletonType + .GetProperty("instance", BindingFlags.Public | BindingFlags.Static) + .GetValue(null, null); + + // 当前分组 (随激活的 Build Target: Standalone / Android / iOS ...) + var currentGroupType = sizesType.GetProperty("currentGroupType").GetValue(instance, null); + var group = sizesType.GetMethod("GetGroup").Invoke(instance, new object[] { currentGroupType }); + var groupType = group.GetType(); + + // 预取组内操作方法: 数量 / 按索引取尺寸 / 新增自定义尺寸 + var getTotalCount = groupType.GetMethod("GetTotalCount"); + var getGameViewSize = groupType.GetMethod("GetGameViewSize"); + var addCustomSize = groupType.GetMethod("AddCustomSize"); + + var widthProp = gvSizeType.GetProperty("width"); + var heightProp = gvSizeType.GetProperty("height"); + + // 先查是否已存在同尺寸 + int index = -1; + int total = (int)getTotalCount.Invoke(group, null); + for (int i = 0; i < total; i++) + { + var size = getGameViewSize.Invoke(group, new object[] { i }); + if ((int)widthProp.GetValue(size, null) == width && + (int)heightProp.GetValue(size, null) == height) + { + index = i; + break; + } + } + + // 不存在则新增一个 FixedResolution (=1) 自定义尺寸 + if (index < 0) + { + var ctor = gvSizeType.GetConstructor( + new[] { gvSizeTypeEnum, typeof(int), typeof(int), typeof(string) }); + var fixedRes = Enum.ToObject(gvSizeTypeEnum, 1); + var newSize = ctor.Invoke(new object[] { fixedRes, width, height, label }); + addCustomSize.Invoke(group, new[] { newSize }); + // 新增后它排在列表末尾, 索引即为 总数-1 + index = (int)getTotalCount.Invoke(group, null) - 1; + } + + // 选中该尺寸 (GameView.selectedSizeIndex 为内部属性) + var gameViewType = editorAsm.GetType("UnityEditor.GameView"); + var gameView = EditorWindow.GetWindow(gameViewType); + gameViewType + .GetProperty("selectedSizeIndex", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) + .SetValue(gameView, index, null); + + Debug.Log($"[LQARestore][EditorSceneHost] 已将 Game 视图分辨率设为 {width}x{height} (index={index})"); + } + catch (Exception e) + { + // 设 Game 视图分辨率纯粹为改善预览对齐, 失败不影响 Restore.png 导出 + Debug.LogWarning($"[LQARestore][EditorSceneHost] 设置 Game 视图分辨率失败: {e.Message}"); + } + } + + /// + /// 将当前场景渲染并截图保存为 PNG (ISceneHost.CaptureToPng 的实现) + /// 流程: 建临时正交相机 → 把 ScreenSpaceOverlay 的 Canvas 临时切成 ScreenSpaceCamera + /// (Overlay 模式不进相机渲染, 切换后才能被 RT 捕获) → 强制刷新布局 → 渲染到 RT → + /// 读像素编码为 PNG 落盘; finally 中还原 Canvas 并销毁所有临时对象 + /// + /// 输出 PNG 的完整路径 + /// 渲染纹理/截图宽度 (像素) + /// 渲染纹理/截图高度 (像素) + public void CaptureToPng(string outPngPath, int width, int height) + { + GameObject camGo = null; + Camera camera = null; + RenderTexture rt = null; + Texture2D tex = null; + + // 备份被临时改成 ScreenSpaceCamera 的 Overlay Canvas, 用于还原 + var overlayBackup = new List>(); + + try + { + // 临时正交相机 + camGo = new GameObject("LQA_CaptureCam"); + camera = camGo.AddComponent(); + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.black; + camera.orthographic = true; + camera.nearClipPlane = 0.01f; + camera.farClipPlane = 100f; + + // 把所有 Overlay Canvas 临时切到 ScreenSpaceCamera, 才能被相机渲染进 RT + foreach (var c in UnityEngine.Object.FindObjectsOfType()) + { + if (!c.enabled || c.renderMode != RenderMode.ScreenSpaceOverlay) continue; + // 先记录原始渲染参数, 供 finally 还原 + overlayBackup.Add(new Tuple( + c, c.renderMode, c.worldCamera, c.planeDistance)); + c.renderMode = RenderMode.ScreenSpaceCamera; + c.worldCamera = camera; + // 强制刷新布局, 保证文本网格已生成 (编辑模式必需) + c.planeDistance = camera.nearClipPlane + 0.01f; + } + + // 强制刷新布局, 保证文本网格已生成 (编辑模式必需) + Canvas.ForceUpdateCanvases(); + + // 渲染到离屏 RenderTexture + rt = new RenderTexture(width, height, 24); + camera.targetTexture = rt; + camera.Render(); + + // 从 RT 读回像素到 Texture2D + RenderTexture.active = rt; + tex = new Texture2D(width, height, TextureFormat.RGB24, false); + tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); + tex.Apply(); + RenderTexture.active = null; + + File.WriteAllBytes(outPngPath, tex.EncodeToPNG()); + Debug.Log($"[LQARestore][EditorSceneHost] 已保存还原画面: {outPngPath}"); + } + catch (Exception e) + { + Debug.LogError($"[LQARestore][EditorSceneHost] 保存 Restore.png 失败: {e.Message}\n{e.StackTrace}"); + } + finally + { + // 还原 Overlay Canvas 的原始渲染参数 (对象可能已被销毁, 需判空) + foreach (var b in overlayBackup) + { + if (b.Item1 != null) + { + b.Item1.renderMode = b.Item2; + b.Item1.worldCamera = b.Item3; + b.Item1.planeDistance = b.Item4; + } + } + // 编辑模式下必须用 DestroyImmediate (非播放态 Destroy 不会立即生效) + if (camera != null) camera.targetTexture = null; + RenderTexture.active = null; + if (rt != null) { rt.Release(); UnityEngine.Object.DestroyImmediate(rt); } + if (tex != null) UnityEngine.Object.DestroyImmediate(tex); + if (camGo != null) UnityEngine.Object.DestroyImmediate(camGo); + } + } + + /// + /// 将当前还原场景标记为脏, 使编辑器识别到内容变更 (一般在还原完成、截图之前调用) + /// + public void MarkDirty() + { + EditorSceneManager.MarkSceneDirty(_scene); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..e20b5e09bc564614264f1b3672d406a3167e8ba1 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfig.cs @@ -0,0 +1,55 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\LqaFontVariantConfig.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 字体变体规则配置 (编辑器侧持久化) + /// 职责: 保存/读取 "还原时字体名的变体模板" (含 {name} 占位符, 如 "{name}@th") + /// 设置一次即持久化 (EditorPrefs), 供 "从 Dump 文件还原" 菜单与 "自动化流水线" 共同复用; + /// 模板为空 → 字体走 dump 原样解析 (不做变体替换); 与译文文件配置相互独立 + /// 存储: EditorPrefs, 键 LQA_Restore_FontVariantTemplate + /// + public class LqaFontVariantConfig + { + public const string KEY_FONT_VARIANT_TEMPLATE = "LQA_Restore_FontVariantTemplate"; + + /// + /// 字体变体模板 (含 {name} 占位符); 空表示未启用 → 字体按 dump 原样还原 + /// + public string FontVariantTemplate = ""; + + /// + /// 从 EditorPrefs 读取 + /// + public static LqaFontVariantConfig Load() + { + var c = new LqaFontVariantConfig(); + c.FontVariantTemplate = EditorPrefs.GetString(KEY_FONT_VARIANT_TEMPLATE, ""); + return c; + } + + /// + /// 写回 EditorPrefs + /// + public void Save() + { + EditorPrefs.SetString(KEY_FONT_VARIANT_TEMPLATE, FontVariantTemplate ?? ""); + } + + /// + /// 便捷读取: 直接拿到持久化的变体模板 (无则空串) + /// + public static string GetTemplate() + { + return EditorPrefs.GetString(KEY_FONT_VARIANT_TEMPLATE, ""); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..c18b7fe25e794d01da93881fdcf9a08109743ab7 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaFontVariantConfigWindow.cs @@ -0,0 +1,72 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\LqaFontVariantConfigWindow.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 字体变体配置窗口 (EditorWindow) + /// 设置一次即持久化 (见 LqaFontVariantConfig), 供 "从 Dump 文件还原" 与 "自动化流水线" 复用: + /// 配了含 {name} 的模板 → 还原时把字体名改写为变体 (如 {name}@th → MyGameFont@th), + /// 工程内找不到该变体时回退原字体; 留空/清除 → 字体按 dump 原样还原 + /// 纯本地配置编辑, 不涉及网络 + /// + public class LqaFontVariantConfigWindow : EditorWindow + { + private LqaFontVariantConfig _config; + + [MenuItem("Tools/LQA/还原/字体变体配置...", false, 203)] + private static void Open() + { + var win = GetWindow(false, "LQA 字体变体配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 500, 200); + win.Show(); + } + + private void OnEnable() + { + _config = LqaFontVariantConfig.Load(); + } + + private void OnGUI() + { + EditorGUILayout.LabelField("字体变体配置 (持久化)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + EditorGUILayout.BeginHorizontal(); + _config.FontVariantTemplate = EditorGUILayout.TextField( + new GUIContent("字体变体模板", + "用 {name} 代表原字体名, 如 {name}@th 会把 MyGameFont 匹配为 MyGameFont@th; 留空则字体按 dump 原样还原"), + _config.FontVariantTemplate); + if (GUILayout.Button("清除", GUILayout.Width(50))) + { + _config.FontVariantTemplate = ""; + GUIUtility.keyboardControl = 0; + } + EditorGUILayout.EndHorizontal(); + + // 当前状态提示 + string tpl = _config.FontVariantTemplate; + if (string.IsNullOrEmpty(tpl)) + EditorGUILayout.HelpBox("未配置变体模板: 字体将按 dump 原样还原", MessageType.None); + else if (!tpl.Contains(FontVariantResolver.PLACEHOLDER)) + EditorGUILayout.HelpBox("模板缺少 {name} 占位符: 该配置无效, 还原时将被忽略", MessageType.Warning); + else + EditorGUILayout.HelpBox("已配置: 还原时字体名将按模板改写, 工程内找不到变体则回退原字体", MessageType.Info); + + EditorGUILayout.Space(6); + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..dc996e3bcbebc6f1d9b7c8ab1bbcba86d70ad9bd --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfig.cs @@ -0,0 +1,55 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\LqaTranslationConfig.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 译文文件配置 (编辑器侧持久化) + /// 职责: 保存/读取 "还原时使用的 i18n_translation_xx.json (示例) 路径" + /// 设置一次即持久化 (EditorPrefs), 供 "从 Dump 文件还原" 菜单与 "自动化流水线" 共同复用; + /// 路径为空 → 还原回退到原文模式 (直接用 dump 里的 textContent) + /// 存储: EditorPrefs, 键 LQA_Restore_TranslationJsonPath + /// + public class LqaTranslationConfig + { + public const string KEY_TRANSLATION_PATH = "LQA_Restore_TranslationJsonPath"; + + /// + /// 译文文件 (i18n_translation_xx.json) 绝对路径; 空表示未配置 → 原文还原 + /// + public string TranslationJsonPath = ""; + + /// + /// 从 EditorPrefs 读取 + /// + public static LqaTranslationConfig Load() + { + var c = new LqaTranslationConfig(); + c.TranslationJsonPath = EditorPrefs.GetString(KEY_TRANSLATION_PATH, ""); + return c; + } + + /// + /// 写回 EditorPrefs + /// + public void Save() + { + EditorPrefs.SetString(KEY_TRANSLATION_PATH, TranslationJsonPath ?? ""); + } + + /// + /// 便捷读取: 直接拿到持久化的译文路径 (无则空串) + /// + public static string GetPath() + { + return EditorPrefs.GetString(KEY_TRANSLATION_PATH, ""); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed4f7387ac0fdc1caa871105e515e5adac723558 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaTranslationConfigWindow.cs @@ -0,0 +1,77 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\LqaTranslationConfigWindow.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using System.IO; +using UnityEditor; +using UnityEngine; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// 译文文件配置窗口 (EditorWindow) + /// 设置一次即持久化 (见 LqaTranslationConfig), 供 "从 Dump 文件还原" 与 "自动化流水线"复用: + /// 配了有效路径 → 按 keyHash / original 匹配译文还原; 留空/清除 → 回退原文还原 + /// 纯本地配置编辑, 不涉及网络 + /// + public class LqaTranslationConfigWindow : EditorWindow + { + private LqaTranslationConfig _config; + + [MenuItem("Tools/LQA/还原/译文文件配置...", false, 202)] + private static void Open() + { + var win = GetWindow(false, "LQA 译文文件配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 200); + win.Show(); + } + + private void OnEnable() + { + _config = LqaTranslationConfig.Load(); + } + + private void OnGUI() + { + EditorGUILayout.LabelField("译文文件配置 (持久化)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + EditorGUILayout.BeginHorizontal(); + _config.TranslationJsonPath = EditorGUILayout.TextField( + new GUIContent("译文文件", "i18n_translation_xx.json (示例) 绝对路径; 留空则用原文还原"), + _config.TranslationJsonPath); + if (GUILayout.Button("浏览...", GUILayout.Width(70))) + { + // 不设默认起始目录 + string p = EditorUtility.OpenFilePanel("选择 i18n_translation_xx.json (示例)", "", "json"); + if (!string.IsNullOrEmpty(p)) _config.TranslationJsonPath = p; + } + if (GUILayout.Button("清除", GUILayout.Width(50))) + { + _config.TranslationJsonPath = ""; + GUIUtility.keyboardControl = 0; + } + EditorGUILayout.EndHorizontal(); + + // 当前状态提示 + string path = _config.TranslationJsonPath; + if (string.IsNullOrEmpty(path)) + EditorGUILayout.HelpBox("未配置译文文件: 还原将直接使用 dump 中的原文 (textContent)", MessageType.None); + else if (!File.Exists(path)) + EditorGUILayout.HelpBox("路径不存在: 还原时会回退为原文还原", MessageType.Warning); + else + EditorGUILayout.HelpBox("已配置: 还原将按 keyHash / original 匹配译文", MessageType.Info); + + EditorGUILayout.Space(6); + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaWindowLayout.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaWindowLayout.cs new file mode 100644 index 0000000000000000000000000000000000000000..d283bb358e8d3a98706119d95257a8f46e2ce475 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Editor/LqaWindowLayout.cs @@ -0,0 +1,44 @@ +// ========================================== +// 文件: LQARestore\Core\Editor\LqaWindowLayout.cs +// 模块: Core.Editor (核心层 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; + +/// +/// LQARestore 核心层 编辑器侧命名空间 +/// +namespace LQARestore.Core.Editor +{ + /// + /// LQA 编辑器窗口布局辅助 + /// 将窗口锁定为固定尺寸 (min==max, 不可缩放), 并在主编辑器窗口内居中 + /// 每次打开 (含聚焦已存在窗口) 调用一次, 即可保证 "固定大小 + 居中" + /// + public static class LqaWindowLayout + { + /// + /// 把窗口设为固定大小并相对主编辑器窗口居中 + /// + /// 目标窗口 (GetWindow 返回的实例) + /// 固定宽度 + /// 固定高度 + public static void ApplyFixedCentered(EditorWindow win, float width, float height) + { + if (win == null) return; + + var size = new Vector2(width, height); + // 先锁定尺寸: min==max 使窗口不可缩放 + // 必须在设置 position 之前, 否则 position 的宽高会被旧的 maxSize 夹取 + win.minSize = size; + win.maxSize = size; + + // 相对主编辑器窗口 (多显示器的虚拟桌面坐标系) 居中 + Rect main = EditorGUIUtility.GetMainWindowPosition(); + float x = main.x + (main.width - width) * 0.5f; + float y = main.y + (main.height - height) * 0.5f; + win.position = new Rect(x, y, width, height); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/FontVariantResolver.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/FontVariantResolver.cs new file mode 100644 index 0000000000000000000000000000000000000000..d34773054a2f1e1ff74d70eabcecfb183dd31ce9 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/FontVariantResolver.cs @@ -0,0 +1,87 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\FontVariantResolver.cs +// 模块: Core (核心层) +// ========================================== + +using System.Collections.Generic; +using UnityEngine; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 语言变体字体解析装饰器 (装饰 IFontResolver): + /// 用用户配置的模板 (含 {name} 占位符) 把字体名改写为变体名后再解析, + /// 如模板 "{name}@th" 会把 MyGameFont → MyGameFont@th + /// 设计要点: + /// - 只改写字体名并清空 assetPath/guid, 强制走内层的 "按名反查" 分支; + /// 原因: 不同语言字体扩展名可能不同 (中文 .otf / 泰语 .ttf), 且 dump 里的 guid 指向原字体, + /// 若不清空会命中原字体, 达不到变体替换目的; + /// - 逐级回退, 保证文本始终可渲染, 且 "匹配不到即等于当前逻辑": + /// 模板为空 / 不含 {name} / 改写后与原名相同 / 变体在工程查不到 → 均回退原始 fontRef; + /// + public class FontVariantResolver : IFontResolver + { + /// + /// 模板占位符: 代表原始字体名, 会被替换为 dump 中记录的字体名 + /// + public const string PLACEHOLDER = "{name}"; + + /// + /// 被装饰的内层解析器 (通常是 EditorFontResolver), 真正的字体加载委托给它 + /// + private readonly IFontResolver _inner; + + /// + /// 变体模板, 含 {name} 占位符, 如 "{name}@th"; 为空/无占位符时本装饰器不介入 + /// + private readonly string _template; + + /// + /// 构造装饰器 + /// + /// 被装饰的内层字体解析器, 不可为 null 才有意义 + /// 含 {name} 占位符的变体模板, 如 "{name}@th" + public FontVariantResolver(IFontResolver inner, string template) + { + _inner = inner; + _template = template; + } + + /// + /// 按变体模板改写字体名后解析; 任一环节不满足条件即回退到原始字体引用 + /// + /// dump 中的字体引用字典 (含 name / assetPath / guid) + /// 解析到的变体字体; 变体不可用时回退内层对原始引用的解析结果 + public Font Resolve(Dictionary fontRef) + { + if (_inner == null) return null; + + // 模板无效 (空 / 不含占位符) 或无字体引用 → 完全直通, 等价于未启用变体 + if (fontRef == null || string.IsNullOrEmpty(_template) + || _template.IndexOf(PLACEHOLDER, System.StringComparison.Ordinal) < 0) + return _inner.Resolve(fontRef); + + string name = fontRef.Get("name"); + if (string.IsNullOrEmpty(name)) return _inner.Resolve(fontRef); + + // 按模板生成变体名 + string variantName = _template.Replace(PLACEHOLDER, name); + + // 改写后与原名相同 (理论上不会发生, 防御性处理) → 直通 + if (string.Equals(variantName, name, System.StringComparison.Ordinal)) + return _inner.Resolve(fontRef); + + // 只携带 name (丢弃 assetPath/guid), 强制内层按名在工程内反查变体字体 + var variantRef = new Dictionary { { "name", variantName } }; + var variant = _inner.Resolve(variantRef); + if (variant != null) return variant; + + // 变体缺失 → 回退原始字体引用 (即当前逻辑), 保证文本仍可渲染 + return _inner.Resolve(fontRef); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/IFontResolver.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/IFontResolver.cs new file mode 100644 index 0000000000000000000000000000000000000000..04f1319369d28b9c972527d76748f21c8e8528bc --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/IFontResolver.cs @@ -0,0 +1,46 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\IFontResolver.cs +// 模块: Core (核心层) +// ========================================== + +using System.Collections.Generic; +using UnityEngine; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 字体解析抽象: 把 dump 数据里的 "字体引用信息" 转换成一个可用于渲染的 Font 实例 + /// 为什么要抽象成接口: + /// 字体的查找方式与运行环境强相关, 而还原流程 (TextNodeBuilder等) 不应关心这些差异 + /// 通过接口把 "如何找到字体" 与 "如何使用字体" 解耦: + /// - Editor 环境: 由 EditorFontResolver 实现, 依赖 AssetDatabase, + /// 既可按 assetPath/guid 精确加载, 也可在 assetPath/guid 缺失时按字体名在工程内反查 + /// - 将来若需要 Runtime (真机运行时无 AssetDatabase) 版本: 可另写实现, + /// 改走 Resources / Addressables 等运行期可用的加载方式 + /// + public interface IFontResolver + { + /// + /// 根据 dump 中的字体引用信息解析出对应的 Font + /// + /// + /// dump 里的 "font" 字典, 通常包含以下键 (均可能缺失): + /// - "name" —— 字体名 (如 "Arial" 或 "xxx.ttf"); + /// - "assetPath" —— 工程内资源路径, 用于精确加载; + /// - "guid" —— 资源 GUID + /// 说明: Editor 采集的 dump 一般带有 assetPath/guid, 可精确定位; + /// Android 真机采集时因无 AssetDatabase,assetPath/guid 均为 null, + /// 此时只能依赖 "name" 在工程内按名反查 + /// 整个字典本身也可能为 null (例如 dump 未记录字体信息) + /// + /// + /// 解析成功返回对应的 Font + /// 当 fontRef 为 null、信息不足或工程内查无此字体时返回 null + /// 调用方需自行处理 null (通常回退到内置默认字体, 注意中文可能显示为方块) + /// + Font Resolve(Dictionary fontRef); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ISceneHost.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ISceneHost.cs new file mode 100644 index 0000000000000000000000000000000000000000..6975f8d015f4fcc23bc6c7bc8a01fec662647c1b --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ISceneHost.cs @@ -0,0 +1,58 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\ISceneHost.cs +// 模块: Core (核心层) +// ========================================== + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 场景宿主抽象: 负责与 Unity 场景/相机/GameView 交互的一组底层能力, + /// 包括: 新建场景 / 设置分辨率 / 截图 / 标记场景为脏 + /// 设计目的: 将平台相关操作 (EditorSceneManager、GameView 反射、相机渲染等) + /// 与核心还原流程解耦, 核心逻辑只依赖此接口而不依赖具体实现 + /// 默认 Editor 实现 (EditorSceneHost) 采用 EditorSceneManager 建场景、 + /// 反射 UnityEditor.GameView 设置分辨率、临时正交相机 + RenderTexture 截图 + /// + public interface ISceneHost + { + /// + /// 新建一个用于文本还原的空场景, 并命名 + /// 调用后当前场景会被替换为这个干净场景, 作为后续还原对象的承载容器 + /// + /// 新场景的名称, 例如 "LQA_Restore_Scene" + void NewRestoreScene(string sceneName); + + /// + /// 设置 Game 视图 (预览) 的分辨率 + /// 通常传入 dump 中记录的原始屏幕宽高, 使还原预览与截图对齐原始画面 + /// 说明: 该操作仅用于改善预览/截图的对齐效果; 即便设置失败也不应中断 + /// 整个还原流程 (实现中应对失败做容错处理) + /// + /// 目标分辨率宽度 (像素), 应为正数, 否则实现可忽略 + /// 目标分辨率高度 (像素), 应为正数, 否则实现可忽略 + /// 该分辨率在 GameView 尺寸列表中的显示标签, 例如 "LQA_Restore" + void SetResolution(int width, int height, string label); + + /// + /// 将当前场景画面渲染并截图保存为 PNG 文件 + /// 用于产出还原结果图 (Restore.png) 以便与原始 dump 画面对比 + /// 实现要点 (以 EditorSceneHost 为例): 使用临时正交相机 + RenderTexture 渲染, + /// 并将 ScreenSpaceOverlay 的 Canvas 临时切换为 ScreenSpaceCamera 以便被相机捕获, + /// 截图完成后需还原这些临时改动 + /// + /// 输出 PNG 文件的完整路径,例如 dumpDir/Restore.png。 + /// 截图/渲染纹理的宽度 (像素)。 + /// 截图/渲染纹理的高度 (像素)。 + void CaptureToPng(string outPngPath, int width, int height); + + /// + /// 将当前场景标记为 "脏" (已修改) + /// 使 Unity 编辑器识别到场景内容发生变化, 从而允许保存等操作 + /// 一般在完成对象还原之后、截图之前调用 + /// + void MarkDirty(); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/DictExt.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/DictExt.cs new file mode 100644 index 0000000000000000000000000000000000000000..eda2f01ef0d25f1b0a3fefc9e5d14efd2a7426bf --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/DictExt.cs @@ -0,0 +1,118 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\Json\DictExt.cs +// 模块: Core.Json (核心层 JSON 数据读写) +// ========================================== + +using System; +using System.Collections.Generic; + +/// +/// LQARestore 核心层 JSON 数据读写命名空间 +/// +namespace LQARestore.Core.Json +{ + /// + /// Dictionary 的取值扩展方法集 + /// 用途: JSON 反序列化后通常得到 Dictionary 这种松散结构, + /// 其值类型是 object (可能是 string / long / double / bool 等), + /// 直接强转易出错, 本类提供一组带默认值、带类型转换、带判空保护的安全取值方法, + /// 避免调用处到处写重复的判空与 try-catch + /// 特点: 全部为无状态纯函数, 故声明为 static 扩展方法; + /// 任何异常/缺键/空值场景都会回退到默认值, 不抛出异常 + /// + public static class DictExt + { + /// + /// 按键取出引用类型的值, 并以指定类型 T 返回 + /// + /// 期望的引用类型 (约束为 class) + /// 源字典, 允许为 null + /// 要读取的键 + /// + /// 命中且能转为 T 时返回该对象; + /// 字典为 null、键不存在、值为 null 或类型不匹配时返回 null + /// + public static T Get(this Dictionary dict, string key) where T : class + { + // 判空保护: 字典为空 / 键不存在 / 值为 null, 任一成立即返回 null + if (dict == null || !dict.TryGetValue(key, out var v) || v == null) return null; + // 使用 as 做安全转换, 类型不匹配时返回 null 而非抛异常 + return v as T; + } + + /// + /// 按键取出字符串值 + /// + /// 源字典, 允许为 null + /// 要读取的键 + /// 取不到时的默认值, 默认空字符串 + /// + /// 值本身是字符串则直接返回; + /// 值为其它类型则调用其 ToString() 转换后返回; + /// 缺键或值为 null 时返回 def + /// + public static string GetInnerString(this Dictionary dict, string key, string def = "") + { + // 判空保护, 命中失败直接回退默认值 + if (dict == null || !dict.TryGetValue(key, out var v) || v == null) return def; + // 已经是字符串则免去 ToString 开销直接返回 + if (v is string s) return s; + // 其它类型 (数字/布尔等) 统一转成字符串 + return v.ToString(); + } + + /// + /// 按键取出 int 值 + /// + /// 源字典, 允许为 null + /// 要读取的键 + /// 取不到或转换失败时的默认值, 默认 0 + /// 成功转换的 int, 否则返回 def + public static int GetInnerInt(this Dictionary dict, string key, int def = 0) + { + // 判空保护, 命中失败直接回退默认值 + if (dict == null || !dict.TryGetValue(key, out var v) || v == null) return def; + // JSON 数字反序列化后类型不确定 (可能是 long/double/string), + // 用 Convert 统一转换; 指定 InvariantCulture 避免不同区域设置下的解析差异; + // 转换失败 (如非数字字符串) 时吞掉异常并回退默认值 + try { return Convert.ToInt32(v, System.Globalization.CultureInfo.InvariantCulture); } catch { return def; } + } + + /// + /// 按键取出 float 值 + /// + /// 源字典, 允许为 null + /// 要读取的键 + /// 取不到或转换失败时的默认值, 默认 0f + /// 成功转换的 float, 否则返回 def + public static float GetInnerFloat(this Dictionary dict, string key, float def = 0f) + { + // 判空保护, 命中失败直接回退默认值 + if (dict == null || !dict.TryGetValue(key, out var v) || v == null) return def; + // 同 GetInnerInt: 统一用 Convert + InvariantCulture 转换, + // 避免小数点在某些区域被解析为逗号等问题; 失败则回退默认值 + try { return Convert.ToSingle(v, System.Globalization.CultureInfo.InvariantCulture); } catch { return def; } + } + + /// + /// 按键取出 bool 值 + /// + /// 源字典, 允许为 null + /// 要读取的键 + /// 取不到或解析失败时的默认值, 默认 false + /// + /// 值本身是 bool 则直接返回; + /// 否则尝试按字符串解析 ("true"/"false"); + /// 解析失败或缺键时返回 def + /// + public static bool GetInnerBool(this Dictionary dict, string key, bool def = false) + { + // 判空保护, 命中失败直接回退默认值 + if (dict == null || !dict.TryGetValue(key, out var v) || v == null) return def; + // 已经是布尔值则直接返回 + if (v is bool b) return b; + // 其它类型转成字符串后尝试解析, 解析成功用结果, 失败回退默认值 + return bool.TryParse(v.ToString(), out var r) ? r : def; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/JsonWriter.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/JsonWriter.cs new file mode 100644 index 0000000000000000000000000000000000000000..9770309a133698303b0f92740a4989521f94fde1 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/JsonWriter.cs @@ -0,0 +1,423 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\Json\JsonWriter.cs +// 模块: Core.Json (核心层 JSON 数据读写) +// ========================================== + +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +/// +/// LQARestore 核心层 JSON 数据读写命名空间 +/// +namespace LQARestore.Core.Json +{ + /// + /// 极简 JSON 序列化器 (与 MiniJson 对称: MiniJson 只解析, 本类只写出) + /// 用途: 把 MiniJson.Parse 得到的对象树 (Dictionary / List / string / bool / double / null) + /// 重新序列化为 JSON 文本, 供 "文本人工显示" 窗口把 manualShow 标记写回磁盘 + /// 为什么需要单独写一个: MiniJson 只负责解析没有序列化能力; 而通用 JSON 库的输出 + /// (缩进风格 / 数字格式 / 键顺序) 与采集侧 LQATool.Utils.JsonBuilder 生成的原始文件不一致, + /// 回写后会与原文件产生大量无意义的 diff, 故这里刻意 "复刻" 采集侧的排版与数字模板 + /// 排版规则 (复刻采集侧 JsonBuilder 的固定模板, 保证回写前后风格一致): + /// 采集侧并非按数据结构递归决定换行, 而是只有固定的 "结构骨架" 层级才多行展开: + /// 根对象 / nodes[] / 每个节点对象 / ObjectData / 组件块 / ChildNodes[] + /// 这些骨架之外的一切 (组件块内部的属性值, 无论标量还是对象/数组) 一律单行内联, + /// 例如 color / font / localEulerAngles / safeArea / activeLayerNames / visibilityDebug 等 + /// 另外: 骨架层级的空容器 (如空 ChildNodes / 空 ObjectData) 仍换行为 "[\n]" / "{\n}", + /// 而内联层级的空容器保持紧凑 "[]" / "{}" + /// 数字格式 (复刻采集侧不同字段的固定小数位, 见 _fmtByKey / ResolveInnerFmt): + /// MiniJson 把所有 JSON 数字统一解析为 double, 丢失了采集侧写入时的小数位模板 + /// (采集侧对不同字段分别用了 F3 / F2 / 原生), 故这里按 "字段键名" 反查模板还原, + /// 使浮点数文本 (如 1.000 / 1.00 / 1920) 与原始文件一致 + /// 值格式约定 (与采集侧一致): + /// - 缩进单位 2 空格; 键值分隔 "key": value (冒号后一个空格); + /// - 字符串转义 \ " \n \r \t 五类, 其余字符 (含中文) 原样输出; + /// - bool: true / false; null: null + /// 实现方式: 递归下降写出, 用 Level 参数标识当前所处骨架层级以决定 "展开 or 内联", + /// 用 NumFmt 参数沿内联子树向下传递数字小数位模板 + /// + public static class JsonWriter + { + // ========================================== + // 骨架键常量: 决定多行展开时机的固定键名 (与采集侧的树结构约定一一对应) + // ========================================== + + /// + /// 根对象下需要展开的节点数组键 + /// + private const string KEY_NODES = "nodes"; + + /// + /// 节点对象下需要展开的组件容器键 (其子对象为各组件块) + /// + private const string KEY_OBJECT_DATA = "ObjectData"; + + /// + /// 节点对象下需要展开的子节点数组键 + /// + private const string KEY_CHILD_NODES = "ChildNodes"; + + /// + /// 骨架层级枚举: 标识当前正在写出的对象处于树的哪一层, 用于决定其子值是否继续展开 + /// (只有骨架层级会多行展开, Inline 层级及更深一律单行内联) + /// + private enum Level + { + Root, // 根对象: 仅 nodes 展开 + Node, // 节点对象: 仅 ObjectData / ChildNodes 展开 + ObjectData, // ObjectData: 其下各组件块全部展开 + Inline // 其它: 一律内联 (组件块内部及更深) + } + + /// + /// 数字格式模式: 对应采集侧不同字段所用的固定小数位 + /// + private enum NumFmt + { + Raw, // InvariantCulture 原生: 整数不带小数点, 小数保留原值 (localScale / 坐标 / 各整型字段等) + F2, // 保留 2 位小数 (lineSpacing) + F3 // 保留 3 位小数 (color / safeArea / screenDpi / ratio 等) + } + + /// + /// "属性键名 -> 该属性数字的小数位模板" 映射, 复刻采集侧 JsonBuilder / ComponentExtractors 的格式 + /// 说明: + /// - color / outlineColor / shadowColor / safeArea 等本身是 "内联对象", 其模板作用于该对象内部的 + /// 所有数字子值 (故这里登记的是 "父键", 由 WriteInline 沿子树继承); + /// - screenDpi / lineSpacing 等 "标量数字字段" 直接以自身键名登记; + /// - 未登记的键一律走 Raw (覆盖整型字段与 localScale 等原生浮点) + /// + private static readonly Dictionary _fmtByKey = new Dictionary + { + // F3 标量字段 + { "screenDpi", NumFmt.F3 }, + { "referencePixelsPerUnit", NumFmt.F3 }, + { "matchWidthOrHeight", NumFmt.F3 }, + // F3 内联对象 (模板作用于其内部所有数字) + { "safeArea", NumFmt.F3 }, + { "color", NumFmt.F3 }, + { "outlineColor", NumFmt.F3 }, + { "shadowColor", NumFmt.F3 }, + // F2 标量字段 + { "lineSpacing", NumFmt.F2 }, + }; + + /// + /// visibilityDebug 是 "混合模板" 的内联对象: 其内部只有 ratio / ratioThreshold 两键用 F3, + /// 其余 (id / maskTotal / diffCount / aabb ...) 用 Raw, 故单独用此集合识别需 F3 的子键 + /// + private static readonly HashSet _visDebugF3 = new HashSet { "ratio", "ratioThreshold" }; + + /// + /// 序列化入口: 把对象树转换为 JSON 文本 + /// + /// 对象树 (根通常为 Dictionary, 由 MiniJson.Parse 产生) + /// 格式化后的 JSON 字符串 + public static string Serialize(object value) + { + var sb = new StringBuilder(); + // 根为对象则按 Root 骨架层级展开; 否则 (极少见) 直接内联写出, 保证鲁棒 + if (value is Dictionary root) + WriteObject(sb, root, 0, Level.Root); + else + WriteInline(sb, value); + return sb.ToString(); + } + + /// + /// 单行内联序列化: 把对象树压成紧凑单行 JSON (对象/数组递归内联) + /// 供调用方自行控制外层换行缩进时, 对 "叶子对象" 做内联序列化 (如 rect_locations 的每个文本框) + /// 复用与 Serialize 相同的字符串转义与数字格式化规则 + /// + /// 对象树 (Dictionary / List / string / bool / double / null) + /// 单行紧凑 JSON 字符串 + public static string SerializeInline(object value) + { + var sb = new StringBuilder(); + WriteInline(sb, value); + return sb.ToString(); + } + + /// + /// 写出一个对象: 依据 level 决定多行展开还是单行内联 + /// + /// 共享的字符串构建器 + /// 待写出的对象 + /// 当前缩进层级 (每级 2 空格) + /// 当前骨架层级, 决定本对象与其子值的展开策略 + private static void WriteObject(StringBuilder sb, Dictionary dict, int indentLevel, Level level) + { + // 仅 Inline 层级单行输出; 骨架层级 (Root/Node/ObjectData) 即使为空也换行展开, + // 以与采集侧 JsonBuilder 的固定模板一致 (如空 ObjectData 输出为 "{\n}") + if (level == Level.Inline) + { + WriteInline(sb, dict); + return; + } + + // 子项缩进 (深一级) 与闭合括号缩进 (本级) + string childIndent = new string(' ', (indentLevel + 1) * 2); + string closeIndent = new string(' ', indentLevel * 2); + + sb.Append("{\n"); + int i = 0; + foreach (var kvp in dict) + { + // 输出 "key": 再由 WriteChild 依据 "父层级 + 键名" 决定其值如何写 + sb.Append(childIndent).Append('"').Append(Escape(kvp.Key)).Append("\": "); + WriteChild(sb, kvp.Key, kvp.Value, indentLevel + 1, level); + // 非最后一项补逗号, 规避非法尾逗号 + if (i < dict.Count - 1) sb.Append(','); + sb.Append('\n'); + i++; + } + sb.Append(closeIndent).Append('}'); + } + + /// + /// 写出对象的某个子值: 依据 "父层级 + 键名" 判定该子值应展开 (骨架) 还是内联, 并分派到对应写法 + /// + /// 共享的字符串构建器 + /// 子值对应的键名 + /// 子值本身 + /// 子值所在的缩进层级 + /// 父对象的骨架层级 + private static void WriteChild(StringBuilder sb, string key, object value, int indentLevel, Level parentLevel) + { + // 依据 "父层级 + 键名" 推断子值的目标骨架层级 (缺省 Inline: 即不展开) + Level childLevel = Level.Inline; + switch (parentLevel) + { + case Level.Root: + // 根对象下只有 nodes 展开 (其元素为节点对象) + if (key == KEY_NODES) childLevel = Level.Node; + break; + case Level.Node: + // 节点对象下: ObjectData 展开为组件块容器, ChildNodes 展开为节点数组 + if (key == KEY_OBJECT_DATA) childLevel = Level.ObjectData; + else if (key == KEY_CHILD_NODES) childLevel = Level.Node; + break; + case Level.ObjectData: + // ObjectData 下的每个键都是组件块 (由下方 Dict 分支单独处理为组件块写法) + childLevel = Level.Inline; + break; + } + + if (value is Dictionary childDict) + { + if (parentLevel == Level.ObjectData) + // ObjectData 的直接子对象即 "组件块": 自身多行展开, 但内部属性一律内联 + WriteComponentBlock(sb, childDict, indentLevel); + else if (childLevel == Level.Inline) + // 内联对象 (如 safeArea): 按父键模板单行内联写出 + WriteInline(sb, childDict, ResolveFmt(key, NumFmt.Raw)); + else + // 骨架对象 (如 ObjectData 容器本身) + WriteObject(sb, childDict, indentLevel, childLevel); + } + else if (value is List childList) + { + // 只有 nodes / ChildNodes 是需要展开的 "节点数组", 其余数组内联 (如 activeLayerNames) + if (childLevel == Level.Node) + WriteNodeArray(sb, childList, indentLevel); + else + WriteInline(sb, childList, ResolveFmt(key, NumFmt.Raw)); + } + else + { + // 标量 (string / bool / double / null): 内联写出, 并按键名解析其数字模板 + WriteInline(sb, value, ResolveFmt(key, NumFmt.Raw)); + } + } + + /// + /// 写出组件块 (ObjectData 下的直接子对象, 如 Text / Canvas / XxxxText): + /// 组件块自身多行展开 (空块也换行), 但其内部每个属性值一律内联 + /// (属性值内联时按属性键名解析数字模板, 如 color -> F3、lineSpacing -> F2) + /// + /// 共享的字符串构建器 + /// 组件块对象 + /// 组件块所在的缩进层级 + private static void WriteComponentBlock(StringBuilder sb, Dictionary dict, int indentLevel) + { + string childIndent = new string(' ', (indentLevel + 1) * 2); + string closeIndent = new string(' ', indentLevel * 2); + + sb.Append("{\n"); + int i = 0; + foreach (var kvp in dict) + { + sb.Append(childIndent).Append('"').Append(Escape(kvp.Key)).Append("\": "); + // 组件块内部属性一律内联; 传入属性键名以便按模板表选择数字小数位 + WriteInline(sb, kvp.Value, ResolveFmt(kvp.Key, NumFmt.Raw)); + if (i < dict.Count - 1) sb.Append(','); + sb.Append('\n'); + i++; + } + sb.Append(closeIndent).Append('}'); + } + + /// + /// 写出节点数组 (nodes / ChildNodes): 多行展开, 每个元素为节点对象 (按 Node 层级展开); + /// 即使为空也换行为 "[\n]", 与采集侧固定模板一致 (不压成 "[]") + /// + /// 共享的字符串构建器 + /// 节点数组 + /// 数组所在的缩进层级 + private static void WriteNodeArray(StringBuilder sb, List list, int indentLevel) + { + string childIndent = new string(' ', (indentLevel + 1) * 2); + string closeIndent = new string(' ', indentLevel * 2); + + sb.Append("[\n"); + for (int i = 0; i < list.Count; i++) + { + sb.Append(childIndent); + // 元素正常应为节点对象, 按 Node 层级展开; 其它类型 (理论上不会出现) 内联兜底 + if (list[i] is Dictionary nodeDict) + WriteObject(sb, nodeDict, indentLevel + 1, Level.Node); + else + WriteInline(sb, list[i]); + if (i < list.Count - 1) sb.Append(','); + sb.Append('\n'); + } + sb.Append(closeIndent).Append(']'); + } + + // ========================================== + // 内联写出 (单行): 对象 / 数组 / 标量 + // ========================================== + + /// + /// 单行内联写出任意值 (对象/数组递归内联, 元素间用 ", " 分隔) + /// + /// 共享的字符串构建器 + /// 待写出的值 + /// 该值 (及其内部数字) 的小数位模板, 缺省 Raw + private static void WriteInline(StringBuilder sb, object value, NumFmt fmt = NumFmt.Raw) + { + switch (value) + { + case null: + sb.Append("null"); + break; + case string s: + // 字符串: 加引号并转义 + sb.Append('"').Append(Escape(s)).Append('"'); + break; + case bool b: + // 布尔: 小写 true/false 以符合 JSON 规范 + sb.Append(b ? "true" : "false"); + break; + case Dictionary dict: + // 内联对象: {"k": v, ...} + sb.Append('{'); + int di = 0; + foreach (var kvp in dict) + { + sb.Append('"').Append(Escape(kvp.Key)).Append("\": "); + // 内部子值的模板: 优先按子键自身模板 (处理 visibilityDebug 混合情形), + // 否则继承父对象的 fmt (处理 color / safeArea 整体 F3) + WriteInline(sb, kvp.Value, ResolveInnerFmt(kvp.Key, fmt)); + if (di < dict.Count - 1) sb.Append(", "); + di++; + } + sb.Append('}'); + break; + case List list: + // 内联数组: [v, ...] (元素统一继承同一 fmt) + sb.Append('['); + for (int i = 0; i < list.Count; i++) + { + WriteInline(sb, list[i], fmt); + if (i < list.Count - 1) sb.Append(", "); + } + sb.Append(']'); + break; + default: + // 其余一律当作数字处理 (MiniJson 解析出的数字为 double) + WriteNumber(sb, value, fmt); + break; + } + } + + /// + /// 写出数字: MiniJson 把所有 JSON 数字解析为 double, 这里按 fmt 还原采集侧的小数位 + /// + /// 共享的字符串构建器 + /// 数字值 (预期为 double) + /// 小数位模板 + private static void WriteNumber(StringBuilder sb, object value, NumFmt fmt) + { + if (value is double d) + { + switch (fmt) + { + case NumFmt.F3: + // 固定 3 位小数 (如 1.000 / 0.698); InvariantCulture 保证小数点为 "." + sb.Append(d.ToString("F3", CultureInfo.InvariantCulture)); + return; + case NumFmt.F2: + // 固定 2 位小数 (如 1.00) + sb.Append(d.ToString("F2", CultureInfo.InvariantCulture)); + return; + default: + // Raw: 无小数部分则输出整数 (如 1920 而非 1920.0), 否则用 "R" 往返格式保留原值精度 + if (d == System.Math.Floor(d) && !double.IsInfinity(d) && + d >= long.MinValue && d <= long.MaxValue) + sb.Append(((long)d).ToString(CultureInfo.InvariantCulture)); + else + sb.Append(d.ToString("R", CultureInfo.InvariantCulture)); + return; + } + } + // 理论上不会走到 (MiniJson 数字均为 double), 兜底以不变文化原样输出 + sb.Append(System.Convert.ToString(value, CultureInfo.InvariantCulture)); + } + + /// + /// 按属性键名解析其数字模板 (适用于 "顶层标量" 或 "内联对象的父键"), 未登记则返回 fallback + /// + /// 属性键名 + /// 未登记时的回退模板 + /// 解析出的数字模板 + private static NumFmt ResolveFmt(string key, NumFmt fallback) + { + return _fmtByKey.TryGetValue(key, out var f) ? f : fallback; + } + + /// + /// 内联对象 "内部子键" 的模板解析 (处理内联对象内部的模板差异): + /// - visibilityDebug 是混合模板: 子键 ratio / ratioThreshold 用 F3, 其余用 Raw; + /// - aabb 是 visibilityDebug 内的子对象, 其内部 x/y/width/height 均为整数 -> Raw; + /// - 其它内联对象 (如 color / safeArea) 的子键继承父对象模板 parentFmt + /// + /// 内联对象内部的子键名 + /// 父对象 (内联对象自身) 的模板 + /// 该子键对应的数字模板 + private static NumFmt ResolveInnerFmt(string childKey, NumFmt parentFmt) + { + if (_visDebugF3.Contains(childKey)) return NumFmt.F3; + if (childKey == "aabb") return NumFmt.Raw; + return parentFmt; + } + + /// + /// 对字符串做 JSON 转义 (与采集侧 JsonBuilder.EscapeJson 规则一致) + /// + /// 原始字符串 (可为 null/空) + /// 转义后的字符串; 输入为 null/空时返回空字符串 + private static string Escape(string str) + { + // 空值保护: null/空串统一返回 "", 避免后续 Replace 抛异常 + if (string.IsNullOrEmpty(str)) return ""; + // 转义顺序至关重要: 反斜杠必须最先替换, 否则后续新引入的 "\" 会被重复转义导致结果错误 + return str.Replace("\\", "\\\\") // 反斜杠 \ -> \\ + .Replace("\"", "\\\"") // 双引号 " -> \" + .Replace("\n", "\\n") // 换行符 -> \n + .Replace("\r", "\\r") // 回车符 -> \r + .Replace("\t", "\\t"); // 制表符 -> \t + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/MiniJson.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/MiniJson.cs new file mode 100644 index 0000000000000000000000000000000000000000..15887922991026448be20f90ed90ece2b7d2e8b0 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/Json/MiniJson.cs @@ -0,0 +1,231 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\Json\MiniJson.cs +// 模块: Core.Json (核心层 JSON 数据读写) +// ========================================== + +using System; +using System.Collections.Generic; +using System.Text; + +/// +/// LQARestore 核心层 JSON 数据读写命名空间 +/// +namespace LQARestore.Core.Json +{ + /// + /// 极简 JSON 解析器 (只解析, 不负责序列化) + /// 用途: 在不引入第三方 JSON 库的前提下, 把 JSON 文本解析成通用的 C# 对象树, + /// 供上层 (配合 DictExt 等) 读取 + /// 解析结果的类型映射约定: + /// JSON object -> Dictionary + /// JSON array -> List + /// JSON string -> string + /// JSON number -> double (统一用 double, 不区分整数/浮点) + /// JSON true/false -> bool + /// JSON null -> null + /// 实现方式: 采用单指针 (ref int i) 递归下降解析, i 表示当前扫描位置, + /// 各 Parse 方法消费掉自己对应的片段后将 i 推进到片段末尾之后 + /// 注意: 这是一个 "宽松" 解析器, 追求实现精简, 对非法 JSON 不做严格校验/报错, + /// 遇到畸形输入通常会尽力解析或回退, 而不会抛出格式异常 + /// + public static class MiniJson + { + /// + /// 解析入口: 将 JSON 文本解析为对象树 + /// + /// JSON 文本, 允许为 null/空 + /// + /// 解析出的对象 (Dictionary / List / string / double / bool / null 之一); + /// 输入为空时返回 null + /// + public static object Parse(string json) + { + // 空输入直接返回 null, 避免后续越界访问 + if (string.IsNullOrEmpty(json)) return null; + // i 为共享的扫描游标, 从头开始解析第一个值 + int i = 0; + return ParseValue(json, ref i); + } + + /// + /// 解析任意一个 JSON 值, 根据当前字符分派到具体的解析方法 + /// + /// 完整 JSON 文本 + /// 扫描游标 (引用传递, 会被推进) + /// 解析出的值对象 + private static object ParseValue(string s, ref int i) + { + // 先跳过值前面的空白字符 + SkipWs(s, ref i); + // 已到末尾, 无值可读 + if (i >= s.Length) return null; + // 根据首字符判断值的类型 (JSON 各类型的起始字符互不相同) + char c = s[i]; + if (c == '{') return ParseObject(s, ref i); // 对象 + if (c == '[') return ParseArray(s, ref i); // 数组 + if (c == '"') return ParseString(s, ref i); // 字符串 + if (c == 't' || c == 'f') return ParseBool(s, ref i); // 布尔 (true/false) + // null: 直接跳过 4 个字符 ("null" 长度) 并返回 null, 不做逐字符校验 + if (c == 'n') { i += 4; return null; } + // 其余情况一律当作数字解析 + return ParseNumber(s, ref i); + } + + /// + /// 解析 JSON 对象 (以 '{' 开头), 返回键值字典 + /// + /// 完整 JSON 文本 + /// 扫描游标, 进入时指向 '{' + /// 键为字符串、值为对象树的字典 + private static Dictionary ParseObject(string s, ref int i) + { + var dict = new Dictionary(); + // 跳过起始的 '{' + i++; + SkipWs(s, ref i); + // 处理空对象 "{}": 紧跟 '}' 则直接返回空字典 + if (i < s.Length && s[i] == '}') { i++; return dict; } + // 循环读取 "键: 值" 对, 直到遇到 '}' 或文本结束 + while (i < s.Length) + { + SkipWs(s, ref i); + // 键必然是字符串, 直接按字符串解析 + string key = ParseString(s, ref i); + SkipWs(s, ref i); + // 跳过键值之间的冒号分隔符 (宽松处理: 缺失也不报错) + if (i < s.Length && s[i] == ':') i++; + // 递归解析该键对应的值 + object val = ParseValue(s, ref i); + dict[key] = val; + SkipWs(s, ref i); + // 逗号: 还有下一对, 继续循环 + if (i < s.Length && s[i] == ',') { i++; continue; } + // 右括号: 对象结束, 跳过 '}' 并退出 + if (i < s.Length && s[i] == '}') { i++; break; } + } + return dict; + } + + /// + /// 解析 JSON 数组 (以 '[' 开头), 返回元素列表 + /// + /// 完整 JSON 文本 + /// 扫描游标, 进入时指向 '[' + /// 元素为对象树的列表 + private static List ParseArray(string s, ref int i) + { + var list = new List(); + // 跳过起始的 '[' + i++; + SkipWs(s, ref i); + // 处理空数组 "[]" + if (i < s.Length && s[i] == ']') { i++; return list; } + // 循环读取元素, 直到遇到 ']' 或文本结束 + while (i < s.Length) + { + // 递归解析一个元素并加入列表 + list.Add(ParseValue(s, ref i)); + SkipWs(s, ref i); + // 逗号: 还有下一个元素 + if (i < s.Length && s[i] == ',') { i++; continue; } + // 右方括号: 数组结束 + if (i < s.Length && s[i] == ']') { i++; break; } + } + return list; + } + + /// + /// 解析 JSON 字符串 (以 '"' 开头), 处理转义字符 + /// + /// 完整 JSON 文本 + /// 扫描游标, 进入时指向起始双引号 + /// 去掉引号并还原转义后的字符串内容 + private static string ParseString(string s, ref int i) + { + var sb = new StringBuilder(); + // 跳过起始的双引号 + i++; + while (i < s.Length) + { + // 读取一个字符并推进游标 + char c = s[i++]; + // 遇到结束双引号即完成 + if (c == '"') return sb.ToString(); + // 反斜杠开启转义序列 (且后面还有字符) + if (c == '\\' && i < s.Length) + { + char esc = s[i++]; + switch (esc) + { + case '"': sb.Append('"'); break; // 转义双引号 + case '\\': sb.Append('\\'); break; // 转义反斜杠 + case '/': sb.Append('/'); break; // 转义斜杠 + case 'n': sb.Append('\n'); break; // 换行 + case 'r': sb.Append('\r'); break; // 回车 + case 't': sb.Append('\t'); break; // 制表符 + case 'b': sb.Append('\b'); break; // 退格 + case 'f': sb.Append('\f'); break; // 换页 + case 'u': + // \uXXXX: 取后续 4 位十六进制转为 Unicode 码点 + if (i + 4 <= s.Length) + { + sb.Append((char)Convert.ToInt32(s.Substring(i, 4), 16)); + i += 4; // 跳过已消费的 4 位十六进制 + } + break; + // 未知转义: 宽松处理, 原样保留转义字符本身 + default: sb.Append(esc); break; + } + } + else sb.Append(c); // 普通字符直接追加 + } + // 未遇到闭合引号就到末尾: 宽松返回已读取的内容 + return sb.ToString(); + } + + /// + /// 解析 JSON 数字, 统一返回 double + /// + /// 完整 JSON 文本 + /// 扫描游标, 进入时指向数字首字符 + /// + /// 解析出的 double; 解析失败时 (TryParse 返回 false) d 为 0, 仍返回该值 + /// + private static object ParseNumber(string s, ref int i) + { + int start = i; + // 贪婪吞掉所有可能构成数字的字符 (含符号、小数点、科学计数法 e/E) + while (i < s.Length && "0123456789+-.eE".IndexOf(s[i]) >= 0) i++; + // 用 InvariantCulture 解析, 保证小数点是 '.' 而不受区域设置影响; + // NumberStyles.Any 兼容各种数字写法; 失败时 d 默认为 0 + double.TryParse(s.Substring(start, i - start), + System.Globalization.NumberStyles.Any, + System.Globalization.CultureInfo.InvariantCulture, out double d); + return d; + } + + /// + /// 解析 JSON 布尔值 (true / false) + /// + /// 完整 JSON 文本 + /// 扫描游标, 进入时指向 't' 或 'f' + /// true 或 false + private static bool ParseBool(string s, ref int i) + { + // 仅凭首字符判断: 't' 说明是 "true" (长度 4) + if (s[i] == 't') { i += 4; return true; } + // 否则是 "false" (长度 5), 直接跳过 5 个字符 + i += 5; return false; + } + + /// + /// 跳过连续的空白字符 (空格、制表、换行等) + /// + /// 完整 JSON 文本 + /// 扫描游标, 会被推进到首个非空白字符处 + private static void SkipWs(string s, ref int i) + { + while (i < s.Length && char.IsWhiteSpace(s[i])) i++; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/LQAKeyInfo.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/LQAKeyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..92ea3761fbec2c655c2a81502e46a8cae64be624 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/LQAKeyInfo.cs @@ -0,0 +1,30 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\LQAKeyInfo.cs +// 模块: Core (核心层) +// ========================================== + +using UnityEngine; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 本地化 Key 说明组件 (还原侧轻量数据载体) + /// 职责: 在还原出的可编辑 UGUI 文本对象上, 携带采集侧从 XxxxLocalize 反射读到的 keyHash, + /// 使本地化/翻译人员在还原场景中选中该文本时, 能在 Inspector 直接看到其对应的本地化 key + /// 设计要点: + /// - 不还原原工程的 XxxxLocalize 组件本身 (类型不在本还原工程引用范围内, 且还原环境无本地化配置表, + /// 挂上去也不会驱动出任何效果), 仅把 keyHash 作为 "数据" 还原出来, 与 XxxxText 用内置 Outline/Shadow + /// 近似其视觉、而不还原组件本身的取舍一致; + /// - 纯数据组件, 无任何运行逻辑 + /// + public class LQAKeyInfo : MonoBehaviour + { + /// + /// 采集侧从 XxxxLocalize.keyHash 反射读到的本地化 key (原样字符串, 可能是十六进制哈希或原文 key) + /// + public string keyHash; + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/NodePostProcessors.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/NodePostProcessors.cs new file mode 100644 index 0000000000000000000000000000000000000000..d88f5890f7d995dc1d3ea299c2bb9be7c820e577 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/NodePostProcessors.cs @@ -0,0 +1,100 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\NodePostProcessors.cs +// 模块: Core (核心层) +// ========================================== + +using System; +using System.Collections.Generic; +using UnityEngine; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 节点后处理器委托: 定义 "对单个还原节点做附加处理" 的统一签名 + /// 触发时机: 在 TextNodeBuilder 完成通用组件 (Text / Canvas / RectTransform) 还原后, + /// 由 NodePostProcessors 逐一回调所有已注册的后处理器, 对该节点做附加还原 (如项目专属特效) + /// 对称设计: 与采集侧 ComponentExtractors 的注册表模式相对应 —— + /// 采集侧负责 "把组件属性抽取成 JSON", 还原侧则负责 "把 JSON 还原回组件/特效" + /// + /// 已完成通用还原的节点 GameObject + /// 该节点从 JSON 反序列化得到的属性字典, 供后处理器读取所需数据 + internal delegate void NodePostProcessor(GameObject go, Dictionary objectData); + + /// + /// 节点后处理器的注册中心 + /// 职责: + /// - 维护一张已注册后处理器的列表; + /// - 提供 ApplyAll: 对某个已完成通用还原的节点, 依次执行所有后处理器; + /// 设计要点: + /// - 采用注册表模式, 新增一类附加还原只需 Register, 无需改动 ApplyAll 遍历逻辑; + /// - 通用还原 (Text / Canvas / RectTransform) 由 TextNodeBuilder 直接完成, 无需在此注册; + /// - 项目专属还原 (对应采集侧的项目专属组件) 由 ProjectCustomRestorers 挂入, 与本类解耦; + /// - 声明为 static, 全局只有一份注册表, 由静态构造函数在首次访问时初始化一次; + /// + internal static class NodePostProcessors + { + // ========================================== + // 注册表存储 + // ========================================== + + /// + /// 全局注册表, 存放所有已登记的后处理器, 由静态构造填充后按注册顺序遍历执行 + /// + private static readonly List _processors = new List(); + + // ========================================== + // 静态构造: 注册所有后处理器 + // ========================================== + + /// + /// 静态构造函数, 在本类被首次访问时由 CLR 自动调用一次 + /// 负责挂入项目专属还原器 (对称于采集侧 ComponentExtractors 的静态构造) + /// + static NodePostProcessors() + { + // 对称采集侧: 通用还原无需注册; 项目专属还原在此挂入 + ProjectCustomRestorers.RegisterAll(); + } + + // ========================================== + // 注册辅助方法 + // ========================================== + + /// + /// 注册一个后处理器, 供 ProjectCustomRestorers 等在初始化时挂入附加还原逻辑 + /// + /// 待注册的后处理器 (为 null 时静默忽略) + internal static void Register(NodePostProcessor processor) + { + if (processor != null) _processors.Add(processor); + } + + // ========================================== + // 公开 API: 供 TextNodeBuilder 调用 + // ========================================== + + /// + /// 对给定节点依次执行所有已注册的后处理器 + /// 由还原流程在完成该节点的通用组件还原后调用一次 + /// + /// 已完成通用还原的节点 GameObject + /// 该节点的属性字典, 转发给每个后处理器读取 + internal static void ApplyAll(GameObject go, Dictionary objectData) + { + // 逐条执行注册表: 用 for 而非 foreach, 避免枚举器分配, 同时明确按注册顺序执行 + for (int i = 0; i < _processors.Count; i++) + { + try { _processors[i](go, objectData); } + catch (Exception e) + { + // 单个后处理器失败不应中断整棵树的还原, 记一条警告后继续处理其余后处理器 + var name = go != null ? go.name : ""; + Debug.LogWarning($"[LQARestore][NodePostProcessors] {name} 后处理失败: {e.Message}"); + } + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ProjectCustomRestorers.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ProjectCustomRestorers.cs new file mode 100644 index 0000000000000000000000000000000000000000..8c8a50a3c189928d6c83fac35e6072dbb6ece0d4 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/ProjectCustomRestorers.cs @@ -0,0 +1,152 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\ProjectCustomRestorers.cs +// 模块: Core (核心层) +// ========================================== + +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 项目专属组件的还原器注册入口 (与通用 TextNodeBuilder 解耦) + /// 设计目的: + /// - 通用 UI 组件 (Text / Canvas / RectTransform 等) 的还原由 TextNodeBuilder 直接完成; + /// - 而项目专属特效 (如 Xxxx 系列文本的描边 / 阴影) 只在特定工程里出现, + /// 因此单独放到本文件, 通过 NodePostProcessors.Register 以 "后处理器回调" 的松耦合方式挂入, + /// 使 NodePostProcessors / TextNodeBuilder 无需感知任何项目专属键名; + /// 对称设计: 与采集侧 ProjectCustomExtractors 一一对应 —— + /// 采集侧把项目专属组件属性抽成 JSON (专属键名 "XxxxText" 只在采集侧那份文件出现), + /// 还原侧则在此把同一份 JSON 还原回 Unity 组件/特效 (专属键名 "XxxxText" 也只在本文件出现) + /// 调用链: NodePostProcessors 的静态构造函数会调用 RegisterAll + /// + internal static class ProjectCustomRestorers + { + /// + /// 注册所有项目专属组件的还原器 + /// 由 NodePostProcessors 的静态构造在初始化时调用一次 + /// + internal static void RegisterAll() + { + // 在此按需注册本项目的自定义还原器 (对应 JSON 块缺失时后处理器会直接 return, 不影响其它节点) + // 可直接复用的辅助工具: + // NodePostProcessors.Register((go, objectData) => {...}) 挂入后处理回调, go 为还原出的节点, objectData 为其 JSON 属性; + // objectData.Get>("组件键") 取某组件的属性块 (缺失返回 null 即代表该节点无此组件); + // dict.GetInnerString / GetInnerFloat (属性键[, 默认值]) 从属性块读取标量值; + // 本类私有 ReadColor(dict) 由含 r/g/b/a 的字典构造 Color + // 用法示例: 仿照下方 RegisterXxxxLocalize / RegisterXxxxText, 新增一个 private static void RegisterYourComp() 方法, + // 在其中 NodePostProcessors.Register(...) 写还原逻辑, 再在上方本方法里补一行 RegisterYourComp() 调用, 并改成你自己的 JSON 键名: + + /* + // 本地化组件: 把 keyHash 作为数据还原到 LQAKeyInfo 组件, 供 Inspector 查看 + RegisterXxxxLocalize(); + // 富文本组件: 用于还原描边 / 阴影等文本视觉特效 + RegisterXxxxText(); + */ + + } + + /* + // ========================================== + // XxxxLocalize 组件 [键名 "XxxxLocalize"] + // ========================================== + + /// + /// 注册 XxxxLocalize 的还原后处理器 + /// 从采集侧导出的 keyHash 中读取本地化 key, 挂一个轻量的 LQAKeyInfo 组件承载它, + /// 使还原出的文本对象在 Inspector 中可直接查看其对应的本地化 key + /// 注意: 不还原原工程的 XxxxLocalize 组件本身 (类型不在本还原工程引用范围内, 且无本地化配置表驱动), + /// 仅把 keyHash 作为数据还原, 与 XxxxText 用内置 Outline/Shadow 近似而不还原组件本身的取舍一致 + /// + private static void RegisterXxxxLocalize() + { + NodePostProcessors.Register((go, objectData) => + { + // 读取该节点 JSON 中的 "XxxxLocalize" 属性块; 缺失说明此节点没有该组件, 直接跳过 + var locProps = objectData.Get>("XxxxLocalize"); + if (locProps == null) return; + + // 取 keyHash; 为空则不挂组件 (避免产生无意义的空信息组件) + string keyHash = locProps.GetInnerString("keyHash"); + if (string.IsNullOrEmpty(keyHash)) return; + + // 挂轻量说明组件, 回填 keyHash 供 Inspector 查看 + var info = go.AddComponent(); + info.keyHash = keyHash; + }); + } + + // ========================================== + // XxxxText 组件 [键名 "XxxxText"] + // ========================================== + + /// + /// 注册 XxxxText 的还原后处理器 + /// 根据采集侧导出的 textEffectType, 在还原后的节点上附加 Outline (描边) 或 Shadow (阴影) 组件, + /// 并回填其颜色与距离参数, 以 1:1 复刻原工程的文本视觉效果 + /// 注意: 原工程的 Xxxx.XxxxText 类型不在本还原插件的引用范围内, + /// 因此这里不还原该组件本身, 而是用 Unity 内置的 Outline / Shadow 近似其视觉结果 + /// + private static void RegisterXxxxText() + { + NodePostProcessors.Register((go, objectData) => + { + // 读取该节点 JSON 中的 "XxxxText" 属性块; 缺失说明此节点没有该特效, 直接跳过 + var projectProps = objectData.Get>("XxxxText"); + if (projectProps == null) return; + // Outline / Shadow 继承自 BaseMeshEffect, 通过修改 Graphic 的网格顶点生效, 仅作用于旧版 UGUI Text; + // TMP 自行生成网格, 不走该管线, 挂这两个特效无效, 故这里仅在存在旧版 Text 时附加 + // (TMP 的描边/阴影需在其材质层面还原, 超出当前近似还原范围) + if (!go.TryGetComponent(out _)) return; + + // 特效类型: 与采集侧 AddEnum 写入的枚举名对应 (忽略大小写以增强容错) + string effect = projectProps.GetInnerString("textEffectType"); + if (string.Equals(effect, "Outline", StringComparison.OrdinalIgnoreCase)) + { + // 描边: 附加 Outline, 回填颜色与偏移距离 + var outline = go.AddComponent(); + var oc = projectProps.Get>("outlineColor"); + if (oc != null) outline.effectColor = ReadColor(oc); + var od = projectProps.Get>("outlineDistance"); + // 缺省距离 (1, -1) 对应 Unity Outline 的默认效果距离 + if (od != null) outline.effectDistance = new Vector2(od.GetInnerFloat("x", 1f), od.GetInnerFloat("y", -1f)); + } + else if (string.Equals(effect, "Shadow", StringComparison.OrdinalIgnoreCase)) + { + // 阴影: 附加 Shadow, 回填颜色与偏移距离 + var shadow = go.AddComponent(); + var sc = projectProps.Get>("shadowColor"); + if (sc != null) shadow.effectColor = ReadColor(sc); + var sd = projectProps.Get>("shadowDistance"); + // 缺省距离 (1, -1) 对应 Unity Shadow 的默认效果距离 + if (sd != null) shadow.effectDistance = new Vector2(sd.GetInnerFloat("x", 1f), sd.GetInnerFloat("y", -1f)); + } + // 其它 (无特效 / 描边+阴影 等) 暂不还原 + }); + } + */ + + // ========================================== + // 辅助方法 + // ========================================== + + /// + /// 从颜色属性字典 (含 r/g/b/a) 读取并构造 Color + /// 独立保留一份, 避免依赖 TextNodeBuilder 的私有 ReadColor, 使本文件可与其解耦 + /// + /// 颜色属性字典, 为 null 时返回白色 (Color.white) + /// 解析出的 Color, 各通道缺省值均为 1 + private static Color ReadColor(Dictionary d) + { + if (d == null) return Color.white; + return new Color(d.GetInnerFloat("r", 1), d.GetInnerFloat("g", 1), + d.GetInnerFloat("b", 1), d.GetInnerFloat("a", 1)); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/RestoreEngine.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/RestoreEngine.cs new file mode 100644 index 0000000000000000000000000000000000000000..09020a9de75cb49b4bb524b94480d7f7c0a0416c --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/RestoreEngine.cs @@ -0,0 +1,393 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\RestoreEngine.cs +// 模块: Core (核心层) +// ========================================== + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEngine.UI; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 还原引擎 (核心层): 把采集工具 (LQATool) 产出的 dump 数据 "反向重建" 成 Unity 场景中的可视画面 + /// 职责: 读取一份 dump 的 JSON 描述文件, 依次完成: + /// 1. 解析 JSON 根对象, 取出原始屏幕分辨率等元信息 + /// 2. 新建一个干净的还原场景, 并把 GameView 分辨率对齐到原始画面 + /// 3. 铺上 "无文本截图" 作为背景画布 (ScreenShot_NoText.png) + /// 4. 委托 TextNodeBuilder 递归重建 dump 里记录的文本节点树 + /// 5. 处理延迟失活 (activeSelf=false) 的节点, 标记场景为脏, 最终截图输出 Restore.png + /// 设计要点: 引擎本身不直接依赖 Unity 编辑器/平台 API, 而是通过 IFontResolver (字体解析) + /// 与 ISceneHost (场景/截图宿主) 两个接口与外界交互, 从而与运行环境解耦, + /// 便于在 Editor / 未来 Runtime 等不同环境下替换实现 + /// + public class RestoreEngine + { + // ========================================== + // 依赖注入 (私有只读字段) —— 由构造函数传入, 供还原流程调用 + // ========================================== + + /// + /// 字体解析器: 把 dump 里的字体引用信息 (name/assetPath/guid) 解析为可渲染的 Font + /// 具体查找方式由实现决定 (Editor 走 AssetDatabase, 真机可另写实现) + /// + private readonly IFontResolver _fontResolver; + + /// + /// 场景宿主: 封装新建场景 / 设置分辨率 / 截图 / 标记脏 等与 Unity 场景强相关的底层能力 + /// + private readonly ISceneHost _sceneHost; + + /// + /// 延迟失活队列: 收集 "需要 SetActive(false)" 的节点操作 + /// 为什么要延迟: 若在重建过程中立即失活某节点, 其未创建完成的子节点会受影响, + /// 因此先原样激活地建完整棵树, 待全部子节点就位后再统一失活, 保证层级结构完整 + /// 由本引擎创建并传给 TextNodeBuilder, 双方共享同一份队列 + /// + private readonly List _pendingDeactivations = new List(); + + /// + /// 构造还原引擎, 注入字体解析与场景宿主两个外部依赖 + /// + /// 字体解析器实现 (如 EditorFontResolver) + /// 场景宿主实现 (如 EditorSceneHost) + public RestoreEngine(IFontResolver fontResolver, ISceneHost sceneHost) + { + _fontResolver = fontResolver; + _sceneHost = sceneHost; + } + + /// + /// 还原主流程: 对应原 RestoreFromDumpFile 的还原主体 (去掉了 OpenFilePanel 选文件的交互部分) + /// 从给定的 JSON 路径读取一份 dump, 重建文本画面并截图输出到同目录的 Restore.png + /// 整个过程包裹在 try/catch 中: 任一步骤异常都不应让编辑器崩溃, 仅记录错误并安全退出 + /// + /// + /// dump 的 JSON 文件完整路径 + /// 其所在目录 (dumpDir) 同时也是背景图 ScreenShot_NoText.png 与输出图 Restore.png 的目录 + /// + /// 可选 i18n_translation_xx.json (示例) 路径; 为空则用 dump 原文还原 + /// 可选字体变体模板 (含 {name}), 如 "{name}@th"; 为空则字体按 dump 原样还原 + public void RestoreFromDump(string jsonPath, string translationPath = null, string fontVariantTemplate = null) + { + // 入参校验: 路径为空或文件不存在, 直接静默返回 (不视为错误) + if (string.IsNullOrEmpty(jsonPath) || !File.Exists(jsonPath)) return; + + // dump 目录: 背景图读取、结果图输出都以此为基准目录 + string dumpDir = Path.GetDirectoryName(jsonPath); + + // 清空延迟失活队列, 避免上一次还原的残留操作影响本次 + _pendingDeactivations.Clear(); + + try + { + // 1. 读取并解析 JSON, 根节点必须是一个对象 (字典), 否则视为格式错误 + string jsonText = File.ReadAllText(jsonPath); + var root = MiniJson.Parse(jsonText) as Dictionary; + if (root == null) throw new Exception("JSON 根不是对象"); + + // 2. 校验 Color Space: dump 记录的颜色空间与当前项目设置不一致时, + // 纯色块/渐变会明显偏亮或偏暗, 还原画面与原图对比会失真, 故给出告警提醒 (不中断还原) + string dumpColorSpace = root.Get("colorSpace"); + if (!string.IsNullOrEmpty(dumpColorSpace)) + { + string projectColorSpace = QualitySettings.activeColorSpace.ToString(); + if (!string.Equals(dumpColorSpace, projectColorSpace, StringComparison.OrdinalIgnoreCase)) + { + Debug.LogWarning( + $"[LQARestore][RestoreEngine] Color Space 不一致: Dump={dumpColorSpace}, " + + $"当前项目={projectColorSpace}; 还原画面的明暗/颜色可能与原始不符, " + + $"建议在 Edit > Project Settings > Player > Other Settings > Color Space 切换为 {dumpColorSpace} 后重新还原"); + } + } + + // 3. 新建一个干净的还原场景, 作为后续所有还原对象的承载容器 + _sceneHost.NewRestoreScene("LQA_Restore_Scene"); + + // 4. 取出 dump 记录的原始屏幕分辨率 (缺省回退到 1920x1080), + // 并把 GameView 尺寸对齐到该分辨率, 使还原预览/截图与原始画面一致 + int dumpW = Convert.ToInt32(root.Get("screenWidth") ?? 1920); + int dumpH = Convert.ToInt32(root.Get("screenHeight") ?? 1080); + _sceneHost.SetResolution(dumpW, dumpH, "LQA_Restore"); + + // 4. 铺背景: 以 "无文本截图" 作为底图画布, 文本节点稍后叠加在其之上 + CreateBackgroundCanvas(dumpDir, root); + + // 5. 递归重建文本节点树 + // TextNodeBuilder 与本引擎共享 _pendingDeactivations 队列: 建树时先全部激活地创建, + // 需要失活的节点被登记进队列, 待整棵树建完后再统一处理 (见下方) + // 同时传入 onTextBuilt 回调, 旁挂收集所有还原出的可见文本节点, 供导出屏幕文本框 (rect_locations) + // 可选: 用户在菜单选择了 i18n_translation_xx.json (示例) 时加载翻译表; 加载失败/未选 → null (原文还原) + TranslationTable translationTable = null; + if (!string.IsNullOrEmpty(translationPath)) + translationTable = TranslationTable.Load(translationPath); + + // 字体解析器: 配了变体模板则用 FontVariantResolver 包一层 (按模板改写字体名, 找不到回退原字体); + // 未配置模板则直接用原始解析器 (等于当前逻辑) + IFontResolver fontResolver = string.IsNullOrEmpty(fontVariantTemplate) + ? _fontResolver + : new FontVariantResolver(_fontResolver, fontVariantTemplate); + + var textNodes = new List(); + var builder = new TextNodeBuilder(fontResolver, _pendingDeactivations, + (go, finalText) => + { + if (go != null && go.TryGetComponent(out var trt)) + textNodes.Add(new TextRectItem + { + Rt = trt, + Text = finalText ?? "" + }); + }, + translationTable != null ? (Func)translationTable.Resolve : null); + var nodes = root.Get>("nodes"); + if (nodes != null) + { + // 遍历顶层节点, 逐个作为根 (parent 为 null) 递归重建 + foreach (var n in nodes) + if (n is Dictionary nodeDict) + builder.BuildTextNode(nodeDict, null); + } + + // 6. 收集图片框: 对原始节点树做一次纯数据遍历, 把可见的 Image/RawImage + // 采集角点 (corners) 原样透传, 供导出 rect_locations 的 image 组 + // 图片位置不随翻译变化, 采集侧已记录屏幕像素角点 (与文本框同坐标系: y 左下原点), + // 故无需在还原场景重建 Image 对象, 直接透传即可 + var imageBoxes = new List(); + CollectImageBoxes(nodes, imageBoxes); + + // 7. 整棵树建完后, 统一执行延迟失活操作 (还原 activeSelf=false 的节点) + // 单个失活失败只告警不中断, 保证其余节点仍能正确处理 + foreach (var deactivate in _pendingDeactivations) + { + try { + deactivate(); + } + catch (Exception ex) { + Debug.LogWarning($"[LQARestore][RestoreEngine] SetActive 失败: {ex.Message}"); + } + } + _pendingDeactivations.Clear(); + + // 8. 标记场景为脏 (使编辑器识别到内容变化), 并打印完成日志 + _sceneHost.MarkDirty(); + Debug.Log($"[LQARestore][RestoreEngine] 文本还原完成,来源: {dumpDir}"); + + // 9. 截图输出: 把还原后的画面渲染保存为 Restore.png, 便于与原始 dump 画面对比 + string outPath = Path.Combine(dumpDir, "Restore.png"); + _sceneHost.CaptureToPng(outPath, dumpW, dumpH); + + // 10. 导出检测框: 把还原出的每个可见文本节点的屏幕矩形 + 采集透传的图片框写成平台 + // rect_locations 格式, 落到 dump 同目录的 rect_locations.json, 供 "提交还原结果" 时上传 + // (Overlay 画布下 UI 的 world 坐标即屏幕像素坐标, 故 GetWorldCorners 得到的就是屏幕角点) + WriteRectLocations(dumpDir, textNodes, imageBoxes, dumpH); + } + catch (Exception e) + { + // 任一环节异常: 记录完整错误与堆栈, 并清空延迟队列, 保证下一次还原从干净状态开始 + Debug.LogError($"[LQARestore][RestoreEngine] 还原失败: {e.Message}\n{e.StackTrace}"); + _pendingDeactivations.Clear(); + } + } + + /// + /// 创建背景画布: 把 dump 目录下的 "无文本截图" (ScreenShot_NoText.png) 作为底图铺满全屏 + /// 该底图承担 "原始画面但抠掉文本" 的角色, 还原出的文本节点会叠加在它之上, 从而复现完整画面 + /// 若文件不存在则跳过 (仅告警), 还原流程仍可继续 (只是没有背景) + /// + /// dump 所在目录, 背景图从此目录读取 + /// dump 的 JSON 根对象, 用于读取原始分辨率作为画布参考分辨率 + private void CreateBackgroundCanvas(string dumpDir, Dictionary root) + { + // 背景图缺失时不作为错误处理: 打印告警并跳过, 让文本仍能还原到透明/默认背景上 + string bgPath = Path.Combine(dumpDir, "ScreenShot_NoText.png"); + if (!File.Exists(bgPath)) + { + Debug.LogWarning("[LQARestore][RestoreEngine] 未找到 ScreenShot_NoText.png, 跳过背景"); + return; + } + + // 从磁盘字节流加载纹理 (初始尺寸随意, LoadImage 会按图片实际尺寸自动重建) + var tex = new Texture2D(2, 2, TextureFormat.RGBA32, false); + tex.LoadImage(File.ReadAllBytes(bgPath)); + tex.name = "ScreenShot_NoText"; + + // 背景画布: Overlay 模式直接贴屏, sortingOrder = -1 保证它位于所有文本节点之下 + var canvasGo = new GameObject("LQA_Background_Canvas"); + var canvas = canvasGo.AddComponent(); + canvas.renderMode = RenderMode.ScreenSpaceOverlay; + canvas.sortingOrder = -1; + + // 缩放器按原始分辨率做参考, 使背景图随 GameView 尺寸等比适配 + var scaler = canvasGo.AddComponent(); + scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; + scaler.referenceResolution = new Vector2( + Convert.ToInt32(root.Get("screenWidth") ?? 1920), + Convert.ToInt32(root.Get("screenHeight") ?? 1080) + ); + + // 补齐 GraphicRaycaster (标准 UI 画布组成部分, 保持结构完整) + canvasGo.AddComponent(); + + // 背景图节点: 用 RawImage 直接显示这张 Texture2D (无需 Sprite 转换) + var bgGo = new GameObject("BG", typeof(RectTransform)); + bgGo.transform.SetParent(canvasGo.transform, false); + bgGo.AddComponent(); + + var bg = bgGo.AddComponent(); + bg.texture = tex; + + // 让背景图铺满整个画布: 锚点拉伸到四角 (0,0)~(1,1), 四边偏移清零 + var rt = bg.rectTransform; + rt.anchorMin = Vector2.zero; + rt.anchorMax = Vector2.one; + rt.offsetMin = Vector2.zero; + rt.offsetMax = Vector2.zero; + } + + /// + /// 还原过程中收集的一个文本节点: 其 RectTransform 与文本内容 + /// + private struct TextRectItem + { + public RectTransform Rt; + public string Text; + } + + /// + /// 把收集到的文本节点屏幕矩形导出为平台 rect_locations 格式, 写到 dumpDir/rect_locations.json + /// + /// 平台 (image/service.py auto_review) 约定: rect_locations 是 { 组key: [ { "corners":[4个{x,y}点] }, ... ] }; + /// corners 需按 1左下 → 2左上 → 3右上 → 4右下 逆时针顺序给出全部四点, 且 y 为 "左下原点" + /// Unity 的 RectTransform.GetWorldCorners 在 Overlay 画布下返回屏幕像素坐标(y 向上为正, 即左下原点), + /// 顺序为 [0]左下 [1]左上 [2]右上 [3]右下, 这里按平台约定重排为左下起逆时针 + /// + private void WriteRectLocations(string dumpDir, List items, List imageBoxes, int dumpH) + { + try + { + // 生成前强制刷新一次布局, 保证 RectTransform 的世界角点已是最终值 + Canvas.ForceUpdateCanvases(); + + var boxes = new List(); + var wc = new Vector3[4]; + foreach (var it in items) + { + if (it.Rt == null) continue; + it.Rt.GetWorldCorners(wc); // [0]左下 [1]左上 [2]右上 [3]右下 (屏幕像素, y 左下原点) + float xMin = Mathf.Min(wc[0].x, wc[2].x); + float xMax = Mathf.Max(wc[0].x, wc[2].x); + float yMin = Mathf.Min(wc[0].y, wc[2].y); + float yMax = Mathf.Max(wc[0].y, wc[2].y); + + // 过滤零面积/异常框 + if (xMax - xMin < 1f || yMax - yMin < 1f) continue; + + // 平台约定: 从左下起逆时针采集全部四点, 依次 1左下 → 2左上 → 3右上 → 4右下 (左下原点) + var corners = new List + { + MakePoint(xMin, yMin), // 1 左下 + MakePoint(xMin, yMax), // 2 左上 + MakePoint(xMax, yMax), // 3 右上 + MakePoint(xMax, yMin), // 4 右下 + }; + boxes.Add(new Dictionary + { + { "corners", corners }, + { "textStr", it.Text ?? "" }, + }); + } + + // 顶层两个分组: "text" (还原重算的文本框) 与 "image" (采集透传的图片框) + // 平台按 dict 的 key 分组, 键名本身不参与几何计算 + // 排版: 根对象与数组多行展开, 每个框对象单行内联 (与 ui_data_all.json 风格一致) + var sb = new System.Text.StringBuilder(); + sb.Append('{'); + AppendGroup(sb, "text", boxes, isFirst: true); + AppendGroup(sb, "image", imageBoxes, isFirst: false); + sb.Append("\n}"); + + string outPath = Path.Combine(dumpDir, "rect_locations.json"); + File.WriteAllText(outPath, sb.ToString()); + Debug.Log($"[LQARestore][RestoreEngine] 已导出检测框: {outPath} (文本 {boxes.Count} 个, 图片 {imageBoxes.Count} 个)"); + } + catch (Exception e) + { + Debug.LogWarning($"[LQARestore][RestoreEngine] 导出 rect_locations 失败: {e.Message}"); + } + } + + /// + /// 构造平台角点对象 {"x":.., "y":..} (取整为像素) + /// + private static Dictionary MakePoint(float x, float y) + { + return new Dictionary + { + { "x", (double)Mathf.RoundToInt(x) }, + { "y", (double)Mathf.RoundToInt(y) }, + }; + } + + /// + /// 递归遍历原始节点树, 收集所有 "可见" 图片 (Image / RawImage) 的采集角点 + /// 与文本重建解耦: 直接读采集写入的屏幕像素角点, 不重建 Image 对象 + /// + private void CollectImageBoxes(List nodes, List outBoxes) + { + if (nodes == null) return; + foreach (var n in nodes) + { + if (!(n is Dictionary nodeDict)) continue; + + var objectData = nodeDict.Get>("ObjectData"); + if (objectData != null) + { + TryAddImageBox(objectData.Get>("Image"), outBoxes); + TryAddImageBox(objectData.Get>("RawImage"), outBoxes); + } + + CollectImageBoxes(nodeDict.Get>("ChildNodes"), outBoxes); + } + } + + /// + /// 若图片属性存在、可见且含有效角点, 则以 { "corners": [...] } 形式加入结果 + /// corners 原样透传采集值 (采集侧已按 1左下→2左上→3右上→4右下 记录屏幕像素角点) + /// + private static void TryAddImageBox(Dictionary imgProps, List outBoxes) + { + if (imgProps == null) return; + // 只导出可见图片 (采集侧固定写入 isVisuallyVisible, 缺省保守判为可见) + if (!imgProps.GetInnerBool("isVisuallyVisible", true)) return; + + var corners = imgProps.Get>("corners"); + if (corners == null || corners.Count == 0) return; + + outBoxes.Add(new Dictionary { { "corners", corners } }); + } + + /// + /// 把一组框以 "key": [ 单行内联对象, ... ] 形式追加到 sb + /// isFirst=false 时先补一个逗号分隔上一组, 空组输出 "key": [] + /// + private static void AppendGroup(System.Text.StringBuilder sb, string key, List boxes, bool isFirst) + { + if (!isFirst) sb.Append(','); + sb.Append("\n \"").Append(key).Append("\": ["); + for (int i = 0; i < boxes.Count; i++) + { + sb.Append("\n ").Append(JsonWriter.SerializeInline(boxes[i])); + if (i < boxes.Count - 1) sb.Append(','); + } + if (boxes.Count > 0) sb.Append("\n "); + sb.Append(']'); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TextNodeBuilder.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TextNodeBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..c799916da623f2856998f7baac307ecfd17ceb52 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TextNodeBuilder.cs @@ -0,0 +1,464 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\TextNodeBuilder.cs +// 模块: Core (核心层) +// ========================================== + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; +using UnityEngine.UI; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 文本节点构建器: 把 Dump 导出的 UI 节点字典 (Dictionary) 还原为运行时的 GameObject 树 + /// 职责: + /// - 递归遍历 Dump JSON 反序列化后的节点字典, 为每个节点重建 GameObject 及其组件; + /// - 只关心通用文本还原链路 (Canvas / CanvasScaler / RectTransform / Text); + /// - 项目专属组件 (如 XxxxText 特效) 的附加还原委托给 NodePostProcessors 注册表, 本类不感知; + /// 唯一例外: 本地化 keyHash 因需参与 "最终文本" 的译文解析, 内联读取于 BuildTextNode + /// (见该处 "[项目专属]" 注释); 迁移到其它项目时只改那一处的键名即可; + /// - 依据 "有效可见性" 剪枝, 不可见的文本节点连同整棵子树一起跳过重建; + /// 设计要点: + /// - 还原是 "把 UI 平铺到截图之上" 的 2D 合成场景, 没有原始 UI 相机, 故 Canvas 统一退化为 Overlay; + /// - 字体加载委托给 IFontResolver, 兼容真机 (Android) 采集时缺少 AssetDatabase 的场景; + /// - 有效可见性判定: 节点根层若有人工显示标记 manualShow (由 LQATextShowWindow 写入) 则以其为准, + /// 否则回退采集侧的像素可见性 isVisuallyVisible; 判为不可见即跳过重建 (不生成该节点及其子树); + /// - activeSelf=false 的节点先建后禁用: 关闭动作延迟到整棵树构建完成后统一执行, + /// 避免在父节点尚未激活时子节点无法继续挂载 + /// + public class TextNodeBuilder + { + /// + /// 字体解析器: 按 Dump 中记录的字体引用 (assetPath / guid / name) 在工程内定位 Font 资源 + /// + private readonly IFontResolver _fontResolver; + + /// + /// 延迟禁用动作队列: 收集所有 activeSelf=false 节点的 SetActive(false) 调用, + /// 待整棵树构建完毕后由调用方统一回放, 保证禁用不影响子节点的挂载过程 + /// + private readonly List _pendingDeactivations; + + /// + /// 可选回调: 每还原出一个 "含 Text 组件" 的节点时被调用一次, 传入该节点 GameObject 与其最终文本 + /// 供外部 (如导出文本框 rect_locations)旁挂收集, 不影响还原本身; 为 null 时不触发 + /// + private readonly Action _onTextBuilt; + + /// + /// 可选翻译解析委托: 入参 (keyHash, textContent), 返回最终文本; 为 null 时表示不翻译, 直接用 textContent + /// + private readonly Func _translationResolver; + + /// + /// 构造函数 + /// + /// 字体解析器, 可为 null (为 null 时一律回退到内置字体) + /// 外部持有的延迟禁用队列, 本类只往里追加, 由调用方负责回放 + /// 可选: 每建出一个含 Text 的节点时回调(GameObject, 最终文本), 用于旁挂收集 + /// 可选: 翻译解析委托 (keyHash, textContent) → 最终文本; 为 null 时用原文 + public TextNodeBuilder(IFontResolver fontResolver, List pendingDeactivations, + Action onTextBuilt = null, + Func translationResolver = null) + { + _fontResolver = fontResolver; + _pendingDeactivations = pendingDeactivations; + _onTextBuilt = onTextBuilt; + _translationResolver = translationResolver; + } + + /// + /// 递归构建单个文本节点: 依据节点字典重建 GameObject, 挂载并还原相关组件, 再向下处理子节点 + /// + /// 当前节点的字典数据 (含 name / ObjectData / ChildNodes) + /// 父节点 Transform, 根节点传入时可为 null + public void BuildTextNode(Dictionary nodeDict, Transform parent) + { + string name = nodeDict.Get("name") ?? "Unnamed"; + var objectData = nodeDict.Get>("ObjectData") ?? new Dictionary(); + + // 可见性过滤 (有效可见性判定): + // - 节点根层若存在 manualShow (人工显示标记, 由 LQATextShowWindow 写入), 以它为准; + // - 否则回退到采集侧的 isVisuallyVisible (像素差分判定, 缺省保守判为可见); + // 不可见时连同整个子树一起跳过重建, 避免被隐藏/被遮挡的文本叠加到画面上 + // 文本属性块: 旧版 Text 走 "Text" 键, TMP 走 "TMP" 键 + var textProps = objectData.Get>("Text"); + var tmpProps = objectData.Get>("TMP"); + var anyTextProps = textProps ?? tmpProps; + if (anyTextProps != null) + { + bool effectiveVisible = nodeDict.ContainsKey("manualShow") + ? nodeDict.GetInnerBool("manualShow", true) + : anyTextProps.GetInnerBool("isVisuallyVisible", true); + if (!effectiveVisible) return; + } + + GameObject go; + // 该节点是否为一个 Canvas 节点, 决定挂载的组件集合 + bool hasCanvas = objectData.ContainsKey("Canvas"); + + // 统一带 RectTransform 创建 (UI 节点默认使用 RectTransform 而非普通 Transform) + go = new GameObject(name, typeof(RectTransform)); + if (parent != null) go.transform.SetParent(parent, false); + + if (hasCanvas) + { + // Canvas 节点: 补齐 Canvas / CanvasScaler / GraphicRaycaster 三件套后还原属性 + var canvas = go.AddComponent(); + var scaler = go.AddComponent(); + go.AddComponent(); + ApplyCanvas(canvas, scaler, objectData); + } + else + { + // 只有文本节点 (Text / TMP) 需要 CanvasRenderer + if (objectData.ContainsKey("Text") || objectData.ContainsKey("TMP")) + go.AddComponent(); + } + + // 还原 RectTransform 定位 + if (go.TryGetComponent(out var rt)) + ApplyRect(rt, objectData); + + // ========================================== + // [项目专属] 本地化组件 keyHash 提取 —— 迁移到其它项目时改这一处 + // ========================================== + // 键名 "XxxxLocalize" / "keyHash" 是当前项目 (Xxxx 系列) 本地化组件的专属约定, + // 由采集侧 ProjectCustomExtractors 写入 JSON, 语义为该文本对应的本地化 key 哈希 + // 为何破例内联在核心层 (本类其余项目专属还原均已解耦到 NodePostProcessors / ProjectCustomRestorers): + // keyHash 需参与 "最终显示文本" 的译文解析 (见下方 _translationResolver 调用), 而文本内容必须在 + // 通用 Text/TMP 还原的当下就确定; 后处理器在文本还原之后才执行, 无法回改已写入的文本, + // 因此这处 keyHash 读取只能就地内联, 这是本类唯一感知项目专属键名的地方 + // 迁移指引: 换到其它项目时, 若本地化组件的键名/字段不同 —— 只需改下面这一行的 + // "XxxxLocalize" / "keyHash"; 若目标项目没有本地化组件 —— 让 keyHash 取到空串即可 + // (translationResolver 会自动退化为仅按 original 匹配) + // 翻译匹配规则本身 (keyHash 优先, 回退 original) 封装在 TranslationTable, 与本处无关 + string keyHash = objectData.Get>("XxxxLocalize").GetInnerString("keyHash"); + + // 通用 Text 还原 + if (objectData.TryGetValue("Text", out var txtObj) && txtObj is Dictionary txtProps) + { + // 无翻译表时 finalText 即原始 textContent (行为与原来一致); 有则按 keyHash/original 规则解析 + string original = txtProps.Get("textContent") ?? ""; + string finalText = _translationResolver != null ? _translationResolver(keyHash, original) : original; + ApplyText(go, txtProps, finalText); + // 旁挂回调: 通知外部 "这里还原出了一个可见文本节点" (供收集屏幕框导出 rect_locations) + if (_onTextBuilt != null) _onTextBuilt(go, finalText); + } + else if (objectData.TryGetValue("TMP", out var tmpObj) && tmpObj is Dictionary tmpTextProps) + { + string original = tmpTextProps.Get("textContent") ?? ""; + string finalText = _translationResolver != null ? _translationResolver(keyHash, original) : original; + ApplyTmp(go, tmpTextProps, finalText); + // TMP 键同样含 textContent, rect_locations 导出可正常收集其文本框 + if (_onTextBuilt != null) _onTextBuilt(go, finalText); + } + + // 项目专属组件后处理 (如 XxxxText 描边/阴影), 通过注册表注入, 核心不感知具体类型 + NodePostProcessors.ApplyAll(go, objectData); + + // 处理 activeSelf: 需要禁用的节点不立即关闭, 而是登记到延迟队列, + // 避免父节点提前禁用导致后续子节点无法正常挂载 + var goProps = objectData.Get>("GameObject"); + if (goProps != null && !goProps.GetInnerBool("activeSelf", true)) + { + var capturedGo = go; + _pendingDeactivations.Add(() => + { + if (capturedGo != null) capturedGo.SetActive(false); + }); + } + + // 递归子节点 + var children = nodeDict.Get>("ChildNodes"); + if (children != null) + { + foreach (var c in children) + { + if (c is Dictionary cd) + BuildTextNode(cd, go.transform); + } + } + } + + /// + /// 还原 Text 组件: 文本内容、字号、颜色、对齐、溢出、富文本、字体 + /// (项目专属特效如 XxxxText 描边/阴影不在此处理, 见 NodePostProcessors) + /// + /// 目标 GameObject, Text 组件将挂载在其上 + /// Text 组件的属性字典 + /// 最终显示文本 (已按翻译规则解析) + private void ApplyText(GameObject go, Dictionary txtProps, string overrideText) + { + var txt = go.AddComponent(); + + txt.text = overrideText ?? ""; + txt.fontSize = txtProps.GetInnerInt("fontSize", 14); + + // Line Spacing: 行间距倍率, 影响多行文本的行高, 不还原时多行文本行距会偏离原始效果 + txt.lineSpacing = txtProps.GetInnerFloat("lineSpacing", 1f); + + var color = txtProps.Get>("color"); + if (color != null) txt.color = ReadColor(color); + + // 枚举型属性: 用 Enum.TryParse 从字符串还原, 解析失败则保持组件默认值 + if (Enum.TryParse(txtProps.GetInnerString("alignment"), out var al)) + txt.alignment = al; + if (Enum.TryParse(txtProps.GetInnerString("fontStyle"), out var fs)) + txt.fontStyle = fs; + if (Enum.TryParse(txtProps.GetInnerString("horizontalOverflow"), out var hw)) + txt.horizontalOverflow = hw; + if (Enum.TryParse(txtProps.GetInnerString("verticalOverflow"), out var vw)) + txt.verticalOverflow = vw; + + // Best Fit: 自动缩放字号以适配文本框 + // 不还原会被强制按原始 fontSize 渲染, 在竖向偏紧的小框 (如角标数字框 43.5px / 字号 36) + // 里因 verticalOverflow=Truncate 被整行截掉 → 数字完全不显示 + bool bf = txtProps.GetInnerBool("bestFit"); + txt.resizeTextForBestFit = bf; + if (bf) + { + txt.resizeTextMinSize = txtProps.GetInnerInt("minSize", 10); + txt.resizeTextMaxSize = txtProps.GetInnerInt("maxSize", txt.fontSize); + } + + txt.supportRichText = txtProps.GetInnerBool("richText", true); + txt.raycastTarget = txtProps.GetInnerBool("raycastTarget", true); + + // 字体加载 + // 兼容 Android 采集: 真机运行时无 AssetDatabase, dump 里 font 只有 name, + // assetPath/guid 均为 null, 故在 assetPath 精确加载失败后按字体名在工程内反查 + var fontRef = txtProps.Get>("font"); + Font font = _fontResolver != null ? _fontResolver.Resolve(fontRef) : null; + // 逐级回退: 解析失败 → 运行时内置字体 → 旧版 Arial 内置字体, 确保文本始终可渲染 + if (font == null) font = Resources.GetBuiltinResource("LegacyRuntime.ttf"); + if (font == null) font = Resources.GetBuiltinResource("Arial.ttf"); + txt.font = font; + } + + /// + /// 还原 TMP 文本节点 + /// 策略: 还原工程安装了 TextMeshPro → 反射创建 TextMeshProUGUI 精确还原; + /// 未安装 → 用内置 UnityEngine.UI.Text 近似 (文本/字号/颜色/富文本), 保证截图与文本框仍可产出 + /// + private void ApplyTmp(GameObject go, Dictionary tmpProps, string overrideText) + { + Type tmpType = ResolveTmpType(); + + // 分支一: 工程装了 TMP, 反射还原 TextMeshProUGUI + if (tmpType != null) + { + var tmp = go.AddComponent(tmpType); + + SetProp(tmp, "text", overrideText ?? ""); + SetProp(tmp, "fontSize", tmpProps.GetInnerFloat("fontSize", 36f)); + + var color = tmpProps.Get>("color"); + if (color != null) SetProp(tmp, "color", ReadColor(color)); + + SetProp(tmp, "richText", tmpProps.GetInnerBool("richText", true)); + SetProp(tmp, "raycastTarget", tmpProps.GetInnerBool("raycastTarget", true)); + + bool autoSize = tmpProps.GetInnerBool("enableAutoSizing"); + SetProp(tmp, "enableAutoSizing", autoSize); + if (autoSize) + { + SetProp(tmp, "fontSizeMin", tmpProps.GetInnerFloat("fontSizeMin", 10f)); + SetProp(tmp, "fontSizeMax", tmpProps.GetInnerFloat("fontSizeMax", 72f)); + } + + // 枚举按名称解析后写入 (alignment / fontStyle / overflowMode) + SetEnumProp(tmp, "alignment", tmpProps.GetInnerString("alignment")); + SetEnumProp(tmp, "fontStyle", tmpProps.GetInnerString("fontStyle")); + SetEnumProp(tmp, "overflowMode", tmpProps.GetInnerString("overflowMode")); + + SetProp(tmp, "characterSpacing", tmpProps.GetInnerFloat("characterSpacing", 0f)); + SetProp(tmp, "wordSpacing", tmpProps.GetInnerFloat("wordSpacing", 0f)); + SetProp(tmp, "lineSpacing", tmpProps.GetInnerFloat("lineSpacing", 0f)); + SetProp(tmp, "paragraphSpacing", tmpProps.GetInnerFloat("paragraphSpacing", 0f)); + + // 字体资源不强制还原, 交由 TMP 默认字体渲染 (跨工程字体资源难以精确定位) + return; + } + + // 分支二: 未装 TMP, 用内置 Text 近似 + var txt = go.AddComponent(); + txt.text = overrideText ?? ""; + txt.fontSize = Mathf.RoundToInt(tmpProps.GetInnerFloat("fontSize", 36f)); + + var col = tmpProps.Get>("color"); + if (col != null) txt.color = ReadColor(col); + + txt.supportRichText = tmpProps.GetInnerBool("richText", true); + txt.raycastTarget = tmpProps.GetInnerBool("raycastTarget", true); + // TMP 默认不裁剪, 近似时统一放开溢出, 避免文字被 Truncate 掉 + txt.horizontalOverflow = HorizontalWrapMode.Overflow; + txt.verticalOverflow = VerticalWrapMode.Overflow; + + Font font = Resources.GetBuiltinResource("LegacyRuntime.ttf"); + if (font == null) font = Resources.GetBuiltinResource("Arial.ttf"); + txt.font = font; + } + + // TMP 类型解析缓存 (未安装 TMP 时恒为 null) + private static Type _tmpTypeCache; + private static bool _tmpTypeResolved; + + /// + /// 解析 TMPro.TextMeshProUGUI 类型 (遍历已加载程序集), 未安装 TMP 时返回 null + /// + private static Type ResolveTmpType() + { + if (_tmpTypeResolved) return _tmpTypeCache; + _tmpTypeResolved = true; + foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) + { + var t = asm.GetType("TMPro.TextMeshProUGUI"); + if (t != null) { _tmpTypeCache = t; break; } + } + return _tmpTypeCache; + } + + /// + /// 反射写公开实例属性 (属性不存在/只读/类型不匹配时静默跳过) + /// + private static void SetProp(Component comp, string propName, object value) + { + if (comp == null) return; + var p = comp.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.Instance); + if (p == null || !p.CanWrite) return; + try { p.SetValue(comp, value, null); } catch { } + } + + /// + /// 反射把字符串按属性的枚举类型解析后写入 (解析失败静默跳过) + /// + private static void SetEnumProp(Component comp, string propName, string enumName) + { + if (comp == null || string.IsNullOrEmpty(enumName)) return; + var p = comp.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.Instance); + if (p == null || !p.CanWrite || !p.PropertyType.IsEnum) return; + try { p.SetValue(comp, Enum.Parse(p.PropertyType, enumName), null); } catch { } + } + + /// + /// 还原 Canvas 与 CanvasScaler 属性 + /// 注意: 渲染模式被强制改为 ScreenSpaceOverlay (见方法内注释), 其余排序/缩放属性照常还原 + /// + /// 目标 Canvas 组件 + /// 目标 CanvasScaler 组件 + /// 当前节点的 ObjectData, 从中读取 Canvas / CanvasScaler 子字典 + private void ApplyCanvas(Canvas canvas, CanvasScaler scaler, Dictionary data) + { + var canvasProps = data.Get>("Canvas"); + if (canvasProps != null) + { + // 还原是 "把 UI 平铺到截图之上" 的 2D 合成场景, 没有原始 UI 相机, + // Camera/World 模式都无法正确贴屏渲染, 统一退化为 Overlay + // sortingOrder / overrideSorting 仍照常还原, 排序行为不受影响 + canvas.renderMode = RenderMode.ScreenSpaceOverlay; + + canvas.sortingOrder = canvasProps.GetInnerInt("sortingOrder", 0); + + canvas.pixelPerfect = canvasProps.GetInnerBool("pixelPerfect"); + canvas.overrideSorting = canvasProps.GetInnerBool("overrideSorting"); + + string sln = canvasProps.GetInnerString("sortingLayerName"); + if (!string.IsNullOrEmpty(sln)) + canvas.sortingLayerName = sln; + } + + var scalerProps = data.Get>("CanvasScaler"); + if (scalerProps != null) + { + if (Enum.TryParse(scalerProps.GetInnerString("uiScaleMode"), out var sm)) + scaler.uiScaleMode = sm; + + var refRes = scalerProps.Get>("referenceResolution"); + if (refRes != null) + scaler.referenceResolution = new Vector2( + refRes.GetInnerFloat("x", 1920), + refRes.GetInnerFloat("y", 1080)); + + if (Enum.TryParse(scalerProps.GetInnerString("screenMatchMode"), out var smm)) + scaler.screenMatchMode = smm; + + scaler.matchWidthOrHeight = scalerProps.GetInnerFloat("matchWidthOrHeight", 0.5f); + scaler.referencePixelsPerUnit = scalerProps.GetInnerFloat("referencePixelsPerUnit", 100f); + } + } + + /// + /// 还原 RectTransform 布局属性 (锚点/轴心/尺寸/位置) 以及 Transform 的缩放与旋转 + /// + /// 目标 RectTransform 组件 + /// 当前节点的 ObjectData, 从中读取 RectTransform / Transform / Canvas 子字典 + private void ApplyRect(RectTransform rt, Dictionary data) + { + var rtProps = data.Get>("RectTransform"); + if (rtProps != null) + { + var aMin = rtProps.Get>("anchorMin"); + if (aMin != null) rt.anchorMin = new Vector2(aMin.GetInnerFloat("x"), aMin.GetInnerFloat("y")); + + var aMax = rtProps.Get>("anchorMax"); + if (aMax != null) rt.anchorMax = new Vector2(aMax.GetInnerFloat("x"), aMax.GetInnerFloat("y")); + + var pivot = rtProps.Get>("pivot"); + if (pivot != null) rt.pivot = new Vector2(pivot.GetInnerFloat("x"), pivot.GetInnerFloat("y")); + + var sizeDelta = rtProps.Get>("sizeDelta"); + if (sizeDelta != null) + rt.sizeDelta = new Vector2(sizeDelta.GetInnerFloat("x", 100), sizeDelta.GetInnerFloat("y", 100)); + + var anchoredPos = rtProps.Get>("anchoredPosition"); + if (anchoredPos != null) + rt.anchoredPosition = new Vector2(anchoredPos.GetInnerFloat("x", 0), anchoredPos.GetInnerFloat("y", 0)); + } + + var tProps = data.Get>("Transform"); + if (tProps != null) + { + // 仅跳过 "根 Canvas" 的 localScale (如根画布 0.029, 是配合 UI 相机距离的补偿, + // Overlay 还原时由 Unity 重新驱动) + // 嵌套子 Canvas (isRootCanvas=false) 的 localScale 是设计者真实设置的布局缩放, + // 必须保留, 否则父节点施加的放大 (如 UITRCardItem 的 2.02) 得不到子画布 0.41 的回缩, + // 整棵子树被放大 ~2.44 倍 (典型现象: 中央卡片 "赵云" 等文本明显过大) + bool isRootCanvas = false; + var canvasProps = data.Get>("Canvas"); + if (canvasProps != null) + isRootCanvas = canvasProps.GetInnerBool("isRootCanvas"); + + if (!isRootCanvas) + { + var scale = tProps.Get>("localScale"); + if (scale != null) + rt.localScale = new Vector3(scale.GetInnerFloat("x", 1), scale.GetInnerFloat("y", 1), scale.GetInnerFloat("z", 1)); + } + + var euler = tProps.Get>("localEulerAngles"); + if (euler != null) + rt.localEulerAngles = new Vector3(euler.GetInnerFloat("x"), euler.GetInnerFloat("y"), euler.GetInnerFloat("z")); + } + } + + /// + /// 从颜色字典读取 Color, 缺省通道按不透明白 (r=g=b=a=1) 填充 + /// + /// 含 r/g/b/a 分量的字典, 为 null 时返回 Color.white + /// 还原后的 Color + private Color ReadColor(Dictionary d) + { + if (d == null) return Color.white; + return new Color( + d.GetInnerFloat("r", 1), d.GetInnerFloat("g", 1), + d.GetInnerFloat("b", 1), d.GetInnerFloat("a", 1)); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TranslationTable.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TranslationTable.cs new file mode 100644 index 0000000000000000000000000000000000000000..92b883f9c0dddbfdb4c6d4a7d504c4916bd6e309 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Core/Runtime/TranslationTable.cs @@ -0,0 +1,119 @@ +// ========================================== +// 文件: LQARestore\Core\Runtime\TranslationTable.cs +// 模块: Core (核心层) +// ========================================== + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using LQARestore.Core.Json; + +/// +/// LQARestore 核心层命名空间 +/// +namespace LQARestore.Core +{ + /// + /// 翻译表: 加载 i18n_translation_xx.json (示例), 按 keyHash / original 为还原文本提供译文 + /// 判定顺序 (Resolve): + /// 1. 有 keyHash 且 entries 命中且其 translation 非空 → 用该 translation; + /// 2. 否则用 textContent 完全匹配所有 entries.original 相等的条目, 收集其 translation 为候选; + /// 3. 候选取 translation 最长者 (长度相同取靠后遍历到的), 非空则用之; + /// 4. 仍为空 → 回退显示原始 textContent 字符串; + /// + public class TranslationTable + { + /// + /// keyHash → 该条目字典 (含 original / translation), 供规则 1 的 O(1) 命中 + /// + private readonly Dictionary> _byKeyHash; + + /// + /// original → 该原文对应的所有 translation (按文件出现顺序), 供规则 2/3 的候选匹配 + /// + private readonly Dictionary> _byOriginal; + + private TranslationTable( + Dictionary> byKeyHash, + Dictionary> byOriginal) + { + _byKeyHash = byKeyHash; + _byOriginal = byOriginal; + } + + /// + /// 从 i18n_translation_xx.json (示例) 加载翻译表; 路径无效或解析失败时返回 null (仅告警, 不抛异常) + /// + /// i18n_translation_xx.json (示例) 的完整路径 + /// 加载成功的翻译表, 失败返回 null (调用方据此回退到原文还原) + public static TranslationTable Load(string path) + { + if (string.IsNullOrEmpty(path) || !File.Exists(path)) return null; + try + { + var root = MiniJson.Parse(File.ReadAllText(path)) as Dictionary; + var entries = root.Get>("entries"); + if (entries == null) throw new Exception("缺少 entries 字段"); + + var byKeyHash = new Dictionary>(); + var byOriginal = new Dictionary>(); + foreach (var kv in entries) + { + if (!(kv.Value is Dictionary entry)) continue; + byKeyHash[kv.Key] = entry; + + // original 缺失的条目无法参与原文匹配, 跳过其 original 索引 (仍保留 keyHash 索引) + string original = entry.Get("original"); + if (original == null) continue; + string translation = entry.Get("translation") ?? ""; + if (!byOriginal.TryGetValue(original, out var list)) + { + list = new List(); + byOriginal[original] = list; + } + list.Add(translation); + } + Debug.Log($"[LQARestore][TranslationTable] 已加载翻译表: {path} (entries={byKeyHash.Count})"); + return new TranslationTable(byKeyHash, byOriginal); + } + catch (Exception e) + { + Debug.LogWarning($"[LQARestore][TranslationTable] 加载失败: {path}, {e.Message}"); + return null; + } + } + + /// + /// 解析最终文本 (判定顺序见类注释) + /// + /// 节点 XxxxLocalize.keyHash, 无则传空 + /// 节点 Text/TMP.textContent (兜底文本) + /// 最终用于还原/导出的文本 + public string Resolve(string keyHash, string textContent) + { + // 1. keyHash 命中且译文非空 → 直接用; 命中但译文为空则继续往下走候选匹配 + if (!string.IsNullOrEmpty(keyHash) && _byKeyHash.TryGetValue(keyHash, out var entry)) + { + string t = entry.Get("translation"); + if (!string.IsNullOrEmpty(t)) return t; + } + + // 2/3. textContent 完全匹配 original 收集候选, 取最长译文 (等长取靠后); textContent 为空则跳过 + if (!string.IsNullOrEmpty(textContent) && _byOriginal.TryGetValue(textContent, out var candidates)) + { + string best = null; + foreach (var t in candidates) + { + if (string.IsNullOrEmpty(t)) continue; + // >= 保证长度相同时后遍历到的覆盖前者 + if (best == null || t.Length >= best.Length) best = t; + } + if (!string.IsNullOrEmpty(best)) return best; + } + + // 4. 兜底: 显示原始 textContent + return textContent ?? ""; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQADumpDelayWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQADumpDelayWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..9ac06fad33327ffccccfcc99dd168459449c3a7f --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQADumpDelayWindow.cs @@ -0,0 +1,79 @@ +// ========================================== +// 文件: LQARestore\Entry\Editor\LQADumpDelayWindow.cs +// 模块: Entry.Editor (入口层 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 入口层 编辑器侧命名空间 +/// +namespace LQARestore.Entry.Editor +{ + /// + /// "LQA Dump 延时设置" 编辑器窗口 + /// 职责: 提供一个可视化界面, 用于设置 "执行 Dump 前等待的延时秒数", + /// 由菜单 "Tools/LQA/Set Dump Delay Seconds..." (见 LQARestoreMenu) 打开 + /// 配置链路: 本窗口把用户输入的秒数写入 PlayerPrefs (Key: LQA_DumpDelaySeconds), + /// 运行时由 LQATool.Core.LQAToolManager.HandleDumpRequest 读取该值并决定 Dump 前等待多久, + /// 因此这里的 Key 必须与 LQAToolManager.DumpDelayPrefsKey 保持一致 + /// + public class LQADumpDelayWindow : EditorWindow + { + /// + /// PlayerPrefs 中保存 "Dump 前延时秒数" 的 Key + /// 注意: 必须与运行时 LQATool.Core.LQAToolManager.DumpDelayPrefsKey 完全一致, + /// 否则本窗口写入的配置不会被 Dump 流程读到 + /// + public const string KEY_DUMP_DELAY_SECONDS = "LQA_DumpDelaySeconds"; + + /// + /// 窗口内当前编辑的延时秒数 (单位: 秒) + /// 打开窗口时从 PlayerPrefs 读取初始化, 保存时回写到 PlayerPrefs + /// + private int _delaySeconds; + + /// + /// 打开窗口的静态入口 (供 LQARestoreMenu 的菜单项调用) + /// 创建 (或聚焦) 一个 "LQA Dump 延时设置" 工具窗口, + /// 并用 PlayerPrefs 中已保存的延时值初始化界面, 再固定窗口尺寸 + /// + public static void Open() + { + // 获取一个工具窗口实例 (utility = true 表示浮动工具窗, 不可停靠到主编辑器布局) + var win = GetWindow(true, "LQA Dump 延时设置"); + // 读取已持久化的延时值作为初始显示 (缺省 0, 表示立即 Dump) + win._delaySeconds = PlayerPrefs.GetInt(KEY_DUMP_DELAY_SECONDS, 0); + // 固定窗口尺寸 300 x 100 并居中, 避免内容简单却可随意拉伸 + LqaWindowLayout.ApplyFixedCentered(win, 300, 100); + } + + /// + /// Unity EditorWindow 的 IMGUI 绘制回调, 每次界面刷新时被调用 + /// 负责绘制 "延时秒数" 输入区与 "保存" 按钮, 并处理保存逻辑 + /// + private void OnGUI() + { + // 说明性标签: 向用户解释该配置的含义 (0 表示不等待, 直接 Dump) + EditorGUILayout.LabelField("Dump 前延时秒数 (0 = 立即 Dump)"); + // 整数输入框; 用 Mathf.Max 把下限钳制为 0, 防止配置出负数延时 + _delaySeconds = Mathf.Max(0, EditorGUILayout.IntField("延时秒数", _delaySeconds)); + // 在输入区与按钮之间留出一段垂直间距, 让布局更清晰 + EditorGUILayout.Space(); + // 点击 "保存" 后, 把当前值写回 PlayerPrefs 并持久化 + if (GUILayout.Button("保存")) + { + // 写入延时配置 + PlayerPrefs.SetInt(KEY_DUMP_DELAY_SECONDS, _delaySeconds); + // 立即落盘, 确保配置在编辑器意外退出时也不会丢失 + PlayerPrefs.Save(); + // 打印一条日志, 便于在 Console 中确认配置已生效 (附带 Key 便于排查) + Debug.Log($"[LQARestore][LQADumpDelayWindow] Dump 延时已设置为 {_delaySeconds} 秒 (LQA_DumpDelaySeconds)"); + // 保存成功后关闭窗口 + Close(); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQAResetMenu.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQAResetMenu.cs new file mode 100644 index 0000000000000000000000000000000000000000..d34c18be720a17e19870049b7c9e80f5a07cf3ce --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQAResetMenu.cs @@ -0,0 +1,90 @@ +// ========================================== +// 文件: LQARestore\Entry\Editor\LQAResetMenu.cs +// 模块: Entry.Editor (入口层 编辑器侧) +// ========================================== + +using System; +using UnityEditor; +using UnityEngine; +using LQARestore.Platform.Editor; +using LQARestore.Core.Editor; + +/// +/// LQARestore 入口层 编辑器侧命名空间 +/// +namespace LQARestore.Entry.Editor +{ + /// + /// LQA "恢复默认设置" 菜单入口 + /// 职责: 一键清空本插件写入的全部持久化配置 (EditorPrefs + PlayerPrefs), + /// 使所有配置回落到各 config 类 Load() 时的默认值, 并关闭已打开的 LQA 窗口。 + /// + public static class LQAResetMenu + { + /// + /// 菜单项: Tools/LQA/恢复默认设置... (priority 900) + /// 与平台组 (300+) 相差远大于 10, Unity 会在其上方自动绘制分隔线, 使其靠底部并与上方分组隔开 + /// + [MenuItem("Tools/LQA/恢复默认设置...", false, 900)] + private static void ResetAllToDefault() + { + // 1. 二次确认: 该操作不可撤销 + bool ok = EditorUtility.DisplayDialog( + "LQA 恢复默认设置", + "将清空 LQA 插件的全部配置 (平台连接/项目/任务/筛选/上传/提交/译文/字体变体、" + + "采集开关、Dump 延时), 并关闭已打开的 LQA 窗口\n\n此操作不可撤销, 是否继续?", + "恢复默认", "取消"); + if (!ok) return; + + // 2. 删除 EditorPrefs 配置 (16 个): 删除后各 config.Load() 会回落到默认值 + EditorPrefs.DeleteKey(LqaPlatformConfig.KEY_HOST); + EditorPrefs.DeleteKey(LqaPlatformConfig.KEY_AUTH); + EditorPrefs.DeleteKey(LqaPlatformConfig.KEY_API_PATH); + EditorPrefs.DeleteKey(LqaPlatformConfig.KEY_DOWNLOAD_PATH); + EditorPrefs.DeleteKey(LqaProjectConfig.KEY_PROJECT_ID); + EditorPrefs.DeleteKey(LqaJobConfig.KEY_JOB_ID); + EditorPrefs.DeleteKey(LqaFilterConfig.KEY_LANGUAGE); + EditorPrefs.DeleteKey(LqaFilterConfig.KEY_COUNT); + EditorPrefs.DeleteKey(LqaFilterConfig.KEY_MIN_ID); + EditorPrefs.DeleteKey(LqaFilterConfig.KEY_MODULE_IDS); + EditorPrefs.DeleteKey(LqaUploadConfig.KEY_MODULE_ID); + EditorPrefs.DeleteKey(LqaUploadConfig.KEY_RESOURCE_VERSION); + EditorPrefs.DeleteKey(LqaSubmitConfig.KEY_TRIGGER_AI); + EditorPrefs.DeleteKey(LqaTranslationConfig.KEY_TRANSLATION_PATH); + EditorPrefs.DeleteKey(LqaFontVariantConfig.KEY_FONT_VARIANT_TEMPLATE); + + // 3. 删除 PlayerPrefs 配置 (2 个) 并立即落盘 + PlayerPrefs.DeleteKey(LQARestoreMenu.KEY_SHOW_DUMP_AND_GET_BTN); + PlayerPrefs.DeleteKey(LQADumpDelayWindow.KEY_DUMP_DELAY_SECONDS); + PlayerPrefs.Save(); + + // 4. 采集开关回默认 (关闭): 让当前 Play 会话立即生效, 与删除 key 后的缺省 0 保持一致 + try + { + LQATool.Core.LQATool.SetEnable(false); + } + catch (Exception ex) + { + // 调用失败仅告警不中断 (例如 LQATool 程序集缺失或未编译时) + Debug.LogWarning($"[LQARestore][LQAResetMenu] 调用 LQATool.SetEnable 失败: {ex.Message}"); + } + + // 5. 关闭所有已打开的 LQA 窗口 (命名空间以 LQARestore 开头, 覆盖平台/核心/入口三组窗口) + int closed = 0; + foreach (var w in Resources.FindObjectsOfTypeAll()) + { + if (w == null) continue; + var ns = w.GetType().Namespace; + if (ns != null && ns.StartsWith("LQARestore")) + { + w.Close(); + closed++; + } + } + + // 6. 输出结果日志与完成提示 + Debug.Log($"[LQARestore][LQAResetMenu] 已恢复默认设置: 清除 EditorPrefs 14 项 + PlayerPrefs 2 项, 关闭窗口 {closed} 个"); + EditorUtility.DisplayDialog("LQA 恢复默认设置", "已恢复默认设置", "OK"); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQARestoreMenu.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQARestoreMenu.cs new file mode 100644 index 0000000000000000000000000000000000000000..9a8bfb951051ebecc3f057234bbdcd7eff9207e3 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQARestoreMenu.cs @@ -0,0 +1,149 @@ +// ========================================== +// 文件: LQARestore\Entry\Editor\LQARestoreMenu.cs +// 模块: Entry.Editor (入口层 编辑器侧) +// ========================================== + +using System; +using System.IO; +using UnityEditor; +using UnityEngine; +using LQARestore.Core; +using LQARestore.Core.Editor; + +/// +/// LQARestore 入口层 编辑器侧命名空间 +/// +namespace LQARestore.Entry.Editor +{ + /// + /// LQARestore 插件在 Unity 编辑器菜单栏 (Tools/LQA) 下的统一入口 + /// 职责: 通过 [MenuItem] 特性注册菜单项, 把编辑器里的常用操作 "挂" 到菜单上: + /// 1. Tools/LQA/采集/启用 LQA 采集工具 —— 切换 LQATool 采集工具的总开关 (写 PlayerPrefs 并立即生效) + /// 2. Tools/LQA/还原/从 Dump 文件还原 —— 选择一份 dump 的 JSON, 触发文本画面还原 (按译文配置决定原文/译文) + /// 3. Tools/LQA/采集/设置 Dump 延时秒数... —— 打开 "Dump 前延时" 设置窗口 + /// 4. Tools/LQA/还原/文本显隐标记... —— 打开 "文本显隐标记" 窗口, 搜索/标记文本显示与否并写回 JSON + /// 5. Tools/LQA/还原/译文文件配置... —— 设置并持久化 i18n 译文文件路径, 供还原/自动化按译文重建文本 + /// 设计要点: 本类只做 "菜单入口 + 参数编排" 这类轻量工作, 真正逻辑分别委托给 + /// LQATool.Core.LQATool.SetEnable / LQADumpDelayWindow / RestoreEngine / LQATextShowWindow, 保持入口层薄而清晰 + /// + public static class LQARestoreMenu + { + /// + /// PlayerPrefs 中保存 "LQATool 启用开关" 的 Key (值: 1 = 启用, 0 = 禁用) + /// 注意: 必须与运行时 LQATool.Core.LQATool.AutoInit 读取的 Key 完全一致, + /// 否则本菜单写入的开关不会被采集工具的自动初始化逻辑读到 + /// + public const string KEY_SHOW_DUMP_AND_GET_BTN = "LQA_ShowDumpAndGetNodeButtons"; + + /// + /// 菜单项: Tools/LQA/采集/启用 LQA 采集工具 (priority 100, 数值越小越靠前, 故排在该子菜单最前) + /// 点击后翻转 LQATool 的启用状态: 1 -> 0 或 0 -> 1, + /// 先写回 PlayerPrefs 持久化, 再调用 LQATool.SetEnable 让当前 Play 会话立即生效 + /// + [MenuItem("Tools/LQA/采集/启用 LQA 采集工具", false, 100)] + private static void ToggleDumpButtons() + { + // 1. 读取当前开关值 (缺省 0, 即首次进入时默认按 "未启用" 处理, 与采集工具运行时缺省保持一致) + int cur = PlayerPrefs.GetInt(KEY_SHOW_DUMP_AND_GET_BTN, 0); + // 2. 翻转状态 (1 <-> 0) + int next = cur == 1 ? 0 : 1; + bool enable = (next == 1); + + // 3. 把新状态写回 PlayerPrefs 并立即落盘, 保证重启编辑器后仍生效 + PlayerPrefs.SetInt(KEY_SHOW_DUMP_AND_GET_BTN, next); + PlayerPrefs.Save(); + + // 4. 让开关在运行时立即生效 + // LQATool.Core.LQATool 是采集工具插件的静态入口 (采用全限定名以明确归属); + // 其 SetEnable 通过启用/禁用管理器对象实现整体开关 + try + { + LQATool.Core.LQATool.SetEnable(enable); + } + catch (Exception ex) + { + // 调用失败仅告警不中断 (例如 LQATool 程序集缺失或未编译时), 避免编辑器抛异常 + Debug.LogWarning($"[LQARestore][LQARestoreMenu] 调用 LQATool.SetEnable 失败: {ex.Message}"); + } + + // 5. 输出结果日志, 便于在 Console 中确认开关已切换且已持久化 + Debug.Log($"[LQARestore][LQARestoreMenu] LQATool {(enable ? "已启用" : "已禁用")} (已持久化, 且当前 Play 会话立即生效)"); + } + + /// + /// 菜单项校验方法 (validate function): 对应 "Enable LQA Tool" 菜单项 + /// 由 Unity 在菜单显示前调用, 用于控制菜单项的可用性与勾选显示: + /// - Menu.SetChecked 让该菜单项前显示/取消对勾, 直观反映当前开关状态; + /// - 返回 true 表示该菜单项始终可点击 + /// + /// 恒为 true (菜单项始终可用) + [MenuItem("Tools/LQA/采集/启用 LQA 采集工具", true)] + private static bool ToggleDumpButtons_Validate() + { + // 根据 PlayerPrefs 中的开关值决定是否在菜单项前显示对勾 (缺省 0 = 不勾选, 与采集工具运行时缺省保持一致) + Menu.SetChecked("Tools/LQA/采集/启用 LQA 采集工具", PlayerPrefs.GetInt(KEY_SHOW_DUMP_AND_GET_BTN, 0) == 1); + return true; + } + + /// + /// 菜单项: Tools/LQA/还原/从 Dump 文件还原 (priority 200) + /// 让用户选择一个 dump 的 JSON 描述文件, 然后启动一次文本画面还原 + /// 流程: 弹出文件选择框 -> 校验所选文件 -> 读取持久化的译文文件配置 (LqaTranslationConfig) + /// -> 读取持久化的字体变体模板 (LqaFontVariantConfig) + /// -> 组装编辑器实现的两个依赖 (EditorFontResolver 字体解析 + EditorSceneHost 场景宿主) + /// -> 交给 RestoreEngine 执行还原 + /// (译文路径为空/失效时按原文还原; 字体变体模板为空时字体按 dump 原样还原) + /// + [MenuItem("Tools/LQA/还原/从 Dump 文件还原", false, 200)] + private static void RestoreFromDumpFile() + { + // 1. 弹出文件选择框, 限定只显示 json 文件; 用户取消时返回空字符串 + string jsonPath = EditorUtility.OpenFilePanel("选择 Dump 的 ui_data_text.json", "", "json"); + // 2. 未选择文件: 直接返回, 不做任何处理 + if (string.IsNullOrEmpty(jsonPath)) return; + // 3. 防御性校验: 所选路径不存在时弹窗提示 (正常情况下 OpenFilePanel 不会返回不存在文件) + if (!File.Exists(jsonPath)) + { + EditorUtility.DisplayDialog("LQA Restore", "文件不存在", "OK"); + return; + } + + // 4. 读取持久化的译文文件配置 (在 Tools/LQA/还原/译文文件配置... 中一次设置, 长期复用): + // 配了有效路径 → 按译文还原; 未配置或路径已失效 → 传 null, 回退原文还原 + string translationPath = LqaTranslationConfig.GetPath(); + if (!string.IsNullOrEmpty(translationPath) && !File.Exists(translationPath)) + { + Debug.LogWarning($"[LQARestore][LQARestoreMenu] 配置的译文文件不存在, 本次将用原文还原: {translationPath}"); + translationPath = null; + } + + // 5. 读取持久化的字体变体模板 (在 Tools/LQA/还原/字体变体配置... 中设置): + // 含 {name} 时还原会把字体名改写为变体 (工程内找不到则回退原字体); 空则字体按 dump 原样还原 + string fontVariantTemplate = LqaFontVariantConfig.GetTemplate(); + + // 6. 组装编辑器环境下的两个依赖并创建还原引擎: + // - EditorFontResolver: 负责把 dump 里的字体引用解析为工程内真实 Font + // - EditorSceneHost: 负责新建场景 / 对齐分辨率 / 截图输出 / 标记脏 + var engine = new RestoreEngine(new EditorFontResolver(), new EditorSceneHost()); + // 7. 执行还原主流程 (译文路径为空时即原文还原) + engine.RestoreFromDump(jsonPath, translationPath, fontVariantTemplate); + } + + /// + /// 菜单项: Tools/LQA/采集/设置 Dump 延时秒数... (priority 101) + /// 打开 "LQA Dump 延时设置" 窗口, 供用户配置 Dump 前等待的秒数 + /// 逻辑全部委托给 LQADumpDelayWindow.Open (详见该窗口的配置链路说明) + /// + [MenuItem("Tools/LQA/采集/设置 Dump 延时秒数...", false, 101)] + private static void SetDumpDelaySeconds() => LQADumpDelayWindow.Open(); + + /// + /// 菜单项: Tools/LQA/还原/文本显隐标记... (priority 201) + /// 打开 "文本显隐标记" 窗口: 搜索/显示当前 dump JSON 里的文本 (name + textContent + isVisuallyVisible), + /// 对每条文本用 "显示" 勾选决定还原时是否显示, 并把 manualShow 写回 JSON; + /// 还原时: 有 manualShow 则以其为准, 无则回退 isVisuallyVisible + /// + [MenuItem("Tools/LQA/还原/文本显隐标记...", false, 201)] + private static void OpenTextManualShow() => LQATextShowWindow.Open(); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQATextShowWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQATextShowWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..b70711dbc94857571ca858b0d117424d7c402d61 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Entry/Editor/LQATextShowWindow.cs @@ -0,0 +1,380 @@ +// ========================================== +// 文件: LQARestore\Entry\Editor\LQATextShowWindow.cs +// 模块: Entry.Editor (入口层 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Json; +using LQARestore.Core.Editor; + +/// +/// LQARestore 入口层 编辑器侧命名空间 +/// +namespace LQARestore.Entry.Editor +{ + /// + /// "文本显隐标记" 编辑器窗口 + /// 职责: + /// 1. 让用户独立选择一份 dump 的 ui_data_text.json, 解析后平铺列出其中所有含文本的节点 + /// (每行展示: 显示勾选 / 原始判定 / name / textContent); + /// 2. 提供关键字搜索, 按 name 或 textContent 实时过滤列表; + /// 3. 对每条文本用 "显示" 勾选框决定还原时是否显示, 保存时把 manualShow 写回对应节点并回写原 JSON; + /// 语义 (与还原侧约定一致): + /// - manualShow = true 表示还原时显示该文本; + /// - manualShow = false 表示还原时不重建该节点 (隐藏); + /// - 某条文本尚无 manualShow 字段时, 勾选状态默认取其自身的 isVisuallyVisible (显示语义一致), + /// 保存后即为该文本补上 manualShow 字段; + /// 还原侧 (LQARestore.Core.TextNodeBuilder): 节点有 manualShow 则以其为准, 无则回退 isVisuallyVisible + /// 设计要点: + /// - 本窗口直接持有 MiniJson 解析出的节点字典引用 (TextEntry.nodeDict), 标记就地写在字典上, + /// 无需靠 name/path 二次查找, 保存时整棵树用 JsonWriter 重新序列化回写, 天然精确; + /// - textContent 常含换行 (\n) 或超长富文本, 直接用单行 Label 会重叠/溢出, + /// 故列表统一折成 "单行预览" (换行 -> ↵, 超长截断 + 省略号), 并以固定单行高度 + 裁剪样式绘制, + /// 预览串在加载时预计算并缓存 (见 TextEntry.preview), 避免 OnGUI 每帧重算; 完整原文通过悬停 Tooltip 查看 + /// + public class LQATextShowWindow : EditorWindow + { + /// + /// 平铺后的单条文本记录 + /// 关键点: nodeDict 直接持有 MiniJson 解析出的节点字典引用, 保存时就地写标记 (无需按 name/path 反查) + /// + private class TextEntry + { + /// + /// 节点 GameObject 名称 (对应 JSON 节点的 name 字段) + /// + public string name; + + /// + /// 文本完整原文 (对应 ObjectData.Text.textContent), 用于 Tooltip 展示与搜索匹配 + /// + public string textContent; + + /// + /// 预计算的单行预览串 (换行折成 ↵ / 超长截断) + /// 在加载 (Collect) 时算一次并缓存, 供 OnGUI 每帧直接使用, 避免每帧重复 Replace/Substring 产生临时字符串 + /// + public string preview; + + /// + /// 采集侧的像素可见性判定结果 (对应 ObjectData.Text.isVisuallyVisible) + /// 只读, 作为 "原始判定" 列展示; 采集侧缓存无记录时保守判为不可见 (false) + /// + public bool isVisuallyVisible; + + /// + /// 该节点在解析对象树中的字典引用 (manualShow 标记直接写在其根层) + /// + public Dictionary nodeDict; + + /// + /// 当前 "显示" 勾选状态 (true = 还原时显示该文本) + /// + public bool manualShow; + } + + /// + /// 当前已打开的 JSON 文件完整路径 (保存时回写至此); 未加载时为 null + /// + private string _jsonPath; + + /// + /// MiniJson 解析出的 JSON 根对象 (通常为 Dictionary) + /// 保存时对其整棵树做序列化回写; 为 null 表示尚未成功加载 + /// + private object _root; + + /// + /// 平铺后的全部文本记录 (只读字段, 内容通过 Clear/Add 复用同一实例) + /// + private readonly List _entries = new List(); + + /// + /// 搜索关键字 (为空时不过滤) + /// + private string _search = ""; + + /// + /// 列表区域的滚动位置 + /// + private Vector2 _scroll; + + /// + /// 单行、末尾裁剪 (TextClipping.Clip) 的标签样式 + /// GUIStyle 不能在构造期/序列化期创建, 故懒初始化于 OnGUI 首次绘制时 + /// + private GUIStyle _ellipsisStyle; + + /// + /// 打开窗口的静态入口 (供 LQARestoreMenu 的菜单项 "文本显隐标记..." 调用) + /// 获取 (或聚焦) 一个工具窗口, 设置最小尺寸, 立即弹出文件选择框加载 JSON, 再显示窗口 + /// + public static void Open() + { + // utility = true 表示浮动工具窗 (不可停靠); 第三个参数 focus = true 打开即获得焦点 + var win = GetWindow(true, "LQA 文本显隐标记", true); + // 固定尺寸 620 x 400 并居中: 保证 4 列 (显示/原始判定/name/textContent) 有足够展开空间 + LqaWindowLayout.ApplyFixedCentered(win, 900, 600); + // 打开即引导用户选文件加载 + win.PickAndLoad(); + win.Show(); + } + + /// + /// 弹出文件选择框选取 JSON, 选中后触发解析与平铺 + /// 用户取消选择 (返回空路径) 时静默返回, 不做任何处理 + /// + private void PickAndLoad() + { + // 限定只显示 json 文件; 用户取消时 OpenFilePanel 返回空字符串 + string path = EditorUtility.OpenFilePanel("选择 Dump 的 ui_data_text.json", "", "json"); + if (string.IsNullOrEmpty(path)) return; + LoadJson(path); + } + + /// + /// 读取并解析指定路径的 JSON, 递归收集所有含 Text.textContent 的节点到 _entries + /// 整个过程包裹在 try/catch 中: 任何解析异常都不让编辑器崩溃, 仅弹窗告知并把状态复位 + /// + /// 待加载的 JSON 文件完整路径 + private void LoadJson(string path) + { + // 先清空上一次的加载状态, 保证本次从干净状态开始 (失败时也不残留旧数据) + _entries.Clear(); + _root = null; + _jsonPath = null; + + // 防御性校验: 文件不存在直接弹窗返回 (正常情况下 OpenFilePanel 不会返回不存在的文件) + if (!File.Exists(path)) + { + EditorUtility.DisplayDialog("LQA 文本显隐标记", "文件不存在", "OK"); + return; + } + + try + { + // 解析 JSON, 根必须是一个对象 (字典), 否则视为格式错误 + _root = MiniJson.Parse(File.ReadAllText(path)); + var rootDict = _root as Dictionary; + if (rootDict == null) throw new System.Exception("JSON 根不是对象"); + + // 遍历顶层 nodes 数组, 逐个作为根递归收集含文本的节点 + var nodes = rootDict.Get>("nodes"); + if (nodes != null) + { + foreach (var n in nodes) + if (n is Dictionary nodeDict) + Collect(nodeDict); + } + + // 逐条处理: 缺失 manualShow 的文本, 勾选状态默认取其自身 isVisuallyVisible + // (已在 Collect 中通过 GetInnerBool("manualShow", vis) 完成, 此处无需额外收尾; + // 最终落盘时 Save 会为每个文本都写入 manualShow) + + // 全部成功后才记录路径, 保证 _jsonPath 与 _root/_entries 状态一致 + _jsonPath = path; + Debug.Log($"[LQARestore][LQATextShowWindow] 已加载 {_entries.Count} 条文本, 来源: {path}"); + } + catch (System.Exception e) + { + // 解析失败: 记录错误 + 弹窗提示, 并把 _root 复位为 null (界面回到 "未加载" 态) + Debug.LogError($"[LQARestore][LQATextShowWindow] 解析失败: {e.Message}"); + EditorUtility.DisplayDialog("LQA 文本显隐标记", $"解析失败: {e.Message}", "OK"); + _root = null; + } + } + + /// + /// 递归遍历节点树, 把含 Text.textContent 的节点收集为 TextEntry 加入 _entries + /// 收集时顺带预计算单行预览串并读取 manualShow 初值, 避免后续在绘制期重复计算 + /// + /// 当前节点的字典数据 (含 ObjectData / ChildNodes 等) + private void Collect(Dictionary nodeDict) + { + // 只有存在 ObjectData 下 Text/TMP 的 textContent 的节点才是 "文本节点", 才需要收集 + // 文本属性块: 旧版 Text 走 "Text" 键, TMP 走 "TMP" 键 (与还原侧 TextNodeBuilder 口径一致) + var objectData = nodeDict.Get>("ObjectData"); + var textProps = objectData.Get>("Text") + ?? objectData.Get>("TMP"); + if (textProps != null) + { + string content = textProps.Get("textContent"); + if (content != null) + { + // 采集侧缓存无记录时保守判为不可见, 故这里默认取 false 与其口径一致 + bool vis = textProps.GetInnerBool("isVisuallyVisible", false); + _entries.Add(new TextEntry + { + name = nodeDict.Get("name") ?? "Unnamed", + textContent = content, + // 预览串在加载时算一次并缓存, 供 OnGUI 每帧直接使用 (避免每帧 Replace/Substring) + preview = MakePreview(content), + isVisuallyVisible = vis, + // 直接持有该节点字典引用, 保存时就地写 manualShow + nodeDict = nodeDict, + // 有 manualShow 则读它, 无则默认取自身 isVisuallyVisible (显示语义一致) + manualShow = nodeDict.GetInnerBool("manualShow", vis) + }); + } + } + + // 递归子节点 (无论当前节点是否含文本, 子孙仍可能含文本) + var children = nodeDict.Get>("ChildNodes"); + if (children != null) + { + foreach (var c in children) + if (c is Dictionary cd) + Collect(cd); + } + } + + /// + /// Unity EditorWindow 的 IMGUI 绘制回调, 每次界面刷新时被调用 + /// 依次绘制: 顶部工具行 (打开/保存) → 搜索行 → 表头 → 可滚动的文本列表 + /// + private void OnGUI() + { + // 懒初始化单行裁剪样式: 超出列宽直接裁剪, 不换行, 避免多行文本撑高行、溢出到相邻行 + if (_ellipsisStyle == null) + { + _ellipsisStyle = new GUIStyle(EditorStyles.label) + { + clipping = TextClipping.Clip, + wordWrap = false + }; + } + + // 顶部工具行: 打开文件 + 保存 + 当前文件名 + using (new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button("打开 JSON...", GUILayout.Width(100))) PickAndLoad(); + + // 未加载 (无 _root) 时禁用 "保存", 防止空数据误写 + using (new EditorGUI.DisabledScope(_root == null)) + { + if (GUILayout.Button("保存", GUILayout.Width(80))) Save(); + } + + // 右侧顶到边显示当前文件名 (仅文件名, 未加载时显示占位提示) + GUILayout.FlexibleSpace(); + GUILayout.Label(string.IsNullOrEmpty(_jsonPath) ? "(未加载)" : Path.GetFileName(_jsonPath), + EditorStyles.miniLabel); + } + + // 尚未成功加载: 给出提示并结束本次绘制 (不画搜索/列表) + if (_root == null) + { + EditorGUILayout.HelpBox("请先打开一份 Dump 的 ui_data_text.json 文件", MessageType.Info); + return; + } + + // 搜索行 + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Label("搜索", GUILayout.Width(32)); + _search = EditorGUILayout.TextField(_search); + } + + // 表头 (各列宽度需与下方数据行保持一致, 以对齐) + using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar)) + { + GUILayout.Label("显示", GUILayout.Width(40)); + GUILayout.Label("原始判定", GUILayout.Width(80)); + GUILayout.Label("name", GUILayout.Width(180)); + GUILayout.Label("textContent"); + } + + // 文本列表 (可滚动) + _scroll = EditorGUILayout.BeginScrollView(_scroll); + // 统一的单行行高, 保证每行高度固定、彼此不重叠 + float rowHeight = EditorGUIUtility.singleLineHeight; + foreach (var e in _entries) + { + // 搜索过滤: 关键字非空且既不匹配 name 也不匹配 textContent 时跳过该行 (忽略大小写) + if (!string.IsNullOrEmpty(_search) && + e.name.IndexOf(_search, System.StringComparison.OrdinalIgnoreCase) < 0 && + e.textContent.IndexOf(_search, System.StringComparison.OrdinalIgnoreCase) < 0) + continue; + + using (new EditorGUILayout.HorizontalScope(GUILayout.Height(rowHeight))) + { + // 显示勾选框 (勾选 = 还原时显示该文本), 固定单行高度 + e.manualShow = EditorGUILayout.Toggle(e.manualShow, + GUILayout.Width(40), GUILayout.Height(rowHeight)); + + // 原始判定列: 只读展示 "✓ 可见" / "✗ 不可见", 用绿色/红色区分, 直观对照人工 "显示" 决策 + var prevColor = GUI.color; + GUI.color = e.isVisuallyVisible ? new Color(0.55f, 0.9f, 0.55f) : new Color(0.95f, 0.55f, 0.55f); + EditorGUILayout.LabelField(e.isVisuallyVisible ? "✓ 可见" : "✗ 不可见", + _ellipsisStyle, GUILayout.Width(80), GUILayout.Height(rowHeight)); + GUI.color = prevColor; + + // name 列: 单行裁剪显示, 悬停 Tooltip 看完整名称 + EditorGUILayout.LabelField(new GUIContent(e.name, e.name), + _ellipsisStyle, GUILayout.Width(180), GUILayout.Height(rowHeight)); + + // textContent 列: 显示预计算的单行预览 (缓存于 e.preview), 悬停 Tooltip 显示完整原文 + EditorGUILayout.LabelField( + new GUIContent(e.preview, e.textContent), + _ellipsisStyle, GUILayout.Height(rowHeight)); + } + } + EditorGUILayout.EndScrollView(); + } + + /// + /// 把多行/超长文本折成适合单行显示的预览串: + /// - 换行 \r\n / \n / \r 统一替换为可见符号 ↵ (避免行高突变与相邻行重叠); + /// - 制表符替换为空格; + /// - 超过 maxLen 时截断并补省略号 (完整原文仍可通过 Tooltip 查看) + /// + /// 原始 textContent (可为 null/空) + /// 预览最大字符数, 超出则截断, 默认 120 + /// 单行预览串; 输入为空时返回空字符串 + private static string MakePreview(string s, int maxLen = 120) + { + // 空值保护: null/空串直接返回 "", 避免后续 Replace 抛异常 + if (string.IsNullOrEmpty(s)) return ""; + // 依次折叠各类换行与制表符为可读的单行形式 (\r\n 必须先于 \n/\r 处理, 避免产生两个 ↵) + string oneLine = s.Replace("\r\n", " ↵ ") + .Replace("\n", " ↵ ") + .Replace("\r", " ↵ ") + .Replace("\t", " "); + // 超长截断并补省略号 + return oneLine.Length > maxLen ? oneLine.Substring(0, maxLen) + " …" : oneLine; + } + + /// + /// 保存: 把各条 "显示" 勾选状态写回其节点字典, 再序列化整棵树回写原文件 + /// 需求约定: 保存时为每个文本节点都写入 manualShow 字段 (无论 true/false), 以显式固化显示/隐藏决策 + /// 写盘包裹在 try/catch 中, 失败仅弹窗提示不崩溃 + /// + private void Save() + { + // 状态未就绪 (无根对象或无目标路径) 直接返回 + if (_root == null || string.IsNullOrEmpty(_jsonPath)) return; + + // 逐条把当前勾选状态写入对应节点字典 (nodeDict 是解析树中的引用, 就地修改即反映到 _root) + foreach (var e in _entries) + { + e.nodeDict["manualShow"] = e.manualShow; + } + + try + { + // 用 JsonWriter 把整棵树序列化 (排版/数字格式复刻采集侧, 见 JsonWriter) 后覆盖写回原文件 + File.WriteAllText(_jsonPath, JsonWriter.Serialize(_root)); + Debug.Log($"[LQARestore][LQATextShowWindow] 已保存 manualShow 到: {_jsonPath}"); + EditorUtility.DisplayDialog("LQA 文本显隐标记", "保存成功", "OK"); + } + catch (System.Exception e) + { + Debug.LogError($"[LQARestore][LQATextShowWindow] 保存失败: {e.Message}"); + EditorUtility.DisplayDialog("LQA 文本显隐标记", $"保存失败: {e.Message}", "OK"); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Font/.gitkeep b/timi_hok_game_translator/Unity_LQARestore_Plugin/Font/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaConfigGuiUtil.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaConfigGuiUtil.cs new file mode 100644 index 0000000000000000000000000000000000000000..a77c8ab5f208f73bd0ae75ab54ee04d4ec8d0038 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaConfigGuiUtil.cs @@ -0,0 +1,52 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaConfigGuiUtil.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 配置窗口共用的 GUI 小工具 (编辑器侧) + /// 目前提供 "配置存储位置" 只读展示区, 供平台连接/项目/任务三个配置窗口复用, 避免重复代码 + /// + public static class LqaConfigGuiUtil + { + /// + /// 绘制 "配置存储位置" 只读区: 说明配置存于 EditorPrefs (非磁盘文件) + 键名 + 实际落点 + /// 全部用 SelectableLabel (只读可复制, 不可编辑, 无回写), 便于用户去 注册表/plist 定位, 无篡改风险 + /// + /// 要展示的 EditorPrefs 键名文本 (如 "KeyA, KeyB") + public static void DrawStorageLocation(string keysText) + { + // 区块标题: 加粗样式, 同时用 "(仅查看)" 明确提示本区内容只读, 不可修改 + EditorGUILayout.LabelField("配置存储位置 (仅查看)", EditorStyles.boldLabel); + + // 说明存储方式: 左侧标签 "存储方式" + 右侧固定说明文本 + // 告知用户配置写入 Unity EditorPrefs (编辑器级键值存储), 而非项目里的磁盘配置文件 + EditorGUILayout.LabelField("存储方式", "Unity EditorPrefs (编辑器级键值, 非磁盘配置文件)"); + + // 第 1 行: 展示 EditorPrefs 的键名 + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("键名"); + + // SelectableLabel 只读但可选中复制, 不产生任何写回值; 套 textField 样式并限高单行 + EditorGUILayout.SelectableLabel(keysText, EditorStyles.textField, + GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + + // 第 2 行: 展示配置在操作系统中的实际落点 (由 LqaPlatformConfig 按平台返回注册表/plist/prefs 路径) + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("实际位置"); + // 同样用只读可复制的 SelectableLabel, 方便用户直接复制去 注册表/plist 定位 + EditorGUILayout.SelectableLabel(LqaPlatformConfig.GetStorageLocationDescription(), + EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..4c2cd19f91d4bfc330650b588af481f7552ac7e6 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfig.cs @@ -0,0 +1,80 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaFilterConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 筛选变量配置 (编辑器侧) + /// 职责: 集中管理 "从某个任务里怎么筛数据" 的查询过滤变量 —— 对应 GET /api/job/datas 的 + /// language / count / minID / module_ids + /// 这些是筛选条件, 语义上独立于 "任务是哪个" (job_id, 见 LqaJobConfig) 与 + /// "项目上下文" (project_id 等, 见 LqaProjectConfig), 故单独成一层, 不与项目/任务混在一起 + /// 存储: EditorPrefs, 键前缀 LQA_Filter_ (与 LQA_Platform_ / LQA_Project_ / LQA_Job_ 区分) + /// + public class LqaFilterConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Filter_, 与平台/项目/任务三组配置隔离) + /// 每个键一一对应下方同名字段, 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_LANGUAGE = "LQA_Filter_Language"; + public const string KEY_COUNT = "LQA_Filter_Count"; + public const string KEY_MIN_ID = "LQA_Filter_MinID"; + public const string KEY_MODULE_IDS = "LQA_Filter_ModuleIds"; + + /// + /// 语言代码 (平台内部数字码 value, 由筛选窗口从平台拉取下拉后选定) + /// 对应 query 的 language; 空串 = 未选择 (不按语言过滤) + /// + public string Language = ""; + + /// + /// 单次拉取条数 (对应 query 的 count) + /// 默认 "1" + /// + public string Count = "1"; + + /// + /// 增量游标 (对应 query 的 minID): 只拉取 id 大于该值的数据, 用于增量分页 + /// 默认 "0" = 从头拉取所有数据 + /// + public string MinID = "0"; + + /// + /// 模块过滤 (对应 query 的 module_ids): 多个模块以 '_' 分隔, 请求时会替换为 ',' + /// 空串 = 不按模块过滤 + /// + public string ModuleIds = ""; + + /// + /// 从 EditorPrefs 读取全部筛选变量; 键缺失时回落到与字段初始值一致的默认值 + /// + public static LqaFilterConfig Load() + { + var c = new LqaFilterConfig(); + c.Language = EditorPrefs.GetString(KEY_LANGUAGE, ""); // 缺省: 未选语言 + c.Count = EditorPrefs.GetString(KEY_COUNT, "1"); // 缺省: 拉 1 条 + c.MinID = EditorPrefs.GetString(KEY_MIN_ID, "0"); // 缺省: 从头拉取 + c.ModuleIds = EditorPrefs.GetString(KEY_MODULE_IDS, ""); // 缺省: 不过滤模块 + return c; + } + + /// + /// 写回 EditorPrefs; 各字段用 ?? 兜底, 避免字段为 null 时写入异常并保持与默认值一致 + /// + public void Save() + { + EditorPrefs.SetString(KEY_LANGUAGE, Language ?? ""); + EditorPrefs.SetString(KEY_COUNT, Count ?? "1"); + EditorPrefs.SetString(KEY_MIN_ID, MinID ?? "0"); + EditorPrefs.SetString(KEY_MODULE_IDS, ModuleIds ?? ""); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..98bbd5524819d3ce4d225ce743c9f65925f68566 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaFilterConfigWindow.cs @@ -0,0 +1,272 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaFilterConfigWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Json; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 筛选变量配置窗口 (EditorWindow) + /// 集中管理 "从某个任务里怎么筛数据" 的查询过滤变量: + /// language / count / minID / module_ids (见 LqaFilterConfig, 对应 GET /api/job/datas 的 query) + /// Language 是这里唯一的语言来源: 平台的 GET /api/job/datas 与提交 image 的 /api/image/entity + /// 都要 "平台内部语言码(数字 value)", 二者同一套码, 故本窗口用下拉从平台动态拉语言列表选择, + /// 存的是数字码; 其它窗口 (如提交还原) 只读复用该值, 不再单独输入语言 + /// 与 "任务标识" (job_id, Job Config)、"项目上下文" (project_id 等, Project Config) 分开管理, 互不混合 + /// + public class LqaFilterConfigWindow : EditorWindow + { + /// + /// 当前编辑中的筛选变量配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// + private LqaFilterConfig _config; + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// 下拉显示用的语言名数组 (形如 "en (1)"), 与 _langCodes 一一对应; 未拉取时为空 + /// + private string[] _langNames = new string[0]; + + /// + /// 下拉各项对应的平台数字语言码数组, 与 _langNames 索引对齐; 选中项的码写入 _config.Language + /// + private string[] _langCodes = new string[0]; + + /// + /// 当前下拉选中项索引; -1 表示尚未选择 (通常因为还没拉取列表) + /// + private int _langIndex = -1; + + /// + /// 正在进行的 "拉取语言" 请求句柄; null 表示当前无请求 (完成/取消后置回 null) + /// + private LqaRequest _langReq; + + /// + /// 拉取语言进行中标志; 用于禁用按钮并显示 "拉取中..." + /// + private bool _langLoading; + + /// + /// 菜单入口: Tools/LQA/平台/配置/筛选变量... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/筛选变量...", false, 303)] + private static void Open() + { + var win = GetWindow(false, "LQA 筛选变量", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存的筛选变量到 _config + /// + private void OnEnable() + { + _config = LqaFilterConfig.Load(); + } + + /// + /// 窗口关闭/禁用时清理: 摘除每帧轮询回调, 并中止未完成的拉取语言请求 + /// 避免窗口关掉后回调仍被触发或请求句柄泄漏 + /// + private void OnDisable() + { + EditorApplication.update -= TickLang; + if (_langReq != null) { _langReq.Abort(); _langReq = null; } + } + + /// + /// 绘制面板: Language 下拉(需先拉取) + Count/MinID/ModuleIds 文本框 + 保存 + 存储位置说明 + /// + private void OnGUI() + { + // MouseDown 时清键盘焦点, 避免 SelectableLabel 抢焦点吃掉按钮首次点击 + if (Event.current != null && Event.current.type == EventType.MouseDown) + GUIUtility.keyboardControl = 0; + + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + EditorGUILayout.LabelField("筛选变量 (拉取时的过滤条件)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + // Language: 下拉选择(需先从平台拉取); 拉到列表后选中项的数字码写入 _config.Language + EditorGUILayout.BeginHorizontal(); + // 已拉到语言列表: 显示下拉, 切换选项即把对应数字码写入 _config.Language + if (_langNames != null && _langNames.Length > 0) + { + int newIdx = EditorGUILayout.Popup( + new GUIContent("语言", "从平台拉取的语言列表; 选中项的数字码即拉取/提交共用的平台语言码"), + Mathf.Clamp(_langIndex, 0, _langNames.Length - 1), _langNames); // Clamp 防越界 + if (newIdx != _langIndex) + { + _langIndex = newIdx; + _config.Language = _langCodes[_langIndex]; // 存数字码 + } + } + else + { + // 未拉取时: 只读显示当前已存的码 + 提示去拉取 + EditorGUILayout.PrefixLabel(new GUIContent("语言", "点右侧 \"拉取语言\" 从平台获取列表后选择")); + EditorGUILayout.SelectableLabel( + string.IsNullOrEmpty(_config.Language) ? "(未选择, 请拉取语言)" : "code = " + _config.Language, + EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)); + } + // 拉取进行中禁用按钮, 防重复点击发起多个请求 + using (new EditorGUI.DisabledScope(_langLoading)) + { + if (GUILayout.Button(_langLoading ? "拉取中..." : "拉取语言", GUILayout.Width(80))) + StartLoadLanguages(); + } + EditorGUILayout.EndHorizontal(); + + // 其余筛选变量: 纯文本输入, 语义见各 GUIContent 的 tooltip + _config.Count = EditorGUILayout.TextField( + new GUIContent("拉取条数", "单次拉取条数"), _config.Count); + _config.MinID = EditorGUILayout.TextField( + new GUIContent("最小 ID", "增量游标, 只拉 id 大于它的数据"), _config.MinID); + _config.ModuleIds = EditorGUILayout.TextField( + new GUIContent("模块 ID", "模块过滤, 多个用 '_' 分隔 (请求时转 ','); 空=不过滤"), _config.ModuleIds); + + EditorGUILayout.Space(6); + + // 保存: 把当前 _config 写回 EditorPrefs, 并弹出短暂提示 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + EditorGUILayout.Space(6); + // 复用公共小工具展示 "配置存哪 (EditorPrefs 键名 + 实际落点)", 这里把本组全部键名拼给它 + LqaConfigGuiUtil.DrawStorageLocation( + LqaFilterConfig.KEY_LANGUAGE + " , " + + LqaFilterConfig.KEY_COUNT + " , " + LqaFilterConfig.KEY_MIN_ID + " , " + LqaFilterConfig.KEY_MODULE_IDS); + + EditorGUILayout.Space(6); + // 使用须知: 语言码来源、拉取前置条件 (Host/JobId)、以及各配置的分工边界 + EditorGUILayout.HelpBox( + "语言 需从平台拉取后下拉选择 (存数字码), 拉取与提交共用该码\n" + + "拉取语言需要有效 Host (平台连接配置) 与 任务ID (任务配置)\n" + + "筛选变量独立管理: 任务标识在 \"任务配置\", 项目/上传字段在 \"项目配置\"/\"上传配置\"", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + + // ========================================== + // 拉取语言列表 (GET /api/job/entity?mappings=1) + // ========================================== + + /// + /// 发起 "拉取语言列表" 请求: 校验前置条件 (Host + JobId) 后, 用 LqaApiClient 发请求, + /// 并挂上每帧轮询回调 TickLang 等待完成 (编辑器内无协程, 用 update 轮询) + /// + private void StartLoadLanguages() + { + var conn = LqaPlatformConfig.Load(); + var job = LqaJobConfig.Load(); + // 前置校验: 缺 Host 或 JobId 都无法请求, 提示后直接返回 + if (string.IsNullOrEmpty(conn.Host)) { ShowNotification(new GUIContent("请先配置 Host")); return; } + if (job.IsIdle) { ShowNotification(new GUIContent("请先配置 任务ID")); return; } + + _langLoading = true; + _langReq = new LqaApiClient(conn).GetLanguageMappings(job.JobId); + // 先摘再挂, 保证同一回调只注册一次 (避免重复订阅) + EditorApplication.update -= TickLang; + EditorApplication.update += TickLang; + Repaint(); + } + + /// + /// 每帧轮询拉取语言请求: 未完成则直接返回; 完成后摘除回调、按结果分支处理 + /// (成功则解析 body 填充下拉, 失败则提示并记日志) + /// + private void TickLang() + { + // 请求为空或尚未完成: 本帧不处理 + if (_langReq == null || !_langReq.Poll()) return; + // 已完成: 立即摘除回调并清除进行中标志 + EditorApplication.update -= TickLang; + _langLoading = false; + + // 非 2xx: 视为失败, 提示 + 记录 HTTP 码与错误信息, 清空句柄后重绘 + if (_langReq.Kind != LqaResponseKind.Success) + { + ShowNotification(new GUIContent("拉取语言失败")); + Debug.LogWarning("[LQA] 拉取语言失败: HTTP " + _langReq.Code + " " + _langReq.Error); + _langReq = null; + Repaint(); + return; + } + + // 成功: 先取出响应体再清空句柄 (避免后续解析期间句柄仍被引用), 然后解析填充下拉 + string body = _langReq.Text; + _langReq = null; + ParseLanguages(body); + Repaint(); + } + + /// + /// 解析 { data: { mappings: { language: [{name, value, label}] } } } 填充下拉, 并对齐当前已存码的选中项 + /// + private void ParseLanguages(string body) + { + var names = new List(); + var codes = new List(); + try + { + // 逐层安全下钻 (DictExt.Get 命中失败返回 null), 任一层缺失都不会抛异常 + var root = MiniJson.Parse(body ?? "") as Dictionary; + var data = root.Get>("data"); + var mappings = data.Get>("mappings"); + var langs = mappings != null ? mappings.Get>("language") : null; + if (langs != null) + { + foreach (var o in langs) + { + var d = o as Dictionary; + if (d == null) continue; + // value 是平台数字语言码 (拉取/提交共用); 为空的项无意义, 跳过 + string val = d.GetInnerString("value", ""); + // 显示名优先取 name, 缺失回退 label, 再缺失就用码本身 + string nm = d.GetInnerString("name", d.GetInnerString("label", val)); + if (string.IsNullOrEmpty(val)) continue; + // 显示项带上码便于辨识, 如 "en (1)", 实际存的仍是纯数字码 + names.Add(nm + " (" + val + ")"); + codes.Add(val); + } + } + } + catch (System.Exception e) { Debug.LogWarning("[LQA] 解析语言失败: " + e.Message); } + + // 一条都没解析到: 提示并保持原状 (不清空已有下拉) + if (codes.Count == 0) + { + ShowNotification(new GUIContent("未解析到语言")); + return; + } + _langNames = names.ToArray(); + _langCodes = codes.ToArray(); + // 若当前已存码在列表里, 选中它; 否则默认第一项并写回 + _langIndex = 0; + for (int i = 0; i < _langCodes.Length; i++) + if (_langCodes[i] == _config.Language) { _langIndex = i; break; } + _config.Language = _langCodes[_langIndex]; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..692670f926f54c9d8e2e66b7c29528e9deeb2770 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfig.cs @@ -0,0 +1,62 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaJobConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 任务配置 (编辑器侧) + /// 职责: 只保存/读取 "当前操作的是哪个任务批次" —— job_id 这一个任务标识 + /// 稳定的项目上下文 (project_id 等) 在 LqaProjectConfig + /// 任务从属于项目 (job 属于某 project_id) + /// 存储: EditorPrefs, 键前缀 LQA_Job_ + /// + public class LqaJobConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Job_, 与平台/项目/筛选三组配置隔离) + /// 一一对应下方 JobId 字段, 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_JOB_ID = "LQA_Job_JobId"; + + /// + /// 任务批次 ID (平台 job 实体主键, 拉取数据时定位到具体任务) + /// "0" (或空串) 表示无远程任务: 处于空闲态, 不应发起拉取 + /// + public string JobId = "0"; + + /// + /// 是否为 "无远程任务" 状态 (JobId 空或 "0") + /// 为 true 时上层不应发起拉取; 供调用方在请求前做前置判断 + /// + public bool IsIdle + { + get { return string.IsNullOrEmpty(JobId) || JobId == "0"; } + } + + /// + /// 从 EditorPrefs 读取任务标识; 键缺失时回落到与字段初始值一致的默认值 "0" (空闲态) + /// + public static LqaJobConfig Load() + { + var c = new LqaJobConfig(); + // 缺省: "0" = 无远程任务 + c.JobId = EditorPrefs.GetString(KEY_JOB_ID, "0"); + return c; + } + + /// + /// 写回 EditorPrefs; 用 ?? 兜底, 避免 JobId 为 null 时写入异常并保持与默认值一致 + /// + public void Save() + { + EditorPrefs.SetString(KEY_JOB_ID, JobId ?? "0"); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..29ecc95c49b20caa8f8b6a6c20af741b3b07becf --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaJobConfigWindow.cs @@ -0,0 +1,121 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaJobConfigWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 任务配置窗口 (EditorWindow) + /// 只管理 "当前操作的是哪个任务批次" —— job_id 这一个任务标识 + /// 任务从属于项目, 故窗口顶部只读显示当前所属 project_id (取自 LqaProjectConfig), 提醒用户 + /// 正在为哪个项目配任务, 避免张冠李戴; 若要改项目请去 "项目配置" 窗口 + /// 纯本地配置编辑, 不涉及网络 (需要与服务器交互时统一走 LqaApiClient) + /// + public class LqaJobConfigWindow : EditorWindow + { + /// + /// 当前编辑中的任务配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// + private LqaJobConfig _config; + + /// + /// 只读展示用的当前所属项目 ID (取自 LqaProjectConfig, 非本窗口编辑) + /// 仅用于顶部提示 "任务属于哪个 project_id"; 缺省/未配置时为 "0" + /// + private string _ownerProjectId = "0"; // 只读展示: 当前所属项目 + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// 菜单入口: Tools/LQA/平台/配置/任务配置... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/任务配置...", false, 302)] + private static void Open() + { + var win = GetWindow(false, "LQA 任务配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存任务标识, 并读取当前所属项目 ID 用于顶部只读展示 + /// + private void OnEnable() + { + _config = LqaJobConfig.Load(); + _ownerProjectId = LqaProjectConfig.Load().ProjectId; + } + + /// + /// 窗口重新获得焦点时: 刷新所属项目 ID + /// 防止用户在 "项目配置" 窗口改了 project_id 后, 本窗口顶部仍显示旧值 + /// + private void OnFocus() + { + // 重新聚焦时刷新所属项目, 保证与 "项目配置" 窗口的改动同步 + _ownerProjectId = LqaProjectConfig.Load().ProjectId; + } + + /// + /// 绘制面板: 顶部只读展示所属项目上下文 + Job ID 文本框 + 保存 + 存储位置说明 + 使用须知 + /// + private void OnGUI() + { + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + // 只读: 所属项目上下文 + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(new GUIContent("所属项目 (仅查看)", "任务从属于该 项目ID; 修改请去 项目配置 窗口")); + // 未配置 (空或 "0") 时给出引导文案, 否则显示 project_id 原值; SelectableLabel 只读可复制不回写 + EditorGUILayout.SelectableLabel( + string.IsNullOrEmpty(_ownerProjectId) || _ownerProjectId == "0" + ? "(未配置, 请先在 Tools/LQA/平台/配置/项目配置 设置 项目ID)" + : "project_id = " + _ownerProjectId, + EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.Space(4); + EditorGUILayout.LabelField("任务配置", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + // Job ID: 本窗口唯一可编辑项, 空或 "0" 视为无远程任务 + _config.JobId = EditorGUILayout.TextField( + new GUIContent("任务 ID", "任务 ID; \"0\" 表示无远程任务"), _config.JobId); + + EditorGUILayout.Space(6); + + // 保存: 把当前 _config 写回 EditorPrefs, 并弹出短暂提示 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + EditorGUILayout.Space(6); + // 复用公共小工具展示 "配置存哪 (EditorPrefs 键名 + 实际落点)", 本窗口只有 Job ID 一个键 + LqaConfigGuiUtil.DrawStorageLocation(LqaJobConfig.KEY_JOB_ID); + + EditorGUILayout.Space(6); + // 使用须知: 说明本窗口与筛选变量/项目配置的分工边界, 以及 Job ID 为空/0 时的空闲语义 + EditorGUILayout.HelpBox( + "本窗口只管任务标识 任务ID, 筛选变量 (语言/数量/最小ID/模块ID) 在 \"筛选配置\" 窗口; " + + "稳定的 项目ID / 模块ID / 资源版本 在 \"项目配置\" 窗口,\n" + + "任务ID 为空或 0 时视为无远程任务, 后续拉取不会发起", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..d78c7be11d559026435788299754aa5a30cb145c --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConfig.cs @@ -0,0 +1,108 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaPlatformConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 平台连接配置 (编辑器侧, 仅连接信息) + /// 职责: 集中保存/读取 "连接 LQA 平台" 所需的凭证 —— Host (平台地址) 与 Authorization (JWT) + /// 本类只管连接信息, 不含任何任务过滤参数 (JobId/Language 等), + /// 保持 "平台连接配置" 这一职责单一 + /// 存储方式: 落 EditorPrefs (编辑器级键值存储), 原因: + /// - 连接测试只在编辑器内运行, 无需随工程/打包分发; + /// - 不硬编码任何 Host/JWT (避免把内网地址与凭证写死进源码/版本库); + /// - 换机器/换账号时只改本机 EditorPrefs, 不动代码 + /// + public class LqaPlatformConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Platform_, 与项目/任务/筛选三组配置隔离, 避免与工程其它键冲突) + /// 每个键一一对应下方同名字段, 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_HOST = "LQA_Platform_Host"; + public const string KEY_AUTH = "LQA_Platform_Authorization"; + public const string KEY_API_PATH = "LQA_Platform_ApiPath"; + public const string KEY_DOWNLOAD_PATH = "LQA_Platform_DownloadPath"; + + /// + /// 平台地址, 仅含协议+主机+端口 (不含路径前缀), 例: http://127.0.0.1:8080 + /// + public string Host = ""; + + /// + /// 鉴权 JWT (放入请求头 LQA-Authorization) + /// + public string Authorization = ""; + + /// + /// 平台接口路径前缀, 例: /api-pro + /// 拼在 Host 与具体接口 (/api/...) 之间; 留空=直接拼 Host + /// + public string ApiPath = ""; + + /// + /// 数据下载路径前缀 + /// 拼在 Host 与 file_path 之间; 留空=直接拼 Host + /// + public string DownloadPath = ""; + + /// + /// dump 下载专用 Host: 把任务端口 :8080 换成静态服务端口 :80 + /// (连接测试用不到, 保留以备后续下载功能复用) + /// + public string DownloadHost + { + get { return string.IsNullOrEmpty(Host) ? Host : Host.Replace(":8080", ":80"); } + } + + /// + /// 从 EditorPrefs 读取配置 + /// + public static LqaPlatformConfig Load() + { + var c = new LqaPlatformConfig(); + c.Host = EditorPrefs.GetString(KEY_HOST, ""); + c.Authorization = EditorPrefs.GetString(KEY_AUTH, ""); + c.ApiPath = EditorPrefs.GetString(KEY_API_PATH, ""); + c.DownloadPath = EditorPrefs.GetString(KEY_DOWNLOAD_PATH, ""); + return c; + } + + /// + /// 把当前配置写回 EditorPrefs + /// + public void Save() + { + EditorPrefs.SetString(KEY_HOST, Host ?? ""); + EditorPrefs.SetString(KEY_AUTH, Authorization ?? ""); + EditorPrefs.SetString(KEY_API_PATH, ApiPath ?? ""); + EditorPrefs.SetString(KEY_DOWNLOAD_PATH, DownloadPath ?? ""); + } + + /// + /// 配置的实际存储位置描述 (供界面展示) + /// 注意: 配置存于 EditorPrefs (编辑器级键值存储), 不是磁盘上的配置文件; + /// 其物理落点随操作系统不同: + /// - Windows: 注册表 HKCU\Software\Unity Technologies\Unity Editor 5.x\ (键名带哈希后缀) + /// - macOS: ~/Library/Preferences/com.unity3d.UnityEditor5.x.plist + /// - Linux: ~/.config/unity3d/prefs + /// + public static string GetStorageLocationDescription() + { +#if UNITY_EDITOR_WIN + return @"注册表 HKCU\Software\Unity Technologies\Unity Editor 5.x\"; +#elif UNITY_EDITOR_OSX + return "~/Library/Preferences/com.unity3d.UnityEditor5.x.plist"; +#else + return "~/.config/unity3d/prefs"; +#endif + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConnectionWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConnectionWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed13f52966ce3aa005b785e8ef5acfece99f624d --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaPlatformConnectionWindow.cs @@ -0,0 +1,387 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaPlatformConnectionWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 平台连接配置窗口 (EditorWindow) + /// 职责单一: 管理 "连接 LQA 平台" 的凭证 (Host + Authorization) 并测试连通性 + /// - 编辑并保存 Host / JWT (落 EditorPrefs, 见 LqaPlatformConfig); + /// - 一键 "测试连通性": 通过 LqaApiClient 发一次带鉴权探测, 判定 网络可达 + 服务存活 + JWT 是否有效 + /// 本窗口只负责 UI 与交互; 所有与服务器的交互都委托给 LqaApiClient(见该类), 不含任务信息, + /// 也不做下载/还原 —— 那些属于后续功能, 届时同样复用 LqaApiClient + /// 编辑器内无 MonoBehaviour 主循环, 故用 EditorApplication.update 轮询 LqaRequest.Poll 完成状态 + /// + public class LqaPlatformConnectionWindow : EditorWindow + { + /// + /// 当前编辑中的平台连接配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// 仅含连接凭证 Host + Authorization, 不含任何任务/筛选参数 + /// + private LqaPlatformConfig _config; + + /// + /// 与平台交互的客户端 (每次发起测试时基于当前 _config 新建) + /// 所有 HTTP 交互都经由它, 本窗口不直接碰 UnityWebRequest + /// + private LqaApiClient _client; + + /// + /// 测试连通性的进行中请求句柄 (null 表示当前无测试在跑) + /// 由 StartTest 创建, Tick 每帧轮询, 完成/取消后置回 null + /// + private LqaRequest _testReq; + + /// + /// 测试结果的展示类别; 决定结果区用哪种 HelpBox 图标 (信息/警告/错误) 以及按钮禁用状态 + /// + private enum ResultKind { None, Testing, Success, Warning, Error } + + /// + /// 当前结果类别 (默认 None = 不显示结果区); Testing 期间会禁用 "测试" 按钮、启用 "取消" 按钮 + /// + private ResultKind _resultKind = ResultKind.None; + + /// + /// 结果区展示的文案 (与 _resultKind 配套) + /// + private string _resultMsg = ""; + + /// + /// 是否显示 "明文 HTTP 被 Player Settings 拦截" 的引导 (含跳转/一键放开按钮) + /// 仅当本次失败被判定为明文 HTTP 被禁用时置 true (见 IsInsecureHttpError) + /// + private bool _showInsecureHttpHint; + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// JWT 输入框样式: 基于 textArea 开启自动换行 (懒初始化, 因 GUIStyle 依赖 EditorStyles, 只能在 OnGUI 期间构造) + /// + private GUIStyle _wrapTextAreaStyle; + + /// + /// 菜单入口: Tools/LQA/平台/配置/平台连接... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/平台连接...", false, 300)] + private static void Open() + { + var win = GetWindow(false, "LQA 平台连接", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存的连接配置到 _config + /// + private void OnEnable() + { + _config = LqaPlatformConfig.Load(); + } + + /// + /// 窗口关闭/禁用时清理: 中止进行中的测试请求并摘除每帧轮询回调 + /// 避免窗口关掉后回调仍被触发或请求句柄泄漏 + /// + private void OnDisable() + { + // 窗口关闭时清理进行中的测试请求与轮询回调 + CancelTest(); + } + + /// + /// 绘制面板: Host / Authorization 输入 + 保存/测试/取消按钮 + 存储位置说明 + 结果区 + 使用须知 + /// + private void OnGUI() + { + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + EditorGUILayout.LabelField("平台连接信息", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + // Host / Authorization: 一旦编辑内容, 清掉旧的结果/错误提示 (但测试进行中不打断) + EditorGUI.BeginChangeCheck(); + + // Host + _config.Host = EditorGUILayout.TextField( + new GUIContent("Host", "平台地址, 仅含 http:// 与端口 (不含路径前缀), 例: http://127.0.0.1:8080"), + _config.Host); + + // 平台接口路径: 拼在 Host 与具体接口之间 + _config.ApiPath = EditorGUILayout.TextField( + new GUIContent("平台接口路径", + "接口公共前缀, 例: /api-pro; 留空则直接拼 Host"), + _config.ApiPath); + + // 数据下载路径: 拼在 Host 与 file_path 之间 + _config.DownloadPath = EditorGUILayout.TextField( + new GUIContent("数据下载路径", + "资源/下载公共前缀, 留空则直接拼 Host"), + _config.DownloadPath); + + // Authorization (JWT) —— 用多行自动换行区域, 便于查看/粘贴很长的 token + // 样式懒初始化: GUIStyle 依赖 EditorStyles, 只能在 OnGUI 期间构造 + if (_wrapTextAreaStyle == null) + _wrapTextAreaStyle = new GUIStyle(EditorStyles.textArea) { wordWrap = true }; + EditorGUILayout.LabelField(new GUIContent("Authorization (JWT)", "放入请求头 LQA-Authorization 的令牌")); + _config.Authorization = EditorGUILayout.TextArea( + _config.Authorization, _wrapTextAreaStyle, GUILayout.MinHeight(64)); + + // 输入有变化且当前不在测试中: 清掉上次结果, 避免旧提示与新输入不一致 + if (EditorGUI.EndChangeCheck() && _resultKind != ResultKind.Testing) + SetResult(ResultKind.None, ""); + + EditorGUILayout.Space(6); + + using (new EditorGUILayout.HorizontalScope()) + { + // 保存: 只写回 EditorPrefs, 不发起网络请求 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + // 测试进行中时禁用按钮, 避免重复发起 + EditorGUI.BeginDisabledGroup(_resultKind == ResultKind.Testing); + if (GUILayout.Button("保存并测试连通性", GUILayout.Height(24))) + { + _config.Save(); + StartTest(); + } + EditorGUI.EndDisabledGroup(); + + // "取消测试" 只在测试进行中可用 + EditorGUI.BeginDisabledGroup(_resultKind != ResultKind.Testing); + if (GUILayout.Button("取消测试", GUILayout.Width(90), GUILayout.Height(24))) + { + CancelTest(); + SetResult(ResultKind.None, ""); + } + EditorGUI.EndDisabledGroup(); + } + + EditorGUILayout.Space(6); + + // 配置存储位置说明 (只读, 复用共享工具): 配置存 EditorPrefs 而非磁盘文件 + LqaConfigGuiUtil.DrawStorageLocation( + LqaPlatformConfig.KEY_HOST + " , " + LqaPlatformConfig.KEY_AUTH + " , " + + LqaPlatformConfig.KEY_API_PATH + " , " + LqaPlatformConfig.KEY_DOWNLOAD_PATH); + + EditorGUILayout.Space(6); + + // 结果区: 按 _resultKind 展示测试结果 (含明文 HTTP 引导) + DrawResult(); + + EditorGUILayout.Space(6); + // 使用须知: 说明测试探测的行为、各返回码含义, 以及本窗口的职责边界 + EditorGUILayout.HelpBox( + "测试会向 {Host}/api/test 发一次带鉴权 (LQA-Authorization) 的探测请求:\n" + + "· 成功 (2xx) = 网络可达 + 服务存活 + 鉴权通过;\n· 302 跳登录页/401/403 = 能连上但鉴权未通过 (检查 JWT);\n· 连接错误 = 网络不通或 Host 填错 (注意内网可达);\n" + + "本窗口只负责连接配置与连通性验证, 不含任务信息, 也不下载/还原", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + + /// + /// 绘制结果区: 按 _resultKind 映射到对应图标的 HelpBox; + /// 当本次失败为 "明文 HTTP 被禁用" 时, 追加放开步骤说明与快捷入口按钮 + /// + private void DrawResult() + { + // None: 无结果可显示, 直接返回 (不占版面) + if (_resultKind == ResultKind.None) return; + + // 结果类别 -> HelpBox 图标类型 + MessageType mt; + switch (_resultKind) + { + case ResultKind.Success: mt = MessageType.Info; break; + case ResultKind.Warning: mt = MessageType.Warning; break; + case ResultKind.Error: mt = MessageType.Error; break; + default: mt = MessageType.None; break; // Testing + } + EditorGUILayout.HelpBox(_resultMsg, mt); + + // 明文 HTTP 被工程禁用时, 显示放开步骤与快捷入口 + if (_showInsecureHttpHint) + { + EditorGUILayout.HelpBox( + "允许明文 HTTP 连接的步骤:\n" + + "1. 菜单 Edit → Project Settings\n" + + "2. 左侧选 Player → Other Settings\n" + + "3. 找到 Configuration 分组下的 Insecure HTTP Option (部分版本叫 \"Allow downloads over HTTP\")\n" + + "4. 由 Not allowed 改为 Always allowed, 然后重新测试", + MessageType.Info); + + using (new EditorGUILayout.HorizontalScope()) + { + // 快捷入口: 直接打开 Player Settings, 省去用户手动翻菜单 + if (GUILayout.Button("打开 Player Settings", GUILayout.Height(22))) + SettingsService.OpenProjectSettings("Project/Player"); + +#if UNITY_2022_1_OR_NEWER + // 2022.1+ 才有 insecureHttpOption API: 一键把设置改为始终允许并存盘 + if (GUILayout.Button("一键允许 HTTP 连接", GUILayout.Height(22))) + { + PlayerSettings.insecureHttpOption = InsecureHttpOption.AlwaysAllowed; + AssetDatabase.SaveAssets(); + ShowNotification(new GUIContent("已允许 HTTP 连接, 请重新测试")); + _showInsecureHttpHint = false; + } +#endif + } + } + } + + // ========================================== + // 连通性测试: 通过 LqaApiClient 发起 -> 每帧轮询 -> 按归类给出提示 + // ========================================== + + /// + /// 发起连通性测试: 先做前置校验 (Host / Authorization 非空), 再用 LqaApiClient 发探测请求, + /// 并挂上每帧轮询回调 Tick 等待完成 (编辑器内无协程, 用 update 轮询) + /// + private void StartTest() + { + _showInsecureHttpHint = false; // 每次新测试前清掉上次的 HTTP 引导 + + // 前置校验: 缺 Host 或 JWT 都无法发起, 提示后直接返回 + if (string.IsNullOrEmpty(_config.Host)) + { + SetResult(ResultKind.Error, "请先填写 Host"); + return; + } + + if (_config.Authorization == null || _config.Authorization.Trim().Length == 0) + { + SetResult(ResultKind.Error, "请先填写 Authorization(JWT)"); + return; + } + + CancelTest(); // 保险: 清掉可能残留的上一次请求 + + _client = new LqaApiClient(_config); + _testReq = _client.TestConnection(); + SetResult(ResultKind.Testing, "正在测试连通性..."); + + // 先摘再挂, 保证同一回调只注册一次 (避免重复订阅) + EditorApplication.update -= Tick; + EditorApplication.update += Tick; + } + + /// + /// 每帧轮询测试请求: 未完成则直接返回; 完成后摘除回调, + /// 按 LqaResponseKind 把结果归类成 成功/鉴权失败/网络错误/服务端错误 并给出对应提示 + /// + private void Tick() + { + // 请求为空或尚未完成: 本帧不处理 + if (_testReq == null || !_testReq.Poll()) return; + + // 已完成: 立即摘除回调 + EditorApplication.update -= Tick; + + long code = _testReq.Code; + string err = _testReq.Error; + + switch (_testReq.Kind) + { + // 2xx: 网络 + 服务 + 鉴权全部正常 + case LqaResponseKind.Success: + SetResult(ResultKind.Success, + "连通成功 (HTTP " + code + "): 网络可达、平台服务存活、鉴权通过, 连接可用"); + break; + + // 302 跳登录页 / 401 / 403: 能连上但 JWT 无效或过期 + case LqaResponseKind.AuthFailed: + SetResult(ResultKind.Warning, + "能连上平台, 但鉴权未通过 (HTTP " + code + "): \n" + + "请检查 Authorization(JWT) 是否已填写且未过期 (平台对未鉴权请求会跳登录页 302)"); + break; + + // 网络层失败: 进一步区分 "明文 HTTP 被禁用" 与 普通不可达, 前者给放开引导 + case LqaResponseKind.NetworkError: + if (IsInsecureHttpError(_config.Host, err)) + { + _showInsecureHttpHint = true; + SetResult(ResultKind.Error, + "连接失败: 平台地址是明文 HTTP, 但当前工程禁止了非安全 (HTTP) 连接, 请求未发出\n" + + "请按下方步骤在 Player Settings 中允许 HTTP 连接后重试"); + } + else + { + _showInsecureHttpHint = false; + SetResult(ResultKind.Error, + "连接失败: " + (string.IsNullOrEmpty(err) ? "网络不可达" : err) + + "\n请检查 Host 是否正确、是否在可访问该地址的网络环境 (如内网)"); + } + break; + + // 其它 4xx/5xx: 网络本身通, 但服务端返回错误 + default: // ServerError + SetResult(ResultKind.Warning, + "能连上平台, 但服务端返回 HTTP " + code + (string.IsNullOrEmpty(err) ? "" : (": " + err)) + + "\n(网络本身是通的; 若为 4xx/5xx 请与平台侧确认服务状态)"); + break; + } + + _testReq = null; + Repaint(); + } + + /// + /// 中止进行中的测试: 摘除每帧轮询回调, 并 Abort + 清空请求句柄 + /// 供 "取消测试" 按钮、窗口关闭、以及新测试发起前的清理复用 + /// + private void CancelTest() + { + EditorApplication.update -= Tick; + if (_testReq != null) { _testReq.Abort(); _testReq = null; } + } + + /// + /// 设置结果类别与文案并请求重绘 (统一入口, 避免各处漏掉 Repaint) + /// + private void SetResult(ResultKind kind, string msg) + { + _resultKind = kind; + _resultMsg = msg; + Repaint(); + } + + /// + /// 判断本次失败是否为 "明文 HTTP 被 Player Settings 禁止" 所致 + /// + private static bool IsInsecureHttpError(string host, string err) + { + // 优先看底层错误文案 (不同 Unity 版本略有差异, 做宽松匹配) + if (!string.IsNullOrEmpty(err) && + err.IndexOf("Insecure", System.StringComparison.OrdinalIgnoreCase) >= 0) + return true; + + // 兜底: Host 是明文 http 且工程当前禁用了 HTTP +#if UNITY_2022_1_OR_NEWER + if (!string.IsNullOrEmpty(host) && + host.TrimStart().StartsWith("http://", System.StringComparison.OrdinalIgnoreCase) && + PlayerSettings.insecureHttpOption == InsecureHttpOption.NotAllowed) + return true; +#endif + return false; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..13a14bae617618eebd3197d7f77ebbc2e408ea32 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfig.cs @@ -0,0 +1,54 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaProjectConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 项目配置 (编辑器侧) + /// 职责: 只保存/读取 "当前测试项目" 这一核心标识 —— project_id + /// 它是拉取/上传都要用的上级上下文 (变更频率低) + /// 上传时随数据带上的 module_id / resource_version 已拆到独立的"上传配置"(LqaUploadConfig), + /// 任务标识 job_id 在 LqaJobConfig, 筛选变量在 LqaFilterConfig, 各司其职不混合 + /// 存储: EditorPrefs, 键前缀 LQA_Project_ + /// + public class LqaProjectConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Project_, 与平台/任务/筛选三组配置隔离) + /// 一一对应下方 ProjectId 字段, 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_PROJECT_ID = "LQA_Project_ProjectId"; + + /// + /// 项目 ID (平台 /api/project 实体主键, 拉取/上传均需的上级上下文) + /// "0" (或空串) 表示尚未配置项目; 任务/筛选等操作应以该项目为归属 + /// + public string ProjectId = "0"; + + /// + /// 从 EditorPrefs 读取项目标识; 键缺失时回落到与字段初始值一致的默认值 "0" (未配置) + /// + public static LqaProjectConfig Load() + { + var c = new LqaProjectConfig(); + // 缺省: "0" = 未配置项目 + c.ProjectId = EditorPrefs.GetString(KEY_PROJECT_ID, "0"); + return c; + } + + /// + /// 写回 EditorPrefs; 用 ?? 兜底, 避免 ProjectId 为 null 时写入异常并保持与默认值一致 + /// + public void Save() + { + EditorPrefs.SetString(KEY_PROJECT_ID, ProjectId ?? "0"); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..fcb1638383b16e1e407e33bd2acfb61bb741ec95 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaProjectConfigWindow.cs @@ -0,0 +1,90 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaProjectConfigWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 项目配置窗口 (EditorWindow) + /// 只管理"当前测试项目"的核心标识 project_id (见 LqaProjectConfig) —— 拉取/上传共享的上级上下文 + /// 上传随数据带的 module_id / resource_version 已拆到"上传配置"窗口 (LqaUploadConfigWindow) + /// 纯本地配置编辑, 不涉及网络 (需要与服务器交互时统一走 LqaApiClient) + /// + public class LqaProjectConfigWindow : EditorWindow + { + /// + /// 当前编辑中的项目配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// + private LqaProjectConfig _config; + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// 菜单入口: Tools/LQA/平台/配置/项目配置... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/项目配置...", false, 301)] + private static void Open() + { + var win = GetWindow(false, "LQA 项目配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存的项目标识到 _config + /// + private void OnEnable() + { + _config = LqaProjectConfig.Load(); + } + + /// + /// 绘制面板: Project ID 文本框 + 保存 + 存储位置说明 + 使用须知 + /// + private void OnGUI() + { + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + EditorGUILayout.LabelField("项目配置 (稳定上下文)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + // Project ID: 本窗口唯一可编辑项, 平台项目实体主键, 拉取/上传都要用 + _config.ProjectId = EditorGUILayout.TextField( + new GUIContent("项目ID", "平台项目实体主键; 拉取/上传均需"), _config.ProjectId); + + EditorGUILayout.Space(6); + + // 保存: 把当前 _config 写回 EditorPrefs, 并弹出短暂提示 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + EditorGUILayout.Space(6); + // 复用公共小工具展示 "配置存哪 (EditorPrefs 键名 + 实际落点)", 本窗口只有 Project ID 一个键 + LqaConfigGuiUtil.DrawStorageLocation(LqaProjectConfig.KEY_PROJECT_ID); + + EditorGUILayout.Space(6); + // 使用须知: 说明本窗口只管项目标识, 以及与上传/任务/筛选各配置窗口的分工边界 + EditorGUILayout.HelpBox( + "本窗口只管项目标识 项目ID (拉取/上传共享), 上传随数据带的 模块ID / 资源版本 在 \"上传配置\" 窗口; " + + "任务批次 任务ID 在 \"任务配置\" 窗口; 筛选变量在 \"筛选变量\" 窗口", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..1db2ab23993cb3887042aff21a5665f0581555d4 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfig.cs @@ -0,0 +1,52 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaSubmitConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 提交结果配置 (编辑器侧) + /// 职责: 集中管理 "提交还原结果" 这一动作 (POST /api/image/entity) 的配套开关 —— ai_sign + /// 与 "上传数据回填" (module_id / resource_version, 见 LqaUploadConfig, 走 PATCH /api/data/entity) + /// 是不同接口、不同动作, 故分开管理, 互不混合 + /// 存储: EditorPrefs, 键前缀 LQA_Submit_ (与 LQA_Platform_ / LQA_Upload_ 等区分) + /// + public class LqaSubmitConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Submit_) + /// 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_TRIGGER_AI = "LQA_Submit_TriggerAI"; + + /// + /// 提交图片 (POST /api/image/entity) 时是否触发平台 AI 检测 (ai_sign): + /// true => ai_sign=1 (触发 AI 检测/建bug); false => ai_sign=0 (只存图与框); 默认 true + /// + public bool TriggerAI = true; + + /// + /// 从 EditorPrefs 读取; 键缺失时回落到默认值 (true, 默认触发 AI) + /// + public static LqaSubmitConfig Load() + { + var c = new LqaSubmitConfig(); + c.TriggerAI = EditorPrefs.GetBool(KEY_TRIGGER_AI, true); + return c; + } + + /// + /// 写回 EditorPrefs + /// + public void Save() + { + EditorPrefs.SetBool(KEY_TRIGGER_AI, TriggerAI); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..98842df1a1afdd701ad9b4e9d8a6f99989c2583c --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaSubmitConfigWindow.cs @@ -0,0 +1,89 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaSubmitConfigWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 提交结果配置窗口 (EditorWindow) + /// 管理 "提交还原结果" (POST /api/image/entity) 的配套开关: ai_sign (见 LqaSubmitConfig) + /// 该开关被 "提交还原结果" 与 "自动化流水线" 两处提交步骤共用; 纯本地配置编辑, 不涉及网络 + /// + public class LqaSubmitConfigWindow : EditorWindow + { + /// + /// 当前编辑中的提交配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// + private LqaSubmitConfig _config; + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// 菜单入口: Tools/LQA/平台/配置/提交配置... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/提交配置...", false, 305)] + private static void Open() + { + var win = GetWindow(false, "LQA 提交配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存的提交配置到 _config + /// + private void OnEnable() + { + _config = LqaSubmitConfig.Load(); + } + + /// + /// 绘制面板: 触发 AI 勾选框 + 保存 + 存储位置说明 + 使用须知 + /// + private void OnGUI() + { + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + EditorGUILayout.LabelField("提交结果配置 (提交还原结果时生效)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + _config.TriggerAI = EditorGUILayout.Toggle( + new GUIContent("提交后触发 AI 检测", + "勾选则提交图片时 AI标记=1, 平台触发 AI 检测/建bug; 取消则只存图与框 (AI标记=0)"), _config.TriggerAI); + + EditorGUILayout.Space(6); + + // 保存: 把当前 _config 写回 EditorPrefs, 并弹出短暂提示 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + EditorGUILayout.Space(6); + // 复用公共小工具展示 "配置存哪 (EditorPrefs 键名 + 实际落点)" + LqaConfigGuiUtil.DrawStorageLocation(LqaSubmitConfig.KEY_TRIGGER_AI); + + EditorGUILayout.Space(6); + // 使用须知: 说明本开关作用于提交还原结果与自动流水线的提交步骤 + EditorGUILayout.HelpBox( + "本开关作用于 \"提交还原结果\" 与 \"自动化流水线\" 的提交步骤 (POST /api/image/entity)\n" + + "勾选: 平台收到图后触发 AI 检测/建bug; 取消: 只存图与框", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfig.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b0ffaffe571379c3eca8ce0c03524488ef638b4 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfig.cs @@ -0,0 +1,63 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaUploadConfig.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 上传配置 (编辑器侧) + /// 职责: 集中管理 "上传数据时随数据带上" 的字段 —— module_id / resource_version + /// 这两项仅在上传回填 (PATCH /api/data/entity) 时用到, 语义上属于 "上传" 这一动作的配套参数, + /// 与 "项目标识" (project_id, 见 LqaProjectConfig, 拉取/上传都要用) 分开管理, 互不混合 + /// 存储: EditorPrefs, 键前缀 LQA_Upload_ (与 LQA_Platform_ / LQA_Project_ / LQA_Job_ / LQA_Filter_ 区分) + /// + public class LqaUploadConfig + { + /// + /// EditorPrefs 存储键 (前缀统一为 LQA_Upload_, 与平台/项目/任务/筛选四组配置隔离) + /// 每个键一一对应下方同名字段, 也供外部 (如 LQAResetMenu 一键清空配置) 引用删除 + /// + public const string KEY_MODULE_ID = "LQA_Upload_ModuleId"; + public const string KEY_RESOURCE_VERSION = "LQA_Upload_ResourceVersion"; + + /// + /// 模块 ID (对应上传回填时随数据带上的 module_id) + /// 空串 = 不带该字段 + /// + public string ModuleId = ""; + + /// + /// 资源版本号 (如 0.20142.29.0; 上传回填时随数据带上的 resource_version) + /// 空串 = 不带该字段 + /// + public string ResourceVersion = ""; + + /// + /// 从 EditorPrefs 读取全部上传字段; 键缺失时回落到与字段初始值一致的默认值 (空串) + /// + public static LqaUploadConfig Load() + { + var c = new LqaUploadConfig(); + // 缺省: 不带 module_id + c.ModuleId = EditorPrefs.GetString(KEY_MODULE_ID, ""); + // 缺省: 不带 resource_version + c.ResourceVersion = EditorPrefs.GetString(KEY_RESOURCE_VERSION, ""); + return c; + } + + /// + /// 写回 EditorPrefs; 各字段用 ?? 兜底, 避免字段为 null 时写入异常并保持与默认值一致 + /// + public void Save() + { + EditorPrefs.SetString(KEY_MODULE_ID, ModuleId ?? ""); + EditorPrefs.SetString(KEY_RESOURCE_VERSION, ResourceVersion ?? ""); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfigWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfigWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..4d5f7d99c360d8fa83904b69a785bf387dde1aad --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Config/LqaUploadConfigWindow.cs @@ -0,0 +1,93 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Config\LqaUploadConfigWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 上传配置窗口 (EditorWindow) + /// 管理 "上传数据时随数据带上" 的字段: module_id / resource_version (见 LqaUploadConfig) + /// 这两项仅在上传回填 (PATCH /api/data/entity) 时用到, 与 "项目标识" (project_id, Project Config) + /// 分开管理, 互不混合; 纯本地配置编辑, 不涉及网络 + /// + public class LqaUploadConfigWindow : EditorWindow + { + /// + /// 当前编辑中的上传配置 (OnEnable 时从 EditorPrefs 载入, 点 "保存" 时写回) + /// + private LqaUploadConfig _config; + + /// + /// 整个面板的滚动位置 (内容超出窗口高度时可滚动) + /// + private Vector2 _scroll; + + /// + /// 菜单入口: Tools/LQA/平台/配置/上传配置... + /// 打开 (或聚焦已存在的) 窗口, 并锁定为 800x500 固定大小且在主编辑器窗口内居中 + /// + [MenuItem("Tools/LQA/平台/配置/上传配置...", false, 304)] + private static void Open() + { + var win = GetWindow(false, "LQA 上传配置", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 500); + win.Show(); + } + + /// + /// 窗口启用时: 从 EditorPrefs 载入已存的上传字段到 _config + /// + private void OnEnable() + { + _config = LqaUploadConfig.Load(); + } + + /// + /// 绘制面板: Module ID / Resource Version 文本框 + 保存 + 存储位置说明 + 使用须知 + /// + private void OnGUI() + { + _scroll = EditorGUILayout.BeginScrollView(_scroll); + + EditorGUILayout.LabelField("上传配置 (上传时随数据带上)", EditorStyles.boldLabel); + EditorGUILayout.Space(2); + + // Module ID / Resource Version: 纯文本输入, 空则上传时不带该字段, 语义见各 GUIContent 的 tooltip + _config.ModuleId = EditorGUILayout.TextField( + new GUIContent("模块ID", "上传回填时随数据带上的模块 ID; 空则不带"), _config.ModuleId); + _config.ResourceVersion = EditorGUILayout.TextField( + new GUIContent("资源版本", "资源版本号, 如 0.20142.29.0; 上传回填时随数据带上; 空则不带"), _config.ResourceVersion); + + EditorGUILayout.Space(6); + + // 保存: 把当前 _config 写回 EditorPrefs, 并弹出短暂提示 + if (GUILayout.Button("保存", GUILayout.Height(24))) + { + _config.Save(); + ShowNotification(new GUIContent("已保存")); + } + + EditorGUILayout.Space(6); + // 复用公共小工具展示 "配置存哪 (EditorPrefs 键名 + 实际落点)", 这里把本组两个键名拼给它 + LqaConfigGuiUtil.DrawStorageLocation( + LqaUploadConfig.KEY_MODULE_ID + " , " + LqaUploadConfig.KEY_RESOURCE_VERSION); + + EditorGUILayout.Space(6); + // 使用须知: 说明本窗口字段仅用于上传回填, 与项目标识的分工边界, 以及留空时的语义 + EditorGUILayout.HelpBox( + "上传配置仅在上传数据的回填步骤 (PATCH /api/data/entity) 用到, 项目标识 项目ID 在 \"项目配置\" 窗口\n" + + "留空则上传时不带该字段", + MessageType.Info); + + EditorGUILayout.EndScrollView(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaApiClient.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaApiClient.cs new file mode 100644 index 0000000000000000000000000000000000000000..7c1055663c26609ecf9d53b2c7ebd88106012683 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaApiClient.cs @@ -0,0 +1,526 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Core\LqaApiClient.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System; +using UnityEngine; +using UnityEngine.Networking; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 与 LQA 平台服务端交互的统一客户端 (编辑器侧) + /// 目的: 把 "和服务器打交道" 的所有通用细节收敛到一处, 供连通性测试 / 以后的拉取任务 / 下载 dump / + /// 上传结果等功能直接复用, 避免每个功能各写一份 UnityWebRequest 样板与踩同样的坑 + /// 统一封装的要点 (都是之前在连通性测试里踩出来的经验): + /// 1. 自动拼接 Host + path, 自动加鉴权头 LQA-Authorization; + /// 2. redirectLimit = 0 —— 平台对未鉴权请求会 302 跳登录页, 禁止自动跟随可避免 + /// "Redirect limit exceeded" 的模糊报错, 让 302 作为响应码被直接识别; + /// 3. 统一超时; + /// 4. 统一的响应归类 (LqaResponseKind), 把 HTTP 码 + 网络错误翻译成业务语义; + /// 5. 编辑器内无 MonoBehaviour 主循环, 故请求以 "异步句柄 + 每帧 Poll" 的形式对外 + /// (调用方在 EditorApplication.update 里轮询 LqaRequest.Poll) + /// 用法示例 (连通性测试): + /// var client = new LqaApiClient(LqaPlatformConfig.Load()); + /// var req = client.TestConnection(); + /// // 每帧: if (req.Poll()) { switch(req.Kind){...} 用 req.Code / req.Text / req.Error } + /// 用法示例 (以后拉取, GET JSON): + /// var req = client.Get("/api/job/datas?job_id=65&count=1"); + /// // Poll 完成后 req.Text 就是响应体, 交给 MiniJson 解析 + /// + public class LqaApiClient + { + /// + /// 鉴权请求头名 (平台全局鉴权中间件读取) + /// + public const string AuthHeader = "LQA-Authorization"; + + /// + /// 默认请求超时 (秒) + /// + public const int DefaultTimeoutSec = 10; + + /// + /// 平台连接配置 (Host / DownloadHost / 鉴权令牌 Authorization 等), 构造时注入, 全程只读 + /// + private readonly LqaPlatformConfig _config; + + /// + /// 构造客户端, 配置由调用方读取后注入, 本类不负责加载/持久化 + /// + /// 平台连接配置, 通常来自 LqaPlatformConfig.Load() + public LqaApiClient(LqaPlatformConfig config) + { + _config = config; + } + + /// + /// 当前配置 (只读访问, 供调用方读取 Host/DownloadHost 等) + /// + public LqaPlatformConfig Config { get { return _config; } } + + // ========================================== + // 通用请求构造 + // ========================================== + + /// + /// 发起一个 GET 请求, 返回可轮询的句柄 + /// + /// 相对路径 (以 / 开头, 如 "/api/test?num=1"); 也可传绝对 URL + /// 是否携带鉴权头 (默认 true; 平台几乎所有接口都需要) + /// 是否用 DownloadPath 前缀 (下载 dump/资源时用), 否则用 ApiPath 前缀 + public LqaRequest Get(string path, bool withAuth = true, bool useDownloadPath = false) + { + var req = UnityWebRequest.Get(BuildUrl(path, useDownloadPath)); + Prepare(req, withAuth); + return LqaRequest.Send(req); + } + + /// + /// 发起一个 POST 请求 (JSON body), 返回可轮询的句柄 + /// + /// 相对路径或绝对 URL + /// JSON 字符串请求体 + /// 是否携带鉴权头 + public LqaRequest PostJson(string path, string jsonBody, bool withAuth = true) + { + return SendJson(UnityWebRequest.kHttpVerbPOST, path, jsonBody, withAuth); + } + + /// + /// 发起一个带 JSON body 的请求, 支持任意 HTTP 方法 (POST/PATCH 等) + /// + /// HTTP 方法, 如 "POST" / "PATCH" + /// 相对路径或绝对 URL + /// JSON 字符串请求体 + /// 是否携带鉴权头 + public LqaRequest SendJson(string verb, string path, string jsonBody, bool withAuth = true) + { + var req = new UnityWebRequest(BuildUrl(path, false), verb); + byte[] body = System.Text.Encoding.UTF8.GetBytes(jsonBody ?? ""); + req.uploadHandler = new UploadHandlerRaw(body); + req.downloadHandler = new DownloadHandlerBuffer(); + req.SetRequestHeader("Content-Type", "application/json"); + Prepare(req, withAuth); + return LqaRequest.Send(req); + } + + /// + /// 发起一个 multipart/form-data POST 请求 (上传文件/表单), 返回可轮询的句柄, 为以后 "上传结果" 预留 + /// + /// 相对路径或绝对 URL + /// 已构造好的 WWWForm (可含字段与文件) + /// 是否携带鉴权头 + public LqaRequest PostForm(string path, WWWForm form, bool withAuth = true) + { + var req = UnityWebRequest.Post(BuildUrl(path, false), form); + Prepare(req, withAuth); + return LqaRequest.Send(req); + } + + // ========================================== + // 具体业务 API + // ========================================== + + /// + /// 连通性测试: GET /api/test?num=1&delay=0 (带鉴权) + /// 该接口只回显参数, 但会过平台全局鉴权中间件, 故能一次验证 网络可达 + 服务存活 + JWT 有效 + /// + public LqaRequest TestConnection() + { + return Get("/api/test?num=1&delay=0", withAuth: true, useDownloadPath: false); + } + + /// + /// 拉取任务数据清单: GET /api/job/datas (带鉴权) + /// 返回体形如 { code, data: { bug_ids, datas: [{ id, file_path, module_id }] } } + /// - id: 平台数据标识 (data_id), 用作本地文件命名; + /// - file_path: 该条 dump 数据在平台的存储路径 (gzip), 供下一步下载; + /// - module_id: 所属模块 + /// + /// 任务批次 ID + /// 语言码 (平台码, 如 en/pt) + /// 拉取条数上限 + /// 增量游标, 只拉 id 大于它的数据 + /// 模块过滤, 多个用 '_' 分隔 (转成 ',' 发送); 空=不过滤 + public LqaRequest GetJobDatas(string jobId, string language, + string count, string minId, string moduleIds) + { + var sb = new System.Text.StringBuilder("/api/job/datas?"); + sb.Append("job_id=").Append(UnityWebRequest.EscapeURL(jobId ?? "0")); + if (!string.IsNullOrEmpty(language)) + sb.Append("&language=").Append(UnityWebRequest.EscapeURL(language)); + if (!string.IsNullOrEmpty(count)) + sb.Append("&count=").Append(UnityWebRequest.EscapeURL(count)); + if (!string.IsNullOrEmpty(minId)) + sb.Append("&minID=").Append(UnityWebRequest.EscapeURL(minId)); + if (!string.IsNullOrEmpty(moduleIds)) + // 平台约定: module_ids 用 ',' 分隔; 本地配置用 '_' 分隔便于输入, 这里转换 + sb.Append("&module_ids=").Append(UnityWebRequest.EscapeURL(moduleIds.Replace('_', ','))); + return Get(sb.ToString(), withAuth: true, useDownloadPath: false); + } + + /// + /// 下载单条 dump 数据: GET {Host}{DownloadPath}{file_path} + /// file_path 来自 GetJobDatas 返回的每项 file_path (平台资源路径, gzip 压缩) + /// 资源需鉴权, 故带上 LQA-Authorization + /// 完成后 req.Bytes 即 gzip 原始字节, 交给 LqaDumpDecoder 解码为 dump json + /// + public LqaRequest DownloadDataDump(string filePath) + { + // file_path 通常以 / 开头的相对路径; Get 会自动拼到 Host + DownloadPath 后 + return Get(filePath, withAuth: true, useDownloadPath: true); + } + + // 说明: 上传相关业务 API 已在下方实现; 若后续还需新增其它接口, 按上面 Get/PostJson/PostForm 的封装方式追加即可 + + // ========================================== + // 上传相关业务 API (三步链路, 对齐平台上传协议) + // 1. UploadDataJson -> POST /api/data/entity 建 data, 返回 data_id + // 2. UploadFile -> POST /api/upload_file 传截图, 返回 file_path + // 3. UpdateDataImage -> PATCH /api/data/entity 回填 shot_img_path/module_id/resource_version + // ========================================== + + /// + /// [上传第1步] POST /api/data/entity: 用补全后的 dump json 建一条 data + /// body = { project_id, job_id, data:{...} } (application/json) + /// 成功响应形如 { code:0, data:{ data:{ id, ... } } }, 其中 data.data.id 即新建的平台 data_id + /// + /// 项目 ID + /// 任务 ID + /// 已补全平台必需 key 的 data 对象的 JSON 字符串 (调用方拼好) + public LqaRequest UploadDataJson(string projectId, string jobId, string dataJsonObject) + { + // 手工拼外层 JSON: {"project_id": ..,"job_id": ..,"data": } + // dataJsonObject 已是合法 JSON 文本, 直接内嵌 (不再二次转义) + var sb = new System.Text.StringBuilder(); + sb.Append("{\"project_id\":").Append(ToJsonNumberOrString(projectId)) + .Append(",\"job_id\":").Append(ToJsonNumberOrString(jobId)) + .Append(",\"data\":").Append(string.IsNullOrEmpty(dataJsonObject) ? "{}" : dataJsonObject) + .Append("}"); + return PostJson("/api/data/entity", sb.ToString(), withAuth: true); + } + + /// + /// [上传第2步] POST /api/upload_file: 上传单个文件 (如截图), multipart 字段名固定为 "file" + /// 成功响应形如 { code:0, data:{ file_name, file_path } }, file_path 供第3步回填 + /// + /// 文件原始字节 + /// 文件名 (含扩展名, 平台据此取扩展名) + public LqaRequest UploadFile(byte[] fileBytes, string fileName) + { + var form = new WWWForm(); + // 平台上传接口取请求里的第一个文件, 字段名约定为 "file" + form.AddBinaryData("file", fileBytes ?? new byte[0], fileName ?? "file.png", "application/octet-stream"); + return PostForm("/api/upload_file", form, withAuth: true); + } + + /// + /// [上传第3步] PATCH /api/data/entity: 给已建的 data 回填截图路径与可选的 module_id/resource_version + /// body = { id, shot_img_path, module_id?, resource_version? } (application/json) + /// + /// 第1步返回的平台 data_id + /// 第2步返回的 file_path + /// 模块 ID (空则不带) + /// 资源版本 (空则不带) + public LqaRequest UpdateDataImage(string dataId, string shotImgPath, string moduleId, string resourceVersion) + { + var sb = new System.Text.StringBuilder(); + sb.Append("{\"id\":").Append(ToJsonNumberOrString(dataId)) + .Append(",\"shot_img_path\":").Append(JsonStr(shotImgPath)); + if (!string.IsNullOrEmpty(moduleId)) + sb.Append(",\"module_id\":").Append(ToJsonNumberOrString(moduleId)); + if (!string.IsNullOrEmpty(resourceVersion)) + sb.Append(",\"resource_version\":").Append(JsonStr(resourceVersion)); + sb.Append("}"); + return SendJson("PATCH", "/api/data/entity", sb.ToString(), withAuth: true); + } + + /// + /// [提交还原结果] POST /api/image/entity: 把一张还原图 (Restore.png) 连同文本框 rect_locations 作为 + /// image 提交, 关联到指定 data_id。multipart: 一个文件字段 (图) + 若干表单字段 + /// 平台提交图片接口必需: project_id/job_id/data_id (int)、language (int, 内部语言码)、rect_locations (str) + /// ai_sign 默认 0 —— 传 0 表示"只存图与框, 不触发 AI 检测/建 bug", 契合手动提交还原结果的语义 + /// + /// 项目 ID + /// 任务 ID + /// 该还原图对应的平台 data_id + /// 平台内部语言码 (数字字符串) + /// 文本框 JSON (平台 rect_locations 格式) + /// 还原图字节 (Restore.png) + /// 图片文件名 (含扩展名) + /// 是否触发 AI 检测, 默认 "0" (不触发) + public LqaRequest UploadImageEntity(string projectId, string jobId, string dataId, string language, + string rectLocationsJson, byte[] imageBytes, string imageFileName, + string aiSign = "0") + { + var form = new WWWForm(); + form.AddField("project_id", projectId ?? "0"); + form.AddField("job_id", jobId ?? "0"); + form.AddField("data_id", dataId ?? "0"); + form.AddField("language", language ?? "0"); + form.AddField("rect_locations", string.IsNullOrEmpty(rectLocationsJson) ? "{}" : rectLocationsJson); + form.AddField("ai_sign", aiSign ?? "0"); + form.AddBinaryData("file", imageBytes ?? new byte[0], imageFileName ?? "Restore.png", "image/png"); + return PostForm("/api/image/entity", form, withAuth: true); + } + + /// + /// 拉取语言映射: GET /api/job/entity?job_id=&mappings=1&fields=id (带鉴权) + /// 该接口在 mappings=1 时返回 data.mappings.language = [{ name, value, label }], + /// 其中 value 即提交 image 时要用的 "平台内部语言码" (数字), name 为显示名 (如 en/中文) + /// 语言列表是项目相关且存于平台 DB, 故动态拉取而非硬编码, 保证与平台一致 + /// + /// 任意有效 job_id (语言表随该 job 所属项目返回) + public LqaRequest GetLanguageMappings(string jobId) + { + return Get("/api/job/entity?job_id=" + UnityWebRequest.EscapeURL(jobId ?? "0") + "&mappings=1&fields=id", + withAuth: true, useDownloadPath: false); + } + + /// + /// 把纯数字字符串按 JSON 数字输出, 否则按 JSON 字符串输出 (兼容 id 为数字/字符串) + /// + private static string ToJsonNumberOrString(string s) + { + if (string.IsNullOrEmpty(s)) return "0"; + long n; + if (long.TryParse(s, out n)) return s; // 纯整数, 直接作数字 + return JsonStr(s); + } + + /// + /// 把字符串转成合法的 JSON 字符串字面量 (加引号并转义) + /// + private static string JsonStr(string s) + { + if (s == null) return "\"\""; + var sb = new System.Text.StringBuilder("\""); + foreach (char c in s) + { + switch (c) + { + case '\"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: sb.Append(c); break; + } + } + sb.Append("\""); + return sb.ToString(); + } + + // ========================================== + // 内部 + // ========================================== + + /// + /// 拼接完整 URL: 绝对 URL 原样返回; 相对路径拼到 Host + (ApiPath | DownloadPath) 之后 + /// + private string BuildUrl(string path, bool useDownloadPath) + { + if (!string.IsNullOrEmpty(path) && + (path.StartsWith("http://") || path.StartsWith("https://"))) + return path; + + string host = (_config.Host ?? "").TrimEnd('/'); + string prefix = NormalizePrefix(useDownloadPath ? _config.DownloadPath : _config.ApiPath); + string p = path ?? ""; + if (p.Length > 0 && !p.StartsWith("/")) p = "/" + p; + return host + prefix + p; + } + + /// + /// 规范化路径前缀: 去首尾空白, 保证以 / 开头且不以 / 结尾; 空则返回空串 + /// + private static string NormalizePrefix(string prefix) + { + if (string.IsNullOrEmpty(prefix)) return ""; + prefix = prefix.Trim(); + if (prefix.Length == 0) return ""; + if (!prefix.StartsWith("/")) prefix = "/" + prefix; + return prefix.TrimEnd('/'); + } + + /// + /// 统一设置鉴权头 / redirectLimit / 超时 + /// + private void Prepare(UnityWebRequest req, bool withAuth) + { + if (withAuth && !string.IsNullOrEmpty(_config.Authorization)) + req.SetRequestHeader(AuthHeader, _config.Authorization); + // 禁止自动跟随重定向: 平台对未鉴权请求 302 跳登录页, 让其作为响应码直接暴露, 而非报 Redirect limit exceeded + req.redirectLimit = 0; + req.timeout = DefaultTimeoutSec; + } + } + + /// + /// 响应的业务归类 (把 HTTP 码 + 网络错误翻译成语义) + /// + public enum LqaResponseKind + { + /// + /// 请求尚未完成 + /// + Pending, + /// + /// 成功 (2xx) + /// + Success, + /// + /// 鉴权未通过 (301/302/307/308 跳登录页, 或 401/403) + /// + AuthFailed, + /// + /// 网络层失败 (连不上 / 超时 / DNS / 非内网) + /// + NetworkError, + /// + /// 能连上但服务端返回其它错误 (其它 4xx/5xx) + /// + ServerError, + } + + /// + /// 一次 LQA 平台请求的句柄: 持有 UnityWebRequest, 调用方每帧 Poll 直至完成 + /// 完成后用 Kind/Code/Text/Error 读取结果, 设计为 "编辑器友好" (不依赖协程) + /// + public class LqaRequest + { + private UnityWebRequest _req; + private UnityWebRequestAsyncOperation _op; + + /// + /// 是否已完成 + /// + public bool IsDone { get; private set; } + /// + /// HTTP 响应码 (完成后有效; 网络层失败时通常为 0) + /// + public long Code { get; private set; } + /// + /// 响应体文本 (完成且非纯二进制时有效) + /// + public string Text { get; private set; } + /// + /// 响应体原始字节 (下载 dump 等场景用) + /// + public byte[] Bytes { get; private set; } + /// + /// 底层错误信息 (成功时为空) + /// + public string Error { get; private set; } + /// + /// 业务归类 + /// + public LqaResponseKind Kind { get; private set; } + + /// + /// 创建并发起请求 (由 LqaApiClient 调用) + /// + internal static LqaRequest Send(UnityWebRequest req) + { + var r = new LqaRequest(); + r._req = req; + r.Kind = LqaResponseKind.Pending; + try + { + r._op = req.SendWebRequest(); + } + catch (Exception e) + { + // 发送阶段就失败 (如明文 HTTP 被 Player Settings 禁止、URL 非法等): + // 转成 "已完成的网络错误", 避免异常穿透调用方的 OnGUI 造成 GUILayout 状态错乱 + r.Error = e.Message; + r.Kind = LqaResponseKind.NetworkError; + r.IsDone = true; + if (r._req != null) { r._req.Dispose(); r._req = null; } + r._op = null; + } + return r; + } + + /// + /// 每帧轮询: 未完成返回 false; 本帧刚完成则解析结果并返回 true (幂等) + /// 调用方通常在 EditorApplication.update 里调它 + /// + public bool Poll() + { + if (IsDone) return true; + if (_op == null || !_op.isDone) return false; + + try + { + Code = _req.responseCode; + Error = _req.error; + var dh = _req.downloadHandler; + if (dh != null) + { + Bytes = dh.data; + Text = dh.text; + } + Kind = Classify(_req, Code); + } + catch (Exception e) + { + Kind = LqaResponseKind.ServerError; + Error = "处理响应异常: " + e.Message; + } + finally + { + if (_req != null) { _req.Dispose(); _req = null; } + _op = null; + IsDone = true; + } + return true; + } + + /// + /// 主动放弃并释放 (调用方取消时用) + /// + public void Abort() + { + if (_req != null) + { + try { _req.Abort(); } catch { } + _req.Dispose(); + _req = null; + } + _op = null; + IsDone = true; + } + + /// + /// 把 UnityWebRequest 结果翻译成业务归类 + /// + private static LqaResponseKind Classify(UnityWebRequest req, long code) + { + if (code == 301 || code == 302 || code == 307 || code == 308) return LqaResponseKind.AuthFailed; + if (code == 401 || code == 403) return LqaResponseKind.AuthFailed; + if (HasNetworkError(req) && code == 0) return LqaResponseKind.NetworkError; + if (code >= 200 && code < 300) return LqaResponseKind.Success; + return LqaResponseKind.ServerError; + } + + /// + /// 请求底层是否连接/协议失败 (兼容不同 Unity 版本的 result 枚举) + /// + private static bool HasNetworkError(UnityWebRequest req) + { +#if UNITY_2020_2_OR_NEWER + return req.result == UnityWebRequest.Result.ConnectionError + || req.result == UnityWebRequest.Result.ProtocolError + || req.result == UnityWebRequest.Result.DataProcessingError; +#else + return req.isNetworkError || req.isHttpError; +#endif + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaDumpDecoder.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaDumpDecoder.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed204e7e9e43fa5eb1e7b099ab8bb507fc04ebed --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaDumpDecoder.cs @@ -0,0 +1,91 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Core\LqaDumpDecoder.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System; +using System.IO; +using System.IO.Compression; +using System.Text; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// dump 数据解码器 (编辑器侧) + /// 平台下发的 dump 数据是 gzip 压缩后的 json + /// 从 DownloadHost 下载得到的原始字节需经 "三连解码" 才能得到干净的 dump json: + /// 1. 魔数判定: 前两字节是否 0x1F 0x8B (gzip) —— 是则解压, 否则视为明文 json; + /// 2. 解压: GZipStream 解为 UTF-8 文本; + /// 3. 截断: 截到最后一个 '}' 为止 —— gzip 尾部可能带 padding/多余字节, 不截会导致 + /// JSON 解析在末尾报错 (曾实际踩过的坑, 必须保留处理) + /// + public static class LqaDumpDecoder + { + /// + /// 判定原始字节流是否为 gzip 压缩数据: 依据 gzip 固定文件头魔数 0x1F 0x8B (前两字节) + /// 用于 Decode 决定走 "解压" 还是 "按明文处理" 分支 + /// + /// 待判定的原始字节数组 + /// 前两字节为 gzip 魔数时返回 true; data 为 null 或长度不足 2 时返回 false + private static bool IsGzip(byte[] data) + { + // 先做空/长度保护 (不足 2 字节无从比对魔数), 再逐字节比对 gzip 头 0x1F 0x8B + return data != null && data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B; + } + + /// + /// 把下载得到的原始字节解码为 dump json 文本, 失败时抛异常 (调用方捕获给出提示) + /// 流程: 空内容校验 → gzip 魔数判定 (是则解压, 否则按明文) → 截断尾部多余字节 + /// + /// 从 DownloadHost 下载得到的原始字节 (可能是 gzip 压缩, 也可能是明文 json) + /// 解码并截断后的干净 dump json 文本 + /// raw 为 null 或空时抛出 "下载内容为空" + public static string Decode(byte[] raw) + { + // 空内容直接判失败: 后续解压/解析都无意义, 提前抛异常让调用方给出明确提示 + if (raw == null || raw.Length == 0) + throw new Exception("下载内容为空"); + + string text; + if (IsGzip(raw)) + { + // gzip 分支: 用 GZipStream 解压, CopyTo 到内存流后按 UTF-8 还原文本 + // using 逐层释放三个流 (输入源流 / 解压流 / 输出流), 避免句柄/内存泄漏 + using (var input = new MemoryStream(raw)) + using (var gz = new GZipStream(input, CompressionMode.Decompress)) + using (var output = new MemoryStream()) + { + gz.CopyTo(output); + text = Encoding.UTF8.GetString(output.ToArray()); + } + } + else + { + // 非 gzip, 视为明文 json (兼容平台未压缩下发的情况) + text = Encoding.UTF8.GetString(raw); + } + + // 无论走哪个分支, 统一截断尾部多余字节后再返回 (见 TrimToLastBrace) + return TrimToLastBrace(text); + } + + /// + /// 截断到最后一个 '}' (含), 去掉尾部可能的 padding/多余字节 + /// 若文本中没有 '}', 原样返回 (交给上层 JSON 解析去报错) + /// + /// 解压/解码后的原始文本 + /// 截断到最后一个 '}' 的文本; text 为空或不含 '}' 时原样返回 + private static string TrimToLastBrace(string text) + { + // 空文本无需处理, 原样返回避免 LastIndexOf/Substring 越界 + if (string.IsNullOrEmpty(text)) return text; + // 定位最后一个 '}': gzip 解压后尾部可能残留 padding/多余字节, 以最后一个右花括号作为 json 结尾 + int idx = text.LastIndexOf('}'); + // 找到则截到该 '}' (含, 故 +1); 未找到说明本就不是合法 json, 原样交给上层解析报错 + return idx >= 0 ? text.Substring(0, idx + 1) : text; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaUploadPayload.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaUploadPayload.cs new file mode 100644 index 0000000000000000000000000000000000000000..6a1ad11b5d087402afd178573a1973c58d4f736b --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Core/LqaUploadPayload.cs @@ -0,0 +1,171 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Core\LqaUploadPayload.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using LQARestore.Core.Json; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 上传数据的载荷构造器 (编辑器侧) + /// 职责: 把一个 LQATool 采集产物目录 (含 ui_data_text.json + ScreenShot_*.png) 整理成 + /// 平台 POST /api/data/entity 需要的 data 对象 JSON, 并定位待上传的截图/背景图 + /// 平台建 data 接口从 data 对象里读取的必需/可选字段: + /// - name: 必填非空 (用采集目录名或 json 文件名); + /// - gameData.resourceVersion: 资源版本 (可选); + /// - phoneType: 机型 (可选); + /// - sizeX / sizeY: 屏幕宽高 (可选, 缺省 0); + /// - bg_data: 背景图 hex 字符串 (平台侧还原比对用); + /// 其余字段原样保留 (平台会把整个 data gzip 存盘) + /// 与其它采集源 dump 结构的差异 (关键): + /// 某些采集源的 dump 会带 meta/version/device 字段并在上传前 pop 掉 —— 那是针对其自身结构 + /// Unity 的 ui_data_text.json 是 UIDumpResult 结构 (appVersion/systemLanguage/screenWidth/screenHeight...), + /// 没有 meta/version/device, 照搬那套 pop 会直接抛异常, 故这里改为从 Unity 实际字段映射: + /// resourceVersion < appVersion; sizeX/sizeY < screenWidth/screenHeight; phoneType < systemLanguage(兜底) + /// 若平台对这些值有更严格要求, 可在此调整映射, 逻辑集中一处便于维护 + /// + public static class LqaUploadPayload + { + /// + /// 一个采集目录整理后的上传素材 (Build 的产物, 供上传流程逐字段消费) + /// + public class Payload + { + /// + /// 补全后的 data 对象 JSON 文本 (喂给 UploadDataJson 作为 POST body) + /// + public string DataJson; + + /// + /// 待上传的截图文件绝对路径 (喂给 UploadFile); 目录无截图时为空串 + /// + public string ShotImagePath; + + /// + /// 该条数据名 (取采集目录名, 仅用于日志展示与问题定位) + /// + public string Name; + } + + /// + /// 采集截图候选名 (按优先级挑一张作为上传的 shot 图: 完整图 > 文本 ID 图) + /// + private static readonly string[] ShotCandidates = + { + "ScreenShot_Full.png", "ScreenShot_TextId.png", + }; + + /// + /// 背景图候选名 (按优先级挑一张作为 bg_data 来源: 无文字图优先, 其次专用背景图) + /// + private static readonly string[] BgCandidates = + { + "ScreenShot_NoText.png", "ScreenShot_BG.png", + }; + + /// + /// 判断一个目录是否是可上传的采集产物目录 (至少含 ui_data_text.json) + /// 供批量上传前的目录筛选/过滤使用, 避免把非采集目录送进 Build 触发异常 + /// + public static bool IsDumpDir(string dir) + { + return !string.IsNullOrEmpty(dir) && Directory.Exists(dir) && + File.Exists(Path.Combine(dir, "ui_data_text.json")); + } + + /// + /// 把一个采集目录整理成上传素材, 失败抛异常 (调用方捕获并计入失败) + /// + public static Payload Build(string dir) + { + string jsonPath = Path.Combine(dir, "ui_data_text.json"); + if (!File.Exists(jsonPath)) + throw new Exception("目录缺少 ui_data_text.json"); + + string raw = File.ReadAllText(jsonPath, Encoding.UTF8); + // 清洗非法数字字面量 (nan/inf 一类不是合法 JSON 数字), 统一替成 0, + // 否则后续 MiniJson.Parse 会解析失败; 顺序上先替带符号/带括号的长写法, 再替短写法 + raw = raw.Replace("-nan(ind)", "0").Replace("nan(ind)", "0") + .Replace("-nan", "0").Replace("nan", "0") + .Replace("-inf", "0").Replace("inf", "0"); + + object parsed = MiniJson.Parse(raw); + var root = parsed as Dictionary; + if (root == null) + throw new Exception("ui_data_text.json 不是合法的 JSON 对象"); + + // name: 平台侧要求必填非空, 优先用采集目录名 (最能标识这条数据的来源), + // 目录名意外为空时回退到固定的 json 文件名占位 + string name = new DirectoryInfo(dir).Name; + if (string.IsNullOrEmpty(name)) name = "ui_data_text.json"; + root["name"] = name; + + // gameData.resourceVersion <- appVersion + // Unity 采集侧没有独立的资源版本字段, 用 appVersion 映射充当; + // 若 gameData 已带该键则尊重原值不覆盖, appVersion 为空时也不写入 + string appVersion = root.GetInnerString("appVersion", ""); + var gameData = root.Get>("gameData"); + if (gameData == null) { gameData = new Dictionary(); root["gameData"] = gameData; } + if (!string.IsNullOrEmpty(appVersion) && !gameData.ContainsKey("resourceVersion")) + gameData["resourceVersion"] = appVersion; + + // sizeX / sizeY <- screenWidth / screenHeight + // 平台按此值还原画布尺寸; 采集侧缺字段时 GetInnerInt 回退 0 (平台侧视为未知宽高) + root["sizeX"] = root.GetInnerInt("screenWidth", 0); + root["sizeY"] = root.GetInnerInt("screenHeight", 0); + + // phoneType: 采集侧无真实机型字段, 用 systemLanguage 兜底 (仅占位, 平台侧为可选字段); + // 若原 data 已带 phoneType 则保留原值不覆盖 + if (!root.ContainsKey("phoneType")) + root["phoneType"] = root.GetInnerString("systemLanguage", ""); + + // bg_data: 平台侧还原比对时用的背景图。目录里存在候选背景图时, 读原始字节转 hex 写入; + // 没有背景图则不写该键 (平台侧按缺省处理) + string bgPath = FindFirst(dir, BgCandidates); + if (!string.IsNullOrEmpty(bgPath)) + root["bg_data"] = ToHex(File.ReadAllBytes(bgPath)); + + // 把补全/映射完的 data 对象序列化回 JSON 文本, 作为最终 POST body + string dataJson = JsonWriter.Serialize(root); + + // 按候选优先级定位一张截图作为上传的 shot 图 (可能为空串, 由上传流程决定是否跳过传图) + string shot = FindFirst(dir, ShotCandidates); + + return new Payload { DataJson = dataJson, ShotImagePath = shot, Name = name }; + } + + /// + /// 在目录里按候选名顺序找第一张存在的文件, 命中即返回其绝对路径; 全部不存在返回 "" + /// 用于在多个可能的截图/背景图文件名之间按优先级择一 + /// + private static string FindFirst(string dir, string[] candidates) + { + foreach (var c in candidates) + { + string p = Path.Combine(dir, c); + if (File.Exists(p)) return p; + } + return ""; + } + + /// + /// 字节转 hex 字符串 (小写, 与平台约定的图片 hex 编码口径保持一致, 保证平台侧解析一致) + /// 空数据返回 ""; 使用 StringBuilder 预分配 2 倍长度避免频繁扩容 + /// + private static string ToHex(byte[] data) + { + if (data == null || data.Length == 0) return ""; + var sb = new StringBuilder(data.Length * 2); + foreach (byte b in data) sb.Append(b.ToString("x2")); + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaAutoPipelineWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaAutoPipelineWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..e243e23a54597cf39621b3d7255ad6191e8c5d47 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaAutoPipelineWindow.cs @@ -0,0 +1,798 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Windows\LqaAutoPipelineWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; +using LQARestore.Core; +using LQARestore.Core.Editor; +using LQARestore.Core.Json; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// LQA 自动化流水线 (EditorWindow) + /// 把前面几个 "手动菜单" 串成一条自动循环, 无需人工逐步操作: + /// 监控任务数据 (轮询 GET /api/job/datas) → 有数据则逐条: 下载 dump → 解码落盘 → 还原并截图/导框 + /// → 提交结果 (POST /api/image/entity) → 全部处理完毕后继续监控下一批 + /// 复用已有能力 (不重复造轮子): + /// - LqaApiClient.GetJobDatas / DownloadDataDump / UploadImageEntity (HTTP); + /// - LqaDumpDecoder (gzip 三连解码); + /// - RestoreEngine.RestoreFromDump (同步还原, 内部截图 Restore.png + 导出 rect_locations.json) + /// 配置来源: Host/JWT(Platform)、project_id(Project)、job_id(Job)、language/count/module_ids(Filter) + /// language 用筛选窗口选定的平台数字码; minID 由本窗口自动推进 (处理过的最大 data_id), 无需手填 + /// 编辑器内无 MonoBehaviour 主循环, 全程用 EditorApplication.update 驱动状态机, 不用协程 + /// 还原是编辑器态能力 (依赖 EditorSceneHost/AssetDatabase), 故整条流水线只在 Unity 编辑器内运行 + /// + public class LqaAutoPipelineWindow : EditorWindow + { + /// + /// 打开窗口的菜单入口 (Tools/LQA/平台/自动化/自动化流水线...) + /// 创建 (或聚焦) 窗口后固定尺寸并居中, 打开时先刷新一次四类配置快照再显示 + /// + [MenuItem("Tools/LQA/平台/自动化/自动化流水线...", false, 340)] + public static void Open() + { + var win = GetWindow(false, "LQA 自动化流水线", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 700); + win.Refresh(); + win.Show(); + } + + // ========================================== + // 配置快照 (启动/刷新时从各自持久化配置读取一次, 运行期不再变更) + // ========================================== + + /// + /// 平台连接配置 (Host / DownloadHost / 鉴权令牌), 决定请求发往哪个平台 + /// + private LqaPlatformConfig _conn; + + /// + /// 项目配置 (project_id), 提交结果时关联到的项目上下文 + /// + private LqaProjectConfig _proj; + + /// + /// 任务配置 (job_id), 指定监控/拉取哪个任务批次的数据 + /// + private LqaJobConfig _job; + + /// + /// 筛选配置 (language / count / minID / module_ids), 决定 "怎么从任务里筛数据" + /// + private LqaFilterConfig _filter; + + /// + /// 提交配置 (提供 ai_sign 开关), 提交结果时决定是否触发平台 AI 检测 + /// + private LqaSubmitConfig _submit; + + // ========================================== + // 可调参数 (仅停机态可改, 运行期锁定) + // ========================================== + + /// + /// 监控轮询间隔 (秒): 两轮监控之间的等待时间, 范围 5~300, 默认 30 + /// + private float _monitorInterval = 30f; + + /// + /// 还原后是否自动提交: 关掉则只拉取+还原(供人工核对), 不走提交步骤 + /// + private bool _autoSubmit = true; + + // ========================================== + // 运行状态机 + // ========================================== + + /// + /// 流水线阶段枚举: + /// Stopped 未运行; + /// Monitoring 等待到点并发起监控请求; + /// ListPending 监控请求进行中(等清单返回); + /// Downloading 处理当前条目: 下载 dump(下载完成后同步还原); + /// Submitting 处理当前条目: 提交还原结果 + /// + private enum Phase { Stopped, Monitoring, ListPending, Downloading, Submitting } + + /// + /// 当前流水线阶段, 由 Tick 驱动流转 + /// + private Phase _phase = Phase.Stopped; + + /// + /// 平台客户端 (启动时按连接配置构造, 全程复用) + /// + private LqaApiClient _client; + + /// + /// 当前进行中的 HTTP 请求句柄 (监控/下载/提交三种请求复用同一字段, 同一时刻只有一个在飞) + /// + private LqaRequest _req; + + /// + /// 下次发起监控的时间点 (以 EditorApplication.timeSinceStartup 为基准) + /// + private double _nextMonitorTime; + + /// + /// 还原引擎实例 (启动时构造, 逐条还原时复用同一实例) + /// + private RestoreEngine _engine; + + /// + /// 本次运行使用的译文文件路径 (启动时从持久化配置读一次; 空 = 用原文还原) + /// + private string _translationPath; + + /// + /// 本次运行使用的字体变体模板 (启动时读一次; 空 = 字体按 dump 原样还原) + /// + private string _fontVariantTemplate; + + /// + /// 当前批次待处理队列 (由一次监控返回的 datas 解析而来, 逐条消费) + /// + private readonly List _queue = new List(); + + /// + /// _qIndex: 队列中当前处理到的下标; _retry: 当前条目已重试次数 + /// + private int _qIndex, _retry; + + /// + /// 单条目的最大尝试次数 (含首次): 达到即跳过该条 + /// + private const int MaxRetry = 3; + + /// + /// 当前条目落盘后的 dump json 路径 (还原/提交都基于其所在目录读写) + /// + private string _curJsonPath; + + /// + /// 当前条目的平台 data_id (字符串形式, 用于日志与提交) + /// + private string _curDataId; + + // ========================================== + // 统计与游标 + // ========================================== + + /// + /// 运行以来累计: 拉取 / 还原 / 提交 / 失败 条数 (界面统计栏显示) + /// + private int _totalPulled, _totalRestored, _totalSubmitted, _totalFailed; + + /// + /// 已处理过的最大 data_id, 作为下次监控请求的 minID, 避免重复领取 + /// + private long _minIdCursor; + + /// + /// 日志区滚动位置 + /// + private Vector2 _scrollLog; + + /// + /// 运行日志缓冲 (界面日志区显示的文本源) + /// + private readonly StringBuilder _log = new StringBuilder(); + + /// + /// 单条待处理数据: Id(平台 data_id)、FilePath(平台 dump 存储路径)、ModuleId(所属模块) + /// + private class DataItem { public int Id; public string FilePath; public string ModuleId; } + + /// + /// 窗口失活/关闭时停止流水线, 防止后台状态机继续跑或请求悬挂 + /// + private void OnDisable() { StopInternal(); } + + /// + /// 窗口获得焦点时, 若处于停机态则刷新一次配置快照 (让界面显示最新的四类配置) + /// + private void OnFocus() { if (_phase == Phase.Stopped) Refresh(); } + + /// + /// 重新读取平台/项目/任务/筛选四类持久化配置到本地快照 + /// + private void Refresh() + { + _conn = LqaPlatformConfig.Load(); + _proj = LqaProjectConfig.Load(); + _job = LqaJobConfig.Load(); + _filter = LqaFilterConfig.Load(); + _submit = LqaSubmitConfig.Load(); + } + + /// + /// EditorWindow 的 IMGUI 绘制回调: 顶部说明 + 只读配置回显 + 可调参数 + 启停按钮 + 状态/统计/日志 + /// + private void OnGUI() + { + // 点击空白处时取消输入框焦点, 避免键盘控制停留在某个控件上 + if (Event.current != null && Event.current.type == EventType.MouseDown) + GUIUtility.keyboardControl = 0; + + EditorGUILayout.LabelField("自动化流水线", EditorStyles.boldLabel); + Rect helpRect = EditorGUILayout.GetControlRect(false, 62f); + EditorGUI.HelpBox(helpRect, + "自动循环: 监控任务数据 → 有数据则逐条 下载→还原(截图+导框)→提交 → 继续监控,\n" + + "配置取自 平台连接/项目配置/任务配置/筛选变量/提交配置 及 译文文件/字体变体 配置 (语言码 用筛选里选的平台码, 最小ID 自动推进),\n" + + "整条流水线在编辑器内运行 (还原依赖编辑器); 关闭窗口即停止", + MessageType.Info); + + // 只读回显当前生效的四类配置, 便于启动前核对 + EditorGUILayout.Space(2); + DrawReadonly("平台 Host (仅查看)", string.IsNullOrEmpty(_conn.Host) ? "(未配置)" : _conn.Host); + DrawReadonly("项目 ID (仅查看)", _proj.ProjectId); + DrawReadonly("任务 ID (仅查看)", _job.JobId); + DrawReadonly("语言码 (仅查看)", string.IsNullOrEmpty(_filter.Language) ? "(未选, 去 筛选变量 拉取选择)" : _filter.Language); + DrawReadonly("筛选 (仅查看)", string.Format("数量={0} 模块ID={1} 最小ID(游标)={2}", + _filter.Count, + string.IsNullOrEmpty(_filter.ModuleIds) ? "(空)" : _filter.ModuleIds, _minIdCursor)); + DrawReadonly("译文文件 (仅查看)", string.IsNullOrEmpty(LqaTranslationConfig.GetPath()) + ? "(未配置, 用原文还原)" : LqaTranslationConfig.GetPath()); + + EditorGUILayout.Space(4); + + // 运行中禁用可调参数, 只有停机态才允许修改间隔与自动提交开关 + using (new EditorGUI.DisabledScope(_phase != Phase.Stopped)) + { + _monitorInterval = EditorGUILayout.Slider( + new GUIContent("监控间隔 (秒)", "两轮监控之间的等待时间"), _monitorInterval, 5f, 300f); + _autoSubmit = EditorGUILayout.Toggle( + new GUIContent("还原后自动提交", "关闭则只监控+拉取+还原, 提交留人工 (用 \"提交还原结果\" 菜单)"), _autoSubmit); + } + + EditorGUILayout.Space(6); + + // 启停按钮随阶段切换: 停机显示 "启动", 其余显示 "停止" + if (_phase == Phase.Stopped) + { + if (GUILayout.Button("启动流水线", GUILayout.Height(30))) StartPipeline(); + } + else + { + if (GUILayout.Button("停止流水线", GUILayout.Height(30))) { StopInternal(); AppendLog("== 已停止 =="); } + } + + EditorGUILayout.Space(4); + EditorGUILayout.LabelField("状态", PhaseText()); + EditorGUILayout.LabelField("统计", string.Format( + "拉取 {0} / 还原 {1} / 提交 {2} / 失败 {3}", _totalPulled, _totalRestored, _totalSubmitted, _totalFailed)); + + // 有日志时才绘制可滚动的日志区 + if (_log.Length > 0) + { + EditorGUILayout.LabelField("日志", EditorStyles.boldLabel); + _scrollLog = EditorGUILayout.BeginScrollView(_scrollLog, GUILayout.ExpandHeight(true)); + string logText = _log.ToString(); + // 按内容真实高度绘制: 内容多则可滚动、不裁剪; 内容少则不硬撑留白 + // 预留约 25px 给竖向滚动条, 使换行宽度与实际绘制宽度一致 + float logWidth = EditorGUIUtility.currentViewWidth - 25f; + float logHeight = EditorStyles.textArea.CalcHeight(new GUIContent(logText), logWidth); + EditorGUILayout.SelectableLabel(logText, EditorStyles.textArea, + GUILayout.Width(logWidth), GUILayout.Height(logHeight)); + EditorGUILayout.EndScrollView(); + } + } + + /// + /// 绘制一行 "标签 + 只读可选中文本" (用文本框样式呈现, 方便复制但不可编辑) + /// + /// 左侧前缀标签 + /// 右侧显示值 (null 视为空串) + private void DrawReadonly(string label, string value) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(label); + EditorGUILayout.SelectableLabel(value ?? "", EditorStyles.textField, + GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + } + + /// + /// 把当前阶段翻译成界面状态栏的人类可读文本 (监控倒计时 / 清单获取中 / 第几条下载或提交) + /// + private string PhaseText() + { + switch (_phase) + { + case Phase.Monitoring: + double wait = _nextMonitorTime - EditorApplication.timeSinceStartup; + return wait > 0 ? string.Format("监控中: {0:0}s 后拉取下一批", wait) : "监控中: 即将拉取"; + case Phase.ListPending: return "监控中: 正在获取任务清单..."; + case Phase.Downloading: return string.Format("处理中 {0}/{1}: 下载 数据ID={2}", _qIndex + 1, _queue.Count, _curDataId); + case Phase.Submitting: return string.Format("处理中 {0}/{1}: 提交 数据ID={2}", _qIndex + 1, _queue.Count, _curDataId); + default: return "已停止"; + } + } + + // ========================================== + // 启停 + // ========================================== + + /// + /// 启动流水线: 校验必填配置 → 构造客户端与还原引擎 → 重置统计与游标 → + /// 读取译文/字体变体配置 → 挂接 EditorApplication.update 状态机 → 立即发起首次监控 + /// 任一前置校验失败则记日志并中止, 不进入运行态 + /// + private void StartPipeline() + { + Refresh(); + // 前置校验: Host / Job / Project 必填; 自动提交额外要求 Language 为有效数字码 + if (string.IsNullOrEmpty(_conn.Host)) { AppendLog("[错误] 平台 Host 未配置 (平台连接)"); return; } + if (_job.IsIdle) { AppendLog("[错误] 任务 ID 未配置或为 0 (任务配置)"); return; } + if (string.IsNullOrEmpty(_proj.ProjectId) || _proj.ProjectId == "0") { AppendLog("[错误] 项目 ID 未配置 (项目配置)"); return; } + if (_autoSubmit && !IsAllDigits(_filter.Language)) { AppendLog("[错误] 自动提交需要有效 语言码 (去 筛选变量 拉取选择)"); return; } + + _client = new LqaApiClient(_conn); + _engine = new RestoreEngine(new EditorFontResolver(), new EditorSceneHost()); + _totalPulled = _totalRestored = _totalSubmitted = _totalFailed = 0; + // minID 初始取筛选配置 (可为 0), 之后自动推进 + long.TryParse(_filter.MinID, out _minIdCursor); + + // 读取持久化的译文文件配置 (译文文件配置窗口设置); 路径失效则回退原文还原 + _translationPath = LqaTranslationConfig.GetPath(); + if (!string.IsNullOrEmpty(_translationPath) && !File.Exists(_translationPath)) + { + _translationPath = null; + } + + // 读取持久化的字体变体模板 (字体变体配置窗口设置); 空=字体按 dump 原样还原 + _fontVariantTemplate = LqaFontVariantConfig.GetTemplate(); + + _log.Length = 0; + AppendLog("== 流水线启动 (间隔 " + _monitorInterval + "s, 自动提交=" + _autoSubmit + + ", 译文=" + (string.IsNullOrEmpty(_translationPath) ? "原文" : _translationPath) + + ", 字体变体=" + (string.IsNullOrEmpty(_fontVariantTemplate) ? "无" : _fontVariantTemplate) + ") =="); + + // 先摘再挂, 避免重复订阅导致 Tick 被多次调用 + EditorApplication.update -= Tick; + EditorApplication.update += Tick; + // 立即发起第一次监控 + _nextMonitorTime = EditorApplication.timeSinceStartup; + _phase = Phase.Monitoring; + Repaint(); + } + + /// + /// 停止流水线并复位: 摘除状态机回调 → 中止并释放在飞请求 → 清空队列 → 回到停机态 + /// (统计与游标不清零, 便于停机后查看结果) + /// + private void StopInternal() + { + EditorApplication.update -= Tick; + if (_req != null) { _req.Abort(); _req = null; } + _queue.Clear(); + _phase = Phase.Stopped; + } + + // ========================================== + // 状态机主循环 + // ========================================== + + /// + /// 挂在 EditorApplication.update 上的每帧驱动: 按当前阶段分派到对应的 Tick 处理 + /// + private void Tick() + { + switch (_phase) + { + case Phase.Monitoring: TickMonitoring(); break; + case Phase.ListPending: TickListPending(); break; + case Phase.Downloading: TickDownloading(); break; + case Phase.Submitting: TickSubmitting(); break; + } + } + + /// + /// 监控阶段: 未到点只刷新倒计时显示; 到点则发起 GET /api/job/datas 并切到 ListPending + /// + private void TickMonitoring() + { + // 到点才发起监控请求, 否则刷新一下倒计时显示 + if (EditorApplication.timeSinceStartup < _nextMonitorTime) { Repaint(); return; } + + AppendLog("[监控] 拉取清单 (最小ID>" + _minIdCursor + ", 数量=" + _filter.Count + ") ..."); + _req = _client.GetJobDatas(_job.JobId, _filter.Language, + _filter.Count, _minIdCursor.ToString(), _filter.ModuleIds); + _phase = Phase.ListPending; + Repaint(); + } + + /// + /// 等清单返回: 请求未完成直接返回; 失败则排下一轮监控; 成功则解析队列, + /// 无数据排下一轮监控, 有数据则累计并开始逐条下载 + /// + private void TickListPending() + { + if (_req == null || !_req.Poll()) return; + + if (_req.Kind != LqaResponseKind.Success) + { + AppendLog(" -> 监控请求失败: " + Describe(_req) + " (稍后重试)"); + _req = null; + ScheduleNextMonitor(); + return; + } + + string body = _req.Text; + _req = null; + int n = ParseList(body); + if (n <= 0) + { + AppendLog(" -> 暂无新数据"); + ScheduleNextMonitor(); + return; + } + + AppendLog(" -> 发现 " + n + " 条新数据, 开始处理"); + _totalPulled += n; + _qIndex = 0; _retry = 0; + BeginItemDownload(); + } + + /// + /// 解析监控返回体 data.datas[] 填充待处理队列; 跳过缺 id/file_path 的无效条目, 返回入队条数 + /// + /// GET /api/job/datas 的响应体 JSON + private int ParseList(string body) + { + _queue.Clear(); + object root = null; + try { root = MiniJson.Parse(body); } catch { } + var rootDict = root as Dictionary; + var data = rootDict.Get>("data"); + var datas = data != null ? data.Get>("datas") : null; + if (datas == null) return 0; + foreach (var o in datas) + { + var d = o as Dictionary; + if (d == null) continue; + int id = d.GetInnerInt("id", 0); + string fp = d.GetInnerString("file_path", ""); + if (id <= 0 || string.IsNullOrEmpty(fp)) continue; + _queue.Add(new DataItem { Id = id, FilePath = fp, ModuleId = d.GetInnerString("module_id", "") }); + } + return _queue.Count; + } + + // ========================================== + // 逐条: 下载 + // ========================================== + + /// + /// 开始下载当前下标的条目: 队列耗尽则收尾批次; 否则记录 data_id 并发起 dump 下载, 切到 Downloading + /// + private void BeginItemDownload() + { + if (_qIndex >= _queue.Count) { OnBatchDone(); return; } + var item = _queue[_qIndex]; + _curDataId = item.Id.ToString(); + _retry = 0; + AppendLog(string.Format("[{0}/{1}] 数据ID={2} 文件路径={3} 下载 ...", _qIndex + 1, _queue.Count, _curDataId, item.FilePath)); + _req = _client.DownloadDataDump(item.FilePath); + _phase = Phase.Downloading; + Repaint(); + } + + /// + /// 等下载返回: 成功则 gzip 解码并按 "每条独立目录" 落盘为 dump json, 随后同步还原; + /// 下载或解码/落盘失败走重试或跳过 + /// + private void TickDownloading() + { + if (_req == null || !_req.Poll()) return; + var item = _queue[_qIndex]; + + if (_req.Kind == LqaResponseKind.Success) + { + byte[] raw = _req.Bytes; + _req = null; + try + { + // 每条独立目录, 避免多条的 Restore.png 互相覆盖 + string dir = Path.Combine(Application.persistentDataPath, "LQAAuto", + "Job_" + Sanitize(_job.JobId), item.Id.ToString()); + Directory.CreateDirectory(dir); + _curJsonPath = Path.Combine(dir, item.Id + ".json"); + // 先解码得到干净 dump json, 落盘后再从中还原无文本背景图 + string json = LqaDumpDecoder.Decode(raw); + File.WriteAllText(_curJsonPath, json, new UTF8Encoding(false)); + // 还原 bg_data -> ScreenShot_NoText.png (供还原引擎铺底图) + TryRestoreBackground(dir, json); + AppendLog(" -> 已落盘, 还原中 ..."); + DoRestore(item); // 同步还原 + } + catch (System.Exception e) + { + AppendLog(" -> 下载/解码/落盘失败: " + e.Message); + RetryOrSkip(BeginItemDownload); + } + } + else + { + AppendLog(" -> 下载失败: " + Describe(_req)); + _req = null; + RetryOrSkip(BeginItemDownload); + } + } + + /// + /// 同步还原当前条目 (截图 Restore.png + 导出 rect_locations.json), 然后进入提交或跳到下一条 + /// 还原异常计失败并跳过; 未产出 Restore.png (无可见文本) 或关闭自动提交时, 仅还原不提交 + /// + /// 当前处理的数据条目 (用于取 module_id 等) + private void DoRestore(DataItem item) + { + try + { + // 同步: 完成后目录内已有 Restore.png(+rect_locations.json) + _engine.RestoreFromDump(_curJsonPath, _translationPath, _fontVariantTemplate); + _totalRestored++; + } + catch (System.Exception e) + { + AppendLog(" -> 还原失败: " + e.Message); + _totalFailed++; + NextItem(); + return; + } + + string png = Path.Combine(Path.GetDirectoryName(_curJsonPath), "Restore.png"); + if (!File.Exists(png)) + { + AppendLog(" -> 还原未产出 Restore.png (可能无可见文本), 跳过提交"); + NextItem(); + return; + } + + if (!_autoSubmit) + { + AppendLog(" -> 已还原 (自动提交关闭), 跳过提交"); + NextItem(); + return; + } + BeginItemSubmit(); + } + + // ========================================== + // 逐条: 提交 + // ========================================== + + /// + /// 开始提交当前条目: 读取还原目录内的 Restore.png 与 rect_locations.json, + /// 发起 POST /api/image/entity (带 language) 并切到 Submitting; 读图失败则计失败并跳过 + /// + private void BeginItemSubmit() + { + string dir = Path.GetDirectoryName(_curJsonPath); + string png = Path.Combine(dir, "Restore.png"); + string rectPath = Path.Combine(dir, "rect_locations.json"); + byte[] bytes; + try { bytes = File.ReadAllBytes(png); } + catch (System.Exception e) { AppendLog(" -> 读还原图失败: " + e.Message); _totalFailed++; NextItem(); return; } + + // 文本框文件缺失时用空对象兜底, 保证提交仍带上合法的 rect_locations 字段 + bool hasRect = File.Exists(rectPath); + string rects = hasRect ? SafeRead(rectPath) : "{}"; + _retry = 0; + string uploadName = _job.JobId + "-" + _curDataId + "-" + _filter.Language + ".png"; + AppendLog(" -> 提交还原结果 (语言=" + _filter.Language + ", AI=" + _submit.TriggerAI + ", 文件名=" + uploadName + ") ..."); + AppendLog(" 图片: " + png); + AppendLog(" JSON: " + (hasRect ? rectPath : rectPath + " (缺失, 用空对象兜底)")); + _req = _client.UploadImageEntity(_proj.ProjectId, _job.JobId, _curDataId, _filter.Language, + rects, bytes, uploadName, _submit.TriggerAI ? "1" : "0"); + _phase = Phase.Submitting; + Repaint(); + } + + /// + /// 等提交返回: 成功则计数并推进到下一条; 失败走重试或跳过 + /// + private void TickSubmitting() + { + if (_req == null || !_req.Poll()) return; + if (_req.Kind == LqaResponseKind.Success) + { + _req = null; + _totalSubmitted++; + AppendLog(" -> 提交成功"); + NextItem(); + } + else + { + AppendLog(" -> 提交失败: " + Describe(_req)); + _req = null; + RetryOrSkip(BeginItemSubmit); + } + } + + // ========================================== + // 条目推进 / 重试 + // ========================================== + + /// + /// 失败后的重试/跳过决策: 未达上限则自增重试次数并重跑给定步骤; 达上限则计失败并跳到下一条 + /// + /// 重试时要重新执行的步骤 (BeginItemDownload / BeginItemSubmit) + private void RetryOrSkip(System.Action retryStep) + { + if (_retry < MaxRetry - 1) + { + _retry++; + AppendLog(" -> 重试 " + _retry + "/" + (MaxRetry - 1) + " ..."); + retryStep(); + } + else + { + _totalFailed++; + AppendLog(" -> 达重试上限, 跳过 data_id=" + _curDataId); + NextItem(); + } + } + + /// + /// 推进到下一条: 先用当前 data_id 推进 minID 游标 (取已处理过的最大 id) 避免下轮重复领取, + /// 再自增下标并复位重试计数, 开始下一条下载 + /// + private void NextItem() + { + // 推进 minID 游标 (取已处理过的最大 id), 避免下轮监控重复领取 + if (int.TryParse(_curDataId, out int cur) && cur > _minIdCursor) _minIdCursor = cur; + _qIndex++; + _retry = 0; + BeginItemDownload(); + } + + /// + /// 当前批次全部处理完毕: 记日志并排下一轮监控 + /// + private void OnBatchDone() + { + AppendLog("[批次完成] 继续监控 (最小ID 已推进到 " + _minIdCursor + ")"); + ScheduleNextMonitor(); + } + + /// + /// 安排下一轮监控: 设定下次监控时间点并切回 Monitoring 阶段 + /// + private void ScheduleNextMonitor() + { + _nextMonitorTime = EditorApplication.timeSinceStartup + _monitorInterval; + _phase = Phase.Monitoring; + Repaint(); + } + + // ========================================== + // 辅助 + // ========================================== + + /// + /// 安全读取文本文件: 任何异常都回落为空 JSON 对象 "{}", 不抛出 + /// + /// 文件路径 + private static string SafeRead(string p) { try { return File.ReadAllText(p); } catch { return "{}"; } } + + /// + /// 判断字符串是否非空且全部由数字字符组成 (用于校验 Language 是否为合法平台数字码) + /// + private static bool IsAllDigits(string s) + { + if (string.IsNullOrEmpty(s)) return false; + foreach (char c in s) if (c < '0' || c > '9') return false; + return true; + } + + /// + /// 把字符串清洗为合法文件名片段 (非法字符替换为 '_'; 空值回退 "0"), 用于拼接落盘目录名 + /// + private static string Sanitize(string s) + { + if (string.IsNullOrEmpty(s)) return "0"; + foreach (char c in Path.GetInvalidFileNameChars()) s = s.Replace(c, '_'); + return s; + } + + /// + /// 从 dump json 取出 bg_data(PNG 的 hex), 还原成纯背景图 ScreenShot_NoText.png + /// 还原引擎 (RestoreEngine) 铺底图依赖此文件; 无 bg_data 或还原失败均只记日志, 不中断流水线 + /// + /// 该数据项的落盘子目录 (背景图写入此处) + /// 已解码的 dump json 文本 + private void TryRestoreBackground(string itemDir, string json) + { + // 解析 dump 取 bg_data (PNG 的 hex 编码); 无此字段则跳过, 属正常情况 + object root = null; + try { root = MiniJson.Parse(json); } catch { } + var dict = root as Dictionary; + string hex = dict.GetInnerString("bg_data", ""); + if (string.IsNullOrEmpty(hex)) + { + AppendLog(" -> 无 bg_data, 跳过背景图还原"); + return; + } + try + { + // hex -> 字节 -> 写为 PNG 文件 + byte[] png = HexToBytes(hex); + string bgPath = Path.Combine(itemDir, "ScreenShot_NoText.png"); + File.WriteAllBytes(bgPath, png); + AppendLog(" -> 背景图还原成功: ScreenShot_NoText.png (" + png.Length + " 字节)"); + } + catch (System.Exception e) + { + // 背景图还原失败不影响 json 已保存成功, 仅记日志 + AppendLog(" -> 背景图还原失败: " + e.Message); + } + } + + /// hex 字符串转字节 (与上传侧 ToHex 互逆; 逐字符解析, 避免大字符串 Substring 开销) + /// 十六进制字符串 (长度须为偶数) + /// 解析出的字节数组; 空输入返回空数组 + private static byte[] HexToBytes(string hex) + { + if (string.IsNullOrEmpty(hex)) return new byte[0]; + if ((hex.Length & 1) != 0) throw new System.Exception("bg_data hex 长度非偶数"); + var bytes = new byte[hex.Length / 2]; + // 每两个 hex 字符合成一个字节 (高 4 位 + 低 4 位) + for (int i = 0; i < bytes.Length; i++) + { + int hi = HexVal(hex[i * 2]); + int lo = HexVal(hex[i * 2 + 1]); + if (hi < 0 || lo < 0) throw new System.Exception("bg_data 含非法 hex 字符"); + bytes[i] = (byte)((hi << 4) | lo); + } + return bytes; + } + + /// + /// 单个 hex 字符转 0-15 的数值 (兼容大小写), 非法字符返回 -1 + /// + /// 十六进制字符 0-9/a-f/A-F + /// 对应数值 0-15; 非法字符返回 -1 + private static int HexVal(char c) + { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + } + + /// + /// 把失败请求翻译成人类可读的错误描述 (业务归类 + 可选 HTTP 码 + 底层错误信息), 用于日志 + /// + /// 已完成且非成功的请求句柄 + private static string Describe(LqaRequest req) + { + var sb = new StringBuilder(); + switch (req.Kind) + { + case LqaResponseKind.AuthFailed: sb.Append("鉴权未通过 (JWT无效/过期)"); break; + case LqaResponseKind.NetworkError: sb.Append("网络不可达 (检查Host/内网)"); break; + case LqaResponseKind.ServerError: sb.Append("服务端错误"); break; + default: sb.Append("未知"); break; + } + if (req.Code > 0) sb.Append(" [HTTP ").Append(req.Code).Append("]"); + if (!string.IsNullOrEmpty(req.Error)) sb.Append(" ").Append(req.Error); + return sb.ToString(); + } + + /// + /// 追加一行日志到缓冲并触发界面重绘 (让日志区实时刷新) + /// + /// 要追加的日志行 + private void AppendLog(string line) { _log.AppendLine(line); Repaint(); } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaPullDataWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaPullDataWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d0b9cf9373d5019e8498bcfd1e6f01174c0e071 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaPullDataWindow.cs @@ -0,0 +1,656 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Windows\LqaPullDataWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Json; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 拉取项目任务数据到本地 (EditorWindow) + /// 职责: 按当前 "平台连接 + 项目 + 任务" 配置, 从平台拉取一批任务数据 (dump) 下载到本地, + /// 并以平台的数据标识 (data_id) 命名每个文件 + /// 完整链路 (均由平台源码确认): + /// 1. GET /api/job/datas?job_id=&language=&count=&minID=&module_ids= + /// -> data.datas = [{ id, file_path, module_id }]; id 即平台 data_id, file_path 是 gzip dump 的存储路径; + /// 2. 逐条 GET {DownloadHost}{file_path} 下载 gzip 原始字节; + /// 3. LqaDumpDecoder 三连解码 (魔数判定 -> GZip解压 -> 截断到最后 '}') 得 dump json; + /// 4. 以 data_id 命名建子目录落盘: {persistentDataPath}/LQAPull/Job_{jobId}/{data_id}/{data_id}.json, + /// 并把 dump 里的 bg_data(PNG hex) 还原为同目录下的 ScreenShot_NoText.png + /// 依赖: LqaApiClient(HTTP) / LqaDumpDecoder(解码) / MiniJson+DictExt(解析清单与 bg_data) / + /// LqaPlatformConfig(连接) + LqaProjectConfig(项目) + LqaJobConfig(任务标识) + LqaFilterConfig(筛选变量) + /// 编辑器内无 MonoBehaviour 主循环, 故用 EditorApplication.update 逐帧轮询请求句柄, 不用协程 + /// 本窗口做 "拉取+落盘+背景图还原"; UI 结构层面的还原仍是 RestoreEngine 的职责, 可另起功能对接 + /// + public class LqaPullDataWindow : EditorWindow + { + /// + /// 菜单入口: Tools/LQA/平台/单步/拉取任务数据... + /// 打开 (或聚焦已存在的) 窗口, 锁定固定大小并在主编辑器内居中, 打开时先刷新一次配置快照 + /// + [MenuItem("Tools/LQA/平台/单步/拉取任务数据...", false, 320)] + public static void Open() + { + var win = GetWindow(true, "LQA 拉取任务数据", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 700); + win.Refresh(); + win.Show(); + } + + // ========================================== + // 配置快照 (打开/聚焦时从 EditorPrefs 刷新, 全程只读展示) + // ========================================== + + /// + /// 平台连接配置 (Host / DownloadHost / 鉴权令牌等) + /// + private LqaPlatformConfig _conn; + + /// + /// 项目配置 (project_id 等) + /// + private LqaProjectConfig _proj; + + /// + /// 任务配置 (job_id 任务批次标识) + /// + private LqaJobConfig _job; + + /// + /// 筛选变量配置 (language/count/minID/module_ids) + /// + private LqaFilterConfig _filter; + + // ========================================== + // 运行时状态 + // ========================================== + + /// + /// 拉取流程的阶段: 就绪 -> 拉清单 -> 下载 -> 完成 + /// + private enum Phase { Idle, FetchingList, Downloading, Done } + + /// + /// 当前所处阶段, 决定 Tick 走哪条分支与 UI 展示 + /// + private Phase _phase = Phase.Idle; + + /// + /// 本次拉取使用的 HTTP 客户端 (StartPull 时按当前连接配置新建) + /// + private LqaApiClient _client; + + /// + /// 拉清单的请求句柄 (每帧 Poll 直至完成) + /// + private LqaRequest _listReq; + + /// + /// 当前正在下载的 dump 请求句柄 (每帧 Poll 直至完成) + /// + private LqaRequest _dumpReq; + + /// + /// 待下载队列 (由清单解析填充) + /// + private readonly List _queue = new List(); + + /// + /// 当前处理到队列的第几个 (下载阶段游标) + /// + private int _index; + + /// + /// 当前项已重试次数 + /// + private int _retry; + + /// + /// 单个数据项的最大尝试次数 (含首次), 达上限则跳过 + /// + private const int MaxRetry = 3; + + /// + /// 成功落盘条数 / 失败(跳过)条数, 用于进度与完成汇总 + /// + private int _okCount, _failCount; + + /// + /// 本次落盘的根目录 (以 job 分组) + /// + private string _outputDir = ""; + + /// + /// 日志区滚动位置 + /// + private Vector2 _scroll; + + /// + /// 过程日志缓冲 (追加式, 显示在窗口底部) + /// + private readonly StringBuilder _log = new StringBuilder(); + + /// + /// 清单中的一条数据项 + /// + private class DataItem + { + /// + /// 平台数据标识 data_id, 用作本地文件/目录命名 + /// + public int Id; + + /// + /// 该条 dump 在平台的存储路径 (gzip), 供下载用 + /// + public string FilePath; + + /// + /// 所属模块 ID + /// + public string ModuleId; + } + + /// + /// 窗口重新获得焦点时: 仅在空闲/已完成状态刷新配置快照 + /// 避免在拉取进行中因用户在别处改配置而打断当前流程 + /// + private void OnFocus() { if (_phase == Phase.Idle || _phase == Phase.Done) Refresh(); } + + /// + /// 从 EditorPrefs 重新载入四份配置快照 (连接/项目/任务/筛选) + /// + private void Refresh() + { + _conn = LqaPlatformConfig.Load(); + _proj = LqaProjectConfig.Load(); + _job = LqaJobConfig.Load(); + _filter = LqaFilterConfig.Load(); + } + + /// + /// IMGUI 绘制回调: 顶部说明 + 当前配置摘要(只读) + 操作区 + 状态/进度 + 日志 + /// + private void OnGUI() + { + EditorGUILayout.LabelField("拉取任务数据到本地", EditorStyles.boldLabel); + EditorGUILayout.HelpBox( + "按当前 \"平台连接 + 项目 + 任务 + 筛选变量\" 配置拉取一批 Dump 数据到本地, 以平台数据标识 (data_id) 命名\n" + + "配置分别在 Tools/LQA/平台/配置 的 平台连接 / 项目配置 / 任务配置 / 筛选变量 里设置", + MessageType.Info); + + EditorGUILayout.Space(4); + + // 当前配置摘要 (只读展示, 空/未配置时给出引导文案) + EditorGUILayout.LabelField("当前配置", EditorStyles.boldLabel); + DrawReadonly("平台 Host (仅查看)", string.IsNullOrEmpty(_conn.Host) ? "(未配置, 去 平台连接 设置)" : _conn.Host); + DrawReadonly("项目 ID (仅查看)", string.IsNullOrEmpty(_proj.ProjectId) || _proj.ProjectId == "0" + ? "(未配置, 去 项目配置 设置)" : _proj.ProjectId); + DrawReadonly("任务 ID (仅查看)", _job.IsIdle ? "(未配置或为0, 去 任务配置 设置)" : _job.JobId); + DrawReadonly("筛选变量 (仅查看)", string.Format("语言={0} 数量={1} 最小ID={2} 模块ID={3}", + _filter.Language, _filter.Count, _filter.MinID, + string.IsNullOrEmpty(_filter.ModuleIds) ? "(空)" : _filter.ModuleIds)); + + EditorGUILayout.Space(6); + + // 操作区: 拉取进行中禁用按钮, 防止重复发起; 有输出目录时可一键在文件管理器中打开 + using (new EditorGUI.DisabledScope(_phase == Phase.FetchingList || _phase == Phase.Downloading)) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("开始拉取", GUILayout.Height(28))) + StartPull(); + using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(_outputDir) || !Directory.Exists(_outputDir))) + { + if (GUILayout.Button("打开输出目录", GUILayout.Width(120), GUILayout.Height(28))) + EditorUtility.RevealInFinder(_outputDir); + } + EditorGUILayout.EndHorizontal(); + } + + // 仅在进行中显示取消按钮 + if (_phase == Phase.FetchingList || _phase == Phase.Downloading) + { + if (GUILayout.Button("取消", GUILayout.Height(22))) + CancelPull("已取消"); + } + + EditorGUILayout.Space(4); + + // 状态/进度: 按当前阶段拼一句人类可读的状态文案 + string status; + switch (_phase) + { + case Phase.FetchingList: status = "正在拉取任务数据清单..."; break; + case Phase.Downloading: status = string.Format("正在下载 {0}/{1} (成功 {2}, 失败 {3})", + _index + 1, _queue.Count, _okCount, _failCount); break; + case Phase.Done: status = string.Format("完成: 共 {0} 条, 成功 {1}, 失败 {2}", + _queue.Count, _okCount, _failCount); break; + default: status = "就绪"; break; + } + EditorGUILayout.LabelField("状态", status); + if (!string.IsNullOrEmpty(_outputDir)) + DrawReadonly("输出目录 (仅查看)", _outputDir); + + // 日志区: 独立 ScrollView, 上半部分固定不动, 仅此区域随内容滚动 (对齐上传窗口) + if (_log.Length > 0) + { + EditorGUILayout.Space(4); + EditorGUILayout.LabelField("日志", EditorStyles.boldLabel); + _scroll = EditorGUILayout.BeginScrollView(_scroll, GUILayout.ExpandHeight(true)); + string logText = _log.ToString(); + // 按内容真实高度绘制: 内容多则可滚动、不裁剪; 内容少则不硬撑留白 + // 预留约 25px 给竖向滚动条, 使换行宽度与实际绘制宽度一致 + float logWidth = EditorGUIUtility.currentViewWidth - 25f; + float logHeight = EditorStyles.textArea.CalcHeight(new GUIContent(logText), logWidth); + EditorGUILayout.SelectableLabel(logText, EditorStyles.textArea, + GUILayout.Width(logWidth), GUILayout.Height(logHeight)); + EditorGUILayout.EndScrollView(); + } + } + + /// + /// 绘制一行 "只读键值": 左侧前缀标签 + 右侧可选中复制但不可编辑的文本域 + /// + /// 左侧字段名 + /// 右侧只读值 + private void DrawReadonly(string label, string value) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(label); + EditorGUILayout.SelectableLabel(value, EditorStyles.textField, + GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + } + + // ========================================== + // 拉取流程: 校验 -> 拉清单 -> 逐条下载落盘 + // ========================================== + + /// + /// "开始拉取": 刷新配置 -> 前置校验 -> 重置运行时状态 -> 建输出目录 -> 发起清单请求 -> 挂载逐帧轮询 + /// + private void StartPull() + { + Refresh(); + + // 前置校验: Host 与 JobId 是发起拉取的必要条件, 缺失直接失败并引导用户去配置 + if (string.IsNullOrEmpty(_conn.Host)) + { + Fail("平台 Host 未配置, 请先去 Tools/LQA/平台/配置/平台连接 设置"); + return; + } + if (_job.IsIdle) + { + Fail("任务 ID 未配置或为 0, 请先去 Tools/LQA/平台/配置/任务配置 设置一个真实任务批次号"); + return; + } + + // 重置状态: 清空队列/计数/日志, 并按当前连接配置新建客户端 + _queue.Clear(); + _index = 0; _retry = 0; _okCount = 0; _failCount = 0; + _log.Length = 0; + _client = new LqaApiClient(_conn); + + // 输出目录: 以 job 分组, 便于区分不同批次 + _outputDir = Path.Combine( + Application.persistentDataPath, "LQAPull", "Job_" + Sanitize(_job.JobId)); + try { Directory.CreateDirectory(_outputDir); } + catch (System.Exception e) { Fail("创建输出目录失败: " + e.Message); return; } + + AppendLog("输出目录: " + _outputDir); + AppendLog("拉取清单: 任务ID=" + _job.JobId + " 语言=" + _filter.Language + + " 数量=" + _filter.Count + " 最小ID=" + _filter.MinID); + + // 发起清单请求, 进入拉清单阶段, 并把 Tick 挂到 EditorApplication.update 逐帧轮询 (先减后加防重复挂载) + _listReq = _client.GetJobDatas(_job.JobId, _filter.Language, + _filter.Count, _filter.MinID, _filter.ModuleIds); + _phase = Phase.FetchingList; + EditorApplication.update -= Tick; + EditorApplication.update += Tick; + Repaint(); + } + + /// + /// 逐帧轮询总入口 (挂在 EditorApplication.update 上): 按当前阶段分派到拉清单/下载处理 + /// + private void Tick() + { + if (_phase == Phase.FetchingList) TickFetchList(); + else if (_phase == Phase.Downloading) TickDownload(); + } + + /// + /// 拉清单阶段的每帧处理: 等清单请求完成 -> 校验结果 -> 解析清单 -> 无数据则结束/有数据进入下载 + /// + private void TickFetchList() + { + // 未完成则本帧不处理 + if (_listReq == null || !_listReq.Poll()) return; + + // 非 2xx 一律判失败, 附带原因与明细 + if (_listReq.Kind != LqaResponseKind.Success) + { + Fail("拉取清单失败: " + DescribeKind(_listReq) + BuildDetail(_listReq)); + _listReq = null; + return; + } + + string body = _listReq.Text; + _listReq = null; + + // 解析 { code, data: { datas: [{id, file_path, module_id}] } } + int parsed = ParseList(body); + if (parsed < 0) { Fail("清单解析失败: 响应不是预期的 JSON 结构"); return; } + + AppendLog("清单解析成功, 共 " + parsed + " 条待下载"); + if (parsed == 0) + { + // 结构正常但 0 条: 常见于 minID 已越过全部 data_id, 或该 job 本就无数据 + AppendLog("没有符合条件的数据 (检查 最小ID 是否已越过全部 数据ID, 或该 任务 是否有数据)"); + Finish(); + return; + } + + // 进入下载阶段, 从队首开始 + _index = 0; _retry = 0; + _phase = Phase.Downloading; + BeginDownloadCurrent(); + } + + /// 解析清单, 填充 _queue; 返回条数, 结构异常返回 -1 + /// 清单接口返回的 JSON 文本 + /// 有效数据条数; 顶层/ data 结构异常返回 -1; 有 data 但无 datas 视为 0 + private int ParseList(string body) + { + // 顶层必须是对象, 解析失败或非对象即视为结构异常 + object root = null; + try { root = MiniJson.Parse(body); } catch { } + var rootDict = root as Dictionary; + if (rootDict == null) return -1; + + var data = rootDict.Get>("data"); + if (data == null) return -1; + + var datas = data.Get>("datas"); + if (datas == null) return 0; // 有 data 但无 datas, 视为 0 条 + + // 逐条转成 DataItem; 跳过 id 或 file_path 缺失的无效项 + foreach (var o in datas) + { + var d = o as Dictionary; + if (d == null) continue; + var item = new DataItem + { + Id = d.GetInnerInt("id", 0), + FilePath = d.GetInnerString("file_path", ""), + ModuleId = d.GetInnerString("module_id", ""), + }; + if (item.Id <= 0 || string.IsNullOrEmpty(item.FilePath)) + { + AppendLog("跳过一条无效项 (数据ID 或 文件路径 缺失)"); + continue; + } + _queue.Add(item); + } + return _queue.Count; + } + + /// + /// 为队列当前项发起 dump 下载请求, 并记一条进度日志 + /// + private void BeginDownloadCurrent() + { + var item = _queue[_index]; + AppendLog(string.Format("[{0}/{1}] 下载 数据ID={2} {3}", + _index + 1, _queue.Count, item.Id, item.FilePath)); + _dumpReq = _client.DownloadDataDump(item.FilePath); + Repaint(); + } + + /// + /// 下载阶段的每帧处理: 等 dump 请求完成 -> 成功则解码/落盘/还原背景图并推进, 失败则重试或跳过 + /// + private void TickDownload() + { + // 未完成则本帧不处理 + if (_dumpReq == null || !_dumpReq.Poll()) return; + + var item = _queue[_index]; + + if (_dumpReq.Kind == LqaResponseKind.Success) + { + byte[] raw = _dumpReq.Bytes; + _dumpReq = null; + try + { + // 三连解码得到干净 dump json + string json = LqaDumpDecoder.Decode(raw); + // 以平台标识 (data_id) 命名建子目录, json 与还原的背景图都放进去 + string itemDir = Path.Combine(_outputDir, item.Id.ToString()); + Directory.CreateDirectory(itemDir); + string path = Path.Combine(itemDir, item.Id + ".json"); + // 用无 BOM 的 UTF-8 写出, 避免下游解析对 BOM 敏感 + File.WriteAllText(path, json, new UTF8Encoding(false)); + _okCount++; + AppendLog(" -> 保存成功: " + item.Id + "/" + item.Id + ".json (" + json.Length + " 字符)"); + TryRestoreBackground(itemDir, json); // 新增: 还原纯背景图 + AdvanceNext(); + } + catch (System.Exception e) + { + // 解码或落盘出错: 走重试/跳过逻辑 + AppendLog(" -> 解码/落盘失败: " + e.Message); + RetryOrSkip(item); + } + } + else + { + // 下载本身失败 (鉴权/网络/服务端): 走重试/跳过逻辑 + string detail = DescribeKind(_dumpReq) + BuildDetail(_dumpReq); + _dumpReq = null; + AppendLog(" -> 下载失败: " + detail); + RetryOrSkip(item); + } + } + + /// 当前项重试或跳过, 然后推进 + /// 当前处理的数据项 (仅用于日志) + private void RetryOrSkip(DataItem item) + { + // 未达上限则原地重试同一项; 达上限则计失败并推进到下一项 + if (_retry < MaxRetry - 1) + { + _retry++; + AppendLog(" -> 重试 " + _retry + "/" + (MaxRetry - 1) + " ..."); + BeginDownloadCurrent(); + } + else + { + _failCount++; + AppendLog(" -> 达重试上限, 跳过 数据ID=" + item.Id); + AdvanceNext(); + } + } + + /// + /// 推进到队列下一项: 重置重试计数; 队列走完则收尾, 否则发起下一项下载 + /// + private void AdvanceNext() + { + _index++; + _retry = 0; + if (_index >= _queue.Count) { Finish(); return; } + BeginDownloadCurrent(); + } + + /// + /// 正常收尾: 摘除逐帧轮询, 置完成态, 打印汇总, 刷新资源库并重绘 + /// + private void Finish() + { + EditorApplication.update -= Tick; + _phase = Phase.Done; + AppendLog(string.Format("== 完成: 共 {0} 条, 成功 {1}, 失败 {2} ==", + _queue.Count, _okCount, _failCount)); + AssetDatabase.Refresh(); + Repaint(); + } + + /// + /// 用户主动取消: 摘除轮询, 中止在途请求并释放, 置完成态并记原因 + /// + /// 取消原因 (写入日志) + private void CancelPull(string reason) + { + EditorApplication.update -= Tick; + if (_listReq != null) { _listReq.Abort(); _listReq = null; } + if (_dumpReq != null) { _dumpReq.Abort(); _dumpReq = null; } + _phase = Phase.Done; + AppendLog("== " + reason + " =="); + Repaint(); + } + + /// + /// 因错误终止: 摘除轮询, 中止在途请求并释放, 置完成态并记错误信息 + /// + /// 错误描述 (写入日志) + private void Fail(string msg) + { + EditorApplication.update -= Tick; + if (_listReq != null) { _listReq.Abort(); _listReq = null; } + if (_dumpReq != null) { _dumpReq.Abort(); _dumpReq = null; } + _phase = Phase.Done; + AppendLog("[错误] " + msg); + Repaint(); + } + + // ========================================== + // 辅助 + // ========================================== + + /// + /// 向日志缓冲追加一行并触发重绘, 使日志实时可见 + /// + /// 日志内容 (自动换行) + private void AppendLog(string line) + { + _log.AppendLine(line); + Repaint(); + } + + /// 把 Kind 翻译成人类可读的原因 + /// 已完成的请求句柄 + /// 该失败归类对应的中文原因描述 + private static string DescribeKind(LqaRequest req) + { + switch (req.Kind) + { + case LqaResponseKind.AuthFailed: + return "鉴权未通过 (JWT 无效/过期, 或被 302 跳登录页)"; + case LqaResponseKind.NetworkError: + return "网络不可达 (检查 Host / 是否在内网)"; + case LqaResponseKind.ServerError: + return "服务端错误"; + default: + return "未知"; + } + } + + /// + /// 拼接失败明细: 有 HTTP 码则附 [HTTP xxx], 有底层错误则附错误文本 + /// + /// 已完成的请求句柄 + /// 形如 " [HTTP 500] xxx" 的补充明细 (可能为空) + private static string BuildDetail(LqaRequest req) + { + var sb = new StringBuilder(); + if (req.Code > 0) sb.Append(" [HTTP ").Append(req.Code).Append("]"); + if (!string.IsNullOrEmpty(req.Error)) sb.Append(" ").Append(req.Error); + return sb.ToString(); + } + + /// 清洗成安全的文件夹名片段 (防止 JobId 里有异常字符) + /// 原始字符串 (通常是 JobId) + /// 非法文件名字符被替换为 '_' 的安全片段; 空则返回 "0" + private static string Sanitize(string s) + { + if (string.IsNullOrEmpty(s)) return "0"; + foreach (char c in Path.GetInvalidFileNameChars()) + s = s.Replace(c, '_'); + return s; + } + + /// 从 dump json 取出 bg_data(PNG 的 hex), 还原成纯背景图 ScreenShot_NoText.png + /// 该数据项的落盘子目录 (背景图写入此处) + /// 已解码的 dump json 文本 + private void TryRestoreBackground(string itemDir, string json) + { + // 解析 dump 取 bg_data (PNG 的 hex 编码); 无此字段则跳过, 属正常情况 + object root = null; + try { root = MiniJson.Parse(json); } catch { } + var dict = root as Dictionary; + string hex = dict.GetInnerString("bg_data", ""); + if (string.IsNullOrEmpty(hex)) + { + AppendLog(" -> 无 bg_data, 跳过背景图还原"); + return; + } + try + { + // hex -> 字节 -> 写为 PNG 文件 + byte[] png = HexToBytes(hex); + string bgPath = Path.Combine(itemDir, "ScreenShot_NoText.png"); + File.WriteAllBytes(bgPath, png); + AppendLog(" -> 背景图还原成功: ScreenShot_NoText.png (" + png.Length + " 字节)"); + } + catch (System.Exception e) + { + // 背景图还原失败不影响 json 已保存成功, 仅记日志 + AppendLog(" -> 背景图还原失败: " + e.Message); + } + } + + /// hex 字符串转字节 (与上传侧 ToHex 互逆; 逐字符解析, 避免大字符串 Substring 开销) + /// 十六进制字符串 (长度须为偶数) + /// 解析出的字节数组; 空输入返回空数组 + /// 长度非偶数或含非法 hex 字符时抛出 + private static byte[] HexToBytes(string hex) + { + if (string.IsNullOrEmpty(hex)) return new byte[0]; + if ((hex.Length & 1) != 0) throw new System.Exception("bg_data hex 长度非偶数"); + var bytes = new byte[hex.Length / 2]; + // 每两个 hex 字符合成一个字节 (高 4 位 + 低 4 位) + for (int i = 0; i < bytes.Length; i++) + { + int hi = HexVal(hex[i * 2]); + int lo = HexVal(hex[i * 2 + 1]); + if (hi < 0 || lo < 0) throw new System.Exception("bg_data 含非法 hex 字符"); + bytes[i] = (byte)((hi << 4) | lo); + } + return bytes; + } + + /// + /// 单个 hex 字符转 0-15 的数值 (兼容大小写), 非法字符返回 -1 + /// + /// 十六进制字符 0-9/a-f/A-F + /// 对应数值 0-15; 非法字符返回 -1 + private static int HexVal(char c) + { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaSubmitRestoreWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaSubmitRestoreWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..268fb015bd1df994e6aaa89beae274d8261c59d2 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaSubmitRestoreWindow.cs @@ -0,0 +1,528 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Windows\LqaSubmitRestoreWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 提交还原结果到平台 (EditorWindow) + /// 职责: 把 "手动还原(跳过背景)" 产出的还原图连同文本框上传到平台, 关联到对应的平台 data_id + /// 一个 "可提交项" = 一个还原目录, 需含三样 (还原流程与拉取落盘约定产生): + /// - {data_id}.json: dump(拉取时以 data_id 命名落盘), 文件名即平台 data_id; + /// - Restore.png: 还原结果图(RestoreEngine 截图输出到 dump 同目录); + /// - rect_locations.json: 文本框(RestoreEngine 还原时导出, 平台 rect_locations 格式) + /// 上传: POST /api/image/entity (multipart, 见 LqaApiClient.UploadImageEntity), ai_sign=0 只存图与框、不触发 AI + /// project_id 取自 Project Config; job_id 取自 Job Config; language 在本窗口填 (平台内部语言码, 数字) + /// 编辑器内用 EditorApplication.update 逐帧轮询请求句柄, 不用协程 + /// + public class LqaSubmitRestoreWindow : EditorWindow + { + /// + /// 菜单入口: Tools/LQA/平台/单步/提交还原结果... + /// 打开 (或聚焦已存在的) 窗口, 锁定固定大小且在主编辑器窗口内居中, 打开即刷新一次配置快照 + /// + [MenuItem("Tools/LQA/平台/单步/提交还原结果...", false, 322)] + public static void Open() + { + // 普通 (非 utility) 窗口: utility 置顶会挡住 OpenFolderPanel + var win = GetWindow(false, "LQA 提交还原结果", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 700); + win.Refresh(); + win.Show(); + } + + /// + /// 平台连接配置快照 (Host / 鉴权令牌等, Refresh 时从 LqaPlatformConfig 载入) + /// + private LqaPlatformConfig _conn; + + /// + /// 项目配置快照 (提供 project_id, Refresh 时从 LqaProjectConfig 载入) + /// + private LqaProjectConfig _proj; + + /// + /// 任务配置快照 (提供 job_id, Refresh 时从 LqaJobConfig 载入) + /// + private LqaJobConfig _job; + + /// + /// 提交配置快照 (提供 ai_sign 开关, Refresh 时从 LqaSubmitConfig 载入) + /// + private LqaSubmitConfig _submit; + + /// + /// 平台内部语言码 (数字字符串), 只读: 取自筛选变量(Filter Config)选好的语言, 本窗口不编辑 + /// + private string _language = ""; + + /// + /// 待提交的还原目录列表 (每个目录为一个可提交项) + /// + private readonly List _dirs = new List(); + + /// + /// 是否正在提交中 (提交期间禁用编辑类按钮, 避免中途改动列表) + /// + private bool _running; + + /// + /// 当前处理到的目录下标 (_index) 与当前目录已重试次数 (_retry) + /// + private int _index, _retry; + + /// + /// 单个目录的最大尝试次数 (含首次, 即最多重试 MaxRetry-1 次) + /// + private const int MaxRetry = 3; + + /// + /// 平台客户端 (StartSubmit 时按当前连接配置构造) + /// + private LqaApiClient _client; + + /// + /// 当前在途的上传请求句柄 (Tick 中每帧轮询直至完成) + /// + private LqaRequest _req; + + /// + /// 累计成功 (_okCount) 与失败 (_failCount) 的目录数 + /// + private int _okCount, _failCount; + + /// + /// 目录列表滚动位置 (_scrollDirs) 与日志区滚动位置 (_scrollLog) + /// + private Vector2 _scrollDirs, _scrollLog; + + /// + /// 运行日志缓冲 (AppendLog 追加, OnGUI 只读展示) + /// + private readonly StringBuilder _log = new StringBuilder(); + + /// + /// 待处理的文件夹选择类型: 无 / 选单个还原目录 / 选父目录扫子目录 + /// + private enum PendingPick { None, Single, Parent } + + /// + /// 已排队但尚未执行的文件夹选择类型 (延迟到 GUI 帧外才真正弹窗) + /// + private PendingPick _pendingPick = PendingPick.None; + + /// + /// 是否已向 delayCall 注册过一次待执行的选择 (防止重复注册) + /// + private bool _pickScheduled; + + /// + /// 窗口重新获得焦点时: 非提交中则刷新配置快照, 同步其它配置窗口的改动 + /// + private void OnFocus() { if (!_running) Refresh(); } + + /// + /// 窗口禁用/关闭时清理: 反注册延迟选择与逐帧轮询, 并中止在途请求, 防止回调打到已销毁窗口 + /// + private void OnDisable() + { + if (_pickScheduled) { EditorApplication.delayCall -= DoPendingPick; _pickScheduled = false; } + EditorApplication.update -= Tick; + if (_req != null) { _req.Abort(); _req = null; } + } + + /// + /// 从各配置载入最新快照 (连接/项目/任务), 语言只读复用筛选变量里选好的数字码 + /// + private void Refresh() + { + _conn = LqaPlatformConfig.Load(); + _proj = LqaProjectConfig.Load(); + _job = LqaJobConfig.Load(); + _submit = LqaSubmitConfig.Load(); + // 语言只读复用筛选变量 (Filter Config) 里选好的数字码, 本窗口不再输入语言 + _language = LqaFilterConfig.Load().Language; + } + + /// + /// 一个还原目录是否可提交: 含 Restore.png + rect_locations.json + 至少一个 {digits}.json + /// + private static bool IsRestoreDir(string dir) + { + if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) return false; + if (!File.Exists(Path.Combine(dir, "Restore.png"))) return false; + return !string.IsNullOrEmpty(FindDataIdJson(dir)); + } + + /// + /// 在目录里找 "文件名是纯数字的 json" (即拉取落盘的 {data_id}.json), 返回其 data_id; 找不到返回 "" + /// + private static string FindDataIdJson(string dir) + { + foreach (var p in Directory.GetFiles(dir, "*.json")) + { + string name = Path.GetFileNameWithoutExtension(p); + if (IsAllDigits(name)) return name; + } + return ""; + } + + /// + /// 判断字符串是否为非空且全部由数字字符 (0-9) 组成 + /// + private static bool IsAllDigits(string s) + { + if (string.IsNullOrEmpty(s)) return false; + foreach (char c in s) if (c < '0' || c > '9') return false; + return true; + } + + /// + /// 绘制面板: 顶部只读配置上下文 + 待提交目录列表(增删) + 开始/取消按钮 + 状态与日志 + /// + private void OnGUI() + { + // 见上一窗口经验: MouseDown 时清键盘焦点, 避免 SelectableLabel 抢焦点吃掉按钮首次点击 + if (Event.current != null && Event.current.type == EventType.MouseDown) + GUIUtility.keyboardControl = 0; + + EditorGUILayout.LabelField("提交还原结果到平台", EditorStyles.boldLabel); + + // 固定高度画 HelpBox, 避免自动高度在两趟布局不一致导致下方按钮点击热区错位 + Rect helpRect = EditorGUILayout.GetControlRect(false, 58f); + EditorGUI.HelpBox(helpRect, + "把手动还原产出的 Restore.png + rect_locations.json 提交到平台 (POST /api/image/entity, AI标记 由 \"提交配置\" 决定)\n" + + "目录需含: {数据ID}.json + Restore.png + rect_locations.json, 项目ID/任务ID 取自 项目配置/任务配置", + MessageType.Info); + + EditorGUILayout.Space(2); + DrawReadonly("平台 Host (仅查看)", string.IsNullOrEmpty(_conn.Host) ? "(未配置)" : _conn.Host); + DrawReadonly("项目 ID (仅查看)", _proj.ProjectId); + DrawReadonly("任务 ID (仅查看)", _job.JobId); + + // 语言只读: 取自 "筛选变量" 窗口选好的数字码, 本窗口不输入 (改语言请去 Filter Config 拉取选择) + DrawReadonly("语言码 (仅查看)", string.IsNullOrEmpty(_language) + ? "(未设置, 请去 筛选配置 拉取并选择语言)" : _language); + + EditorGUILayout.Space(6); + + EditorGUILayout.LabelField("待提交目录 (" + _dirs.Count + ")", EditorStyles.boldLabel); + using (new EditorGUI.DisabledScope(_running)) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("添加目录...")) SchedulePick(PendingPick.Single); + if (GUILayout.Button("添加父目录(扫子目录)...")) SchedulePick(PendingPick.Parent); + if (GUILayout.Button("清空", GUILayout.Width(60))) _dirs.Clear(); + EditorGUILayout.EndHorizontal(); + } + + _scrollDirs = EditorGUILayout.BeginScrollView(_scrollDirs, GUILayout.Height(120)); + int removeAt = -1; + for (int i = 0; i < _dirs.Count; i++) + { + EditorGUILayout.BeginHorizontal(); + bool ok = IsRestoreDir(_dirs[i]); + // 不可提交的目录前打 ⚠ 标记, 提示缺文件 + EditorGUILayout.LabelField(ok ? "" : "⚠", GUILayout.Width(16)); + EditorGUILayout.SelectableLabel(_dirs[i], + EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)); + using (new EditorGUI.DisabledScope(_running)) + { + if (GUILayout.Button("移除", GUILayout.Width(50))) removeAt = i; + } + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndScrollView(); + // 遍历中不改集合, 循环结束后再删, 避免枚举/布局错位 + if (removeAt >= 0) _dirs.RemoveAt(removeAt); + + EditorGUILayout.Space(6); + + using (new EditorGUI.DisabledScope(_running || _dirs.Count == 0)) + { + if (GUILayout.Button("开始提交", GUILayout.Height(28))) StartSubmit(); + } + if (_running && GUILayout.Button("取消", GUILayout.Height(22))) Cancel("已取消"); + + string status = _running + ? string.Format("提交中 {0}/{1} (成功 {2}, 失败 {3})", _index + 1, _dirs.Count, _okCount, _failCount) + : (_okCount + _failCount > 0 + ? string.Format("完成: 成功 {0}, 失败 {1}", _okCount, _failCount) : "就绪"); + EditorGUILayout.LabelField("状态", status); + + if (_log.Length > 0) + { + EditorGUILayout.LabelField("日志", EditorStyles.boldLabel); + _scrollLog = EditorGUILayout.BeginScrollView(_scrollLog, GUILayout.ExpandHeight(true)); + string logText = _log.ToString(); + // 按内容真实高度绘制: 内容多则可滚动、不裁剪; 内容少则不硬撑留白 + // 预留约 25px 给竖向滚动条, 使换行宽度与实际绘制宽度一致 + float logWidth = EditorGUIUtility.currentViewWidth - 25f; + float logHeight = EditorStyles.textArea.CalcHeight(new GUIContent(logText), logWidth); + EditorGUILayout.SelectableLabel(logText, EditorStyles.textArea, + GUILayout.Width(logWidth), GUILayout.Height(logHeight)); + EditorGUILayout.EndScrollView(); + } + } + + /// + /// 画一行只读的 "标签 + 可选中复制文本" (值为空时显示空串) + /// + /// 左侧字段名 + /// 右侧只读展示的值 + private void DrawReadonly(string label, string value) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(label); + EditorGUILayout.SelectableLabel(value ?? "", EditorStyles.textField, + GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + } + + // ========================================== + // 添加目录 (延迟到 GUI 帧外弹选择框) + // ========================================== + + /// + /// 排队一次文件夹选择: 记录选择类型并注册到 delayCall, 待离开 OnGUI 事件流程后再弹窗 + /// (在 OnGUI 里同步弹 OpenFolderPanel 会打断布局, 故延迟到帧外) + /// + /// 本次选择类型 (单个目录 / 父目录扫子目录) + private void SchedulePick(PendingPick which) + { + _pendingPick = which; + if (_pickScheduled) return; + _pickScheduled = true; + EditorApplication.delayCall += DoPendingPick; + } + + /// + /// delayCall 回调: 反注册自身并取出排队的选择类型, 真正执行目录添加 + /// + private void DoPendingPick() + { + EditorApplication.delayCall -= DoPendingPick; + _pickScheduled = false; + var which = _pendingPick; + _pendingPick = PendingPick.None; + if (which == PendingPick.None) return; + AddDir(which == PendingPick.Parent); + } + + /// + /// 弹文件夹选择框并把结果加入待提交列表: + /// asParent=true 时把所选目录及其可提交子目录逐个加入; 否则只加所选的单个目录 (不可提交则记日志提示) + /// + /// true=按父目录扫描其下的还原子目录; false=添加单个还原目录 + private void AddDir(bool asParent) + { + string picked = EditorUtility.OpenFolderPanel( + asParent ? "选择父目录 (扫描其下的还原子目录)" : "选择一个还原目录", "", ""); + if (string.IsNullOrEmpty(picked)) return; + + if (asParent) + { + int added = 0; + foreach (var sub in Directory.GetDirectories(picked)) + if (IsRestoreDir(sub) && !_dirs.Contains(sub)) { _dirs.Add(sub); added++; } + // 父目录自身也可能就是一个还原目录, 一并纳入 + if (IsRestoreDir(picked) && !_dirs.Contains(picked)) { _dirs.Add(picked); added++; } + AppendLog("扫描到 " + added + " 个可提交还原目录"); + } + else + { + if (_dirs.Contains(picked)) return; + _dirs.Add(picked); + if (!IsRestoreDir(picked)) + AppendLog("⚠ 该目录缺少 Restore.png 或 {数据ID}.json, 提交时会被跳过: " + picked); + } + Repaint(); + } + + // ========================================== + // 提交流程 + // ========================================== + + /// + /// 开始提交: 先刷新并校验前置配置 (Host/JobId/ProjectId/Language), 全部就绪后 + /// 重置计数与日志, 构造客户端, 注册逐帧轮询 Tick, 并从第一个目录开始处理 + /// + private void StartSubmit() + { + Refresh(); + if (string.IsNullOrEmpty(_conn.Host)) { Fatal("平台 Host 未配置, 去 平台连接配置 设置"); return; } + if (_job.IsIdle) { Fatal("任务ID 未配置或为 0, 去 任务配置 设置"); return; } + if (string.IsNullOrEmpty(_proj.ProjectId) || _proj.ProjectId == "0") { Fatal("项目ID 未配置, 去 项目配置 设置"); return; } + if (!IsAllDigits(_language)) { Fatal("语言 未设置或非数字码; 请去 筛选配置 拉取并选择语言"); return; } + + _client = new LqaApiClient(_conn); + _running = true; + _index = 0; _retry = 0; _okCount = 0; _failCount = 0; + _log.Length = 0; + AppendLog("开始提交, 共 " + _dirs.Count + " 个目录"); + + EditorApplication.update -= Tick; + EditorApplication.update += Tick; + BeginDir(); + } + + /// + /// 开始处理当前下标的目录: 全部处理完则收尾; + /// 目录不可提交 (缺文件) 则计失败并跳到下一个; 否则发起本目录的上传 + /// + private void BeginDir() + { + if (_index >= _dirs.Count) { Finish(); return; } + string dir = _dirs[_index]; + _retry = 0; + + AppendLog(string.Format("[{0}/{1}] {2}", _index + 1, _dirs.Count, dir)); + + if (!IsRestoreDir(dir)) + { + _failCount++; + AppendLog(" -> 跳过: 缺 Restore.png 或 {数据ID}.json"); + NextDir(); + return; + } + SendCurrent(); + } + + /// + /// 发起当前目录的上传请求: 读 data_id / Restore.png / rect_locations.json + /// (读图失败则计失败并跳下一个; 无 rect 文件则用空框 "{}" 兜底), 调 UploadImageEntity 得到在途句柄 _req + /// + private void SendCurrent() + { + string dir = _dirs[_index]; + string dataId = FindDataIdJson(dir); + string pngPath = Path.Combine(dir, "Restore.png"); + string rectPath = Path.Combine(dir, "rect_locations.json"); + + byte[] png; + try { png = File.ReadAllBytes(pngPath); } + catch (System.Exception e) { _failCount++; AppendLog(" -> 读图失败: " + e.Message); NextDir(); return; } + + string rects = "{}"; + if (File.Exists(rectPath)) + { + try { rects = File.ReadAllText(rectPath); } + catch (System.Exception e) { AppendLog(" -> 读 rect_locations 失败 (用空框): " + e.Message); } + } + else AppendLog(" -> 无 rect_locations.json, 用空框提交"); + + string uploadName = _job.JobId + "-" + dataId + "-" + _language + ".png"; + AppendLog(" 提交还原结果 (数据ID=" + dataId + ", 语言=" + _language + ", AI=" + _submit.TriggerAI + ", 文件名=" + uploadName + ") ..."); + _req = _client.UploadImageEntity(_proj.ProjectId, _job.JobId, dataId, _language, rects, png, uploadName, _submit.TriggerAI ? "1" : "0"); + Repaint(); + } + + /// + /// 逐帧轮询 (挂在 EditorApplication.update): 请求完成后按结果分流—— + /// 成功则计数并进下一目录; 失败则在未达重试上限时重发, 否则计失败并进下一目录 + /// + private void Tick() + { + if (!_running || _req == null || !_req.Poll()) return; + + if (_req.Kind == LqaResponseKind.Success) + { + _req = null; + _okCount++; + AppendLog(" -> 提交成功"); + NextDir(); + } + else + { + string detail = Describe(_req); + _req = null; + AppendLog(" -> 提交失败: " + detail); + if (_retry < MaxRetry - 1) + { + _retry++; + AppendLog(" -> 重试 " + _retry + "/" + (MaxRetry - 1) + " ..."); + SendCurrent(); + } + else + { + _failCount++; + AppendLog(" -> 达重试上限, 该目录失败"); + NextDir(); + } + } + } + + /// + /// 前进到下一个目录并开始处理 + /// + private void NextDir() { _index++; BeginDir(); } + + /// + /// 全部目录处理完毕的收尾: 反注册轮询, 置为非运行态, 记录汇总结果 + /// + private void Finish() + { + EditorApplication.update -= Tick; + _running = false; + AppendLog(string.Format("== 完成: 成功 {0}, 失败 {1} ==", _okCount, _failCount)); + Repaint(); + } + + /// + /// 中途取消: 反注册轮询, 中止在途请求, 置为非运行态并记录原因 + /// + /// 取消原因 (写入日志) + private void Cancel(string reason) + { + EditorApplication.update -= Tick; + if (_req != null) { _req.Abort(); _req = null; } + _running = false; + AppendLog("== " + reason + " =="); + Repaint(); + } + + /// + /// 记录一条致命前置错误到日志 (前置校验不通过时用, 不启动流程) + /// + /// 错误说明 + private void Fatal(string msg) { AppendLog("[错误] " + msg); Repaint(); } + + /// + /// 把失败请求归类翻译成可读文案 (业务归类 + 可选 HTTP 码 + Error + 截断后的响应体) + /// + /// 已完成且非成功的请求句柄 + private static string Describe(LqaRequest req) + { + var sb = new StringBuilder(); + switch (req.Kind) + { + case LqaResponseKind.AuthFailed: sb.Append("鉴权未通过 (JWT无效/过期)"); break; + case LqaResponseKind.NetworkError: sb.Append("网络不可达 (检查Host/内网)"); break; + case LqaResponseKind.ServerError: sb.Append("服务端错误"); break; + default: sb.Append("未知"); break; + } + if (req.Code > 0) sb.Append(" [HTTP ").Append(req.Code).Append("]"); + if (!string.IsNullOrEmpty(req.Error)) sb.Append(" ").Append(req.Error); + // 响应体可能很长, 只取前 160 字符入日志, 避免刷屏 + if (!string.IsNullOrEmpty(req.Text)) sb.Append(" ").Append(req.Text.Length > 160 ? req.Text.Substring(0, 160) : req.Text); + return sb.ToString(); + } + + /// + /// 追加一行日志并请求重绘 (使日志区实时刷新) + /// + /// 日志行文本 + private void AppendLog(string line) { _log.AppendLine(line); Repaint(); } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaUploadDataWindow.cs b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaUploadDataWindow.cs new file mode 100644 index 0000000000000000000000000000000000000000..72919e7dd6b546154265359fa32eadb66dbf6084 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Platform/Editor/Windows/LqaUploadDataWindow.cs @@ -0,0 +1,720 @@ +// ========================================== +// 文件: LQARestore\Platform\Editor\Windows\LqaUploadDataWindow.cs +// 模块: Platform.Editor (平台连接 编辑器侧) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; +using LQARestore.Core.Json; +using LQARestore.Core.Editor; + +/// +/// LQARestore 平台连接 编辑器侧命名空间 +/// +namespace LQARestore.Platform.Editor +{ + /// + /// 上传单条或多条数据到平台 (EditorWindow) + /// 职责: 把一个或多个 LQATool 采集产物目录 (含 ui_data_text.json + ScreenShot_*.png) 上传到平台 + /// 每个目录走三步链路 (对齐平台上传协议, 顺序不能乱): + /// 1. POST /api/data/entity 用补全后的 data json 建 data, 拿平台 data_id; + /// 2. POST /api/upload_file 上传截图, 拿 file_path; + /// 3. PATCH /api/data/entity 回填 shot_img_path + module_id + resource_version + /// 数据整理 (字段补全/截图定位) 在 LqaUploadPayload; HTTP 三步在 LqaApiClient(UploadDataJson/UploadFile/UpdateDataImage) + /// project_id 取自 LqaProjectConfig, job_id 取自 LqaJobConfig, module_id/resource_version 取自 LqaProjectConfig + /// 编辑器内无 MonoBehaviour 主循环, 故用 EditorApplication.update 逐帧轮询请求句柄, 不用协程 + /// + public class LqaUploadDataWindow : EditorWindow + { + /// + /// 菜单入口: 打开(或聚焦)上传采集数据窗口, 并刷新配置快照 + /// + [MenuItem("Tools/LQA/平台/单步/上传采集数据...", false, 321)] + public static void Open() + { + // 用普通 (可停靠) 窗口而非 utility 窗口: utility 窗口 always-on-top, 会挡住/抢焦点 + // 导致 EditorUtility.OpenFolderPanel 弹出的系统文件夹对话框无法正常显示 (表现为 "点了没反应") + var win = GetWindow(false, "LQA 上传采集数据", true); + LqaWindowLayout.ApplyFixedCentered(win, 800, 700); + win.Refresh(); + win.Show(); + } + + // ========================================== + // 配置快照 (打开/聚焦时从各 Config 读一次, 上传全程用此快照) + // ========================================== + + /// + /// 平台连接配置 (Host / 鉴权令牌), 用于构造 LqaApiClient + /// + private LqaPlatformConfig _conn; + + /// + /// 项目配置, 提供 project_id + /// + private LqaProjectConfig _proj; + + /// + /// 任务配置, 提供 job_id + /// + private LqaJobConfig _job; + + /// + /// 上传配置, 提供回填用的 module_id / resource_version + /// + private LqaUploadConfig _upload; + + /// + /// 待上传目录列表 (每项为一个 LQATool 采集产物目录的绝对路径) + /// + private readonly List _dirs = new List(); + + // ========================================== + // 运行时状态 + // 每个目录内部三步: BuildPayload -> PostData -> UploadImg -> PatchData + // ========================================== + + /// + /// 单个目录内部的上传阶段 (与三步链路一一对应, None 表示当前无进行中的目录) + /// + private enum Step { None, PostData, UploadImg, PatchData } + + /// + /// 是否正在上传中 (为 true 时禁用编辑操作, 并驱动 Tick 轮询) + /// + private bool _running; + + /// + /// 当前正在处理的目录下标 (指向 _dirs) + /// + private int _index; + + /// + /// 当前步骤已重试次数 (每进入新步骤清零) + /// + private int _retry; + + /// + /// 单个步骤的最大尝试次数 (含首次), 超过则该目录判失败 + /// + private const int MaxRetry = 3; + + /// + /// 当前目录所处的上传阶段 + /// + private Step _step = Step.None; + + /// + /// 平台客户端 (StartUpload 时用配置快照构造) + /// + private LqaApiClient _client; + + /// + /// 当前进行中的请求句柄 (每帧 Poll, 完成后按 _step 分派处理) + /// + private LqaRequest _req; + + /// + /// 当前目录整理出的上传素材 (data json + 截图路径) + /// + private LqaUploadPayload.Payload _payload; + + /// + /// 当前目录第1步 (建 data) 拿到的 data_id, 供第 3 步回填 + /// + private string _curDataId; + + /// + /// 当前目录第 2 步 (传截图) 拿到的 file_path, 供第 3 步回填 + /// + private string _curFilePath; + + /// + /// 成功计数 (含 "仅建 data 成功" 的部分成功) + /// + private int _okCount; + + /// + /// 失败计数 (整理失败/达重试上限/非采集目录被跳过) + /// + private int _failCount; + + /// + /// 目录列表滚动位置 + /// + private Vector2 _scrollDirs; + + /// + /// 日志区滚动位置 + /// + private Vector2 _scrollLog; + + /// + /// 累积日志文本 (逐行 AppendLine) + /// + private readonly StringBuilder _log = new StringBuilder(); + + /// + /// 文件夹选择的 "待办" 意图: 单目录还是父目录 (扫子目录) + /// + private enum PendingPick { None, Single, Parent } + + /// + /// 按钮点击时只记录意图, 待本帧 GUI 画完后 (delayCall) 再真正弹对话框 + /// 直接在 OnGUI 按钮回调里同步调 OpenFolderPanel 会打断 IMGUI 事件循环, 导致"偶尔弹不出来" + /// + private PendingPick _pendingPick = PendingPick.None; + + /// + /// 是否已挂上延迟回调, 防止重复 delayCall + /// + private bool _pickScheduled; + + /// + /// 窗口重新获得焦点时刷新配置快照 (上传进行中不刷, 避免中途换配置) + /// + private void OnFocus() { if (!_running) Refresh(); } + + /// + /// 窗口关闭/禁用时的清理 + /// + private void OnDisable() + { + // 窗口关闭时摘除可能仍挂着的延迟回调, 避免窗口销毁后仍被触发 + if (_pickScheduled) + { + EditorApplication.delayCall -= DoPendingPick; + _pickScheduled = false; + } + } + + /// + /// 重新从磁盘加载四份配置, 刷新界面用的只读快照 + /// + private void Refresh() + { + _conn = LqaPlatformConfig.Load(); + _proj = LqaProjectConfig.Load(); + _job = LqaJobConfig.Load(); + _upload = LqaUploadConfig.Load(); + } + + /// + /// 绘制窗口: 配置摘要 + 目录列表 + 操作区 + 状态 + 日志 (IMGUI) + /// + private void OnGUI() + { + // 修复 "按钮偶尔点了没反应": 界面上有多个可获得焦点的 SelectableLabel (摘要/目录/日志, 为了可复制) + // 当键盘焦点正停在某个 SelectableLabel 上时, 对按钮的第一次 MouseDown 会先被用于 "移走该焦点", + // 这一次点击即被消耗掉、按钮不触发 (焦点在哪个控件是随机的, 故表现为偶发) + // 解决: 在事件到达任何控件之前, 于 MouseDown 时先清掉键盘焦点, 使点击能正常命中按钮 + if (Event.current != null && Event.current.type == EventType.MouseDown) + { + GUIUtility.keyboardControl = 0; + } + + EditorGUILayout.LabelField("上传采集数据到平台", EditorStyles.boldLabel); + // 用 "固定高度" 方式画 HelpBox: EditorGUILayout.HelpBox 的自动高度在 Layout 趟与 Repaint 趟 + // 可能算出不同行数 (含图标+多行中文、窗口宽度临界时尤甚), 两趟高度不一致会把其下方所有控件的 + // 点击热区整体推移 (表现为 "按钮的点击区跑到按钮下方"), 固定高度可彻底消除该偏移 + Rect helpRect = EditorGUILayout.GetControlRect(false, 56f); + EditorGUI.HelpBox(helpRect, + "把一个或多个 LQATool 采集产物目录 (含 ui_data_text.json + ScreenShot_*.png) 上传到平台\n" + + "上传三步: 建 data -> 传截图 -> 回填, 项目ID/任务ID/ 上传字段分别取自 项目配置/任务配置/上传配置", + MessageType.Info); + + // 配置摘要 (只读, 供核对上传去向) + EditorGUILayout.Space(2); + DrawReadonly("平台 Host (仅查看)", string.IsNullOrEmpty(_conn.Host) ? "(未配置)" : _conn.Host); + DrawReadonly("项目 ID (仅查看)", _proj.ProjectId); + DrawReadonly("任务 ID (仅查看)", _job.JobId); + DrawReadonly("模块ID / 版本 (仅查看)", + (string.IsNullOrEmpty(_upload.ModuleId) ? "(空)" : _upload.ModuleId) + " / " + + (string.IsNullOrEmpty(_upload.ResourceVersion) ? "(空)" : _upload.ResourceVersion)); + + EditorGUILayout.Space(6); + + // 待上传目录列表 (含添加/清空按钮, 上传中禁用编辑) + EditorGUILayout.LabelField("待上传目录 (" + _dirs.Count + ")", EditorStyles.boldLabel); + using (new EditorGUI.DisabledScope(_running)) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("添加目录...")) SchedulePick(PendingPick.Single); + if (GUILayout.Button("添加父目录(扫子目录)...")) SchedulePick(PendingPick.Parent); + if (GUILayout.Button("清空", GUILayout.Width(60))) _dirs.Clear(); + EditorGUILayout.EndHorizontal(); + } + + _scrollDirs = EditorGUILayout.BeginScrollView(_scrollDirs, GUILayout.Height(120)); + int removeAt = -1; + for (int i = 0; i < _dirs.Count; i++) + { + EditorGUILayout.BeginHorizontal(); + // 非有效采集目录 (缺 ui_data_text.json) 前面标 ⚠ 提示, 上传时会被跳过 + bool ok = LqaUploadPayload.IsDumpDir(_dirs[i]); + EditorGUILayout.LabelField(ok ? "" : "⚠", GUILayout.Width(16)); + EditorGUILayout.SelectableLabel(_dirs[i], + EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight)); + using (new EditorGUI.DisabledScope(_running)) + { + if (GUILayout.Button("移除", GUILayout.Width(50))) removeAt = i; + } + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndScrollView(); + // 遍历中不能改集合, 记下待移除下标, 循环结束后再删 + if (removeAt >= 0) _dirs.RemoveAt(removeAt); + + EditorGUILayout.Space(6); + + // 操作区: 开始上传 / (上传中) 取消 + using (new EditorGUI.DisabledScope(_running || _dirs.Count == 0)) + { + if (GUILayout.Button("开始上传", GUILayout.Height(28))) StartUpload(); + } + if (_running && GUILayout.Button("取消", GUILayout.Height(22))) CancelUpload("已取消"); + + // 状态行: 运行中显示进度, 结束后显示汇总, 否则 "就绪" + string status = _running + ? string.Format("上传中 {0}/{1} [{2}] (成功 {3}, 失败 {4})", + _index + 1, _dirs.Count, _step, _okCount, _failCount) + : (_okCount + _failCount > 0 + ? string.Format("完成: 成功 {0}, 失败 {1}", _okCount, _failCount) + : "就绪"); + EditorGUILayout.LabelField("状态", status); + + // 日志区 (可复制的 SelectableLabel) + if (_log.Length > 0) + { + EditorGUILayout.LabelField("日志", EditorStyles.boldLabel); + _scrollLog = EditorGUILayout.BeginScrollView(_scrollLog, GUILayout.ExpandHeight(true)); + string logText = _log.ToString(); + // 按内容真实高度绘制: 内容多则可滚动、不裁剪; 内容少则不硬撑留白 + // 预留约 25px 给竖向滚动条, 使换行宽度与实际绘制宽度一致 + float logWidth = EditorGUIUtility.currentViewWidth - 25f; + float logHeight = EditorStyles.textArea.CalcHeight(new GUIContent(logText), logWidth); + EditorGUILayout.SelectableLabel(logText, EditorStyles.textArea, + GUILayout.Width(logWidth), GUILayout.Height(logHeight)); + EditorGUILayout.EndScrollView(); + } + } + + /// + /// 画一行 "标签 + 只读可复制值" (用 SelectableLabel 呈现, 方便复制核对) + /// + /// 左侧标签文本 + /// 右侧只读值 (null 视为空串) + private void DrawReadonly(string label, string value) + { + EditorGUILayout.BeginHorizontal(); + float savedLabelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 180f; // 容纳 "Module Id / Version (仅查看)" 这类较长标签 + EditorGUILayout.PrefixLabel(label); + EditorGUIUtility.labelWidth = savedLabelWidth; // 立即还原, 不影响其它区域 + EditorGUILayout.SelectableLabel(value ?? "", EditorStyles.textField, + GUILayout.Height(EditorGUIUtility.singleLineHeight)); + EditorGUILayout.EndHorizontal(); + } + + // ========================================== + // 添加目录 + // ========================================== + + /// + /// 记录 "要弹文件夹选择框" 的意图, 并调度到本帧 GUI 处理完之后执行 (EditorApplication.delayCall) + /// 关键: 不能在 OnGUI 的按钮回调里同步调 OpenFolderPanel —— 那会在 IMGUI 事件处理中途 + /// 弹出模态系统对话框, 打断事件循环, 造成 "偶尔能弹、偶尔弹不出" 的时序问题 + /// + /// 本次要弹的选择类型 (单目录 / 父目录) + private void SchedulePick(PendingPick which) + { + _pendingPick = which; + if (_pickScheduled) return; // 已调度则不重复 + _pickScheduled = true; + EditorApplication.delayCall += DoPendingPick; + } + + /// + /// 在 GUI 帧外真正弹出文件夹选择框 (由 delayCall 触发) + /// + private void DoPendingPick() + { + EditorApplication.delayCall -= DoPendingPick; + _pickScheduled = false; + var which = _pendingPick; + _pendingPick = PendingPick.None; + if (which == PendingPick.None) return; + AddDir(which == PendingPick.Parent); + } + + /// + /// 弹文件夹选择框并把结果加入待上传列表 (去重) + /// + /// + /// true: 选父目录并扫描其下的采集子目录(父目录本身若也是采集目录一并加入); + /// false: 直接把所选目录当作单个采集目录加入(非采集目录也加, 仅提示上传时会跳过) + /// + private void AddDir(bool asParent) + { + string picked = EditorUtility.OpenFolderPanel( + asParent ? "选择父目录 (将扫描其下的采集子目录)" : "选择一个采集产物目录", "", ""); + if (string.IsNullOrEmpty(picked)) return; + + if (asParent) + { + int added = 0; + foreach (var sub in Directory.GetDirectories(picked)) + { + if (LqaUploadPayload.IsDumpDir(sub) && !_dirs.Contains(sub)) { _dirs.Add(sub); added++; } + } + // 父目录本身也可能就是一个采集目录 + if (LqaUploadPayload.IsDumpDir(picked) && !_dirs.Contains(picked)) { _dirs.Add(picked); added++; } + AppendLog("从父目录扫描到 " + added + " 个采集子目录。"); + } + else + { + if (_dirs.Contains(picked)) return; + _dirs.Add(picked); + if (!LqaUploadPayload.IsDumpDir(picked)) + AppendLog("⚠ 该目录缺少 ui_data_text.json, 上传时会被跳过: " + picked); + } + Repaint(); + } + + // ========================================== + // 上传流程 + // ========================================== + + /// + /// 开始上传: 校验配置 -> 构造客户端 -> 重置计数 -> 挂 Tick 轮询 -> 处理第一个目录 + /// 任一必需配置缺失时直接终止 (Fatal 记日志, 不进入运行态) + /// + private void StartUpload() + { + Refresh(); + if (string.IsNullOrEmpty(_conn.Host)) { Fatal("平台 Host 未配置, 去 Tools/LQA/平台/配置/平台连接 设置"); return; } + if (_job.IsIdle) { Fatal("任务ID 未配置或为 0, 去 Tools/LQA/平台/配置/任务配置 设置"); return; } + if (string.IsNullOrEmpty(_proj.ProjectId) || _proj.ProjectId == "0") { Fatal("项目ID 未配置, 去 Tools/LQA/平台/配置/项目配置 设置"); return; } + + _client = new LqaApiClient(_conn); + _running = true; + _index = 0; _retry = 0; _okCount = 0; _failCount = 0; + _log.Length = 0; + AppendLog("开始上传, 共 " + _dirs.Count + " 个目录"); + + // 先摘再挂, 防止重复订阅导致 Tick 一帧被调多次 + EditorApplication.update -= Tick; + EditorApplication.update += Tick; + BeginDir(); + } + + /// + /// 开始处理当前目录: 整理素材 -> 发起第1步 (整理失败/非采集目录则计失败并跳下一个) + /// + private void BeginDir() + { + if (_index >= _dirs.Count) { Finish(); return; } + + string dir = _dirs[_index]; + _retry = 0; + _curDataId = null; _curFilePath = null; _payload = null; + + AppendLog(string.Format("[{0}/{1}] {2}", _index + 1, _dirs.Count, dir)); + + if (!LqaUploadPayload.IsDumpDir(dir)) + { + _failCount++; + AppendLog(" -> 跳过: 不是有效采集目录 (缺 ui_data_text.json)"); + NextDir(); + return; + } + + try { _payload = LqaUploadPayload.Build(dir); } + catch (System.Exception e) + { + _failCount++; + AppendLog(" -> 整理失败: " + e.Message); + NextDir(); + return; + } + + BeginPostData(); + } + + /// + /// 第1步: 建数据 (POST /api/data/entity), 成功后取 data_id 进第 2 步 + /// + private void BeginPostData() + { + _step = Step.PostData; + AppendLog(" 1) 建数据 (POST /api/data/entity) ..."); + _req = _client.UploadDataJson(_proj.ProjectId, _job.JobId, _payload.DataJson); + Repaint(); + } + + /// + /// 第2步: 传截图 (POST /api/upload_file); 目录无截图时视为部分成功并跳过后两步 + /// + private void BeginUploadImg() + { + if (string.IsNullOrEmpty(_payload.ShotImagePath) || !File.Exists(_payload.ShotImagePath)) + { + // 无截图: 建数据 已成功, 视为部分成功, 跳过后两步 + _okCount++; + AppendLog(" -> 无截图文件, 仅建数据成功 (data_id=" + _curDataId + "), 跳过传图/回填"); + NextDir(); + return; + } + _step = Step.UploadImg; + _retry = 0; + byte[] bytes = File.ReadAllBytes(_payload.ShotImagePath); + string fileName = Path.GetFileName(_payload.ShotImagePath); + AppendLog(" 2) 传截图 " + fileName + " (POST /api/upload_file) ..."); + _req = _client.UploadFile(bytes, fileName); + Repaint(); + } + + /// + /// 第3步: 回填截图路径与 module_id/resource_version (PATCH /api/data/entity) + /// + private void BeginPatchData() + { + _step = Step.PatchData; + _retry = 0; + AppendLog(" 3) 回填截图路径 (PATCH /api/data/entity) ..."); + _req = _client.UpdateDataImage(_curDataId, _curFilePath, _upload.ModuleId, _upload.ResourceVersion); + Repaint(); + } + + /// + /// 每帧轮询当前请求 (挂在 EditorApplication.update): 未完成直接返回, 完成则按 _step 分派到对应回调 + /// + private void Tick() + { + if (!_running || _req == null || !_req.Poll()) return; + + switch (_step) + { + case Step.PostData: OnPostDataDone(); break; + case Step.UploadImg: OnUploadImgDone(); break; + case Step.PatchData: OnPatchDataDone(); break; + } + } + + /// + /// 第 1 步完成回调: 解析 data_id 成功则进第 2 步, 否则按重试策略处理 + /// + private void OnPostDataDone() + { + if (_req.Kind == LqaResponseKind.Success) + { + string dataId = ExtractDataId(_req.Text); + _req = null; + if (string.IsNullOrEmpty(dataId)) + { + AppendLog(" -> 建数据成功但未解析到 数据ID, 响应: " + Trunc(_lastText)); + RetryOrFailStep(BeginPostData); + return; + } + _curDataId = dataId; + AppendLog(" -> 数据ID = " + dataId); + BeginUploadImg(); + } + else + { + AppendLog(" -> 建数据失败: " + Describe(_req)); + _req = null; + RetryOrFailStep(BeginPostData); + } + } + + /// + /// 第 2 步完成回调: 解析 file_path 成功则进第 3 步, 否则按重试策略处理 + /// + private void OnUploadImgDone() + { + if (_req.Kind == LqaResponseKind.Success) + { + string filePath = ExtractFilePath(_req.Text); + _req = null; + if (string.IsNullOrEmpty(filePath)) + { + AppendLog(" -> 传图成功但未解析到 文件路径, 响应: " + Trunc(_lastText)); + RetryOrFailStep(BeginUploadImg); + return; + } + _curFilePath = filePath; + AppendLog(" -> 文件路径 = " + filePath); + BeginPatchData(); + } + else + { + AppendLog(" -> 传图失败: " + Describe(_req)); + _req = null; + RetryOrFailStep(BeginUploadImg); + } + } + + /// + /// 第 3 步完成回调: 回填成功计一次成功并进下一目录, 否则按重试策略处理 + /// + private void OnPatchDataDone() + { + if (_req.Kind == LqaResponseKind.Success) + { + _req = null; + _okCount++; + AppendLog(" -> 上传成功 (数据ID=" + _curDataId + ")"); + NextDir(); + } + else + { + AppendLog(" -> 回填失败: " + Describe(_req)); + _req = null; + RetryOrFailStep(BeginPatchData); + } + } + + /// + /// 当前步骤重试或当前目录失败并跳到下一个 + /// + /// + /// 重试时要重新发起的步骤 (BeginPostData/BeginUploadImg/BeginPatchData) + /// + private void RetryOrFailStep(System.Action retryStep) + { + if (_retry < MaxRetry - 1) + { + _retry++; + AppendLog(" -> 重试 " + _retry + "/" + (MaxRetry - 1) + " ..."); + retryStep(); + } + else + { + _failCount++; + AppendLog(" -> 达重试上限, 该目录失败"); + NextDir(); + } + } + + /// + /// 推进到下一个目录 (下标 +1, 阶段归零, 重新进入 BeginDir) + /// + private void NextDir() + { + _index++; + _step = Step.None; + BeginDir(); + } + + /// + /// 全部目录处理完毕: 摘除 Tick 轮询, 退出运行态并打印汇总 + /// + private void Finish() + { + EditorApplication.update -= Tick; + _running = false; + _step = Step.None; + AppendLog(string.Format("== 完成: 成功 {0}, 失败 {1} ==", _okCount, _failCount)); + Repaint(); + } + + /// + /// 用户取消: 摘除 Tick 轮询, 中止在途请求并退出运行态 + /// + /// 取消原因 (写入日志) + private void CancelUpload(string reason) + { + EditorApplication.update -= Tick; + if (_req != null) { _req.Abort(); _req = null; } + _running = false; + _step = Step.None; + AppendLog("== " + reason + " =="); + Repaint(); + } + + /// 致命前置错误 (配置缺失等): 记日志但不进入运行态 + /// 错误描述 + private void Fatal(string msg) + { + AppendLog("[错误] " + msg); + Repaint(); + } + + // ========================================== + // 响应解析 & 辅助 + // ========================================== + + /// + /// 最近一次响应体原文 (解析失败时用于打印排查) + /// + private string _lastText; + + /// + /// 从建 data 响应 { code, data:{ data:{ id } } } 取 id + /// + /// 第 1 步响应体 JSON 文本 + /// 解析到的 data_id (正整数字符串), 未解析到返回空串 + private string ExtractDataId(string body) + { + _lastText = body; + var root = MiniJson.Parse(body ?? "") as Dictionary; + var data = root.Get>("data"); + var inner = data.Get>("data"); + if (inner == null) return ""; + int id = inner.GetInnerInt("id", 0); + return id > 0 ? id.ToString() : ""; + } + + /// + /// 从传图响应 { code, data:{ file_path } } 取 file_path + /// + /// 第 2 步响应体 JSON 文本 + /// 解析到的 file_path, 未解析到返回空串 + private string ExtractFilePath(string body) + { + _lastText = body; + var root = MiniJson.Parse(body ?? "") as Dictionary; + var data = root.Get>("data"); + return data != null ? data.GetInnerString("file_path", "") : ""; + } + + /// + /// 把请求失败信息翻译成可读文案 (业务归类 + HTTP 码 + 底层错误), 供日志展示 + /// + /// 已完成且非成功的请求句柄 + private static string Describe(LqaRequest req) + { + var sb = new StringBuilder(); + switch (req.Kind) + { + case LqaResponseKind.AuthFailed: sb.Append("鉴权未通过 (JWT无效/过期)"); break; + case LqaResponseKind.NetworkError: sb.Append("网络不可达 (检查Host/内网)"); break; + case LqaResponseKind.ServerError: sb.Append("服务端错误"); break; + default: sb.Append("未知"); break; + } + if (req.Code > 0) sb.Append(" [HTTP ").Append(req.Code).Append("]"); + if (!string.IsNullOrEmpty(req.Error)) sb.Append(" ").Append(req.Error); + return sb.ToString(); + } + + /// + /// 截断过长文本 (超 200 字符加省略号), 避免日志被超大响应体撑爆 + /// + /// 原始文本 + private static string Trunc(string s) + { + if (string.IsNullOrEmpty(s)) return "(空)"; + return s.Length > 200 ? s.Substring(0, 200) + "..." : s; + } + + /// + /// 追加一行日志并请求重绘 (使日志实时可见) + /// + /// 日志行文本 + private void AppendLog(string line) { _log.AppendLine(line); Repaint(); } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/README.md b/timi_hok_game_translator/Unity_LQARestore_Plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8b76fd850ad707b23f8deb49573a6004da0f48 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/README.md @@ -0,0 +1,383 @@ +# LQARestore 插件 + +![Version](https://img.shields.io/badge/version-1.0.0-blue) +![Supported Platforms](https://img.shields.io/badge/platform-Unity%20Editor-lightgrey) +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +--- + +## 简介 + +**LQARestore** 是由 *IEG互动娱乐事业群/天美工作室群* 开发的一个 Unity 引擎插件, 是 **LQATool** 采集工具的下游还原端: 它把采集工具产出的 **Dump 数据** 反向重建为 Unity 场景中的可视文本画面, 并可对接 **LQA 平台** 实现「拉取任务数据 → 还原 → 提交检测结果」的自动化流水线, 服务于本地化 UI 质量检查。 + +- **上游 (LQATool)**: 在游戏运行时采集 UI 节点树、文本属性、字体、可见性与截图, 导出为 Dump JSON (含 `ScreenShot_NoText.png` 无文本背景图)。 +- **本插件 (LQARestore)**: 读取 Dump, 把文本节点树 1:1 重建到还原场景中, 叠加在无文本背景图之上, 截图输出 `Restore.png`, 并导出文本框 `rect_locations.json` 供平台检测使用。 + +--- + +## 使用说明 + +> 本插件的所有功能都是 **Unity 编辑器菜单**, 入口统一在 `Tools/LQA/` 下, 不支持在打出的包里运行 +> 使用前请确认: +> - 工程里同时导入了 **LQATool 采集插件**: `采集` 菜单会直接调用它的接口, 缺少时会编译失败 +> - 已按下文「项目接入指南」完成字体、译文和专属组件的适配 + +### 0. 菜单总览 + +| 菜单 | 作用 | +| --- | --- | +| `Tools/LQA/采集/启用 LQA 采集工具` | 打开或关闭编辑器 Play 模式下的采集悬浮按钮, 菜单前的对勾表示当前状态 | +| `Tools/LQA/采集/设置 Dump 延时秒数...` | 设置点击 Dump 后等多少秒再开始采集 | +| `Tools/LQA/还原/从 Dump 文件还原` | 选一份 Dump JSON 做画面还原, 输出 `Restore.png` 和 `rect_locations.json` | +| `Tools/LQA/还原/文本显隐标记...` | 人工修正每条文本在还原时显示还是隐藏 | +| `Tools/LQA/还原/译文文件配置...` | 指定 `key→译文` JSON, 让还原结果显示译文 | +| `Tools/LQA/还原/字体变体配置...` | 按语种改写字体名 (例如泰语专用字体) | +| `Tools/LQA/平台/配置/...` | 平台连接 / 项目配置 / 任务配置 / 筛选变量 / 上传配置 / 提交配置 | +| `Tools/LQA/平台/单步/...` | 拉取任务数据 / 上传采集数据 / 提交还原结果 | +| `Tools/LQA/平台/自动化/自动化流水线...` | 按「监控 → 下载 → 还原 → 提交」自动循环 | +| `Tools/LQA/恢复默认设置...` | 一键清空本插件写入的所有配置 | + +![菜单总览](docs/images/restore_menu.png) + +常用的三种用法: + +```mermaid +flowchart LR + A[LQATool Dump 目录] -->|本地还原| R[从 Dump 文件还原] + R --> O[Restore.png
rect_locations.json] + A -->|上传采集数据| P[(LQA 平台)] + P -->|拉取任务数据| D["<data_id> 目录"] + D --> R2[从 Dump 文件还原] + R2 -->|提交还原结果| P + P <-->|自动化流水线| AUTO[监控→下载→还原→提交] +``` + +### 1. 在编辑器里辅助采集 (可选) + +在编辑器里直接 Play 采集时, 用下面两个菜单, 不用写代码改开关: + +- **`启用 LQA 采集工具`**: 每点一次切换一次开/关, 状态会保存下来; 正在 Play 时 **立即生效** + - 这个开关只改编辑器本机的 PlayerPrefs, **不影响真机包体**, 真机仍需按采集插件的方式自己开启 +- **`设置 Dump 延时秒数...`**: 填一个大于等于 0 的整数, 点「保存」即生效; 0 表示立即采集 + +![Dump 延时窗口](docs/images/restore_dump_delay.png) + +### 2. 本地还原 (单条 Dump) + +#### 2.1 准备 Dump 目录 + +先把采集产物整个目录拷到电脑上, 确认 **同一个目录** 里有下面两个文件: + +| 文件 | 是否必需 | 说明 | +| --- | --- | --- | +| `ui_data_text.json` (从平台拉下来的数据叫 `.json`) | 必需 | 还原用的 UI 节点树 | +| `ScreenShot_NoText.png` | 强烈建议 | 没有文字的背景图; 缺了也能还原, 但背景是纯黑, Console 会提示 `未找到 ScreenShot_NoText.png, 跳过背景` | + +> 还原结果会直接写回这个目录, 再次还原时同名文件会被 **覆盖** + +#### 2.2 配置译文与字体变体 (可选) + +- **译文**: `Tools/LQA/还原/译文文件配置...` → 点「浏览...」选好译文 JSON → 「保存」 + - 窗口下方会提示当前状态: `未配置` 表示用原文还原 / `路径不存在` 表示会退回原文 / `已配置` 表示按 keyHash 或原文匹配译文 +- **字体变体**: `Tools/LQA/还原/字体变体配置...` → 填一个模板 (例如 `{name}@th`) → 「保存」 + - 模板里没有 `{name}` 占位符时, 这条配置会被忽略 + +两项配置都会保存在本机, 之后的每次还原 (包括自动化流水线) 都会使用, 不需要重复设置 + +![译文与字体变体配置](docs/images/restore_translation_font_config.png) + +#### 2.3 人工修正文本显隐 (可选) + +采集端会按像素差异判断每条文本是否可见, 结果记在 `isVisuallyVisible` 里。如果这个判断不对, 比如被遮住的文字被还原了, 或者能看到的文字没被还原, 可以在还原前手动改: + +1. `Tools/LQA/还原/文本显隐标记...` → 在弹出的对话框里选好 Dump JSON +2. 窗口会把所有文本节点平铺成一个列表: + + | 列 | 说明 | + | --- | --- | + | 显示 | 勾选表示还原时显示; 没有人工标记过时, 默认值等于采集端的判定结果 | + | 原始判定 | 采集端的判定, 只读: 绿色 `✓ 可见` / 红色 `✗ 不可见` | + | name | 节点名 | + | textContent | 单行预览, 换行显示为 `↵`, 太长的会截断; **鼠标悬停可以看到完整原文** | + +3. 用顶部「搜索」框按节点名或文本内容过滤 (不区分大小写), 然后改勾选 +4. 点「保存」, 每个文本节点都会写入 `manualShow` 字段, **直接覆盖原 JSON 文件** (建议先备份) + +还原时有 `manualShow` 就以它为准, 没有就看 `isVisuallyVisible`; 不勾选的节点 **连同它的子节点** 都不会被还原 + +![文本显隐标记窗口](docs/images/restore_text_show.png) + +#### 2.4 执行还原 + +1. **先保存当前场景**: 还原会新建一个场景并替换当前打开的场景, 没保存的修改会丢失 +2. 菜单 `Tools/LQA/还原/从 Dump 文件还原` → 选择 Dump JSON +3. 插件会自动按顺序完成以下步骤: + - 检查 Color Space: 如果 Dump 记录的和当前工程不一致, Console 会给出警告 (还原不中断) + - 新建还原场景 `LQA_Restore_Scene`, 并把 Game 视图分辨率设成 Dump 里的分辨率 (会新增一个叫 `LQA_Restore` 的自定义分辨率) + - 铺上背景图 `ScreenShot_NoText.png` (节点 `LQA_Background_Canvas`) + - 重建可见的文本节点 (配了译文和字体变体就一起生效) + - 截图输出 `Restore.png`, 导出文本框 `rect_locations.json` +4. 完成后 Console 会输出: + + ``` + [LQARestore][EditorSceneHost] 已保存还原画面: /Restore.png + [LQARestore][RestoreEngine] 已导出检测框: /rect_locations.json (文本 N 个, 图片 M 个) + ``` + +![还原完成日志](docs/images/restore_console.png) + +![还原场景](docs/images/restore_scene.png) + +#### 2.5 还原产物 + +| 产物 | 位置 | 说明 | +| --- | --- | --- | +| `Restore.png` | Dump 目录 | 还原后的完整画面, 分辨率和 Dump 一致, 可以直接和 `ScreenShot_Full.png` 对比 | +| `rect_locations.json` | Dump 目录 | 平台检测用的框, 分 `text` (还原后的文本框, 带 `textStr`) 和 `image` (采集端记录的可见图片框) 两组 | +| `LQA_Restore_Scene` | 编辑器当前场景 | 没有保存的还原场景, 可以在 Hierarchy / Inspector 里逐个节点检查 | + +`rect_locations.json` 格式示例 (坐标单位是屏幕像素, **原点在左下角**, 四个角按 左下 → 左上 → 右上 → 右下 排列): + +```json +{ + "text": [ + {"corners":[{"x":100,"y":200},{"x":100,"y":240},{"x":300,"y":240},{"x":300,"y":200}],"textStr":"Start"} + ], + "image": [ + {"corners":[{"x":0,"y":0},{"x":0,"y":1080},{"x":1920,"y":1080},{"x":1920,"y":0}]} + ] +} +``` + +![Full vs Restore](docs/images/restore_full_vs_restore.png) + +### 3. 对接 LQA 平台 + +#### 3.1 首次配置 (每台机器只需一次) + +按下表顺序打开 `Tools/LQA/平台/配置/` 下的各个窗口, 填好后点「保存」, 所有配置都存在本机 EditorPrefs 里, 不会进版本库 + +| 顺序 | 窗口 | 填写内容 | 说明 | +| --- | --- | --- | --- | +| 1 | 平台连接 | `Host` (只写协议和端口, 例如 `http://127.0.0.1:8080`)、`平台接口路径` (例如 `/api-pro`, 可空)、`数据下载路径` (可空)、`Authorization (JWT)` | 点「保存并测试连通性」检查是否能连上 | +| 2 | 项目配置 | `项目ID` | 拉取、上传、提交都要用 | +| 3 | 任务配置 | `任务 ID` | 为空或为 `0` 表示没有远程任务, 不会发起拉取 | +| 4 | 筛选变量 | `语言` (先点「拉取语言」, 再从下拉里选)、`拉取条数` (默认 1)、`最小 ID` (默认 0)、`模块 ID` (多个用 `_` 分隔, 空表示不过滤) | 拉取语言需要先配好 Host 和任务 ID; **拉取和提交都用这里选的语言码** | +| 5 | 上传配置 | `模块ID`、`资源版本` | 只在「上传采集数据」时用, 空就不带 | +| 6 | 提交配置 | `提交后触发 AI 检测` | 勾上后平台收到图片会触发 AI 检测或建 bug; 不勾只保存图和框 | + +连通性测试结果的含义: + +| 提示 | 含义 / 处理 | +| --- | --- | +| 连通成功 (HTTP 2xx) | 网络、服务、鉴权都正常 | +| 鉴权未通过 (302 / 401 / 403) | 能连上平台, 但 JWT 没填、填错或已过期 | +| 连接失败 | Host 填错, 或当前网络访问不到 (例如不在内网) | +| 明文 HTTP 被禁止 | 工程禁用了 HTTP: 按窗口里的步骤把 `Player Settings → Insecure HTTP Option` 改成 `Always allowed`; Unity 2022.1 及以上可以直接点「一键允许 HTTP 连接」 | +| 服务端返回 4xx/5xx | 网络是通的, 请和平台方确认服务状态 | + +![平台连接窗口](docs/images/restore_platform_connection.png) + +![筛选变量窗口](docs/images/restore_filter_config.png) + +#### 3.2 单步模式 + +**A. 上传本地采集数据** + +用于把 LQATool 在本地 Dump 的目录送到平台: + +1. `Tools/LQA/平台/单步/上传采集数据...` +2. 点「添加目录...」选一个 Dump 目录, 或点「添加父目录(扫子目录)...」批量添加; 缺少 `ui_data_text.json` 的目录前面会显示 `⚠`, 上传时会跳过 +3. 点「开始上传」, 每个目录依次执行: **建 data → 传截图 (优先用 `ScreenShot_Full.png`) → 回填模块ID / 资源版本**; 每步失败最多重试 3 次 +4. 平台上的数据名就是目录名, 背景图 `ScreenShot_NoText.png` 会编码后一起传上去 + +![上传采集数据](docs/images/restore_upload_data.png) + +**B. 拉取 → 还原 → 提交** + +1. **拉取**: `Tools/LQA/平台/单步/拉取任务数据...` → 「开始拉取」, 数据按下面的结构保存: + + ``` + Application.persistentDataPath/LQAPull/Job_<任务ID>// + ├── .json # 解码后的 Dump + └── ScreenShot_NoText.png # 用平台数据还原出的背景图 + ``` + + 拉完可以点「打开输出目录」直接跳过去 +2. **还原**: 对每个 `.json` 执行「从 Dump 文件还原」 (需要的话先做文本显隐标记) +3. **提交**: `Tools/LQA/平台/单步/提交还原结果...` → 添加还原好的目录 (必须同时有 `.json` 和 `Restore.png`, 否则显示 `⚠` 并跳过; 没有 `rect_locations.json` 时按空框提交) → 「开始提交」 + - 语言码取「筛选变量」里选的那个, 这个窗口不能改 + - 上传后的文件名是 `<任务ID>--<语言码>.png` + +> 注意: 本地直接 Dump 的目录 (`ui_data_text.json`) 没有平台 `data_id`, **不能直接提交**, 要先用 A 上传到平台, 再按 B 拉回来还原 + +![拉取任务数据](docs/images/restore_pull_data.png) + +![提交还原结果](docs/images/restore_submit.png) + +#### 3.3 自动化流水线 + +用于值守, 把 B 流程自动循环起来: + +1. `Tools/LQA/平台/自动化/自动化流水线...` +2. 确认窗口顶部只读显示的 Host / 项目ID / 任务ID / 语言码 / 筛选条件 / 译文文件都对 +3. 设置参数 (只有停止状态下能改): + - `监控间隔 (秒)`: 5 ~ 300, 默认 30 + - `还原后自动提交`: 关掉后只拉取和还原, 提交可以等人工核对后用「提交还原结果」完成 +4. 点「启动流水线」; 启动前会检查 Host、任务ID、项目ID, 开了自动提交时还会检查语言码, 缺任何一项都会在日志里提示 `[错误]`, 不会启动 +5. 运行中会循环执行: 拉清单 → 逐条下载 → 还原 → 提交 → 等下一轮; 单条失败最多重试 3 次, 之后跳过; 状态栏实时显示 `拉取 / 还原 / 提交 / 失败` 的数量 + +数据保存在 `Application.persistentDataPath/LQAAuto/Job_<任务ID>//`, 每条数据一个目录, 互不覆盖 + +> - **关闭窗口就会停止流水线**; 运行期间每处理一条都会重建还原场景, 请不要同时在编辑器里编辑场景 +> - 「最小 ID」游标从筛选变量里的值开始, 每处理一条自动往后推, 但 **不会写回配置**; 重启流水线后会从筛选变量的值重新开始, 如果不想重复处理, 请先把「筛选变量 → 最小 ID」改成上次日志里最后推进到的值 + +![自动化流水线](docs/images/restore_auto_pipeline.png) + +### 4. 恢复默认设置 + +`Tools/LQA/恢复默认设置...` 会在二次确认后清空本插件的所有配置 (平台连接 / 项目 / 任务 / 筛选 / 上传 / 提交 / 译文 / 字体变体 / 采集开关 / Dump 延时), 并关闭所有打开的 LQA 窗口, **这个操作不能撤销**, 但不会删除已经生成的 Dump 和还原文件 + +--- + +## 常见问题 + +**Q: 还原出来的中文都是方块?** +A: 工程里找不到 Dump 记录的字体, 已经回退到默认字体 (Console 会有警告), 把项目字体放进 `Font/`, 确保字体名和 Dump 里记录的一致; 用了字体变体时, 还要确认工程里有对应的变体字体 + +**Q: Console 提示 `Color Space 不一致`, 还原画面偏亮或偏暗?** +A: 采集包体和当前工程的颜色空间不一样, 到 `Edit → Project Settings → Player → Other Settings → Color Space` 改成提示里 Dump 用的值, 再重新还原 + +**Q: 还原背景是全黑的?** +A: Dump 目录里没有 `ScreenShot_NoText.png`, 本地 Dump 请检查是不是漏拷了; 平台拉下来的数据请看日志里有没有 `无 bg_data`, 如果有, 说明上传时就没带背景图 + +**Q: 有些文本该显示没显示, 或者被遮住的文本也被还原了?** +A: 采集端的可见性判断有误, 用「文本显隐标记」手动改勾选, 保存后重新还原 + +**Q: 配了译文但还原出来还是原文?** +A: 按顺序排查: ① 「译文文件配置」窗口是否显示 `已配置` (路径失效时会退回原文); ② `TextNodeBuilder` 读 keyHash 用的组件键名和字段名是否和本项目一致; ③ Dump 里的 key 和译文表里的 key 是不是同一种算法、同一种格式 + +**Q: 菜单「启用 LQA 采集工具」相关代码编译报错, 找不到 `LQATool`?** +A: 本插件的采集菜单直接依赖 LQATool 采集插件, 请把两个插件一起导入工程 + +**Q: 连通性测试提示鉴权未通过 / 明文 HTTP 被禁止?** +A: 前者请重新获取 JWT 并粘贴到「平台连接」窗口; 后者按窗口里的引导允许 HTTP 连接, 详见「对接 LQA 平台 → 首次配置」里的结果说明 + +**Q: 提交或启动流水线时提示语言码无效?** +A: 语言必须用平台的数字码, 请到「筛选变量」窗口点「拉取语言」, 从下拉里选好后保存 + +**Q: 提交还原结果时目录前面有 `⚠`?** +A: 目录里缺少 `Restore.png` 或 `.json` (文件名必须是纯数字), 本地 Dump 的目录不能直接提交, 要先上传再拉取 + +**Q: 还原后我原来打开的场景不见了?** +A: 还原会新建场景并替换当前场景, 还原前请先保存; 没保存的修改无法恢复 + +--- + +## 目录结构 + +| 目录 | 说明 | 是否需按项目自定义 | +| ---- | ---- | ---- | +| `Core/` | 通用还原内核: 文本节点重建 (`TextNodeBuilder`)、还原引擎 (`RestoreEngine`)、字体解析抽象 (`IFontResolver`)、场景宿主抽象 (`ISceneHost`)、翻译表 (`TranslationTable`) | 基本通用; 仅 `TextNodeBuilder` 有一处内联 keyHash 键名需按项目改 | +| `Entry/` | Unity 编辑器菜单入口 (`Tools/LQA/...`): 从 Dump 还原、文本显隐标记、配置窗口 | 否 (通用) | +| `Platform/` | 对接 LQA 平台的流水线: 拉取任务 / 上传 / 提交 / 自动化 | 流水线通用, 连接参数需按项目填 | +| `Font/` | 还原所需的字体资源 | **是**: 放入你项目自己的字体 | +| `Translation/` | 译文接入: 转换脚本 + `key→译文` JSON + 规范文档 | **是**: 按你项目的译文总表生成 | +| `Core/Runtime/ProjectCustomRestorers.cs` | 项目专属组件的还原器 | **是**: 按你项目的专属组件改写 | + +--- + +## 项目接入指南 + +> `LQARestore` 采用「**通用还原内核 + 项目专属适配**」架构, 接入一个新项目, 只需关注下面 4 个自定义点, 内核 (`Core` 还原流程、`IFontResolver`/`ISceneHost` 抽象、`Platform` 流水线) 均无需改动 + +```mermaid +flowchart LR + A[采集侧 LQATool
产出 Dump] --> B[通用还原内核
Core/TextNodeBuilder] + B --> C{项目自定义适配} + C --> C1[字体资源
Font/] + C --> C2[译文 JSON
Translation/] + C --> C3[专属组件还原器
ProjectCustomRestorers] + C --> C4[平台连接/项目ID
Platform/Config] + C1 & C2 & C3 --> D[Restore.png + rect_locations.json] + C4 --> E[对接 LQA 平台流水线] +``` + +### 1. 放入项目字体资源 (必做) + +还原文本依赖工程内存在对应字体, 否则中文会显示为方块 + +- 把你项目使用的字体 (`.ttf` / `.fnt` 等) 放到 `Font/` 下 +- 字体解析顺序由 `Core/Editor/EditorFontResolver.cs` 实现: + 1. Dump 带 `assetPath` / `guid` → 按路径精确加载; + 2. 仅剩字体名 (如 Android 采集) → 在工程内按名反查; + 3. 查不到 → 回退内置默认字体 (并告警) +- **要点**: 只要字体名与 Dump 记录一致即可被反查命中, 不要求目录结构 + +### 2. 配置字体变体 (可选, 多语种时用) + +当某语种使用独立字体 (如泰语专用字体) 时, 用「变体模板」按语种改写字体名: + +- 菜单: `Tools/LQA/还原/字体变体配置...` +- 模板用 `{name}` 代表原字体名, 例: `{name}@th` 会把 `MyGameFont` 匹配为 `MyGameFont@th`; +- 工程内找不到变体时自动回退原字体, 保证文本始终可渲染; +- 留空 → 字体按 Dump 原样还原 + +### 3. 接入译文 (按语种显示译文时必做) + +还原时若要显示译文而非原文, 需提供一份 `key→译文` JSON + +1. 准备你项目的「译文总表」(CSV, 至少含 `键`、`原始文本`、`翻译文本 <语种>` 列); +2. 参考 `Translation/i18n_convert_spec.md` 规范, 用转换脚本生成符合 Schema 的 JSON (产物样例: `Translation/i18n_en.demo.json`); +3. 菜单 `Tools/LQA/还原/译文文件配置...` 填入生成的 JSON 路径; +4. 还原时查表顺序: `keyHash` 命中 → `original` 原文兜底匹配 → 仍无则回退原文 (见 `Core/Runtime/TranslationTable.cs`) + + +> **keyHash 读取点 (迁移时按需改一行)**: 上面查表用的 `keyHash`, 由 `Core/Runtime/TextNodeBuilder.cs` 中 **唯一一处内联读取** (键名 `"XxxxLocalize"` / 字段 `"keyHash"`), 这是通用内核里唯一感知项目专属键名的地方 —— 因为文本内容必须在通用 `Text`/`TMP` 还原的当下就确定, 而后处理器 (`ProjectCustomRestorers`) 晚于此执行、无法回改已写入的文本, 故只能就地内联, 换到其它项目时: +> - 本地化组件的键名/字段不同 → 只改这一行的 `"XxxxLocalize"` / `"keyHash"`; +> - 目标项目没有本地化组件 → 让 `keyHash` 取到空串即可, `_translationResolver` 会自动退化为仅按 `original` 匹配 + +> **接入前唯一阻塞项**: 先在游戏内 dump 一个已知节点, 确认其 key (如 `XxxxLocalize.keyHash`) 与译文总表的 key 为 **同算法、同格式**, 否则查表会静默失配 + +### 4. 还原项目专属组件 (有自定义组件时必做) + +通用组件 (`Text` / `Canvas` / `RectTransform`) 由内核直接还原, **无需改动**, 只有项目专属组件 (如本地化标记、自定义文本特效) 需要你编写还原器, 与采集侧 (`LQATool` 的 `ProjectCustomExtractors`) 一一对应 + +在 `Core/Runtime/ProjectCustomRestorers.cs` 的 `RegisterAll` 中, 用 `NodePostProcessors.Register` 挂入你的还原逻辑: + +```csharp +NodePostProcessors.Register((go, objectData) => +{ + // 读取采集侧为你的专属组件导出的属性块 (键名需与采集侧一致) + var props = objectData.Get>("YourComponentKey"); + if (props == null) return; // 该节点无此组件, 跳过 + + // 把 JSON 属性还原回 Unity 组件 / 特效 + // 例如挂一个信息组件、或附加 Outline / Shadow 等 +}); +``` + +案例实现 (`XxxxLocalize` 把本地化 key 回填到 `LQAKeyInfo` 组件; `XxxxText` 用内置 `Outline`/`Shadow` 近似还原描边/阴影) 可直接参照, 替换成你项目的键名与组件即可, 单个后处理器抛异常不会中断整棵树的还原 (仅告警) + +### 5. 配置平台连接与项目标识 (对接 LQA 平台时必做) + +若要跑「拉取任务 → 还原 → 提交」流水线, 需填入连接信息 (均存 `EditorPrefs`, 不写入版本库): + +- 平台地址 `Host` 与鉴权 `Authorization` (JWT): `Platform/Editor/Config/LqaPlatformConfig.cs`; +- 当前测试项目 `project_id`: `Platform/Editor/Config/LqaProjectConfig.cs`; +- 其余 `job_id` / 筛选 / 上传参数见 `Platform/Editor/Config/` 下对应配置 + +> 以上配置均为本机 `EditorPrefs`, 换机器/换账号只需重填, 不改代码, 也不会把内网地址与凭证写进源码 + +--- + +## 接入自检清单 + +- [ ] 项目字体已放入 `Font/`, 还原无方块 +- [ ] 多语种, 字体变体模板已配置或确认无需配置 +- [ ] 译文 JSON 已生成并在「译文文件配置」中指定, 且 key 格式与 Dump 一致 +- [ ] `TextNodeBuilder` 中 keyHash 读取的键名/字段已对齐本项目 (无本地化组件则确认取空串) +- [ ] 项目专属组件已在 `ProjectCustomRestorers` 中注册对应还原器 +- [ ] 对接平台, Host / JWT / project_id 已填写并连接测试通过 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_convert_spec.md b/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_convert_spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f7fab92cf519a619ed5e3b5e3612fa9824b76e63 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_convert_spec.md @@ -0,0 +1,111 @@ +# 译文接入转换 JSON 规范 (i18n_convert_spec) + +> **通用规范**: 定义如何把 "译文总表 (CSV)" 转换为可被还原 / 本地化 / 比对工具消费的 **key→译文** JSON, 任何项目只要有一份 "键 → 多语种译文" 的源表, 都可套用本规范, +> 本文以 **「某 Unity 项目的译文总表」× `LQARestore` (Unity 还原工程)** 作为 **应用案例**, 规范本身不绑定任何具体项目或引擎 + +## 1. 适用范围 + +- **通用目标**: 将 "译文总表" 转换为 "按语种分发的 key→译文 JSON", 供任意消费端在运行时按 key 取译文 +- **消费端不限定**: 还原工程、像素比对、TMS 校验、人工核对等只要需要 "按 key 取译文" 的场景均适用 +- **不绑定引擎 / 项目**: 键形态、语种集合、目录约定由具体项目决定; 本规范只规定 JSON 的 **结构与查表语义** + +## 2. 输入: 译文总表 (CSV) + +通用要求: + +| 要求 | 说明 | +| ---- | ---- | +| 至少包含 | `键`、`原始文本`、一列或多列 `翻译文本 <语种>` | +| 键唯一 | 同一份表内 "键" 不重复 | +| 键形态 | 由项目决定 (命名键如 `ZSTips`, 或哈希键如 `#FF..#`); 转换时 **原样保留**, 不做格式转换 | +| 译文列 | 每语种一列; 可同时存在 "正式" 与 "在翻" 两版 (如 `en` / `en_tmp`), 转换时取正式列 | + +**案例来源 (示例)**: 一份译文总表 CSV (示例约 157 MB), 列: +`键, 源文件, 输出文件, 原始文本, 翻译文本 en, 翻译文本 th, 翻译文本 en_tmp, 翻译文本 th_tmp` +它是该项目的 **译文唯一权威源**, 三类键均已收录 + +## 3. 输出: 转换 JSON 模板 Schema + +顶层为纯数据文件 (规范语义见键类型、查表约定), 仅保留消费端与溯源所需的元信息: + +```jsonc +{ + "schemaVersion": "1.0", // 规范版本, 消费端据此判断兼容性 + "language": "en", // 本文件语种, 一份一语种 + "source": { // 来源指向 (仅数据, 不含叙述) + "project": "<项目名>", + "file": "<译文总表相对/绝对路径>", + "translationColumn": "翻译文本 en" // 本文件 translation 取自总表的哪一列 + }, + "keyTypes": ["stringKey", "hashFF", "hashFB"], // 本项目声明的键类型集合 + "generatedAt": "…", + "entries": { // 核心: 扁平字典, 运行时 O(1) 查找 + "": { + "keyType": "", + "source": "<源文件>", + "original": "<原始文本>", + "translation": "<目标语言译文>" + } + } +} +``` + +**字段约束** + +- `entries` 必须为 **对象(字典)** 非数组; key 即总表 "键" 列 **原样字符串** (含 `#` / `$` 等特殊字符) +- `key` 全局唯一 +- `original` 必须保留: 用于构建 "原文→译文" 兜底表 +- `original` / `translation` 的 **换行、制表等控制字符必须是真实字符**, 不得是字面转义序列 (如两字符的 `\n`), 若译文总表单元格用字面 `\n` 表示换行, 转换时必须先反转义为真实换行符再写入, 兜底路径按 `original` 与消费端文本做 **精确相等** 匹配, 而消费端 (如 UI dump 抓取的运行时文本) 持有的是真实换行; 转义层级不一致会导致匹配静默失败 + +## 4. 键类型 (keyTypes) + +通用: 本规范 **不预设** 键类型枚举, 由具体项目在 `keyTypes` 中声明, `keyType` 仅用于消费端识别 key 形态, 不参与查表匹配 + +**案例** 声明三类: + +| keyType | 形态 | 含义 | +| ----------- | ----------- | ----------- | +| `stringKey` | `ZSTips`、`ZhanShi`… | UI 文本命名键 (来自 `i18n.txt`) | +| `hashFF` | `#FFxxxxxxxxxxxxxx#` | 客户端侧哈希键 (实测 14 位十六进制; 运行时按 id 取串可能为 64 位, 二者属不同表示形态, 接表前需核对 dump 键与总表键同格式) | +| `hashFB` | `$FBxxxxxxxxxxxxxx$` | 服务端侧哈希键 (实测 14 位十六进制) | + +## 5. 消费端接入约定 (通用查表语义) + +任何消费端都应遵守以下语义 (与具体实现无关): + +1. **查表主路径**: 按待还原文本的 key (命名键或哈希键) 匹配 `entries.key`, 命中则取 `translation` 填充 +2. **兜底路径**: 若 key 未命中, 可用 `original` 构建 **原文→译文** 表二次匹配 +3. **跳过规则**: 文本含源语言字符 / 纯数字 / 纯标点 / 纯空白 → 不翻译, 直接回原文 +4. **未翻译标记**: 主路径与兜底均不命中 → 标记为未翻译 (如标红), 提示待补译 + +> **实现参考**: 一个典型的还原实现可采用与上述一致的优先级 (含源语言/数字跳过 → Key→译文 → 原文→译文兜底 → 未翻译标记), 可作为参考实现, 但非本规范强制 + +> **匹配前提**: 兜底路径为 **精确字符串相等**匹配, 要求 `original` 与消费端待匹配文本的转义层级一致 (换行等均为真实控制字符), 生成侧须在写入前完成反转义 (字段约束), 否则会因 `\n`(真实换行) 与字面 `\n`(反斜杠+n) 不等而漏配 + +## 6. Demo 片段 + +以下节选自案例产物 `i18n_en.demo.json`, 覆盖三类键: + +```json +{ + "ZhanShi": { "keyType": "stringKey", "source": "i18n.txt", "original": "战士", "translation": "Fighter" }, + "#FFDAEEA48050734A#": { "keyType": "hashFF", "source": "Table/LineupTable.xlsx", "original": "示例:阵容推荐说明文本。", "translation": "Sample: lineup recommendation description text." }, + "$FB505CC795D662A5$": { "keyType": "hashFB", "source": "Mail/GlobalMailTable.xlsx", "original": "欢迎来到游戏世界", "translation": "Welcome to the game world" } +} +``` + +## 7. 应用案例: 某 Unity 项目 × LQARestore + +将本规范落到具体项目: + +- **源 (译文总表)**: 某项目的译文总表 CSV (示例路径), 三类键均已收录, en/th 译文齐备 +- **产物 (符合本规范)**: `LQARestore/Translation/i18n_en.demo.json` (schemaVersion 1.0, en 语种, Demo 仅含 5 条样例) +- **消费端**: `LQARestore` 还原流程 `Core/Runtime/TextNodeBuilder.cs` 的 `ApplyText`; 当前回填原文 (`txt.text = textContent`), 接入时改为先查本表取 `translation`, 未命中回退 `original`/原文 +- **目录约定**: 还原工程内新建 `Translation/` 模块, 与 `Core/`、`Entry/`、`Platform/` 平级, 存放各语种转换 JSON 与本文档 +- **接入前待验证**: 在游戏内 dump 一个已知节点, 确认其 key (如 `XxxxLocalize.keyHash`, 格式 `#{id:X16}#`) 能与总表 / 本表的 key 同算法同格式匹配; 并确认 UI 文本 (命名键) 在 dump 中以命名键还是哈希形态出现, 这是把查表接到 `ApplyText` 前的唯一阻塞项 + +## 8. 批量生成与多语种扩展 + +- **批量生成**: 解析整份译文总表, 按 translationColumn 抽列, 输出为本规范 JSON, 大体量 (百 MB 级) 文件建议预生成、缓存, 避免还原时实时解析, 可参照本规范自行实现转换脚本, 并务必内置字面转义序列反转义 (把单元格里的字面 `\n` / `\r` / `\t` 还原为真实控制字符), 以满足字段约束与匹配前提 +- **多语种**: 复制模板, 改 `language` 与 `source.translationColumn` (如 th → `翻译文本 th`), 一份一语种 +- **可移植**: 换项目时只需替换 `source` (指向新总表) 与 `keyTypes` (声明新键形态), `entries` 结构与查表语义保持不变 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_en.demo.json b/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_en.demo.json new file mode 100644 index 0000000000000000000000000000000000000000..681463ab64848eaa1ccde28aeb99b5b228d59b01 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/Translation/i18n_en.demo.json @@ -0,0 +1,49 @@ +{ + "schemaVersion": "1.0", + "language": "en", + "source": { + "project": "SampleProject", + "file": "path/to/i18n_translation.csv", + "translationColumn": "翻译文本 en" + }, + "keyTypes": ["stringKey", "hashFF", "hashFB"], + "generatedAt": "2026-08-25T15:04:35+08:00", + "entries": { + "ZhanShi": { + "keyType": "stringKey", + "source": "i18n.txt", + "original": "战士", + "translation": "Fighter" + }, + "HeroDrawTitle": { + "keyType": "stringKey", + "source": "i18n.txt", + "original": "示例英雄称号", + "translation": "Sample Hero Title" + }, + "#FFDAEEA48050734A#": { + "keyType": "hashFF", + "source": "Table/LineupTable.xlsx", + "original": "示例:阵容推荐说明文本。", + "translation": "Sample: lineup recommendation description text." + }, + "#FFDAD128D6E3E99C#": { + "keyType": "hashFF", + "source": "Table/LineupTable.xlsx", + "original": "示例:今日推荐阵容。", + "translation": "Sample: today's recommended lineup." + }, + "$FB505CC795D662A5$": { + "keyType": "hashFB", + "source": "Mail/GlobalMailTable.xlsx", + "original": "欢迎来到游戏世界", + "translation": "Welcome to the game world" + }, + "loginNoticeTextPC": { + "keyType": "stringKey", + "source": "i18n.txt", + "original": "健康游戏忠告:抵制不良游戏,拒绝盗版游戏。注意自我保护,谨防受骗上当。适度游戏益脑,沉迷游戏伤身。合理安排时间,享受健康生活。\n根据国家新闻出版署《关于防止未成年人沉迷网络游戏的通知》《关于进一步严格管理 切实防止未成年人沉迷网络游戏的通知》,所有网络游戏用户均需使用有效身份信息完成账号实名注册后方可进入游戏,认证为未成年的玩家将受到防沉迷功能限制。", + "translation": "Healthy Gaming Advice: Resist unhealthy games, refuse pirated games. Protect yourself, beware of being deceived. Moderate gaming benefits the brain, addiction to games hurts it. Arrange your time reasonably, and enjoy a healthy life.\nIn accordance with the \"Notice on Preventing Minors from Gaming Addiction\" and \"Notice on Further Strengthening Management to Effectively Prevent Minors from Gaming Addiction\" issued by the National Press and Publication Administration, all users must complete real-name registration with a valid ID to access the game. Minor users will be restricted by the anti-addiction system." + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_auto_pipeline.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_auto_pipeline.png new file mode 100644 index 0000000000000000000000000000000000000000..3725c2dea87e3d5a3031df87281b11d0d1ed8a47 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_auto_pipeline.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea166b24a4653e0ea2cb7c2f12b0bad43b8ddd59af460aeb82e645030893fccb +size 325048 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_console.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_console.png new file mode 100644 index 0000000000000000000000000000000000000000..7134a1a5dd78198f08672c06fc91d26e415be68c Binary files /dev/null and b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_console.png differ diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_dump_delay.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_dump_delay.png new file mode 100644 index 0000000000000000000000000000000000000000..50c5acef0871c694a74b6703655682ef294a25fa Binary files /dev/null and b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_dump_delay.png differ diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_filter_config.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_filter_config.png new file mode 100644 index 0000000000000000000000000000000000000000..bdc88785e6c0e1a3758831c22bb5c97650c268d8 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_filter_config.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc4c5f85365cb42ff8ca796894ba42ca81a6ce98e8b61c5665ae02eb32ba3192 +size 118061 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_full_vs_restore.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_full_vs_restore.png new file mode 100644 index 0000000000000000000000000000000000000000..1a3c7714a1db451b611dbdfd065083e3e95305df --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_full_vs_restore.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16f1d68be17aaf82887246867658f1a9a6aba02ea8c5c2edece01c2edb290d71 +size 336308 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_menu.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_menu.png new file mode 100644 index 0000000000000000000000000000000000000000..a61ec8840f0d96ce50940b07d800904955b61b42 Binary files /dev/null and b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_menu.png differ diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_platform_connection.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_platform_connection.png new file mode 100644 index 0000000000000000000000000000000000000000..75a0f288971046c54ed5c991483e9753c91d5ed8 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_platform_connection.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad98e9b4fe5a8add4e079aa6f3e27d146a2caec8f8d66d217292b347a3118318 +size 176835 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_pull_data.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_pull_data.png new file mode 100644 index 0000000000000000000000000000000000000000..a6717251309bef908c82f09d8680e7310b5b656c --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_pull_data.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60b525867b231d126bacd8bbe78925631a1a93686e7b570537bf65f919950106 +size 295089 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_scene.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_scene.png new file mode 100644 index 0000000000000000000000000000000000000000..8bbd59c63d3c3edbca26a57312ce7d6df7f3f6cd --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_scene.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:886b152497e4f77ffece964bcdb6b90a85cb688ed2b169762ad17a3e3a98db0c +size 390180 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_submit.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_submit.png new file mode 100644 index 0000000000000000000000000000000000000000..99a6757b4677db333015cfc743697a7b611c86eb --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_submit.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd2e14b893cb89d0c0709ea88b82bac185ccdb1415d29a665d2599575d0faf4b +size 233051 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_text_show.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_text_show.png new file mode 100644 index 0000000000000000000000000000000000000000..eee6b966f06d2fc48f6a94dfe9f76b3d9673a44b --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_text_show.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7b7a34be7138980ce6b4dab1da5d09ffd57f6dbf822691045a35e3453852592 +size 177365 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_translation_font_config.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_translation_font_config.png new file mode 100644 index 0000000000000000000000000000000000000000..f406d1ff6281e47ce362b5b474f338e4cc0132d3 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_translation_font_config.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e5140c09dd0db01d66c456eacbffe5734d65984989cf80a481e508021477e16 +size 204814 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_upload_data.png b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_upload_data.png new file mode 100644 index 0000000000000000000000000000000000000000..2ff32bd62ae5882f0cae4e37becc143401690c5f --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/docs/images/restore_upload_data.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc1669c8aee4b5db75bc9dfe36dded58c7fcd838d7d604163629b8b8c574f7fd +size 380937 diff --git a/timi_hok_game_translator/Unity_LQARestore_Plugin/package.json b/timi_hok_game_translator/Unity_LQARestore_Plugin/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a851f41f94a9b70428233c69c6662d20b6fa6469 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQARestore_Plugin/package.json @@ -0,0 +1,20 @@ +{ + "name": "com.qq.game.lqarestore", + "version": "1.0.0", + "displayName": "LQARestore - Localization UI Restore Tool", + "description": "A UI text and layout restore tool for Unity project localization, restoring dumped content back onto the scene", + "keywords": [ + "localization", + "ui", + "analysis", + "lqa", + "debug", + "test", + "restore" + ], + "author": { + "name": "Tencent Games", + "email": "tencent_games@tencent.com", + "url": "https://game.qq.com/" + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/.gitattributes b/timi_hok_game_translator/Unity_LQATool_Plugin/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..f4d6982a3e6b1dd5c9577990ae0ef92874b728c1 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/.gitattributes @@ -0,0 +1,2 @@ +# auto generated by UGit +*.png filter=lfs diff=lfs merge=binary -text diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/.gitignore b/timi_hok_game_translator/Unity_LQATool_Plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ff86cbb6fbbf381c36b762c98f908b9dc3f09886 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/.gitignore @@ -0,0 +1,3 @@ +*.meta +cache/ +__pycache__/ \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Config/LQAUILayerConfig.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Config/LQAUILayerConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..77b514dd8c8cf8002022b69f8453f2a2db0d6ee6 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Config/LQAUILayerConfig.cs @@ -0,0 +1,100 @@ +// ========================================== +// 文件: LQATool\Config\LQAUILayerConfig.cs +// 模块: Config (配置) +// ========================================== + +using System.Collections.Generic; + +/// +/// LQATool 配置层命名空间 +/// +namespace LQATool.Config +{ + /// + /// LQATool UI 相关的全局静态配置 + /// 集中存放 "分层截图" 与 "文本像素可见性判定" 两类流程所需的常量参数与调试开关, + /// 供 UIDumpService / PixelVisibilityChecker 等服务在运行时读取 + /// + public static class LQAUILayerConfig + { + /// + /// 需要 "单独分层截图" 的 UI 图层 (Layer) 名称列表 + /// UIDumpService 会遍历本列表, 对其中每个在工程里真实存在的 Layer, + /// 单独渲染出一张透明图 ScreenShot_Only_{LayerName}.png + /// 所有未列入本列表的图层则合并渲染为背景图 ScreenShot_BG.png + /// 注意: 列表中若配置了工程中不存在的 Layer 名, 会被自动跳过并打印警告 + /// Dump 时会对本列表做一次快照, 作为 "本次输出了哪些分层截图" 的权威清单 + /// 说明: 上述分层图与背景图的实际落盘受 EmitLayerScreenshots 开关控制, + /// 该开关关闭时本列表仅用于快照记录, 不再触发任何分层/背景截图的渲染与写盘 + /// + public static readonly List UILayerNames = new List + { + "UI", + + "UI_System", + "UI_Background", + }; + + /// + /// 文本可见性判定的 "差异占比" 阈值 (取值 0~1) + /// 判定逻辑: 在文本的屏幕足迹范围内, 统计 "有文本" 与 "无文本" 两张图的差异像素数, + /// 当差异像素数 / 足迹像素总数 大于该比例时, 才判定该文本为可见 + /// 当前 0.10 表示: 至少要有 10% 的足迹像素发生显著变化才算可见 + /// + public const float PixelDiffMaskVisibleRatio = 0.10f; + + /// + /// 单像素 "颜色差异显著" 的判定阈值 + /// 对同一像素在 "有文本" 与 "无文本" 两图中的 RGB 三通道差值求和, + /// 该和值大于此阈值时, 才认为这个像素发生了显著变化 (计入差异像素数) + /// 值越小越敏感, 越容易把细微色差算作差异 + /// + public const int PixelDiffColorThreshold = 12; + + /// + /// 纯色 ID 掩码 "有效足迹像素" 的最小 alpha 阈值 (0~255) + /// 纯色 ID 图背景透明、文字以不透明 ID 色渲染; 抗锯齿会让字形边缘像素呈半透明, + /// 仅 alpha >= 本值的像素才计入文本足迹参与判定 (用于筛掉边缘羽化的脏像素) + /// 128 相当于要求覆盖率 >= 50%; 对小字号/细笔画文本 (如 16px 中文) 可调低 (如 64), + /// 以纳入更多边缘像素, 避免足迹被筛空导致误判为不可见 + /// + public const int PureMaskAlphaThreshold = 128; + + /// + /// 调试开关: 是否把文本 ID 图 (含纯色版) 额外另存为 PNG, 便于人工核对文本足迹映射 + /// 关闭后仅在内存中参与判定, 不落盘调试图 + /// + public const bool EmitTextIdMapDebug = true; + + /// + /// 调试开关: 是否输出可见性判定的中间过程数据与可视化叠加图 + /// (叠加图中 绿=可见 / 红=可见但露出像素少 / 橙=不可见), 用于排查判定结果 + /// + public const bool EmitVisibilityDebug = true; + + /// + /// 输出开关: 是否落盘全量 UI 节点树 ui_data_all.json + /// 与 ui_data_text.json 的差异仅在于节点范围: 本文件保留每个根 Canvas 下的全部节点, + /// 而 text 版只保留含文本或图片的节点及其祖先路径, 两者对每个节点记录的字段口径完全一致 + /// (除 name / Transform / RectTransform / GameObject 等通用信息外, 也含 Text / Image 等组件的专有属性) + /// 关闭后仅跳过本文件写盘, 内存中的全量树仍会构建 (它是 text 版的过滤来源), + /// 不影响 ui_data_text.json 的写盘 (由 EmitTextUIDataJson 独立控制) + /// + public const bool EmitFullUIDataJson = false; + + /// + /// 输出开关: 是否落盘文本/图片剪枝版 UI 节点树 ui_data_text.json + /// 该文件只保留含文本或图片的节点及其祖先路径, 是 EmitFullUIDataJson 全量树的过滤子集 + /// 关闭后仅跳过本文件写盘, 内存中的文本树仍会构建, 不影响全量树 ui_data_all.json 的生成 + /// + public const bool EmitTextUIDataJson = true; + + /// + /// 输出开关: 是否落盘分层截图 (ScreenShot_Only_{Layer}.png) 与背景截图 (ScreenShot_BG.png) + /// 这几张图为纯产物, 无任何下游流程读回消费, 仅供人工核对分层效果 + /// 关闭后整段分层/背景渲染与写盘逻辑都会跳过 (顺带省一轮 GPU 回读与磁盘 IO), + /// 不影响 ScreenShot_Full / ScreenShot_NoText 及像素可见性判定、JSON 生成、工程还原 + /// + public const bool EmitLayerScreenshots = false; + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQATool.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQATool.cs new file mode 100644 index 0000000000000000000000000000000000000000..b3293e59c32f0c34c3f38ec5d78573c861854c63 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQATool.cs @@ -0,0 +1,78 @@ +// ========================================== +// 文件: LQATool\Core\LQATool.cs +// 模块: Core (核心) +// ========================================== + +using UnityEngine; + +/// +/// LQATool 核心层命名空间 +/// +namespace LQATool.Core +{ + /// + /// LQATool 的对外静态入口 (门面/Facade) + /// + /// 职责: 作为整个插件的 "总开关" 与自启动入口, 负责: + /// 1. 在游戏运行时自动创建常驻的 [LQATool_Manager] 游戏对象 (无需手动挂载到场景) + /// 2. 根据 PlayerPrefs 配置决定工具默认是否启用 + /// 3. 对外暴露 SetEnable 接口, 供业务代码在运行时动态开启/关闭工具 + /// + /// 设计要点: 本类只做 "创建管理器 + 开关" 这类轻量协调工作, 具体逻辑全部委托给 + /// LQAToolManager (真正的中枢), 从而让调用方无需感知内部实现细节 + /// + public static class LQATool + { + /// + /// 核心管理器 (LQAToolManager) 的单例引用 + /// 由 AutoInit() 在运行时创建并缓存, 用作是否已初始化的判断依据, 避免重复创建 + /// + private static LQAToolManager _instance; + + /// + /// 自动初始化入口 + /// + /// 借助 [RuntimeInitializeOnLoadMethod] 特性, 由 Unity 在 "首个场景加载完成后" + /// (AfterSceneLoad) 自动调用, 因此无需在任何场景里手动挂载脚本即可让工具生效 + /// + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] + private static void AutoInit() + { + // 幂等保护: 仅当尚未初始化时才创建, 防止重复生成管理器对象 + if (_instance == null) + { + // 1. 创建承载工具的游戏对象 (名称加方括号便于在 Hierarchy 中辨识) + GameObject go = new GameObject("[LQATool_Manager]"); + + // 2. 标记为跨场景常驻, 切换场景时不会被销毁, 保证工具全程可用 + GameObject.DontDestroyOnLoad(go); + + // 3. 挂载核心管理器组件, 由它去创建/连线 UI、输入、Dump 等各子模块 + _instance = go.AddComponent(); + + // 4. 读取本地配置, 决定工具默认是否启用 (缺省为 0, 即默认不启用) + bool shouldEnable = PlayerPrefs.GetInt("LQA_ShowDumpAndGetNodeButtons", 0) == 1; + if (!shouldEnable) + { + // 配置为禁用时: 关闭整个对象 (连带其上的管理器一起停止工作) + go.SetActive(false); + Debug.Log("[LQATool] 工具已按 PlayerPrefs 配置禁用 (LQA_ShowDumpAndGetNodeButtons=0)"); + } + } + } + + /// + /// 运行时动态开启/关闭工具 + /// 通过启用或禁用管理器所在的游戏对象来实现整体开关 + /// + /// true 表示启用工具, false 表示禁用工具 + public static void SetEnable(bool enable) + { + // 仅在已完成自动初始化 (_instance 存在) 时才操作, 避免空引用 + if (_instance != null) + { + _instance.gameObject.SetActive(enable); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQAToolManager.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQAToolManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..d0f9231adf20122f60676f24ba4376f609b4170e --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Core/LQAToolManager.cs @@ -0,0 +1,158 @@ +// ========================================== +// 文件: LQATool\Core\LQAToolManager.cs +// 模块: Core (核心) +// ========================================== + +using System.Collections; +using UnityEngine; +using LQATool.UI; +using LQATool.Input; +using LQATool.Services; + +/// +/// LQATool 核心层命名空间 +/// +namespace LQATool.Core +{ + /// + /// LQATool 的核心管理器 (总协调者), 挂载在场景中的 [LQATool_Manager] 游戏对象上 + /// + /// 职责: 作为整个插件的 "中枢", 负责: + /// 1. 创建并持有三大模块: UI 管理器 (UI 层)、输入检测器 (Input 层)、Dump 服务 (Services 层) + /// 2. 把各模块之间的事件 "连线" (订阅/转发), 让彼此解耦的模块协同工作 + /// 3. 监听全局热键 (F9), 提供除 UI 按钮之外的快捷触发入口 + /// + /// 设计要点: 各模块之间互不直接引用, 全部通过本类订阅事件来通信, 从而保持低耦合 + /// + public class LQAToolManager : MonoBehaviour + { + // ========================================== + // 模块引用 (私有字段) —— 三大子模块由本类创建并持有 + // ========================================== + + /// + /// UI 管理器 (UI 层): 负责构建/显示工具面板、Dump 按钮、GetNode 按钮及信息展示面板 + /// 在 Start() 中通过 AddComponent 动态挂载到同一游戏对象上 + /// + private LQAToolUIManager _uiManager; + + /// + /// 输入检测器 (Input 层): 每帧检测鼠标/触摸的 [按下] 与 [长按] 手势, 并通过事件对外通知 + /// 在 Start() 中通过 AddComponent 动态挂载到同一游戏对象上 + /// + private InputDetector _inputDetector; + + /// + /// UI Dump 服务 (Services 层): 负责执行完整的 UI 转储流程 (截图 + 生成节点树 JSON), + /// 以及长按时的单节点信息查找 (FindNearestTextNode) + /// 注意: 它是普通类 (非 MonoBehaviour), 通过 new 直接实例化 + /// + private UIDumpService _dumpService; + + /// + /// Dump 执行中的互斥标记, 防止在一次 Dump 尚未完成时被重复触发 (按钮连点 / 热键连按) + /// true 表示当前正有一次 Dump 协程在运行 + /// + private bool _isDumping = false; + + /// + /// Dump 前的延时秒数配置 Key (由客户端 GM 面板写入, 整数, 默认 0 表示立即 Dump) + /// + private const string DumpDelayPrefsKey = "LQA_DumpDelaySeconds"; + + /// + /// 触发 UI Dump 的全局热键 (F9), 作为 UI 按钮之外的快捷入口 (主要方便 PC 端调试) + /// + private const KeyCode DumpHotKey = KeyCode.F9; + + /// + /// Unity 生命周期方法: 在对象启用后的第一帧调用一次 + /// 负责创建三大模块并建立它们之间的事件连线 + /// + void Start() + { + // 1. 创建 Dump 服务 (普通类, 直接 new) + _dumpService = new UIDumpService(); + + // 2. 动态挂载 UI 管理器组件, 并初始化 (构建工具 UI、确保 EventSystem 存在) + _uiManager = gameObject.AddComponent(); + _uiManager.Initialize(); + + // 3. 动态挂载输入检测器组件 (默认处于关闭状态, 需由 GetNode 开关开启) + _inputDetector = gameObject.AddComponent(); + + // ========================================== + // 4. 事件连线 (把彼此解耦的模块串联起来) + // ========================================== + + // 点击 UI 上的 Dump 按钮 → 触发一次 UI 转储 + _uiManager.OnDumpClicked += HandleDumpRequest; + + // 切换 UI 上的 GetNode 开关 → 同步开启/关闭输入检测器的长按检测 + _uiManager.OnGetNodeToggled += _inputDetector.SetEnable; + + // 指针再次按下屏幕 → 先隐藏上一次弹出的信息面板 (避免旧面板残留) + _inputDetector.OnPointerDown += _uiManager.HideInfoPanel; + + // 长按屏幕触发 → 查找该位置最近的文本节点并弹出信息面板 + _inputDetector.OnLongPressTriggered += HandleGetNodeRequest; + } + + /// + /// Unity 生命周期方法: 每帧调用 + /// 仅用于监听全局热键, 提供 UI 按钮之外的 Dump 触发方式 + /// + void Update() + { + // 按下 F9 → 等同于点击 Dump 按钮 + if (UnityEngine.Input.GetKeyDown(DumpHotKey)) + { + HandleDumpRequest(); + } + } + + /// + /// 处理 GetNode 请求 (由 InputDetector 的长按事件 OnLongPressTriggered 触发) + /// 根据长按位置查找最近的文本节点, 并在 UI 上弹出该节点的信息面板 + /// + /// 长按发生时指针在屏幕上的坐标 + private void HandleGetNodeRequest(Vector2 pointerPosition) + { + // 在工具画布之外的 UI 中, 查找离长按点最近的文本节点 + var nearestTextNode = _dumpService.FindNearestTextNode(pointerPosition, _uiManager.ToolCanvas); + + // 把查到的节点信息交给 UI 层显示 (面板位置参考长按坐标) + _uiManager.ShowNodeInfo(nearestTextNode, pointerPosition); + } + + /// + /// 处理 Dump 请求 (由 UI 的 Dump 按钮点击, 或 F9 热键触发) + /// 先按 GM 配置的延时秒数等待 (默认 0 即立即执行), 再启动一次完整的 UI 转储协程 + /// _isDumping 标记在延时开始前就置位, 防止倒计时期间被重复触发 + /// + private void HandleDumpRequest() + { + // 互斥保护: 若上一次 Dump 尚未结束 (包含延时等待中), 直接忽略本次请求, 防止重复执行 + if (_isDumping) return; + _isDumping = true; + + int delaySeconds = PlayerPrefs.GetInt(DumpDelayPrefsKey, 0); + StartCoroutine(RunDumpWithDelay(delaySeconds)); + } + + /// + /// 按延时秒数等待后执行真正的 Dump 流程 (delaySeconds <= 0 时不等待, 行为与之前一致) + /// + private IEnumerator RunDumpWithDelay(int delaySeconds) + { + if (delaySeconds > 0) + { + Debug.Log($"[LQATool] Dump 将在 {delaySeconds} 秒后开始采集..."); + yield return new WaitForSecondsRealtime(delaySeconds); + } + + // 启动转储协程, 完成回调 (onComplete) 中把 _isDumping 复位为 false, 允许下一次触发 + yield return _dumpService.ExecuteDump(_uiManager.ToolCanvas, () => _isDumping = false); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Input/InputDetector.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Input/InputDetector.cs new file mode 100644 index 0000000000000000000000000000000000000000..37035c895e7fd94bf1e98cb3f510d7164298b621 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Input/InputDetector.cs @@ -0,0 +1,144 @@ +// ========================================== +// 文件: LQATool\Input\InputDetector.cs +// 模块: Input (输入) +// ========================================== + +using System; +using UnityEngine; + +/// +/// LQATool 输入层命名空间 +/// +namespace LQATool.Input +{ + /// + /// 输入检测器: 挂载在 GameObject 上的 MonoBehaviour + /// 每帧检测鼠标 / 触摸输入, 识别 [按下] 与 [长按] 两类手势, 并通过事件对外通知 + /// 同时兼容 PC 端鼠标 (GetMouseButton*) 与移动端触摸 (Touch) 两种输入源 + /// + public class InputDetector : MonoBehaviour + { + #region 对外抛出的事件 (Actions) + + /// + /// 长按触发事件, 参数为长按发生时指针 (鼠标/手指) 在屏幕上的坐标 (Vector2) + /// 订阅方可据此坐标做后续处理 (如弹出菜单、拾取该位置的对象等) + /// + public Action OnLongPressTriggered; + + /// + /// 指针按下事件, 在按下 (鼠标左键按下 / 手指刚触屏) 的当帧触发一次 + /// + public Action OnPointerDown; + + #endregion + + #region 内部状态变量 + + /// + /// 是否处于检测状态, 为 false 时 Update 直接跳过, 不做任何检测 + /// + private bool _isDetecting = false; + + /// + /// 当前是否正处于按压中 (从按下到抬起之间为 true) + /// + private bool _isPressing = false; + + /// + /// 本次按压的起始时间 (Time.time, 单位秒), 用于计算按压时长 + /// + private float _pressStartTime = 0f; + + /// + /// 判定为长按所需的最短持续时间 (秒), 持续按住超过此值即视为长按 + /// + private const float LONG_PRESS_DURATION = 1.0f; + + /// + /// 本次按压是否已触发过长按 + /// 用于确保一次按压只触发一次长按, 避免达到阈值后每帧重复触发 + /// + private bool _hasTriggeredLongPress = false; + + #endregion + + /// + /// 设置检测开关 + /// + /// true 开启检测, false 关闭检测 + public void SetEnable(bool enable) => _isDetecting = enable; + + /// + /// Unity 生命周期方法, 每帧调用, 负责采集输入并推进长按状态机 + /// + void Update() + { + // 未开启检测时直接返回, 避免不必要的输入采集 + if (!_isDetecting) return; + + // ========================================== + // 采集本帧的三种指针状态 (同时兼容鼠标与触摸) + // ========================================== + + // 按下: 鼠标左键按下 或 首个触摸点处于 Began (刚接触屏幕) 阶段 + bool isPointerDown = UnityEngine.Input.GetMouseButtonDown(0) || + (UnityEngine.Input.touchCount > 0 && UnityEngine.Input.GetTouch(0).phase == TouchPhase.Began); + + // 抬起: 鼠标左键抬起 或 首个触摸点处于 Ended (离开屏幕) / Canceled (被系统取消) 阶段 + bool isPointerUp = UnityEngine.Input.GetMouseButtonUp(0) || + (UnityEngine.Input.touchCount > 0 && (UnityEngine.Input.GetTouch(0).phase == TouchPhase.Ended || UnityEngine.Input.GetTouch(0).phase == TouchPhase.Canceled)); + + // 持续按住: 鼠标左键保持按下 或 首个触摸点处于 Stationary (按住未移动) 阶段 + bool isPointerHeld = UnityEngine.Input.GetMouseButton(0) || + (UnityEngine.Input.touchCount > 0 && UnityEngine.Input.GetTouch(0).phase == TouchPhase.Stationary); + + // 按下瞬间: 抛出按下事件, 并初始化本次按压的状态 + if (isPointerDown) + { + OnPointerDown?.Invoke(); + + _isPressing = true; // 进入按压中 + _hasTriggeredLongPress = false; // 重置长按触发标记 + _pressStartTime = Time.time; // 记录起始时间 + } + + // 抬起瞬间: 结束按压并重置状态 + if (isPointerUp) + { + _isPressing = false; + _hasTriggeredLongPress = false; + } + + // 长按判定: 正在按压、尚未触发过长按、且仍保持按住 + if (_isPressing && !_hasTriggeredLongPress && isPointerHeld) + { + // 按住时长达到阈值 → 触发长按 (一次按压仅触发一次) + if (Time.time - _pressStartTime >= LONG_PRESS_DURATION) + { + _hasTriggeredLongPress = true; + TriggerLongPress(); + } + } + } + + /// + /// 触发长按: 获取当前指针屏幕坐标并通过 OnLongPressTriggered 事件抛出 + /// 优先使用触摸坐标, 无触摸时回退到鼠标坐标 + /// + private void TriggerLongPress() + { + // 默认取鼠标位置 + Vector2 pointerPosition = UnityEngine.Input.mousePosition; + + // 若存在触摸点, 则以首个触摸点的位置为准 (移动端优先) + if (UnityEngine.Input.touchCount > 0) + { + pointerPosition = UnityEngine.Input.GetTouch(0).position; + } + + // 抛出长按事件, 携带指针坐标 + OnLongPressTriggered?.Invoke(pointerPosition); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Models/UIDataModels.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Models/UIDataModels.cs new file mode 100644 index 0000000000000000000000000000000000000000..deb8d8a6ec162730ce62aeac12bf753d6bad4034 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Models/UIDataModels.cs @@ -0,0 +1,177 @@ +// ========================================== +// 文件: LQATool\Models\UIDataModels.cs +// 模块: Models (数据模型) +// ========================================== + +using System; +using System.Collections.Generic; +using UnityEngine; + +/// +/// LQATool 数据模型层命名空间 +/// +namespace LQATool.Models +{ + /// + /// UI 节点数据: 对应场景 Hierarchy 中的单个 GameObject 节点 + /// 多个 UINodeData 通过 ChildNodes 递归嵌套, 构成一棵完整的 UI 节点树 + /// + [Serializable] + public class UINodeData + { + /// + /// GameObject 名称 (对应 Hierarchy 中显示的名字) + /// + public string name; + + /// + /// 节点在 Hierarchy 中的完整路径 (如 "Canvas/Panel/Button"), 便于人工定位 + /// + public string path; + + /// + /// 主要组件类型 (如 Text / Image / Button), 供外部解析工具识别控件种类 + /// + public string objectType; + + /// + /// 该节点自身是否含有文本, 供 "文本/图片剪枝树" 剪枝时判断节点去留 + /// + public bool hasText; + + /// + /// 该节点自身是否含有图片 (Image / RawImage), 供 "文本/图片剪枝树" 剪枝时一并保留图片节点 + /// + public bool hasImage; + + /// + /// 组件属性数据, 两层字典结构: 组件名 -> (属性名 -> 已格式化的 JSON 片段值) + /// 例如: ObjectData["RectTransform"]["anchoredPosition"] = "{\"x\":0,\"y\":0}" + /// 由 AddComponentProperty 写入, JsonBuilder 据此输出嵌套 JSON 对象 + /// + public Dictionary> ObjectData = new Dictionary>(); + + /// + /// 子节点列表, 递归构成节点树 + /// + public List ChildNodes = new List(); + + /// + /// 向 ObjectData 添加/覆盖一条组件属性 + /// 若对应组件的内层字典尚不存在, 会自动创建 + /// + /// 组件名 (外层 Key), 如 "Transform" / "Text" + /// 属性名 (内层 Key), 如 "localScale" + /// 已格式化好的属性值 (JSON 片段字符串) + public void AddComponentProperty(string componentName, string propertyKey, string propertyJsonValue) + { + // 取出该组件对应的内层字典, 不存在则新建并挂入外层字典 + if (!ObjectData.TryGetValue(componentName, out var inner)) + { + inner = new Dictionary(); + ObjectData[componentName] = inner; + } + + // 写入 (或覆盖) 属性值 + inner[propertyKey] = propertyJsonValue; + } + + /// + /// 尝试从 ObjectData 读取指定组件的指定属性值 + /// + /// 组件名 (外层 Key) + /// 属性名 (内层 Key) + /// 输出参数: 命中时返回属性值, 未命中时为 null + /// 组件与属性都存在时返回 true, 否则返回 false + public bool TryGetComponentProperty(string componentName, string propertyKey, out string propertyJsonValue) + { + propertyJsonValue = null; + // 外层命中组件 且 内层命中属性, 两者皆成立才算读取成功 + return ObjectData.TryGetValue(componentName, out var inner) && inner.TryGetValue(propertyKey, out propertyJsonValue); + } + } + + /// + /// UI 导出结果: 一次 Dump 操作的完整产物 + /// 包含运行环境元数据 (分辨率 / 语言 / 画质等) 与场景 UI 节点树 nodes + /// 会被 JsonBuilder 序列化为 ui_data_all.json (全量) 或 ui_data_text.json (文本/图片剪枝树) + /// + [Serializable] + public class UIDumpResult + { + /// + /// 当前激活场景的名称 + /// + public string sceneName; + + /// + /// 游戏客户端版本号 (Player Settings → Version) + /// + public string appVersion; + + /// + /// Unity 引擎版本号 + /// + public string unityVersion; + + /// + /// 屏幕宽度 (像素) + /// + public int screenWidth; + + /// + /// 屏幕高度 (像素) + /// + public int screenHeight; + + /// + /// 屏幕 DPI (设备物理像素密度) + /// + public float screenDpi; + + /// + /// 系统语言 + /// + public string systemLanguage; + + /// + /// 当前激活的 Layer 名称数组 + /// + public string[] activeLayerNames; + + /// + /// 屏幕方向 (如横屏 / 竖屏) + /// + public string orientation; + + /// + /// 安全区域 (刘海屏等的可用显示区域) + /// + public Rect safeArea; + + /// + /// 画质等级索引 + /// + public int qualityLevel; + + /// + /// 画质等级名称 + /// + public string qualityLevelName; + + /// + /// 颜色空间 (Linear / Gamma), 两端不一致时纯色块会明显偏亮或偏暗 + /// + public string colorSpace; + + /// + /// 目标帧率 (-1 表示未限制) + /// + public int targetFrameRate; + + /// + /// 场景 UI 节点树的根节点列表 (通常每个 Canvas 对应一棵子树) + /// + public List nodes = new List(); + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/README.md b/timi_hok_game_translator/Unity_LQATool_Plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3a1b879a4e30ab6aee439d90c0bd18a01f790e0a --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/README.md @@ -0,0 +1,322 @@ +# LQATool 插件 + +![Version](https://img.shields.io/badge/version-1.0.0-blue) +![Supported Platforms](https://img.shields.io/badge/platform-Win64%20|%20Mac%20|%20iOS%20|%20Android-lightgrey) +![License](https://img.shields.io/badge/license-Apache%202.0-blue) + +--- + +## 简介 + +**LQATool** 是由 *IEG互动娱乐事业群/天美工作室群* 开发的一个 Unity 引擎插件, 是本地化 UI 质检流水线的 **上游采集端**: 它在游戏运行时把当前画面的 UI 节点树、文本属性、字体、可见性与截图采集下来, 导出为 **Dump 数据**, 供下游 **LQARestore** 还原端重建画面并对接 **LQA 平台** 做检测, 服务于本地化 UI 质量检查 + +- **本插件 (LQATool)**: 运行时自动常驻 (无需手动挂载), 通过悬浮 UI 按钮或 F9 热键一键 Dump; 采集时冻结画面同帧输出 `ScreenShot_Full.png` (含文本) 与 `ScreenShot_NoText.png` (无文本背景图), 借助文本 ID 染色图与像素差分判定每个文本是否真正可见, 并遍历场景 Canvas 导出 UI 节点树 JSON (`ui_data_all.json` / `ui_data_text.json`, 含分辨率、语言、屏幕方向、安全区、画质、颜色空间等环境元数据), 输出到 `persistentDataPath/LQATool/UIDump_<时间戳>/`; 另支持长按拾取最近文本节点查看详情, 以及按图层拆分截图等可选调试输出 +- **下游 (LQARestore)**: 读取本插件产出的 Dump, 把文本节点树 1:1 重建到还原场景中, 叠加在无文本背景图之上, 截图输出 `Restore.png`, 并导出文本框 `rect_locations.json` 供平台检测使用 + +--- + +## 使用说明 + +### 1. 开启工具 + +插件随游戏启动自动常驻, 但默认 **不显示**, 两种开启方式任选其一: + +| 方式 | 做法 | 生效时机 | +| --- | --- | --- | +| PlayerPrefs 开关 | `PlayerPrefs.SetInt("LQA_ShowDumpAndGetNodeButtons", 1); PlayerPrefs.Save();` | **下次启动游戏** 时生效 (该值只在启动时读取一次), 适合接到 GM 面板 | +| 运行时接口 | `LQATool.Core.LQATool.SetEnable(true);` (传 `false` 关闭) | **立即生效**, 适合接到调试菜单 | + +开启后, 屏幕 **左侧垂直居中** 处会出现两个半透明黑底按钮: **`Dump`** 和 **`GetNode[off]`**, 它们始终在所有游戏 UI 的最上层 (Canvas `sortingOrder = 32767`), Dump 截图时会自动隐藏, 不会被截进去 + +![悬浮按钮](docs/images/usage_tool_buttons.png) + +### 2. 一键 Dump (采集当前画面) + +#### 2.1 操作步骤 + +1. 进入要做本地化检查的界面, 等界面动画播完、画面稳定 +2. 点击 **`Dump`** 按钮, 或按键盘 **F9** (方便 PC / Editor 使用) +3. Dump 过程中会: + - 暂停游戏时间 (`Time.timeScale = 0`), 保证几张截图是同一帧 + - 短暂隐藏工具按钮 + - 依次截图、判定文本可见性、导出 JSON +4. 完成后按钮重新出现, 游戏恢复运行, Console 输出: + + ``` + [LQATool][UIDumpService] 转储完成! 路径: <输出目录> + ``` + +![Dump 完成日志](docs/images/usage_dump_console.png) + +> 防重复触发: 上一次 Dump (包括延时等待阶段) 没结束前, 再点按钮或再按 F9 都会被忽略 + +#### 2.2 延时 Dump (可选) + +有些画面只有在手指按住、鼠标悬停时才会出现 (如 Tips、长按弹窗), 或者手机上需要先关掉 GM 面板, 这时可以设置延时: + +```csharp +// 点击 Dump 后等待 N 秒再开始采集 (按真实时间计, 不受 timeScale 影响), 0 表示立即采集 (默认) +PlayerPrefs.SetInt("LQA_DumpDelaySeconds", 3); +PlayerPrefs.Save(); +``` + +触发后 Console 会提示 `[LQATool] Dump 将在 N 秒后开始采集...`, 在这段时间里把画面切到目标状态即可 + +### 3. 获取 Dump 产物 + +每次 Dump 都会生成一个带时间戳的独立目录: + +``` +Application.persistentDataPath/LQATool/UIDump_yyyy_MM_dd_HH_mm_ss/ +``` + +各平台 `persistentDataPath` 的常见位置 (以 Console 日志打印的实际路径为准): + +| 平台 | 路径 | 取出方式 | +| --- | --- | --- | +| Windows (Editor / 包体) | `%USERPROFILE%\AppData\LocalLow\\\` | 直接在资源管理器打开 | +| macOS (Editor / 包体) | `~/Library/Application Support///` | Finder → 前往文件夹 | +| Android | `/storage/emulated/0/Android/data/<包名>/files/` | `adb pull` (见下方) | +| iOS | `/Documents/` | Xcode → Devices and Simulators → 下载 App Container; 或开启 `UIFileSharingEnabled` 后用 Finder / iTunes 文件共享导出 | + +Android 一次拉取全部 Dump: + +```bash +adb pull /storage/emulated/0/Android/data/<包名>/files/LQATool ./LQATool_Dump +``` + +![输出目录](docs/images/usage_output_folder.png) + +### 4. 产物文件说明 + +| 文件 | 默认是否生成 | 控制开关 | 用途 | +| --- | --- | --- | --- | +| `ScreenShot_Full.png` | 是 | 始终生成 | 完整画面 (含文本), **下游必需** | +| `ScreenShot_NoText.png` | 是 | 始终生成 | 隐藏所有文本 (含 Shadow / Outline、TMP 子网格) 后的背景图, **下游必需** | +| `ui_data_text.json` | 是 | `EmitTextUIDataJson` | 只保留含文本 / 图片的节点及其祖先的 UI 节点树, **下游主要读取它** | +| `ui_data_all.json` | 否 | `EmitFullUIDataJson` | 全量 UI 节点树 (字段与上面相同, 只是不剪枝) | +| `ScreenShot_TextId.png` / `ScreenShot_TextId_Pure.png` | 是 | `EmitTextIdMapDebug` | 文本 ID 染色图, 每个文本一种颜色, 用来人工核对文本足迹 | +| `ScreenShot_VisDebug.png` | 是 | `EmitVisibilityDebug` | 可见性判定结果叠加图 | +| `ScreenShot_Only_.png` / `ScreenShot_BG.png` | 否 | `EmitLayerScreenshots` | 按 `UILayerNames` 分层渲染的截图, 纯调试用, 下游不读取 | + +#### 4.1 JSON 环境元数据 + +两份 JSON 的根对象都带有 Dump 那一刻的环境信息, 供还原端复现相同环境: +`sceneName`、`appVersion`、`unityVersion`、`screenWidth` / `screenHeight`、`screenDpi`、`systemLanguage`、`orientation`、`safeArea`、`qualityLevel` / `qualityLevelName`、`colorSpace`、`targetFrameRate`、`activeLayerNames`, 节点树放在 `nodes` 中 + +![Full vs NoText](docs/images/usage_full_vs_notext.png) + +![TextId 染色图](docs/images/usage_textid.png) + +#### 4.2 查看可见性判定图 `ScreenShot_VisDebug.png` + +在完整截图上, 每个文本的包围盒会按判定结果描上不同颜色的边框: + +| 边框颜色 | 判定 | 含义 / 处理建议 | +| --- | --- | --- | +| 绿色 | 可见 | 文本与背景差异明显 | +| 黄色 | 可见 (临界) | 差异像素很少, 建议人工复核 | +| 红色 | 不可见 | 有足迹, 但差异占比低于 `PixelDiffMaskVisibleRatio` (被遮挡 / 没画出来) | +| 紫色 | 不可见 | 足迹被其它文本覆盖 (文字互相重叠) | +| 青色 | 不可见 | 足迹太弱 (小字号 / 细笔画), 可调低 `PureMaskAlphaThreshold` (如 64) | +| 灰色 | 不可见 | 足迹为空 (被裁剪 / 没渲染 / 被非文本图形挡住) | + +![可见性判定图](docs/images/usage_visdebug.png) + +### 5. 长按拾取文本节点 (GetNode) + +用于在游戏里 **现场查看** 某段文字对应的节点路径、文本内容、本地化 Key 等信息, 不需要先 Dump + +#### 5.1 操作步骤 + +1. 点击 **`GetNode[off]`** 按钮, 按钮变成绿色 **`GetNode[on]`**, 表示拾取已开启 +2. 在要查看的文字附近 **按住不动 1 秒** (鼠标左键或单指) +3. 按住的位置旁弹出信息面板, 显示 **离按住点最近的文本节点** (按文本矩形中心点距离计算, 只算屏幕内、处于激活状态且内容不为空的 Text / TMP) +4. 再次点击 / 触摸屏幕任意位置, 面板关闭 +5. 再点一次 `GetNode[on]` 即可关闭拾取 + +![GetNode 开启](docs/images/usage_getnode_on.png) + +![节点信息面板](docs/images/usage_getnode_panel.png) + +#### 5.2 面板字段 + +| 字段 | 说明 | +| --- | --- | +| `Name` (括号内为主组件类型) | GameObject 名称 | +| `Path` | 节点在 Hierarchy 中的完整路径, 可直接据此在工程里定位 | +| `Text` | 当前显示的文本内容 | +| `KeyHash` | 本地化 Key (需要接入项目, 完成长按详情的适配后才会显示) | +| `AnchoredPosition` / `SizeDelta` | RectTransform 布局信息 | +| `FontStyle` / `FontSize` / `Alignment` / `HorizontalOverflow` / `VerticalOverflow` | **仅 UGUI `Text`** 显示, TMP 文本不显示这几项 | + +> 注意: 拾取 **不会拦截** 游戏输入, 如果长按的位置正好在游戏按钮上, 松手时可能触发该按钮的点击, 建议按在文字旁边的空白处 (面板显示的是 "最近" 的节点, 不必精确按在文字上) + +--- + +## 常见问题 + +**Q: 已经设置 PlayerPrefs 为 1, 但按钮没出现?** +A: 这个值只在游戏启动时读取一次, 需要重启游戏; 或改用 `LQATool.Core.LQATool.SetEnable(true)` 立即开启, 也可以检查 Console 是否有 `[LQATool] 工具已按 PlayerPrefs 配置禁用` 日志 + +**Q: 开启后 Console 不停报 `InvalidOperationException: You are trying to read Input using the UnityEngine.Input class...`?** +A: 插件的 F9 热键和长按检测用的是旧版 `UnityEngine.Input`, 如果工程的 `Player Settings → Active Input Handling` 只选了 `Input System Package (New)`, 请改成 `Both` + +**Q: 按钮点不动?** +A: 插件会在场景里没有 EventSystem 时自动补一个; 如果工程自己的 EventSystem / 输入模块被禁用或拦截了事件, 请检查它的状态, 或者直接用 F9 热键 Dump + +**Q: 很多文本被判为不可见 (红 / 青 / 灰框)?** +A: 按 `ScreenShot_VisDebug.png` 的颜色对照表格排查: 青色多就调低 `PureMaskAlphaThreshold`, 红色多但肉眼明显可见就调低 `PixelDiffMaskVisibleRatio` 或 `PixelDiffColorThreshold` + +**Q: 截图里有动画残影或文本位置不对?** +A: Dump 时虽然会把 `timeScale` 设为 0, 但用 unscaled time 驱动的动画 / Tween 仍会继续播放, 请等界面动画播完后再 Dump, 必要时配合 `LQA_DumpDelaySeconds` 延时 + +--- + +## 接入项目 + +LQATool 本体与具体游戏工程 **解耦**: 通用 Unity 组件 (Canvas / Text / Image / TMP 等) 已内置支持, 无需改动; 你只需针对本工程做三处适配 —— **配置 UI 图层**、**适配项目专属组件**、**(可选) 调优阈值与输出开关**, 下面按步骤引导 + +### 1. 安装与启用 + +1. 将本插件目录放入工程 `Assets/` 下任意位置 (如 `Assets/Plugins/LQATool/` 或 `Assets/LQATool/`) 即可; 脚本会自动编入 `Assembly-CSharp` 参与编译, 无需额外配置 +2. 插件通过 `[RuntimeInitializeOnLoadMethod]` 在首个场景加载后 **自动常驻**, 无需手动挂载任何脚本 +3. 默认是否显示悬浮按钮由 `PlayerPrefs` 控制, 默认关闭, 启用方式: + + ```csharp + // 1 = 启用 (显示 Dump / GetNode 悬浮按钮), 0 = 禁用 + PlayerPrefs.SetInt("LQA_ShowDumpAndGetNodeButtons", 1); + PlayerPrefs.Save(); + ``` + + 启用后, 运行时点击悬浮按钮或按 **F9** 即可一键 Dump, 产物输出到 `Application.persistentDataPath/LQATool/UIDump_<时间戳>/` + +### 2. 配置本工程的 UI 图层 + +打开 `Config/LQAUILayerConfig.cs`, 把本工程需要单独分层截图的 UI Layer 名添加到 `UILayerNames` 中, 插件会对其中每个 Layer 单独渲染分层截图, 未列入的图层合并为背景图; 列表中不存在的 Layer 名会被自动跳过并打印警告 + +```csharp +public static readonly List UILayerNames = new List +{ + "UI", + // 添加你工程里的图层名, 例如: + // "UI_HUD", + // "UI_Popup", +}; +``` + +### 3. 适配项目专属组件 (关键步骤) + +游戏里常见两类 **项目专属脚本** 需要导出, 供下游 LQARestore / LQA 平台使用: + +- **本地化组件**: 导出文本的翻译 Key / Hash, 用于反查原文与译文 +- **富文本组件**: 导出描边 / 阴影 / 特效等视觉参数, 供还原端 1:1 复刻 + +主要适配集中在 `Services/ProjectCustomExtractors.cs`, 通过「**字符串类型名 + 反射读字段**」注册, **不需要** 让插件直接引用你的工程程序集; 若目标类型在当前工程不存在, 会被静默跳过, 不影响其它功能 + +> 另有一处 (长按拾取详情): 若希望 **长按拾取节点的实时详情面板** 也显示本地化 Key, 还需同步修改两个标注 `Project-Specific` 的代码段 —— `Services/UIDumpService.GetNode.cs` (反射读取并写入该键) 与 `UI/LQAToolUIManager.Display.cs` (读取该键并显示), 把其中的组件名 (`XxxxLocalize`) 与字段名 (`keyHash`) 改成你自己的, ⚠️ 两处键名必须保持一致, 否则详情面板读不到 Key, 该路径独立于主 Dump 流程, 只服务于拾取详情显示 + +#### 3.1 先查出组件的字段名 + +你多半不清楚自己组件里字段叫什么 (`keyHash` / `m_Key` / `localizeId` …), 在提取器回调里临时调用 `DumpAllFieldsForDebug`, 运行一次 Dump 即可在 Console 看到该组件的全部字段名、类型与当前值: + +```csharp +ComponentExtractors.RegisterByTypeName("你的本地化组件类名", (comp, node) => +{ + // 临时调试: 打印该组件所有字段 (映射完成后请删除) + DumpAllFieldsForDebug(comp); // 只看脚本自身字段 + // DumpAllFieldsForDebug(comp, true); // 连 Unity 基类字段一起看 +}); +``` + +#### 3.2 注册本地化组件 + +把 `RegisterXxxxLocalize` 换成你自己的组件名与字段名, 类型名可用短名 (`Type.Name`) 或带命名空间的全名 (`Type.FullName`, 用于避免重名冲突): + +```csharp +private static void RegisterMyLocalize() +{ + ComponentExtractors.RegisterByTypeName("MyLocalizeComponent", (comp, node) => + { + // 用 object 兜底, 兼容 string / int / long 等各种哈希类型 + if (!TryGetFieldValue(comp, "你的Key字段名", out var val) || val == null) return; + + string s = val.ToString(); + if (string.IsNullOrEmpty(s)) return; + + // 写入 ObjectData["MyLocalize"]["keyHash"] = "\"xxxx\"" + // 外层双引号是 JSON 字符串字面量的一部分 + node.AddComponentProperty("MyLocalize", "keyHash", $"\"{s}\""); + }); +} +``` + +#### 3.3 注册富文本/视觉组件 (可选) + +借助 `CustomExtractorHelpers` 提供的类型化写入方法, 导出描边/阴影等参数, 建议优先读运行时的 `Current*` 实际值, 比读原始序列化字段更贴近玩家真正看到的效果: + +```csharp +private static void RegisterMyRichText() +{ + ComponentExtractors.RegisterByTypeName("MyNamespace.MyRichText", (comp, node) => + { + const string K = "MyRichText"; // 组件键名, 与下游 JSON 约定一致 + + // 枚举: 用基类 Enum 接住, 避免硬引用具体枚举类型 + if (TryGetFieldValue(comp, "TextEffectType", out var effectType)) + AddEnum(node, K, "textEffectType", effectType); + + // 颜色 (RGBA) + if (TryGetFieldValue(comp, "CurrentOutlineColor", out var outlineColor)) + AddColor(node, K, "outlineColor", outlineColor); + + // Vector2 (像素偏移) + if (TryGetFieldValue(comp, "CurrentOutlineDistance", out var outlineDistance)) + AddVector2(node, K, "outlineDistance", outlineDistance); + }); +} +``` + +#### 3.4 挂到注册入口并清理调试代码 + +在 `RegisterAll` 中登记你的注册方法, 并在确认字段映射正确后删除所有 `DumpAllFieldsForDebug` 调用 (否则每次 Dump 都会反射刷屏): + +```csharp +internal static void RegisterAll() +{ + RegisterMyLocalize(); + RegisterMyRichText(); +} +``` + +> 可直接复用的辅助方法 (均在 `CustomExtractorHelpers` 中): +> `TryGetFieldValue(comp, "字段名", out value)` 反射读字段; +> `AddEnum / AddColor / AddVector2(node, 组件键, 属性键, 值)` 类型化写入; +> `node.AddComponentProperty(组件键, 属性键, JSON字面量)` 写任意原始 JSON 值; +> `DumpAllFieldsForDebug(comp)` 开发期打印全部字段 +> +> 文本内容本身 (UGUI `Text` 与 TMP) 已由 `Utils/TextLike.cs` 自动适配, **无需** 额外注册; 仅当你的文本组件既不继承 `UnityEngine.UI.Text` 也不继承 `TMP_Text` 时才需扩展该文件 + +### 4. 阈值与输出开关调优 (可选) + +`Config/LQAUILayerConfig.cs` 中的其余参数一般保持默认即可, 按需微调: + +| 配置项 | 默认值 | 说明 / 何时调整 | +| --- | --- | --- | +| `PixelDiffMaskVisibleRatio` | `0.10f` | 文本 "可见" 所需的差异像素占比; 误判太多可上调, 漏判可下调 | +| `PixelDiffColorThreshold` | `12` | 单像素颜色差异显著阈值; 值越小越敏感 | +| `PureMaskAlphaThreshold` | `128` | 文本足迹最小 alpha;小字号/细笔画中文误判为不可见时可调低 (如 64) | +| `EmitTextIdMapDebug` | `true` | 是否另存文本 ID 染色图, 便于人工核对足迹 | +| `EmitVisibilityDebug` | `true` | 是否输出可见性判定可视化叠加图 `ScreenShot_VisDebug.png` (颜色含义见使用说明) | +| `EmitFullUIDataJson` | `false` | 是否落盘全量节点树 `ui_data_all.json` | +| `EmitTextUIDataJson` | `true` | 是否落盘文本/图片剪枝版 `ui_data_text.json` | +| `EmitLayerScreenshots` | `false` | 是否落盘分层/背景截图 (纯调试产物, 下游不消费) | + +### 5. 验证接入是否成功 + +运行游戏 → 启用工具 → 按 **F9** 或点击悬浮按钮 Dump, 然后检查输出目录 `Application.persistentDataPath/LQATool/UIDump_<时间戳>/`: + +- `ScreenShot_Full.png` (含文本)、`ScreenShot_NoText.png` (无文本背景图) 正常生成; +- `ui_data_text.json` (及按开关生成的 `ui_data_all.json`) 中, 对应节点下 **出现你注册的组件键** (如 `"MyLocalize"`、`"MyRichText"`) 及其属性, 即说明项目专属组件接入成功 + +--- \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ComponentExtractors.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ComponentExtractors.cs new file mode 100644 index 0000000000000000000000000000000000000000..020ee150e55c4ad11724b75290a3347cdfd04448 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ComponentExtractors.cs @@ -0,0 +1,493 @@ +// ========================================== +// 文件: LQATool\Services\ComponentExtractors.cs +// 模块: Services (业务) +// ========================================== + +using System; +using System.Globalization; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; +using LQATool.Config; +using LQATool.Models; +using LQATool.Utils; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// 组件属性提取器的注册中心 (通用 Unity 组件) + /// + /// 职责: + /// - 维护一张 "组件类型 -> 提取函数" 的注册表; + /// - 提供 ExtractAll: 遍历某个 Transform 上挂载的所有已注册组件, 把它们的属性抽取成 + /// JSON 片段写入 UINodeData.ObjectData, 最终由 JsonBuilder 序列化成导出 JSON; + /// + /// 设计要点: + /// - 采用注册表模式, 新增一种组件的支持只需 Register, 无需改动遍历逻辑; + /// - 通用 Unity 组件 (Canvas / Text 等) 在本类的 RegisterAllExtractors 中集中注册; + /// - 项目专属脚本 (XxxxLocalize / XxxxText 等) 由 ProjectCustomExtractors 通过反射注册, 与本类解耦; + /// - 声明为 static, 全局只有一份注册表, 由静态构造函数在首次访问时初始化一次; + /// + internal static class ComponentExtractors + { + // ========================================== + // 注册表条目 (用 struct 避免 GC) + // ========================================== + + /// + /// 单条注册表条目: 把 "组件类型" 与 "针对该类型的提取函数" 绑定在一起 + /// 用 struct 而非 class, 是为了让条目内联存储在 List 中, 避免为每条注册产生一次堆分配 (减少 GC 压力) + /// + private struct ExtractorEntry + { + /// + /// 目标组件的类型, ExtractAll 会用它调用 Transform.GetComponent(Type) 探测组件是否存在 + /// + public Type ComponentType; + + /// + /// 提取函数: 入参为探测到的组件实例与当前节点数据, 负责把组件属性写入 node + /// 统一以基类 Component 为签名, 泛型版本 Register 内部会做一次向下转型再回调 + /// + public Action Extractor; + } + + // ========================================== + // 注册表存储 + // ========================================== + + /// + /// 全局注册表, 存放所有已登记的 (组件类型, 提取函数) 条目, 由静态构造填充后只读遍历 + /// + private static readonly List _entries = new List(); + + // ========================================== + // 静态构造: 注册所有提取器 + // ========================================== + + /// + /// 静态构造函数, 在本类被首次访问时由 CLR 自动调用一次 + /// 负责填充注册表: 先注册通用 Unity 组件, 再注册项目自定义组件 + /// + static ComponentExtractors() + { + // 注册通用 Unity 组件 (Canvas / CanvasScaler / Text ...) + RegisterAllExtractors(); + // 注册项目专属组件 (通过反射按类型名匹配, 目标类型不存在时会被静默跳过) + ProjectCustomExtractors.RegisterAll(); + } + + // ========================================== + // 公开 API: 供 BuildNodeTree 调用 + // ========================================== + + /// + /// 遍历给定 Transform 上挂载的所有已注册组件, 依次执行对应的提取函数, 把属性写入 node + /// 由 UI 树构建流程 (BuildNodeTree) 对每个节点调用一次 + /// + /// 当前正在处理的节点 Transform + /// 与该 Transform 对应的节点数据, 提取结果写入其 ObjectData + internal static void ExtractAll(Transform t, UINodeData node) + { + // 逐条检查注册表: 用 for 而非 foreach, 避免枚举器分配, 同时明确按注册顺序执行 + for (int i = 0; i < _entries.Count; i++) + { + // 探测该 Transform 上是否挂有此类型的组件 + Component comp = t.GetComponent(_entries[i].ComponentType); + + // 没有该组件则跳过, 交给下一条注册项 + if (comp == null) continue; + + try + { + // 执行提取函数, 把组件属性写入 node.ObjectData + _entries[i].Extractor(comp, node); + } + catch (MissingReferenceException) + { + // 组件/其引用的对象在遍历途中被销毁 (常见于运行时动态 UI), 属预期情况, 静默忽略 + } + catch (System.Exception e) + { + // 其他异常: 单个提取器失败不应中断整棵树的导出, 记一条警告后继续处理其余组件 + Debug.LogWarning($"[LQATool][ComponentExtractors] {t.gameObject.name} 上的提取器 {_entries[i].ComponentType.Name} 失败: {e.Message}"); + } + } + } + + // ========================================== + // 注册辅助方法 + // ========================================== + + /// + /// 泛型注册: 用于编译期已知类型的标准 Unity 组件 + /// 调用方直接以强类型 T 编写提取逻辑, 内部包一层把 Component 向下转型为 T 再回调 + /// + /// 目标组件类型, 必须派生自 Component + /// 针对 T 的提取函数 + internal static void Register(Action extractor) where T : Component + { + _entries.Add(new ExtractorEntry + { + ComponentType = typeof(T), + // 适配层: 注册表统一存 Action, 这里把入参强转成 T 再转发给业务提取器 + Extractor = (comp, node) => extractor((T)comp, node) + }); + } + + /// + /// 按类型名注册: 用于类型不在本插件引用范围内的项目专属组件 (如 XxxxLocalize / Xxxx.XxxxText) + /// 通过反射遍历当前已加载的所有程序集, 查找名称匹配且派生自 Component 的类型 + /// 目标类型在当前工程中不存在时, 仅打印一条日志并放弃注册, 不影响其他提取器 + /// + /// 组件的短名 (Type.Name) 或全名 (Type.FullName) + /// 针对该组件的提取函数 (以基类 Component 为入参, 内部自行反射读字段) + internal static void RegisterByTypeName(string typeName, Action extractor) + { + // 入参保护: 类型名为空或未提供提取函数时直接返回 + if (string.IsNullOrEmpty(typeName) || extractor == null) return; + + // 反射解析: 在所有已加载程序集中查找匹配的组件类型 + Type resolvedType = null; + foreach (var asm in System.AppDomain.CurrentDomain.GetAssemblies()) + { + try + { + foreach (var t in asm.GetTypes()) + { + if (t == null) continue; + // 只接受 Component 的子类, 因为后续要靠 GetComponent 按类型探测 + if (!typeof(Component).IsAssignableFrom(t)) continue; + // 短名或全名任一匹配即认定命中 + if (t.Name == typeName || t.FullName == typeName) + { + resolvedType = t; + break; + } + } + } + catch (System.Reflection.ReflectionTypeLoadException) + { + // 个别程序集类型加载失败 (依赖缺失等) 属正常现象, 跳过该程序集继续查找 + } + // 已找到目标类型, 无需再遍历其余程序集 + if (resolvedType != null) break; + } + + // 当前工程未包含该类型: 记日志并放弃注册 (松耦合设计, 缺少项目脚本时插件仍可正常工作) + if (resolvedType == null) + { + Debug.Log($"[LQATool][ComponentExtractors] 自定义组件类型 \"{typeName}\" 未在当前工程中找到, 该提取器将被忽略"); + return; + } + + // 反射解析成功: 直接存入解析到的类型与提取函数 (提取函数已是 Component 签名, 无需再包适配层) + _entries.Add(new ExtractorEntry + { + ComponentType = resolvedType, + Extractor = extractor + }); + } + + /// + /// 把文本可见性判定的调试快照 (VisibilityDebug) 手动拼接成 JSON 对象片段 + /// 仅在 LQAUILayerConfig.EmitVisibilityDebug 开启时用于把判定中间量一并写入导出结果, 便于问题定位 + /// + /// 可见性判定过程中记录的调试数据 + /// 形如 {"verdict": true, "reason": "...", ...} 的 JSON 片段字符串 + private static string FormatVisibilityDebug(PixelVisibilityChecker.VisibilityDebug d) + { + // 统一使用不变文化格式化浮点, 避免非英语系系统把小数点渲染成 "," 破坏 JSON + var ci = CultureInfo.InvariantCulture; + return "{" + + $"\"verdict\": {d.verdict.ToString().ToLower()}, " // 最终判定: 是否可见 (bool 转小写以符合 JSON 规范) + + $"\"reason\": \"{d.reason}\", " // 判定原因的文字说明 + + $"\"hasId\": {d.hasId.ToString().ToLower()}, " // 是否成功取到该文本的 ID + + $"\"id\": {d.id}, " // 文本对应的 ID (int) + + $"\"aabbValid\": {d.aabbValid.ToString().ToLower()}, " // 包围盒是否有效 + + $"\"aabb\": {{\"x\": {d.aabb.x}, \"y\": {d.aabb.y}, \"width\": {d.aabb.width}, \"height\": {d.aabb.height}}}, " // 屏幕空间包围盒 + + $"\"maskTotal\": {d.maskTotal}, " // 掩码内像素总数 + + $"\"diffCount\": {d.diffCount}, " // 判定为 "露出" 的像素数 + + $"\"weakAlpha\": {d.weakAlpha}, " // 未达 alpha 门槛的弱足迹像素数 (小字号/抗锯齿边缘) + + $"\"coveredByOther\": {d.coveredByOther}, " // 被其它文本覆盖的像素数 + + $"\"ratio\": {d.ratio.ToString("F3", ci)}, " // diffCount / maskTotal 的可见比例 + + $"\"ratioThreshold\": {d.ratioThreshold.ToString("F3", ci)}, " // 判定阈值 + + $"\"useMask\": {d.useMask.ToString().ToLower()}" // 本次是否具备掩码判定条件 + + "}"; + } + + /// + /// 反射读取组件的公开实例属性值 (供 TMP 等未直接引用类型使用) + /// 属性不存在 / 类型不匹配 / getter 抛错时返回 false + /// + private static bool TryGetProp(Component comp, string propName, out T value) + { + value = default; + if (comp == null) return false; + var p = comp.GetType().GetProperty(propName, + System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); + if (p == null) return false; + try + { + object raw = p.GetValue(comp, null); + if (raw is T tv) { value = tv; return true; } + if (raw == null && !typeof(T).IsValueType) return true; + } + catch { } + return false; + } + + /// + /// 通用记录一个图形组件 (Image / RawImage) 的几何与可见性, 写入节点 ObjectData + /// 只做通用记录: 把 RectTransform 的 4 个世界角点逐点投影到屏幕像素后原样写出, + /// 顺序即 GetWorldCorners 原生顺序 ([0]左下 [1]左上 [2]右上 [3]右下) + /// + /// 图形组件 (Image 或 RawImage, 均派生自 Graphic) + /// 当前节点数据 + /// 写入的组件键名 ("Image" 或 "RawImage") + private static void ExtractGraphicImage(Graphic g, UINodeData node, string componentKey) + { + // 非 RectTransform (理论上 UGUI 图形不会出现) 则无从取角点, 跳过 + var rt = g.transform as RectTransform; + if (rt == null) return; + + // 标记本节点含图片, 使其进入 ui_data_text.json 的剪枝树 + node.hasImage = true; + + // 世界->屏幕: Overlay 画布不依赖相机 (传 null), 其它模式用画布相机 + Canvas c = g.canvas; + Camera cam = (c != null && c.renderMode != RenderMode.ScreenSpaceOverlay) ? c.worldCamera : null; + + // 4 个世界角点原样投影到屏幕像素并记录 (顺序: 左下→左上→右上→右下) + Vector3[] world = new Vector3[4]; + rt.GetWorldCorners(world); + Vector2 p0 = RectTransformUtility.WorldToScreenPoint(cam, world[0]); + Vector2 p1 = RectTransformUtility.WorldToScreenPoint(cam, world[1]); + Vector2 p2 = RectTransformUtility.WorldToScreenPoint(cam, world[2]); + Vector2 p3 = RectTransformUtility.WorldToScreenPoint(cam, world[3]); + string corners = "[" + FormatScreenPoint(p0.x, p0.y) + ", " + FormatScreenPoint(p1.x, p1.y) + + ", " + FormatScreenPoint(p2.x, p2.y) + ", " + FormatScreenPoint(p3.x, p3.y) + "]"; + node.AddComponentProperty(componentKey, "corners", corners); + + // 通用可见性: 组件启用 + 节点在层级中激活 + 非全透明 (图片无 Full/NoText 像素差分) + bool visible = g.enabled && g.gameObject.activeInHierarchy && g.color.a > 0.04f; + node.AddComponentProperty(componentKey, "isVisuallyVisible", visible.ToString().ToLower()); + } + + /// + /// 屏幕点格式化为 JSON 片段 {"x":.., "y":..} (取整为像素) + /// + private static string FormatScreenPoint(float x, float y) + => "{\"x\": " + Mathf.RoundToInt(x) + ", \"y\": " + Mathf.RoundToInt(y) + "}"; + + // ========================================== + // 所有组件提取器在此注册 + // ========================================== + + /// + /// 集中注册所有通用 Unity 组件的提取器 + /// 每个 Register 调用对应一种组件类型, lambda 内部把该组件关心的属性写入 node.ObjectData + /// + private static void RegisterAllExtractors() + { + // ========================================== + // Canvas 组件: UI 渲染的根组件, 导出其排序与像素对齐相关属性 + // ========================================== + + Register((canvasComp, node) => + { + // 是否开启像素对齐 (影响 UI 清晰度) + node.AddComponentProperty("Canvas", "pixelPerfect", canvasComp.pixelPerfect.ToString().ToLower()); + // 渲染排序值, 数值越大越靠前显示 + node.AddComponentProperty("Canvas", "sortingOrder", canvasComp.sortingOrder.ToString()); + // 是否为根 Canvas (嵌套 Canvas 时区分层级) + node.AddComponentProperty("Canvas", "isRootCanvas", canvasComp.isRootCanvas.ToString().ToLower()); + // 是否覆盖父级排序 (子 Canvas 独立排序时为 true) + node.AddComponentProperty("Canvas", "overrideSorting", canvasComp.overrideSorting.ToString().ToLower()); + // 排序层名称 (字符串, 需转义并加引号以构成合法 JSON 值) + node.AddComponentProperty("Canvas", "sortingLayerName", $"\"{JsonBuilder.EscapeJson(canvasComp.sortingLayerName)}\""); + }); + + // ========================================== + // CanvasScaler 组件: 控制 UI 随分辨率缩放的策略, 导出其缩放模式与参考分辨率 + // ========================================== + + Register((scalerComp, node) => + { + // UI 缩放模式 (枚举: ConstantPixelSize / ScaleWithScreenSize / ConstantPhysicalSize) + node.AddComponentProperty("CanvasScaler", "uiScaleMode", $"\"{scalerComp.uiScaleMode}\""); + // 参考每单位像素数 (浮点, 用不变文化格式化) + node.AddComponentProperty("CanvasScaler", "referencePixelsPerUnit", scalerComp.referencePixelsPerUnit.ToString("F3", CultureInfo.InvariantCulture)); + // 参考分辨率 (设计分辨率, Vector2) + node.AddComponentProperty("CanvasScaler", "referenceResolution", JsonBuilder.FormatVector2(scalerComp.referenceResolution)); + // 屏幕匹配模式 (决定按宽/高/折中缩放) + node.AddComponentProperty("CanvasScaler", "screenMatchMode", $"\"{scalerComp.screenMatchMode}\""); + // 宽高匹配权重: 0 完全匹配宽, 1 完全匹配高 + node.AddComponentProperty("CanvasScaler", "matchWidthOrHeight", scalerComp.matchWidthOrHeight.ToString("F3", CultureInfo.InvariantCulture)); + }); + + // ========================================== + // Text 组件: 旧版 UGUI 文本组件, 是 LQA 关注的核心, 导出文本内容 + 字体 + 段落 + 颜色等完整视觉参数 + // ========================================== + + Register((textComp, node) => + { + // 标记本节点含文本, 使其进入 ui_data_text.json 的剪枝树 + node.hasText = true; + + // 从可见性缓存读取该文本是否在屏幕上真正可见 (被遮挡/裁剪则为 false) + // 缓存中无记录时保守按不可见处理 + bool isVisuallyVisible; + if (!PixelVisibilityChecker.TryGetCached(textComp.transform, out isVisuallyVisible)) + { + isVisuallyVisible = false; + } + node.AddComponentProperty("Text", "isVisuallyVisible", isVisuallyVisible.ToString().ToLower()); + + // 调试开关开启时, 额外导出可见性判定的中间量快照, 便于定位误判 + if (LQAUILayerConfig.EmitVisibilityDebug) + { + PixelVisibilityChecker.VisibilityDebug vdbg; + if (PixelVisibilityChecker.TryGetDebug(textComp.transform, out vdbg)) + { + node.AddComponentProperty("Text", "visibilityDebug", FormatVisibilityDebug(vdbg)); + } + } + + // 文本实际内容: 复用 JsonBuilder.EscapeJson 做完整转义, 保证 JSON 合法 + node.AddComponentProperty("Text", "textContent", $"\"{JsonBuilder.EscapeJson(textComp.text)}\""); + + // ========================================== + // Character 分组的属性 + // ========================================== + + // 字体资源引用 (输出 name/assetPath/guid 等资源引用 JSON) + node.AddComponentProperty("Text", "font", AssetRefHelper.FormatAssetRef(textComp.font)); + // 字体样式 (枚举: Normal / Bold / Italic / BoldAndItalic) + node.AddComponentProperty("Text", "fontStyle", $"\"{textComp.fontStyle}\""); + // 字号 + node.AddComponentProperty("Text", "fontSize", textComp.fontSize.ToString()); + // 行间距 (浮点, 用不变文化格式化) + node.AddComponentProperty("Text", "lineSpacing", textComp.lineSpacing.ToString("F2", System.Globalization.CultureInfo.InvariantCulture)); + // 是否支持富文本标签解析 + node.AddComponentProperty("Text", "richText", textComp.supportRichText.ToString().ToLower()); + + // ========================================== + // Paragraph 分组的属性 + // ========================================== + + // 对齐方式 (枚举: 左/中/右 + 上/中/下 组合) + node.AddComponentProperty("Text", "alignment", $"\"{textComp.alignment}\""); + // 水平溢出处理 (Wrap 换行 / Overflow 溢出) + node.AddComponentProperty("Text", "horizontalOverflow", $"\"{textComp.horizontalOverflow}\""); + // 垂直溢出处理 (Truncate 截断 / Overflow 溢出) + node.AddComponentProperty("Text", "verticalOverflow", $"\"{textComp.verticalOverflow}\""); + // 是否自动缩放字号以适应文本框 + node.AddComponentProperty("Text", "bestFit", textComp.resizeTextForBestFit.ToString().ToLower()); + // bestFit 开启时的最小/最大字号 + node.AddComponentProperty("Text", "minSize", textComp.resizeTextMinSize.ToString()); + node.AddComponentProperty("Text", "maxSize", textComp.resizeTextMaxSize.ToString()); + + // ========================================== + // Graphic 基类的属性 + // ========================================== + + // 文本颜色 (RGBA, 输出 {"r":..,"g":..,"b":..,"a":..}) + node.AddComponentProperty("Text", "color", JsonBuilder.FormatColor(textComp.color)); + // 是否作为射线检测目标 (影响点击/触摸事件) + node.AddComponentProperty("Text", "raycastTarget", textComp.raycastTarget.ToString().ToLower()); + }); + + // ========================================== + // TMP 组件: TextMeshProUGUI (可选依赖), 用独立 "TMP" 键忠实导出其视觉参数 + // 不直接引用 TMPro 程序集, 通过类型名 + 反射注册, 未安装 TMP 的工程会被静默跳过 + // ========================================== + + RegisterByTypeName("TMPro.TextMeshProUGUI", (comp, node) => + { + const string K = "TMP"; + + // 标记本节点含文本, 使其进入 ui_data_text.json 的剪枝树 + node.hasText = true; + + // 可见性: 与 Text 一致, 走同一套像素判定缓存 (缓存未命中保守判为不可见) + bool vis; + if (!PixelVisibilityChecker.TryGetCached(comp.transform, out vis)) vis = false; + node.AddComponentProperty(K, "isVisuallyVisible", vis.ToString().ToLower()); + + if (LQAUILayerConfig.EmitVisibilityDebug && + PixelVisibilityChecker.TryGetDebug(comp.transform, out var vdbg)) + { + node.AddComponentProperty(K, "visibilityDebug", FormatVisibilityDebug(vdbg)); + } + + var ci = CultureInfo.InvariantCulture; + + // 文本内容 + if (TryGetProp(comp, "text", out var s)) + node.AddComponentProperty(K, "textContent", $"\"{JsonBuilder.EscapeJson(s ?? string.Empty)}\""); + + // 字号 (TMP 为 float) + if (TryGetProp(comp, "fontSize", out var fsz)) + node.AddComponentProperty(K, "fontSize", fsz.ToString("F2", ci)); + + // 颜色 + if (TryGetProp(comp, "color", out var col)) + node.AddComponentProperty(K, "color", JsonBuilder.FormatColor(col)); + + // 对齐 / 字体样式 / 溢出 (均为 TMP 专有枚举, 用基类 Enum 接住按名导出) + if (TryGetProp(comp, "alignment", out var align)) + node.AddComponentProperty(K, "alignment", $"\"{align}\""); + if (TryGetProp(comp, "fontStyle", out var fstyle)) + node.AddComponentProperty(K, "fontStyle", $"\"{fstyle}\""); + if (TryGetProp(comp, "overflowMode", out var of)) + node.AddComponentProperty(K, "overflowMode", $"\"{of}\""); + + // 富文本 + if (TryGetProp(comp, "richText", out var rich)) + node.AddComponentProperty(K, "richText", rich.ToString().ToLower()); + + // 自动缩放 + if (TryGetProp(comp, "enableAutoSizing", out var auto)) + node.AddComponentProperty(K, "enableAutoSizing", auto.ToString().ToLower()); + if (TryGetProp(comp, "fontSizeMin", out var fmin)) + node.AddComponentProperty(K, "fontSizeMin", fmin.ToString("F2", ci)); + if (TryGetProp(comp, "fontSizeMax", out var fmax)) + node.AddComponentProperty(K, "fontSizeMax", fmax.ToString("F2", ci)); + + // 字距 / 词距 / 行距 / 段距 + if (TryGetProp(comp, "characterSpacing", out var cspace)) + node.AddComponentProperty(K, "characterSpacing", cspace.ToString("F2", ci)); + if (TryGetProp(comp, "wordSpacing", out var wspace)) + node.AddComponentProperty(K, "wordSpacing", wspace.ToString("F2", ci)); + if (TryGetProp(comp, "lineSpacing", out var lspace)) + node.AddComponentProperty(K, "lineSpacing", lspace.ToString("F2", ci)); + if (TryGetProp(comp, "paragraphSpacing", out var pspace)) + node.AddComponentProperty(K, "paragraphSpacing", pspace.ToString("F2", ci)); + + // raycastTarget (Graphic 基类, TMP 也有) + if (TryGetProp(comp, "raycastTarget", out var ray)) + node.AddComponentProperty(K, "raycastTarget", ray.ToString().ToLower()); + + // 字体资源 (TMP_FontAsset), 仅记录引用信息 (name/assetPath/guid) + if (TryGetProp(comp, "font", out var fontAsset)) + node.AddComponentProperty(K, "font", AssetRefHelper.FormatAssetRef(fontAsset)); + }); + + // ========================================== + // Image 组件: UGUI 图片, 记录屏幕角点 corners 与可见性 isVisuallyVisible + // 写入全量树, 并因标记 hasImage 一并保留进文本/图片剪枝树 (ui_data_text.json) + // 还原侧从加载的节点树读取这些框, 导出到 rect_locations 的 image 组 + // ========================================== + Register((imgComp, node) => ExtractGraphicImage(imgComp, node, "Image")); + + // ========================================== + // RawImage 组件: 与 Image 同处理, 用独立 "RawImage" 键 + // ========================================== + Register((rawComp, node) => ExtractGraphicImage(rawComp, node, "RawImage")); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/CustomExtractorHelpers.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/CustomExtractorHelpers.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc6528754da9ea22dad13a70edb2b59479505fc2 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/CustomExtractorHelpers.cs @@ -0,0 +1,280 @@ +// ========================================== +// 文件: LQATool\Services\CustomExtractorHelpers.cs +// 模块: Services (业务) +// ========================================== + +using System; +using System.Collections; +using System.Globalization; +using System.Reflection; +using System.Text; +using UnityEngine; +using LQATool.Models; +using LQATool.Utils; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// 项目自定义组件提取器 (ProjectCustomExtractors) 的通用辅助工具集 + /// + /// 为什么单独抽出: + /// - 项目自定义组件 (如 XxxxLocalize / Xxxx.XxxxText) 的类型未必在本插件的引用范围内, + /// 因此只能通过反射读字段, 而非强类型访问; + /// - 这类反射 + 字段写入是高度重复的样板代码, 集中封装可以让 ProjectCustomExtractors + /// 里的每个提取器保持 "读字段 → 写 JSON" 的短小结构; + /// - 同时保留与 ComponentExtractors (通用 Unity 组件提取器) 完全一致的 + /// AddComponentProperty(componentName, propertyKey, propertyJsonValue) 写入风格, + /// 产出的 JSON 片段格式统一, 方便下游解析; + /// + /// 关于 internal 可见性: 仅供本程序集内 ProjectCustomExtractors 使用, + /// 外部调用请走 ComponentExtractors 的公开注册入口 + /// + internal static class CustomExtractorHelpers + { + /// + /// 反射查找字段时统一使用的 BindingFlags 组合: + /// 公共 + 非公共 + 实例字段, 需要遍历继承链时再按需追加 BindingFlags.DeclaredOnly, + /// 以避免同名字段被父类覆盖导致读到错误的成员 + /// + internal const BindingFlags k_FieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + + // ========================================== + // 反射读取: 字段 + // ========================================== + + /// + /// 按字段名反射读取 comp 上的字段值, 并尝试转换为 T + /// + /// 行为要点: + /// 1. 沿继承链自子类向基类逐层查找 (使用 BindingFlags.DeclaredOnly), + /// 这样即使父类存在同名 private 字段也能正确命中当前类中最 "近" 的那个; + /// 2. 命中字段后: + /// - 值可直接 as 成 T → 返回 true; + /// - 值为 null 且 T 是引用类型 → 视为"存在但为空", 返回 true, out 参数保持默认; + /// - 类型不匹配 (例如字段是 int 但 T 是 string) → 返回 false, 不继续沿链查找; + /// 3. FieldInfo.GetValue 抛出异常时静默返回 false, 保证一个字段的失败不会中断整个提取流程; + /// + /// 特别提醒: 若不确定字段的真实类型, 建议以 object 作为 T, 由调用方再做 ToString() 或类型判断, + /// 参见 ProjectCustomExtractors 中 XxxxLocalize.keyHash 的读取方式 + /// + /// 期望的字段类型 + /// 目标组件实例, 允许为 null (直接返回 false) + /// 字段名, 大小写敏感, 允许 null/空 (直接返回 false) + /// 读取成功时返回字段值, 失败时为 default + /// 是否成功读取到符合 T 语义的字段值 + internal static bool TryGetFieldValue(Component comp, string fieldName, out T value) + { + value = default; + if (comp == null || string.IsNullOrEmpty(fieldName)) return false; + + // 沿继承链逐层向上查找, 直到 System.Object 之前停止 + for (Type t = comp.GetType(); t != null && t != typeof(object); t = t.BaseType) + { + // DeclaredOnly: 只看当前类自己声明的字段, 避免与父类同名字段互相干扰 + var f = t.GetField(fieldName, k_FieldFlags | BindingFlags.DeclaredOnly); + if (f == null) continue; + + try + { + object raw = f.GetValue(comp); + if (raw is T tVal) + { + // 直接命中期望类型 + value = tVal; + return true; + } + if (raw == null && !typeof(T).IsValueType) + { + // 引用类型字段允许为 null: 视作 "字段存在, 值为空", 由调用方自行决定是否写入 + value = default; + return true; + } + // 字段已找到但类型对不上, 没必要再沿继承链继续查找同名字段 + return false; + } + catch + { + // 反射读取异常 (如属性访问器抛错、字段被优化剥离等) 一律吞掉, 保证提取流程不被打断 + return false; + } + } + return false; + } + + // ========================================== + // 字段写入: 与 ComponentExtractors 中既有风格保持完全一致 + // ========================================== + + /// + /// 将枚举值以 JSON 字符串字面量的形式写入节点组件属性表 + /// 输出形如 "SomeEnumValue", 与 ComponentExtractors 中 + /// $"\"{sel.transition}\"" 的写法完全一致 + /// + /// 说明: 参数 value 允许为 null, 此时会写入空字符串 "", + /// 保持 JSON 结构完整 (调用方若不希望写入空值, 应在外层自行判空过滤) + /// + /// 目标节点数据 (提取结果的承载对象) + /// 组件键名, 例如 "XxxxText" + /// 属性键名, 例如 "textEffectType" + /// 枚举值, 通常用基类 Enum 接住以避免硬引用具体枚举类型 + internal static void AddEnum(UINodeData node, string compKey, string propKey, Enum value) + { + node.AddComponentProperty(compKey, propKey, $"\"{(value != null ? value.ToString() : string.Empty)}\""); + } + + /// + /// 将 Color (RGBA) 序列化后写入节点组件属性表 + /// 具体的 JSON 格式由 JsonBuilder.FormatColor 统一负责, + /// 与通用组件 (如 Text.color / Image.color) 的输出保持一致, 便于下游按同一 schema 解析 + /// + internal static void AddColor(UINodeData node, string compKey, string propKey, Color value) + { + node.AddComponentProperty(compKey, propKey, JsonBuilder.FormatColor(value)); + } + + /// + /// 将 Vector2 序列化后写入节点组件属性表 + /// 具体的 JSON 格式由 JsonBuilder.FormatVector2 统一负责 + /// (与 CanvasScaler.referenceResolution 等既有属性使用同一序列化器) + /// + internal static void AddVector2(UINodeData node, string compKey, string propKey, Vector2 value) + { + node.AddComponentProperty(compKey, propKey, JsonBuilder.FormatVector2(value)); + } + + // ========================================== + // [临时调试] 全字段转储, 完成自定义字段映射后请删除调用 + // ========================================== + + /// + /// [仅用于开发期调试] 把 comp 所有 (含私有) 实例字段按继承链逐层打印到 Unity Console + /// + /// 使用场景: 在为一个新的项目自定义组件编写提取器时, 通常不清楚字段真实名称 (可能是 CamelCase / camelCase / + /// m_XXX 等多种风格), 在提取器回调里临时调一次本方法, 就能在 Console 里看到该组件的所有字段名 / 类型 / 当前值, + /// 从而据此确定 TryGetFieldValue{T} 的入参 + /// + /// 注意: 生产环境下不应保留调用, 完成映射后请从 ProjectCustomExtractors 中移除相关 DumpAllFieldsForDebug 语句, + /// 以免每帧 (或每次 Dump UI 时) 刷屏并造成反射开销 + /// + /// 要转储的组件, 允许为 null (直接返回) + /// + /// 是否包含 UnityEngine.* / UnityEditor.* 基类中声明的字段 + /// 默认 false: 只关心项目自定义脚本自身声明的字段, 屏蔽 MonoBehaviour / Behaviour / Component 等基类噪声 + /// + internal static void DumpAllFieldsForDebug(Component comp, bool includeUnityBaseFields = false) + { + if (comp == null) return; + + var sb = new StringBuilder(); + sb.Append("[LQATool][CustomExtractorHelpers] 转储组件 ").Append(comp.GetType().FullName).Append(" 位于 '").Append(comp.name).Append("' (InstanceID=").Append(comp.GetInstanceID()).Append(")\n"); + + // 收集从子类到基类 (Object 除外) 的完整继承链, 后续按声明层级分块打印 + var chain = new System.Collections.Generic.List(); + for (Type t = comp.GetType(); t != null && t != typeof(object); t = t.BaseType) + { + chain.Add(t); + } + + int totalFieldCount = 0; + for (int i = 0; i < chain.Count; i++) + { + var t = chain[i]; + + // 默认跳过 Unity 引擎基类, 避免打印 MonoBehaviour / Behaviour / Component 等无关字段 + if (!includeUnityBaseFields && t.FullName != null && (t.FullName.StartsWith("UnityEngine.") || t.FullName.StartsWith("UnityEditor."))) + { + continue; + } + + // DeclaredOnly: 严格只列出当前类声明的字段, 防止与父类同名字段重复打印 + var fields = t.GetFields(k_FieldFlags | BindingFlags.DeclaredOnly); + if (fields == null || fields.Length == 0) continue; + + sb.Append(" ── 类 ").Append(t.FullName).Append(" (声明了 ").Append(fields.Length).Append(" 个字段) ──\n"); + + for (int j = 0; j < fields.Length; j++) + { + var f = fields[j]; + object val; + // 逐字段捕获异常: 属性/字段 getter 抛错时仅标记为读取失败, 不影响其它字段的输出 + try { val = f.GetValue(comp); } + catch (Exception ex) { val = ""; } + + sb.Append(" ").Append(f.IsPublic ? "public " : "private").Append(' ').Append(GetFriendlyTypeName(f.FieldType)).Append(' ').Append(f.Name).Append(" = ").Append(FormatValueForDebug(val)).Append('\n'); + + totalFieldCount++; + } + } + + sb.Append(" 已转储字段总数: ").Append(totalFieldCount); + + // 传入 context 参数 (comp), 在 Console 里点击日志可高亮到对应 GameObject / Component + Debug.Log(sb.ToString(), comp); + } + + /// + /// 将 Type 转成便于阅读的短名字符串, 供 DumpAllFieldsForDebug 打印使用 + /// + /// 处理规则: + /// - null → "?"; + /// - 数组 → 递归输出元素类型 + "[]" (支持多维数组的元素部分, 但不再区分秩); + /// - 泛型 → 去掉 "`N" 后缀并递归展开泛型参数, 例如 List 而非 List`1; + /// - 其它情况直接取 Type.Name (不含命名空间, 保持简洁); + /// + internal static string GetFriendlyTypeName(Type t) + { + if (t == null) return "?"; + if (t.IsArray) return GetFriendlyTypeName(t.GetElementType()) + "[]"; + + if (t.IsGenericType) + { + // 泛型名形如 "List`1", 去掉反引号后缀 + var def = t.GetGenericTypeDefinition().Name; + int tick = def.IndexOf('`'); + if (tick >= 0) def = def.Substring(0, tick); + + var args = t.GetGenericArguments(); + var inner = new string[args.Length]; + for (int i = 0; i < args.Length; i++) inner[i] = GetFriendlyTypeName(args[i]); + return def + "<" + string.Join(", ", inner) + ">"; + } + + return t.Name; + } + + /// + /// 将任意字段值格式化为便于人眼阅读的字符串, 供 DumpAllFieldsForDebug 打印使用 + /// + /// 特殊处理: + /// - null → 字面量 "null"; + /// - string → 加双引号, 直观区分字符串和其它类型 (不做转义, 调试用足够); + /// - UnityEngine.Object → 打印 "TypeName(\"objectName\")", 并额外识别 "伪 null" + /// (Unity 对象被销毁后 ==null 为 true, 但托管引用非空); + /// - ICollection → 只输出类型 + 元素数量, 避免大集合刷屏; + /// - 其它类型 → 回退到 ToString(); + /// + internal static string FormatValueForDebug(object val) + { + if (val == null) return "null"; + if (val is string s) return "\"" + s + "\""; + + if (val is UnityEngine.Object uo) + { + // 处理 Unity 对象的"伪 null": 托管引用尚在但底层原生对象已销毁 + if (uo == null) return ""; + return uo.GetType().Name + "(\"" + uo.name + "\")"; + } + + if (val is ICollection col) + { + // 集合仅显示元素个数, 避免把上万条数据打进日志 + return GetFriendlyTypeName(val.GetType()) + " { Count = " + col.Count + " }"; + } + + return val.ToString(); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ProjectCustomExtractors.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ProjectCustomExtractors.cs new file mode 100644 index 0000000000000000000000000000000000000000..46d5248c5dff73aed314ad51f07e06849dd331fd --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/ProjectCustomExtractors.cs @@ -0,0 +1,143 @@ +// ========================================== +// 文件: LQATool\Services\ProjectCustomExtractors.cs +// 模块: Services (业务) +// ========================================== + +using System; +using UnityEngine; + +// 通过 using static 让 H.AddXxx / H.TryGetFieldValue 写起来更紧凑 +// 这样下面就可以直接调用 TryGetFieldValue / AddEnum / AddColor / AddVector2 等, +// 而无需前缀 CustomExtractorHelpers +using static LQATool.Services.CustomExtractorHelpers; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// 项目自定义组件的属性提取器注册入口 (与通用 Unity 组件的 ComponentExtractors 解耦) + /// + /// 设计目的: + /// - 通用 UI 组件 (Canvas / Text / Image / ScrollRect 等) 在 ComponentExtractors 中集中注册; + /// - 而项目专属脚本 (如 XxxxLocalize / Xxxx.XxxxText) 由于类型可能不在本插件的引用范围内, + /// 因此单独放到本文件, 通过 ComponentExtractors.RegisterByTypeName(string, Action{Component, UINodeData}) + /// 以 "字符串类型名 + 反射读字段" 的松耦合方式注册, 避免直接依赖项目程序集; + /// - 目标类型若不存在于当前工程, 会被 RegisterByTypeName 静默跳过, 不影响插件其他功能; + /// + /// 调用链: ComponentExtractors 的静态构造函数会调用 RegisterAll + /// + internal static class ProjectCustomExtractors + { + /// + /// 注册所有项目自定义组件的提取器 + /// 由 ComponentExtractors 的静态构造在通用提取器注册之后调用一次 + /// + internal static void RegisterAll() + { + // 在此按需注册本项目的自定义组件 (目标类型不存在于当前工程时会被静默跳过, 不影响其它功能) + // 可直接复用的辅助方法 (均来自 using static CustomExtractorHelpers): + // TryGetFieldValue(comp, "字段名", out value) 反射读字段; + // AddEnum / AddColor / AddVector2 (node, 组件键, 属性键, 值) 类型化写入 + // 用法示例: 删掉下方 /* */ 这对块注释符即可启用示例调用, + // 同时需一并放开本类末尾被 /* */ 包裹的 RegisterXxxxLocalize / RegisterXxxxText 方法体, 并改成你自己的组件名与字段名: + + /* + // 本地化组件: 用于导出翻译时匹配 keyHash → 译文 + RegisterXxxxLocalize(); + // 富文本组件: 用于还原描边 / 阴影 / 特效等文本视觉参数 + RegisterXxxxText(); + */ + + } + + /* + // ========================================== + // XxxxLocalize 组件 [XxxxLocalize] + // ========================================== + + /// + /// 注册 XxxxLocalize 组件的字段提取器 + /// 只导出 keyHash 一个字段, 供 LQA 侧根据哈希值反查原始翻译 Key + /// + private static void RegisterXxxxLocalize() + { + // 使用短类型名 "XxxxLocalize" 注册, RegisterByTypeName 会遍历已加载程序集找到匹配的 Component 子类 + ComponentExtractors.RegisterByTypeName("XxxxLocalize", (comp, node) => + { + // 去掉注释可以打印所有字段 (调试用): + // DumpAllFieldsForDebug(comp, true); + // DumpAllFieldsForDebug(comp, false); + // 在不清楚目标组件的字段名 / 属性名时, 打开这两行可以在控制台一次性看到所有可读成员 + + // 反射读取 keyHash 字段 (存在性未知, 用 object 兜底以兼容 string / int / long / 自定义结构等各种实际类型) + // 找不到字段、异常或值为 null 时直接放弃, 不写入 ObjectData + if (!TryGetFieldValue(comp, "keyHash", out var val) || val == null) return; + + // 统一按 ToString() 序列化, 对于数字型哈希, 结果就是十进制字符串, 对于字符串哈希, 就是其原文 + string s = val.ToString(); + // 空串直接跳过, 避免面板 / JSON 中出现无意义的空字段 + if (string.IsNullOrEmpty(s)) return; + + // 写入 ObjectData["XxxxLocalize"]["keyHash"] = "\"xxx\"" + // 外层双引号是 JSON 字符串字面量的一部分, 保证最终 JSON 中该值形如 "8X88XX8X88X888X8" + node.AddComponentProperty("XxxxLocalize", "keyHash", $"\"{s}\""); + }); + } + + // ========================================== + // XxxxText 组件 [Xxxx.XxxxText] + // ========================================== + + /// + /// 注册 Xxxx.XxxxText 组件的字段提取器 + /// 导出文本特效类型、当前描边颜色/距离、当前阴影颜色/距离, 用于外部还原工程按 1:1 复刻文本视觉 + /// + /// 采集的都是 "Current*" 字段: 说明 XxxxText 内部会根据主题 / 状态动态计算最终样式, + /// 直接读运行时值比读原始序列化字段更贴近玩家实际看到的效果 + /// + private static void RegisterXxxxText() + { + // 使用带命名空间的全名注册, 避免与其他项目里同名的 "XxxxText" 短名冲突 + ComponentExtractors.RegisterByTypeName("Xxxx.XxxxText", (comp, node) => + { + // 组件键统一使用短名 "XxxxText" (与外部 JSON 表结构约定一致) + const string K = "XxxxText"; + + // 文本特效类型 (枚举: 无 / 描边 / 阴影 / 描边+阴影 等) + // 用基类 Enum 接住, 避免在此处硬引用具体枚举类型 (不同版本可能改名 / 加值) + if (TryGetFieldValue(comp, "TextEffectType", out var effectType)) + { + AddEnum(node, K, "textEffectType", effectType); + } + + // 当前描边颜色 (RGBA) + if (TryGetFieldValue(comp, "CurrentOutlineColor", out var outlineColor)) + { + AddColor(node, K, "outlineColor", outlineColor); + } + + // 当前描边距离 (X / Y 方向的像素偏移量) + if (TryGetFieldValue(comp, "CurrentOutlineDistance", out var outlineDistance)) + { + AddVector2(node, K, "outlineDistance", outlineDistance); + } + + // 当前阴影颜色 (RGBA) + if (TryGetFieldValue(comp, "CurrentShadowColor", out var shadowColor)) + { + AddColor(node, K, "shadowColor", shadowColor); + } + + // 当前阴影距离 (X / Y 方向的像素偏移量) + if (TryGetFieldValue(comp, "CurrentShadowDistance", out var shadowDistance)) + { + AddVector2(node, K, "shadowDistance", shadowDistance); + } + }); + } + */ + + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.GetNode.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.GetNode.cs new file mode 100644 index 0000000000000000000000000000000000000000..5875c3685366ade4d7f798cf06b26415d283de69 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.GetNode.cs @@ -0,0 +1,213 @@ +// ========================================== +// 文件: LQATool\Services\UIDumpService.GetNode.cs +// 模块: Services (业务) +// ========================================== + +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; +using LQATool.Models; +using LQATool.Utils; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// 使用 partial (分部类), 本文件仅承载 "查找最近文本节点" 相关成员 + /// UIDumpService 的其余功能拆分在其他文件中, 便于按职责组织代码 + /// + public partial class UIDumpService + { + /// + /// 在场景中查找距离指定屏幕坐标最近的文本节点 + /// + /// 目标屏幕坐标 (通常为鼠标/点击位置, 单位: 像素) + /// 工具自身的 Canvas, 需要排除, 避免把工具 UI 也纳入检测 + /// + /// 最近文本节点的数据 UINodeData + /// 若场景中没有可用文本节点则返回 null + /// + public UINodeData FindNearestTextNode(Vector2 screenPosition, Canvas toolCanvas) + { + // 收集所有符合条件 (可见、含文本、在屏幕范围内) 的候选文本节点 + List candidates = new List(); + + // 遍历场景中所有的 Canvas, 逐个 Canvas 递归收集其下的文本节点 + foreach (var canvas in UnityEngine.Object.FindObjectsOfType()) + { + // 跳过工具自身的 Canvas, 避免检测到工具界面的文本 + if (canvas == toolCanvas) continue; + + // 跳过被禁用的 Canvas (不可见的界面无需检测) + if (!canvas.enabled) continue; + + // 从该 Canvas 的根 Transform 开始递归收集文本节点 + CollectTextNodes(canvas.transform, canvas, candidates); + } + + // 没有任何候选文本节点, 直接返回 null + if (candidates.Count == 0) return null; + + // 记录当前找到的最小距离, 初始化为最大值以便后续比较 + float minDistance = float.MaxValue; + // 记录当前距离最近的候选节点 + TextNodeCandidate nearest = null; + + // 遍历所有候选, 计算其屏幕中心点到目标坐标的距离, 取最近者 + foreach (var candidate in candidates) + { + float distance = Vector2.Distance(screenPosition, candidate.screenCenter); + + if (distance < minDistance) + { + minDistance = distance; + nearest = candidate; + } + } + + // 返回最近候选的节点数据, 使用空条件运算符防止 nearest 为空时报错 + return nearest?.nodeData; + } + + /// + /// 文本节点候选项: 封装节点数据及其在屏幕上的中心坐标, 用于距离比较 + /// + private class TextNodeCandidate + { + // 该文本节点收集到的属性数据 + public UINodeData nodeData; + // 该文本节点在屏幕上的中心点坐标 (像素), 用于与点击位置计算距离 + public Vector2 screenCenter; + } + + /// + /// 递归遍历 Transform 层级, 收集满足条件的文本节点作为候选 + /// + /// 当前正在处理的 Transform 节点 + /// 当前节点所属的根 Canvas (用于确定渲染相机) + /// 候选列表, 收集结果写入其中 + private void CollectTextNodes(Transform current, Canvas rootCanvas, List candidates) + { + // 节点及其父级若在层级中处于非激活状态则跳过 (不可见节点不参与检测) + if (!current.gameObject.activeInHierarchy) return; + + // 尝试把当前节点识别为文本组件 (旧版 Text 或 TMP) + Graphic graphicComp = current.GetComponent(); + TextLike textLike = null; + + // 仅处理是文本 (Text/TMP) 且内容非空的节点 + if (graphicComp != null && TextLike.TryWrap(graphicComp, out textLike) + && !string.IsNullOrEmpty(textLike.text)) + { + // 获取 RectTransform, UI 元素依赖它来计算屏幕位置 + RectTransform rt = current.GetComponent(); + if (rt != null) + { + // 计算矩形中心的世界坐标 + Vector3 worldCenter = rt.TransformPoint(rt.rect.center); + + // 根据 Canvas 的渲染模式决定用于坐标转换的相机: + // ScreenSpaceOverlay 模式不需要相机, 其余模式使用 Canvas 指定的 worldCamera + Camera cam = null; + if (rootCanvas.renderMode != RenderMode.ScreenSpaceOverlay) + { + cam = rootCanvas.worldCamera; + } + + // 将世界坐标转换为屏幕坐标 + Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(cam, worldCenter); + + // 仅保留中心点落在屏幕可见范围内的文本节点 + if (screenPos.x >= 0 && screenPos.x <= Screen.width && + screenPos.y >= 0 && screenPos.y <= Screen.height) + { + // 构建节点数据: 名称、层级路径、主组件类型, 并标记含有文本 + UINodeData nodeData = new UINodeData + { + name = current.gameObject.name, + path = UIHelper.GetGameObjectPath(current.gameObject), + objectType = UIHelper.GetPrimaryComponentType(current.gameObject), + hasText = true + }; + + // 两类文本统一写 "Text"/"textContent", 复用运行时面板 (Display) 现有读取逻辑, 免改下游 + nodeData.AddComponentProperty("Text", "textContent", $"\"{JsonBuilder.EscapeJson(textLike.text)}\""); + + // ========================================== + // 项目专属逻辑 (Project-Specific): 本地化组件的译文 Key 反射读取 + // ========================================== + + // 通过反射尝试读取项目自定义的本地化组件 XxxxLocalize 的 keyHash 字段 + // 使用反射是为了在不直接引用该类型的情况下兼容不同项目/程序集 + try + { + var projectLocalize = current.GetComponent("XxxxLocalize"); + if (projectLocalize != null) + { + // 查找 keyHash 字段, 涵盖 public / 非 public 的实例字段 + var field = projectLocalize.GetType().GetField("keyHash", + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.NonPublic | + System.Reflection.BindingFlags.Instance); + if (field != null) + { + var val = field.GetValue(projectLocalize); + // 仅当取到非空值时记录本地化 Key, 便于 LQA 定位翻译条目 + if (val != null && !string.IsNullOrEmpty(val.ToString())) + { + nodeData.AddComponentProperty("XxxxLocalize", "keyHash", $"\"{val}\""); + } + } + } + } + catch (System.Exception) + { + // 反射失败 (如无该组件/字段或跨程序集异常) 时静默忽略, 不影响主流程 + } + + // ========================================== + // 项目专属逻辑 (Project-Specific): 结束 + // ========================================== + + // 记录 RectTransform 的锚定位置与尺寸偏移, 便于还原布局信息 + if (rt != null) + { + nodeData.AddComponentProperty("RectTransform", "anchoredPosition", JsonBuilder.FormatVector2(rt.anchoredPosition)); + nodeData.AddComponentProperty("RectTransform", "sizeDelta", JsonBuilder.FormatVector2(rt.sizeDelta)); + } + + // 以下为旧版 Text 专有字段 (TMP 无同名枚举), 仅旧版文本时写入 + if (!textLike.isTmp && graphicComp is Text uguiText) + { + // 记录文本的字体样式 (粗体/斜体等) + nodeData.AddComponentProperty("Text", "fontStyle", $"\"{uguiText.fontStyle}\""); + // 记录字号 + nodeData.AddComponentProperty("Text", "fontSize", uguiText.fontSize.ToString()); + // 记录文本对齐方式 + nodeData.AddComponentProperty("Text", "alignment", $"\"{uguiText.alignment}\""); + // 记录水平溢出处理方式 (Wrap / Overflow) + nodeData.AddComponentProperty("Text", "horizontalOverflow", $"\"{uguiText.horizontalOverflow}\""); + // 记录垂直溢出处理方式 (Truncate / Overflow) + nodeData.AddComponentProperty("Text", "verticalOverflow", $"\"{uguiText.verticalOverflow}\""); + } + + // 将该文本节点封装为候选项加入列表 + candidates.Add(new TextNodeCandidate + { + nodeData = nodeData, + screenCenter = screenPos + }); + } + } + } + + // 递归处理所有子节点, 确保整棵层级树都被遍历到 + foreach (Transform child in current) + { + CollectTextNodes(child, rootCanvas, candidates); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.NodeTree.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.NodeTree.cs new file mode 100644 index 0000000000000000000000000000000000000000..e67a5d0f40aa245a5c178f6951d74468bd810594 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.NodeTree.cs @@ -0,0 +1,295 @@ +// ========================================== +// 文件: LQATool\Services\UIDumpService.NodeTree.cs +// 模块: Services (业务) +// ========================================== + +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using LQATool.Models; +using LQATool.Utils; +using LQATool.Config; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// UIDumpService 的分部实现 (主定义见 UIDumpService.cs) + /// 本分部聚焦 "UI 节点树采集": 遍历场景 Canvas 生成 UINodeData 树, 并落地为 + /// ui_data_all.json (全量) 与 ui_data_text.json (文本/图片剪枝树), + /// 两者是否写盘分别受 EmitFullUIDataJson / EmitTextUIDataJson 开关控制 + /// + public partial class UIDumpService + { + /// + /// 采集环境元数据 + 遍历场景所有根 Canvas, 生成 UI 节点树 JSON 并写入磁盘 + /// 由 ExecuteDump 在截图流程末尾调用 (此时游戏时间已被冻结 timeScale=0, + /// 保证这里读到的节点状态与前面截的图基于同一帧, 不会因动画/异步加载而漂移) + /// + /// 工具自身的 Canvas, 遍历时必须跳过, 否则会把工具面板也导出 + /// 本次 Dump 的输出目录 (带时间戳), JSON 文件将写入此处 + private void GenerateJsonData(Canvas toolCanvas, string dirPath) + { + // ========================================== + // 采集 Dump 瞬间的环境元数据 (先取快照, 避免多次读取运行时属性) + // 这些数据供还原工程复刻同样的屏幕/画质/语言环境, 是像素级对齐的前提 + // ========================================== + + // 屏幕分辨率快照 (像素) + int capturedWidth = Screen.width; + int capturedHeight = Screen.height; + + // 系统语言 (枚举转字符串, 如 "ChineseSimplified" / "English") + string systemLanguageName = Application.systemLanguage.ToString(); + + // 图层配置快照: 记录本次 Dump 时 "哪些 Layer 被单独截图" 的权威清单 + // 用 ToArray 拷贝一份, 防止后续配置变更污染这份快照, 配置为 null 时兜底为空数组 + string[] layerNamesSnapshot = LQAUILayerConfig.UILayerNames != null ? LQAUILayerConfig.UILayerNames.ToArray() : new string[0]; + + // 屏幕方向 (Portrait / LandscapeLeft 等), 还原端需切到同方向, 否则 RectTransform 全部错位 + string orientationName = Screen.orientation.ToString(); + + // 安全区域 (刘海屏/灵动岛下会小于屏幕尺寸) + Rect capturedSafeArea = Screen.safeArea; + + // 画质等级: 先取当前索引, 再据索引从名称数组中取名 (做越界保护, 越界时给空串) + int capturedQualityLevel = QualitySettings.GetQualityLevel(); + string[] qualityNames = QualitySettings.names; + string capturedQualityName = (qualityNames != null && capturedQualityLevel >= 0 && capturedQualityLevel < qualityNames.Length) ? qualityNames[capturedQualityLevel] : string.Empty; + + // 颜色空间 (Linear / Gamma), 两端不一致时纯色块会明显偏亮或偏暗 + string capturedColorSpace = QualitySettings.activeColorSpace.ToString(); + + // 目标帧率 (-1 表示未限制) + int capturedTargetFrameRate = Application.targetFrameRate; + + // ========================================== + // 构建 "全量版" 结果对象 resultAll, 填充上面采集的所有元数据 + // ========================================== + UIDumpResult resultAll = new UIDumpResult + { + // 当前激活场景名 + sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name, + // 游戏客户端版本号 (Player Settings → Version) + appVersion = Application.version, + // Unity 引擎版本号 + unityVersion = Application.unityVersion, + // 屏幕分辨率 (像素) + screenWidth = capturedWidth, + screenHeight = capturedHeight, + // 屏幕 DPI (设备物理像素密度) + screenDpi = Screen.dpi, + // 系统语言 + systemLanguage = systemLanguageName, + // 当前激活的 Layer 名称 + activeLayerNames = layerNamesSnapshot, + // 屏幕方向 + orientation = orientationName, + // 安全区域 + safeArea = capturedSafeArea, + // 画质等级 + qualityLevel = capturedQualityLevel, + // 画质等级名称 + qualityLevelName = capturedQualityName, + // 颜色空间 + colorSpace = capturedColorSpace, + // 目标帧率 + targetFrameRate = capturedTargetFrameRate, + }; + + // ========================================== + // 构建 "文本/图片版" 结果对象 resultText, 元数据与全量版完全一致 (直接引用 resultAll 的字段) + // 二者的区别仅在于 nodes: resultText 只保留含文本或图片的节点树 (下面循环里剪枝得到) + // ========================================== + UIDumpResult resultText = new UIDumpResult + { + sceneName = resultAll.sceneName, + appVersion = resultAll.appVersion, + unityVersion = resultAll.unityVersion, + screenWidth = resultAll.screenWidth, + screenHeight = resultAll.screenHeight, + screenDpi = resultAll.screenDpi, + systemLanguage = resultAll.systemLanguage, + activeLayerNames = resultAll.activeLayerNames, + orientation = resultAll.orientation, + safeArea = resultAll.safeArea, + qualityLevel = resultAll.qualityLevel, + qualityLevelName = resultAll.qualityLevelName, + colorSpace = resultAll.colorSpace, + targetFrameRate = resultAll.targetFrameRate, + }; + + // ========================================== + // 遍历场景中所有 Canvas, 逐个构建节点树 + // ========================================== + foreach (var canvas in UnityEngine.Object.FindObjectsOfType()) + { + // 跳过工具自身的 Canvas, 避免把 LQA 工具面板导出到结果里 + if (canvas == toolCanvas) continue; + + // 只处理根 Canvas: 子 Canvas (嵌套 Canvas) 会在递归遍历父树时被自然覆盖, + // 若这里不过滤, 子 Canvas 会被重复当成顶层节点导出 + if (!canvas.isRootCanvas) continue; + + // 从该 Canvas 的 Transform 出发, 递归构建完整节点树 + UINodeData canvasNode = BuildNodeTree(canvas.transform); + + // 全量树: 无条件收录 + resultAll.nodes.Add(canvasNode); + + // 文本/图片树: 对全量子树做剪枝, 只保留含文本或图片节点及其祖先, 整棵都没有则返回 null, 直接丢弃 + UINodeData textCanvasNode = FilterTextNodeTree(canvasNode); + if (textCanvasNode != null) resultText.nodes.Add(textCanvasNode); + } + + // ========================================== + // 序列化并落盘 + // ========================================== + + // 全量 JSON: 受配置开关控制 + if (LQAUILayerConfig.EmitFullUIDataJson) + { + File.WriteAllText(Path.Combine(dirPath, "ui_data_all.json"), JsonBuilder.Serialize(resultAll)); + } + + // 文本/图片 JSON: 受配置开关控制 + if (LQAUILayerConfig.EmitTextUIDataJson) + { + File.WriteAllText(Path.Combine(dirPath, "ui_data_text.json"), JsonBuilder.Serialize(resultText)); + } + } + + /// + /// 递归遍历一个 Transform 及其所有子孙, 构建成 UINodeData 树 + /// 每个节点会附带 GameObject / Transform / RectTransform 的基础属性, 以及由 + /// ComponentExtractors 提取的各类 UI 组件属性 (Text / Image / Canvas 等) + /// + /// 当前要处理的 Transform + /// 构建完成的节点 (含其所有子孙节点) + private UINodeData BuildNodeTree(Transform t) + { + // 创建节点并填充 3 项标识信息 + UINodeData node = new UINodeData + { + // GameObject 名称 + name = t.gameObject.name, + // 在 Hierarchy 中的完整路径 (如 "Canvas/Panel/Button"), 便于人工定位 + path = UIHelper.GetGameObjectPath(t.gameObject), + // 主要组件类型 (让外部解析工具知道这是什么控件, 如 Text/Image/Button) + objectType = UIHelper.GetPrimaryComponentType(t.gameObject) + }; + + // ========================================== + // GameObject 层级属性 (bool 统一转小写字符串 "true"/"false", 契合 JSON 布尔写法) + // ========================================== + + // 自身激活状态 (Inspector 顶部勾选框) + node.AddComponentProperty("GameObject", "activeSelf", t.gameObject.activeSelf.ToString().ToLower()); + + // ========================================== + // Transform 层级属性 (局部坐标系, 均格式化为 {x,y,z} 的 JSON 对象) + // ========================================== + + // 局部欧拉角 (旋转) + node.AddComponentProperty("Transform", "localEulerAngles", JsonBuilder.FormatVector3(t.localEulerAngles)); + // 局部缩放 + node.AddComponentProperty("Transform", "localScale", JsonBuilder.FormatVector3(t.localScale)); + + // ========================================== + // RectTransform 属性: 仅当该 Transform 实际是 RectTransform (即 UI 元素) 时才采集 + // 用模式匹配 (t is RectTransform rt) 一次完成类型判断 + 转换 + // ========================================== + + if (t is RectTransform rt) + { + // 锚点坐标 (2D) + node.AddComponentProperty("RectTransform", "anchoredPosition", JsonBuilder.FormatVector2(rt.anchoredPosition)); + // 相对锚点的尺寸增量 + node.AddComponentProperty("RectTransform", "sizeDelta", JsonBuilder.FormatVector2(rt.sizeDelta)); + // 锚点最小/最大 (0~1 归一化, 描述拉伸模式) + node.AddComponentProperty("RectTransform", "anchorMin", JsonBuilder.FormatVector2(rt.anchorMin)); + node.AddComponentProperty("RectTransform", "anchorMax", JsonBuilder.FormatVector2(rt.anchorMax)); + // 轴心 (0~1, 决定旋转/缩放的中心点) + node.AddComponentProperty("RectTransform", "pivot", JsonBuilder.FormatVector2(rt.pivot)); + // 计算后的实际矩形宽高 (只取 width/height, 复用 Vector2 格式化), 还原时不读, 但是保留以供人工排查溢出/截断 + node.AddComponentProperty("RectTransform", "rect", JsonBuilder.FormatVector2(new Vector2(rt.rect.width, rt.rect.height))); + } + + // 交给组件提取器统一提取所有已注册的 UI 组件属性 (Text / Image / Canvas / 项目自定义组件等) + // 提取结果同样写入 node.ObjectData + ComponentExtractors.ExtractAll(t, node); + + // ========================================== + // 递归处理子节点: 先缓存 childCount, 循环中把每个子节点的序号 i 与总数一并传入 + // ========================================== + int childCount = t.childCount; + for (int i = 0; i < childCount; i++) + { + node.ChildNodes.Add(BuildNodeTree(t.GetChild(i))); + } + + return node; + } + + /// + /// 对全量节点树做 "树状剪枝", 生成只含文本或图片的精简树 + /// 保留规则: 一个节点会被保留, 当且仅当它自身含文本或图片 (hasText、hasImage), 或它有任意子孙含文本或图片 + /// (从而保证含文本或图片节点的整条祖先路径都被保留, 树结构不断裂) + /// 采用后序递归: 先处理子节点, 再据 "自身有文本/图片 or 有保留下来的子节点" 决定当前节点去留 + /// + /// 全量树中的原始节点 + /// + /// 剪枝后的新节点 (深拷贝) + /// 若该子树完全不含文本或图片则返回 null + /// + private UINodeData FilterTextNodeTree(UINodeData originalNode) + { + // 先递归剪枝所有子节点, 收集其中真正保留下来的 (非 null) 子节点 + List filteredChildren = new List(); + foreach (var child in originalNode.ChildNodes) + { + var fc = FilterTextNodeTree(child); + + // 子节点自身及其子孙都没文本/图片时返回 null, 直接丢弃 + if (fc != null) filteredChildren.Add(fc); + } + + // 当前节点自身有文本/图片, 或有保留下来的子节点 → 需要保留当前节点 + if (originalNode.hasText || originalNode.hasImage || filteredChildren.Count > 0) + { + // 深拷贝一份新节点 (不复用原对象, 避免与全量树共享引用) + UINodeData newNode = new UINodeData + { + name = originalNode.name, + path = originalNode.path, + objectType = originalNode.objectType, + hasText = originalNode.hasText, + hasImage = originalNode.hasImage, + + // 挂上已剪枝的子节点列表 + ChildNodes = filteredChildren + }; + + // 逐层深拷贝 ObjectData (两层字典), 保证新树与原树在属性数据上完全独立 + foreach (var compKvp in originalNode.ObjectData) + { + var innerCopy = new Dictionary(); + + foreach (var propKvp in compKvp.Value) + { + innerCopy[propKvp.Key] = propKvp.Value; + } + + newNode.ObjectData[compKvp.Key] = innerCopy; + } + + return newNode; + } + + // 整棵子树都不含文本/图片 → 剪掉 + return null; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.Screenshot.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.Screenshot.cs new file mode 100644 index 0000000000000000000000000000000000000000..c3c74652f8bc4eff48a83355a96000a3b7fb5ad2 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.Screenshot.cs @@ -0,0 +1,262 @@ +// ========================================== +// 文件: LQATool\Services\UIDumpService.Screenshot.cs +// 模块: Services (业务) +// ========================================== + +using System; +using System.IO; +using System.Collections.Generic; +using UnityEngine; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// UIDumpService 的截图子模块 (分部类) + /// 类的整体职责说明见主定义文件 UIDumpService.cs + /// 本文件仅封装截图过程中的底层操作: 相机 (Camera) 的临时配置与还原、覆盖层画布 (Overlay Canvas) 的模式切换与还原, + /// 以及渲染纹理 (RenderTexture) 的像素读回并编码为 PNG + /// + public partial class UIDumpService + { + /// + /// 从 "当前激活的渲染目标" 中读回像素, 并编码为 PNG 写入磁盘 + /// 说明: ReadPixels 读取的是当前 RenderTexture.active (或屏幕帧缓冲) 的内容, + /// 因此调用前必须先把目标 RT 设为 active (见 SaveTextureFromRT) + /// + /// 读取区域 (以像素为单位, 原点在左下角), 通常为整张纹理的尺寸 + /// PNG 文件的完整输出路径 + /// 临时纹理格式, RGBA32 可保留 alpha 通道输出透明图 + private void SaveTexture(Rect rect, string path, TextureFormat format) + { + // 创建一块与读取区域等大的临时纹理, 最后一个参数 false 表示不生成 mipmap + Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, format, false); + + // 把当前激活渲染目标 rect 区域的像素读入 tex, 写入位置为 tex 的 (0,0) + tex.ReadPixels(rect, 0, 0); + // 提交像素改动, 使 ReadPixels 的结果在 tex 中生效 + tex.Apply(); + + // 编码为 PNG 字节流并一次性写入文件 + File.WriteAllBytes(path, tex.EncodeToPNG()); + // 临时纹理用完立即销毁, 避免占用内存/显存 + UnityEngine.Object.Destroy(tex); + } + + /// + /// 将指定 RenderTexture 的内容保存为 PNG + /// 相比 SaveTexture, 本方法额外负责设置/清理 RenderTexture.active, 使读回作用于该 RT + /// + /// 源渲染纹理 + /// 读取宽度 (像素) + /// 读取高度 (像素) + /// PNG 文件的完整输出路径 + /// 保存格式, 透明图使用 RGBA32 + private void SaveTextureFromRT(RenderTexture rt, int width, int height, string path, TextureFormat format) + { + // 将该 RT 设为当前激活渲染目标, 后续 ReadPixels 才会读取它的内容 + RenderTexture.active = rt; + // 从 (0,0) 起读取整张 RT 并保存 + SaveTexture(new Rect(0, 0, width, height), path, format); + // 还原 active, 避免影响后续其他渲染读回操作 + RenderTexture.active = null; + } + + /// + /// 获取场景中所有相机, 并按 depth 从小到大排序 (depth 越大越在上层, 越后渲染) + /// 若场景中一个相机都没有, 则创建一个临时相机兜底, 保证截图流程可继续 + /// + /// + /// 出参: 兜底创建的临时相机引用, 若场景本就有相机则为 null + /// 调用方在截图结束后需负责销毁这个临时相机 (连同其 GameObject) + /// + /// 按 depth 升序排列的相机数组 + private Camera[] GetSortedCameras(out Camera tempCam) + { + // 查找场景内所有 Camera 组件 (不含未激活对象上的相机) + Camera[] cameras = UnityEngine.Object.FindObjectsOfType(); + // 按 depth 升序排序: 保证渲染顺序与实际叠加顺序一致 + Array.Sort(cameras, (a, b) => a.depth.CompareTo(b.depth)); + + tempCam = null; + + // 极端情况: 场景没有任何相机, 创建一个临时相机作为兜底 + if (cameras.Length == 0) + { + GameObject camObj = new GameObject("LQATool_TempCamera"); + tempCam = camObj.AddComponent(); + cameras = new Camera[] { tempCam }; + } + + return cameras; + } + + /// + /// 为 "按图层截图" 配置所有相机, 并把每个相机的原始状态备份返回 + /// 具体改动: 统一渲染到同一张 RT、背景清为全透明、按需只保留目标 Layer, 并串联清屏标志 + /// + /// 已按 depth 升序排列的相机数组 + /// 统一的渲染目标纹理 + /// 目标图层掩码 (当 preserveCullingMask 为 false 时生效) + /// + /// 为 true 时保留相机原有 cullingMask (不按图层过滤), 用于需要渲染相机全部内容的场景 + /// + /// 相机 -> 原始状态 的映射, 供 RestoreCameras 还原 + private Dictionary SetupCamerasForLayerMask( + Camera[] cameras, RenderTexture rt, int layerMask, bool preserveCullingMask = false) + { + var states = new Dictionary(); + + for (int i = 0; i < cameras.Length; i++) + { + // 先备份当前相机的关键属性, 后续才能原样还原 + states[cameras[i]] = new CameraState + { + clearFlags = cameras[i].clearFlags, + backgroundColor = cameras[i].backgroundColor, + cullingMask = cameras[i].cullingMask, + targetTexture = cameras[i].targetTexture + }; + + // 仅在不要求保留原掩码时, 才把渲染层限制为目标图层 + if (!preserveCullingMask) + cameras[i].cullingMask = layerMask; + + // 背景清为全透明, 保证输出的是带 alpha 通道的透明图 + cameras[i].backgroundColor = Color.clear; + + // 第一个 (最底层) 相机用 SolidColor 清屏建立透明底, + // 其余相机只清深度 (Depth), 以便逐层叠加而不擦掉前面已渲染的内容 + cameras[i].clearFlags = (i == 0) ? CameraClearFlags.SolidColor : CameraClearFlags.Depth; + + // 所有相机统一渲染到同一张 RT + cameras[i].targetTexture = rt; + } + + return states; + } + + /// + /// 根据备份的状态还原所有相机, 撤销 SetupCamerasForLayerMask 的破坏性修改 + /// 若不还原, 截图结束后游戏画面会异常 (黑屏或只剩 UI) + /// + /// SetupCamerasForLayerMask 返回的原始状态映射 + private void RestoreCameras(Dictionary states) + { + foreach (var kvp in states) + { + // 相机可能在截图期间被销毁, 需判空后再还原 + if (kvp.Key != null) + { + kvp.Key.clearFlags = kvp.Value.clearFlags; + kvp.Key.backgroundColor = kvp.Value.backgroundColor; + kvp.Key.cullingMask = kvp.Value.cullingMask; + kvp.Key.targetTexture = kvp.Value.targetTexture; + } + } + } + + /// + /// 驱动所有相机按顺序手动渲染一帧到指定 RT + /// 使用 Camera.Render() 主动触发离屏渲染, 而不依赖引擎的自动渲染循环 + /// + /// 已按 depth 升序排列的相机数组 + /// 目标渲染纹理 + private void RenderCamerasToRT(Camera[] cameras, RenderTexture rt) + { + foreach (var cam in cameras) + { + // 暂存该相机当前的渲染目标 (调用方通常已设为 rt, 这里再兜底保存/还原一次) + var oldTarget = cam.targetTexture; + cam.targetTexture = rt; + + // 立即执行一次离屏渲染, 结果写入 rt + cam.Render(); + + // 还原该相机自身的渲染目标 + cam.targetTexture = oldTarget; + } + } + + /// + /// 临时把场景中所有 ScreenSpaceOverlay 模式的 Canvas 切换为 ScreenSpaceCamera 模式 + /// 原因: Overlay 画布直接贴屏幕、绕过相机, 无法被 RenderTexture 捕获 + /// 切成 Camera 模式并挂到最上层相机后, 才能一并渲染进 RT + /// 同时会记录每个被修改画布的原始状态, 供 RestoreOverlayCanvases 还原 + /// + /// 最上层相机, 作为切换后画布的 worldCamera + /// 需要跳过的画布 (通常是工具自身的 UI 画布, 避免被截入) + /// 被修改画布的原始状态列表 (Canvas, 原 renderMode, 原 worldCamera, 原 planeDistance) + private List> SetupOverlayCanvases(Camera topCam, Canvas ignoreCanvas) + { + var states = new List>(); + + foreach (var c in UnityEngine.Object.FindObjectsOfType()) + { + // 跳过要忽略的画布和未启用的画布 + if (c == ignoreCanvas || !c.enabled) continue; + + if (c.renderMode == RenderMode.ScreenSpaceOverlay) + { + // 备份原始状态: 画布本身 + 渲染模式 + 世界相机 + 平面距离 + states.Add(new Tuple( + c, c.renderMode, c.worldCamera, c.planeDistance)); + + // 切换为 Camera 模式并绑定到最上层相机, 使其可被 RT 捕获 + c.renderMode = RenderMode.ScreenSpaceCamera; + c.worldCamera = topCam; + + // 平面距离略大于近裁剪面, 保证画布位于相机可视范围内且贴近屏幕 + c.planeDistance = topCam.nearClipPlane + 0.01f; + } + } + + return states; + } + + /// + /// 根据备份状态还原所有被修改过的 Overlay 画布, 撤销 SetupOverlayCanvases 的改动 + /// + /// SetupOverlayCanvases 返回的原始状态列表 + private void RestoreOverlayCanvases(List> states) + { + foreach (var state in states) + { + // 画布可能已被销毁, 需判空后再还原 + if (state.Item1 != null) + { + state.Item1.renderMode = state.Item2; // 还原渲染模式 + state.Item1.worldCamera = state.Item3; // 还原世界相机 + state.Item1.planeDistance = state.Item4; // 还原平面距离 + } + } + } + + /// + /// 按指定图层掩码渲染一帧并保存为透明 PNG (RGBA32) + /// 封装 "配置相机 → 切换 Overlay 画布 → 渲染到 RT → 存图 → 还原现场" 的固定流程, + /// 供分层截图 (单图层 / 背景层 / 全图层兜底) 复用 + /// + /// 场景所有相机 (已按 depth 升序排序) + /// 离屏渲染用的 RenderTexture + /// 最上层相机 (承载临时切换为 Camera 模式的 Overlay 画布) + /// 工具自身的 Canvas, 需排除, 避免拍进工具面板 + /// 目标图层掩码 (-1 表示全部图层) + /// 读取宽度 (像素) + /// 读取高度 (像素) + /// PNG 输出的完整路径 + private void RenderLayerMaskToPng( + Camera[] cameras, RenderTexture rt, Camera topCamera, Canvas toolCanvas, + int layerMask, int width, int height, string path) + { + var camStates = SetupCamerasForLayerMask(cameras, rt, layerMask); + var overlayStates = SetupOverlayCanvases(topCamera, toolCanvas); + RenderCamerasToRT(cameras, rt); + SaveTextureFromRT(rt, width, height, path, TextureFormat.RGBA32); + RestoreCameras(camStates); + RestoreOverlayCanvases(overlayStates); + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.TextIdMap.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.TextIdMap.cs new file mode 100644 index 0000000000000000000000000000000000000000..d5a07bc951f0550e88a7ed20e2c74d0e0e9ef111 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.TextIdMap.cs @@ -0,0 +1,333 @@ +// ========================================== +// 文件: LQATool\Services\UIDumpService.TextIdMap.cs +// 模块: Services (业务) +// ========================================== + +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; +using System.Text.RegularExpressions; +using LQATool.Utils; +using LQATool.Config; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// UIDumpService 的分部实现 —— 文本 ID 图 (TextIdMap) 生成模块 + /// + /// 核心思路: 给场景中每个可见 UI 文本染上一个由整数 ID 编码而来的唯一颜色 + /// (见 LQATool.Utils.TextIdCodec), 再整屏渲染到 RenderTexture 并读回像素 + /// 这样截图里每个像素的颜色都能反解出它属于哪个文本 (ID), 为后续逐像素级的 + /// 文本区域定位 / AABB 计算提供精确依据 + /// + /// 相比传统 "包围盒差分" 方案, 染色法能天然处理文本被裁剪、遮挡、重叠的情况; + /// 仅当文本数量超过颜色编码容量 (LQATool.Utils.TextIdCodec.Capacity) 时, + /// 超出部分会判定为 "不可见", 不染色; + /// + public partial class UIDumpService + { + /// + /// 单个文本染色前的现场备份 + /// 染色会临时篡改文本的颜色 / 内容 / 透明度, 截图完成后必须逐项还原, + /// 否则会污染玩家真实看到的游戏画面 + /// + private struct TextIdBackup + { + /// + /// 被染色的目标文本组件 + /// + public TextLike text; + /// + /// 染色前的原始文字颜色 (还原时写回) + /// + public Color originalColor; + /// + /// 染色前的原始文字内容 (因为可能被 StripColorTags 改写, 需还原) + /// + public string originalText; + /// + /// 染色前 CanvasRenderer 的原始 alpha (染色时被强制拉到 1, 需还原) + /// + public float originalCrAlpha; + } + + /// + /// 文本 "近乎不可见" 的 alpha 阈值 + /// CanvasRenderer alpha 低于此值的文本视为不可见, 直接跳过不染色 (也不占用 ID) + /// 避免为屏幕上根本看不到的文本浪费 ID 容量 + /// + private const float InvisibleAlphaThreshold = 0.04f; + + /// + /// 生成文本 ID 图: 为每个可见文本分配唯一 ID 并染成对应颜色, 渲染整屏后读回像素 + /// + /// 场景所有相机 (已按 depth 升序排序) + /// 最上层相机 (用于把 Overlay Canvas 临时挂到相机模式) + /// 用于离屏渲染的 RenderTexture (后台画板) + /// 读取宽度 (像素), 通常为 Screen.width + /// 读取高度 (像素), 通常为 Screen.height + /// 本工具自身的 Canvas, 需在渲染时排除, 避免把工具 UI 也拍进去 + /// 候选文本列表 (调用方已收集好的待染色文本) + /// 调试图输出目录 + /// [输出] 文本 Transform → 分配到的 ID 的映射 + /// [输出] "纯净版" ID 图: 隐藏所有非文本图形后再渲染一次, 排除遮挡干扰 + /// + /// 常规 ID 图的逐像素颜色数组 (RGBA32) + /// 若没有任何可染色文本则返回 null + /// + private Color32[] CaptureTextIdMap( + Camera[] cameras, Camera topCamera, RenderTexture rt, + int width, int height, Canvas toolCanvas, IReadOnlyList texts, string dumpDir, + out Dictionary textToId, out Color32[] pureIdMap) + { + // 初始化输出参数 + textToId = new Dictionary(); + pureIdMap = null; + + // 记录所有被染色文本的现场, finally 中据此逐一还原 + var textBackups = new List(); + // 记录被临时拉满 alpha 的 CanvasGroup (Key=组件, Value=原始 alpha), 用于还原 + var canvasGroupBackups = new Dictionary(); + + try + { + // ID 从 1 开始编号 (0 在 TextIdCodec 中代表 "无效/无文本") + int id = 1; + foreach (var t in texts) + { + // TextLike 普通类判空 + 底层 graphic 存活判定 + if (t == null || t.graphic == null) continue; + + // ID 超过颜色编码容量 (Levels^3=729): 无法再分配唯一颜色, + // 超出部分的文本将被判为不可见 + if (id > TextIdCodec.Capacity) + { + Debug.LogWarning($"[LQATool][UIDumpService] 文本数超过 ID 容量 {TextIdCodec.Capacity}, 超出部分无法分配 ID, 将被判为不可见"); + break; + } + + // 读取 CanvasRenderer 当前 alpha (它决定文本最终呈现的可见度) + var cr = t.canvasRenderer; + float crAlpha = cr != null ? cr.GetAlpha() : 1f; + + // 近乎透明 → 玩家看不到 → 跳过, 既不染色也不占用 ID + if (crAlpha < InvisibleAlphaThreshold) + continue; + + // 染色前先完整备份现场 + textBackups.Add(new TextIdBackup + { + text = t, + originalColor = t.color, + originalText = t.text, + originalCrAlpha = crAlpha + }); + + // 将 ID 编码为唯一颜色并染到文本上 (这是 "染色定位" 的核心一步) + Color32 idColor = TextIdCodec.Encode(id); + t.color = idColor; + + // 若文本支持富文本, 去掉内嵌的 标签, + // 否则富文本自带的颜色会覆盖掉我们染上的 ID 颜色, 导致解码失败 + if (t.supportRichText) + t.text = StripColorTags(t.text); + // 强制把 CanvasRenderer alpha 拉满, 保证 ID 颜色以最纯净的形态被渲染出来 + if (cr != null) cr.SetAlpha(1f); + + // 向上遍历父链, 把路径上所有 CanvasGroup 的 alpha 也临时拉满, + // 防止某个祖先节点的半透明把文本 "调暗", 干扰 ID 颜色的准确读取 + // 用字典去重, 保证每个 CanvasGroup 只备份一次原始 alpha + Transform cur = t.transform; + while (cur != null) + { + var cg = cur.GetComponent(); + if (cg != null && !canvasGroupBackups.ContainsKey(cg)) + { + canvasGroupBackups[cg] = cg.alpha; + cg.alpha = 1f; + } + cur = cur.parent; + } + + // 记录本文本对应的 ID, 并递增编号 + textToId[t.transform] = id; + id++; + } + + // 没有任何文本被染色 → 无需渲染, 直接返回 + if (textToId.Count == 0) return null; + + // 强制刷新所有 Canvas, 让上面对颜色/文字/alpha 的修改立即生效 + Canvas.ForceUpdateCanvases(); + + // 配置相机: 渲染全部图层 (layerMask=-1), 保留各相机原始 cullingMask + var camStates = SetupCamerasForLayerMask(cameras, rt, -1, preserveCullingMask: true); + // 把 Overlay 模式的 Canvas 临时改为 Camera 模式 (Overlay 无法渲染进 RT), 并排除工具自身 Canvas + var overlayStates = SetupOverlayCanvases(topCamera, toolCanvas); + // 按相机层级把整屏渲染到 RT 上 + RenderCamerasToRT(cameras, rt); + + // 从 RT 读回逐像素颜色, 即常规版文本 ID 图 + Color32[] idMap = ReadRtToColor32(rt, width, height); + + // 调试开关打开时, 把 ID 图另存为 PNG 便于人工核对 + if (LQAUILayerConfig.EmitTextIdMapDebug) + { + SaveTextureFromRT(rt, width, height, + System.IO.Path.Combine(dumpDir, "ScreenShot_TextId.png"), + TextureFormat.RGBA32); + } + + // 再生成一张 "纯净版" ID 图: 隐藏所有非文本图形, 消除遮挡影响 (详见方法内注释) + pureIdMap = CapturePureTextIdMap(cameras, rt, width, height, textBackups, dumpDir); + + // 还原相机与 Overlay Canvas 状态 (文本/CanvasGroup 的还原在 finally 中统一处理) + RestoreCameras(camStates); + RestoreOverlayCanvases(overlayStates); + + return idMap; + } + finally + { + // 无论成功、异常还是提前 return, 都必须还原被篡改的现场: + // 1) 还原每个被染色文本的颜色 / 内容 / CanvasRenderer alpha + foreach (var b in textBackups) + { + if (b.text == null || b.text.graphic == null) continue; + b.text.color = b.originalColor; + b.text.text = b.originalText; + var cr = b.text.canvasRenderer; + if (cr != null) cr.SetAlpha(b.originalCrAlpha); + } + // 2) 还原所有被临时拉满 alpha 的 CanvasGroup + foreach (var kvp in canvasGroupBackups) + { + if (kvp.Key != null) kvp.Key.alpha = kvp.Value; + } + // 3) 再次刷新 Canvas, 让还原后的状态立即回到屏幕 + Canvas.ForceUpdateCanvases(); + } + } + + /// + /// 匹配富文本中会改变字形颜色的标签 (成对/单个): / 与 TMP 的 / + /// 使用 Compiled 提升多次调用性能, IgnoreCase 兼容大小写写法 + /// + private static readonly Regex _colorTagRegex = + new Regex("]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + + /// + /// 剥离字符串中会影响颜色的富文本标签 ( / ), 只保留纯文字 + /// 用于染色前清洗文本, 避免内嵌颜色覆盖我们染上的 ID 颜色 + /// + private static string StripColorTags(string s) + { + if (string.IsNullOrEmpty(s)) return s; + return _colorTagRegex.Replace(s, string.Empty); + } + + /// + /// 生成 "纯净版" 文本 ID 图 + /// 做法: 把场景中所有 "非染色文本" 的图形 (Graphic) 临时隐藏 (alpha=0), + /// 只留下被染色的文本再渲染一次, 这样 ID 颜色不会被前景图片/背景等遮挡, + /// 得到的像素更干净, 便于精确反解每个文本的可见区域 + /// (注意: Mask 组件不隐藏, 否则会破坏原有的裁剪关系) + /// + /// 场景所有相机 (已按 depth 升序排序) + /// 离屏渲染用的 RenderTexture + /// 读取宽度 (像素) + /// 读取高度 (像素) + /// 已染色文本的备份列表 (据此识别哪些是 "染色文本", 不应被隐藏) + /// 调试图输出目录 + /// 纯净版 ID 图的逐像素颜色数组 (RGBA32) + private Color32[] CapturePureTextIdMap( + Camera[] cameras, RenderTexture rt, int width, int height, + List textBackups, string dumpDir) + { + // 收集所有 "已染色文本" 的 CanvasRenderer, 作为渲染时需保留的白名单 + var dyed = new HashSet(); + var rendererBuf = new List(); + foreach (var b in textBackups) + { + if (b.text == null || b.text.graphic == null) continue; + + // 收集该文本的所有渲染器 (TMP 含子 SubMesh), 全部加入 "保留" 白名单 + // (否则 fallback 字体的子网格会被当作非文本图形隐藏, 纯净 ID 图上该文本缺字) + b.text.CollectRenderers(rendererBuf); + foreach (var cr in rendererBuf) + if (cr != null) dyed.Add(cr); + } + + // 记录被临时隐藏的图形 (CanvasRenderer → 原始 alpha), 用于 finally 还原 + var hidden = new List>(); + // 遍历场景中所有 UI 图形 + foreach (var g in UnityEngine.Object.FindObjectsOfType()) + { + if (g == null) continue; + var gcr = g.canvasRenderer; + // 跳过无渲染器的, 以及属于染色文本白名单的 (这些要保留可见) + if (gcr == null || dyed.Contains(gcr)) continue; + // 跳过 Mask: 隐藏它会破坏裁剪逻辑, 反而影响文本的可见范围 + if (g.GetComponent() != null) continue; + // 备份原始 alpha 后置 0 (隐藏) + hidden.Add(new KeyValuePair(gcr, gcr.GetAlpha())); + gcr.SetAlpha(0f); + } + + Color32[] pure; + try + { + // 刷新并重新渲染 (此时画面上只剩染色文本), 读回像素 + Canvas.ForceUpdateCanvases(); + RenderCamerasToRT(cameras, rt); + pure = ReadRtToColor32(rt, width, height); + + // 调试开关打开时另存纯净版 PNG + if (LQAUILayerConfig.EmitTextIdMapDebug) + { + SaveTextureFromRT(rt, width, height, + System.IO.Path.Combine(dumpDir, "ScreenShot_TextId_Pure.png"), + TextureFormat.RGBA32); + } + } + finally + { + // 还原所有被隐藏图形的 alpha, 并刷新回屏幕 + foreach (var kvp in hidden) + if (kvp.Key != null) kvp.Key.SetAlpha(kvp.Value); + Canvas.ForceUpdateCanvases(); + } + return pure; + } + + /// + /// 从 RenderTexture 读回全部像素为 Color32 数组。 + /// 通过临时 Texture2D.ReadPixels 完成 GPU→CPU 的像素回读, 读取后立即销毁临时纹理 + /// + /// 源 RenderTexture + /// 读取宽度 (像素) + /// 读取高度 (像素) + /// 逐像素颜色数组 (RGBA32, 按行优先) + private Color32[] ReadRtToColor32(RenderTexture rt, int width, int height) + { + // 保存当前激活的 RT, 读取完毕后还原, 避免影响后续渲染管线 + var prev = RenderTexture.active; + RenderTexture.active = rt; + + // 创建临时纹理, 从当前激活的 RT 中读回像素 + var tmp = new Texture2D(width, height, TextureFormat.RGBA32, false); + tmp.ReadPixels(new Rect(0, 0, width, height), 0, 0); + tmp.Apply(); + Color32[] px = tmp.GetPixels32(); + + // 释放临时纹理并还原激活的 RT + UnityEngine.Object.Destroy(tmp); + RenderTexture.active = prev; + return px; + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.cs new file mode 100644 index 0000000000000000000000000000000000000000..ceb4b1d480e4170deeb052165adc38570fb61714 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/Services/UIDumpService.cs @@ -0,0 +1,329 @@ +// ========================================== +// 文件: LQATool\Services\UIDumpService.cs +// 模块: Services (业务) +// ========================================== + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEngine.UI; +using LQATool.Utils; +using LQATool.Config; + +/// +/// LQATool 业务层命名空间 +/// +namespace LQATool.Services +{ + /// + /// UIDumpService —— UI 转储服务的主入口 (分部类) + /// + /// 本文件负责编排一次完整的 UI Dump 流程, 产出一组用于 LQA (本地化质量保证) 分析的素材: + /// 1. ScreenShot_Full.png —— 当前完整画面 (含文本) + /// 2. ScreenShot_NoText.png —— 隐藏所有文本后的画面 (供与完整图做像素差分) + /// 3. ScreenShot_TextId(_Pure).png —— 文本 ID 染色图 (可选调试输出, 见 TextIdMap 分部) + /// 4. ScreenShot_Only_{Layer}.png / ScreenShot_BG.png —— 按图层拆分的截图 (可选) + /// 5. UI 节点树 JSON (见 NodeTree 分部) + /// 并借助 PixelVisibilityChecker 判定每个文本是否真正可见 (未被遮挡/裁剪) + /// + /// 其余底层能力拆分在同名分部类文件中: + /// - UIDumpService.Screenshot.cs : 相机/Overlay 画布配置与还原、RT 读回存 PNG + /// - UIDumpService.TextIdMap.cs : 文本 ID 染色图的生成 + /// - UIDumpService.NodeTree.cs : UI 节点树遍历与 JSON 导出 + /// - UIDumpService.GetNode.cs : 单节点数据提取 + /// + public partial class UIDumpService + { + /// + /// 相机关键属性的备份结构, 用于在截图前修改、截图后原样还原 + /// (实际使用见 UIDumpService.Screenshot.cs 的 SetupCamerasForLayerMask / RestoreCameras) + /// + private struct CameraState + { + /// + /// 清屏标志 (SolidColor / Depth 等) + /// + public CameraClearFlags clearFlags; + + /// + /// 相机背景色 + /// + public Color backgroundColor; + + /// + /// 渲染层掩码 (决定相机渲染哪些 Layer) + /// + public int cullingMask; + + /// + /// 渲染目标纹理 (为 null 时渲染到屏幕) + /// + public RenderTexture targetTexture; + } + + /// + /// 执行一次完整的 UI 转储 (协程形式, 需要跨帧等待 WaitForEndOfFrame 以确保渲染完成) + /// + /// 流程概览: + /// 1. 建输出目录并暂停游戏 (timeScale=0)、隐藏工具自身 UI + /// 2. 截取完整画面 + /// 3. 临时隐藏所有文本 (含阴影), 截取无文本画面, 随后还原 + /// 4. 生成文本 ID 图并进行像素可见性判定 + /// 5. (可选) 输出可见性叠加图、按图层拆分的截图 + /// 6. 导出 UI 节点树 JSON + /// 7. finally 中恢复现场: 时间流速、工具 UI、清缓存, 并回调 onComplete + /// + /// 工具自身的 Canvas, 截图时需隐藏/排除, 避免拍进工具面板 + /// 流程结束后的回调 (成功或失败都会触发) + public IEnumerator ExecuteDump(Canvas toolCanvas, Action onComplete) + { + // 以当前时间生成唯一时间戳, 作为本次 Dump 输出目录名的一部分 + string timestamp = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); + // 输出目录位于持久化数据路径下: persistentDataPath/LQATool/UIDump_yyyy_MM_dd_HH_mm_ss + string dirPath = Path.Combine(Application.persistentDataPath, "LQATool", $"UIDump_{timestamp}"); + if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + + // 备份并暂停游戏时间, 冻结画面, 保证多次截图捕获的是同一帧内容 + float originalTimeScale = Time.timeScale; + Time.timeScale = 0f; + + // 隐藏工具自身的 UI, 避免它出现在截图里 + toolCanvas.enabled = false; + + // 等到本帧渲染结束, 使 "隐藏工具 UI" 已经生效再截图 + yield return new WaitForEndOfFrame(); + + // 记录当前屏幕分辨率, 作为后续所有 截图/RT 的尺寸 + int width = Screen.width; + int height = Screen.height; + + // 收集本次需要参与 "可见性判定" 的候选文本 (排除工具自身画布内的文本) + List dumpTexts = UITextCollector.CollectVisibilityCandidates(toolCanvas); + + // 1. 截取完整画面 (含文本) + try + { + SaveTexture(new Rect(0, 0, width, height), Path.Combine(dirPath, "ScreenShot_Full.png"), TextureFormat.RGB24); + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 截取完整画面失败: {e.Message}\n{e.StackTrace}"); + } + + // 记录被隐藏文本的原始 CanvasRenderer alpha, 用于截完无文本图后还原 + var textAlphaBackups = new List>(); + // 记录被隐藏文本阴影 (Shadow/Outline) 的原始颜色, 用于还原 + var shadowColorBackups = new List>(); + + // 2. 临时隐藏所有候选文本及其阴影 (通过把 alpha 置 0) + try + { + // 复用缓冲区, 避免每个文本一次 List 分配 + var rendererBuf = new List(); + foreach (var t in dumpTexts) + { + // t.graphic 为底层图形组件 (Text 或 TMP) + if (t.graphic != null && t.graphic.enabled) + { + // 收集该文本的所有渲染器 (TMP 含子 SubMesh), 逐个隐藏并备份 + // (仅隐藏主体 CanvasRenderer 会漏掉 fallback 字体的子网格, 导致 NoText 图残留文字) + t.CollectRenderers(rendererBuf); + foreach (var cr in rendererBuf) + { + if (cr == null) continue; + textAlphaBackups.Add(new KeyValuePair(cr, cr.GetAlpha())); + cr.SetAlpha(0f); + } + + // Shadow/Outline 仅旧版 Text 常见; TMP 无此组件, GetComponents 返回空数组自然跳过 + Shadow[] shadows = t.graphic.GetComponents(); + foreach (var shadow in shadows) + { + if (shadow != null && shadow.enabled) + { + shadowColorBackups.Add(new KeyValuePair(shadow, shadow.effectColor)); + Color sc = shadow.effectColor; + sc.a = 0f; + shadow.effectColor = sc; + } + } + } + } + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 隐藏文本组件失败: {e.Message}\n{e.StackTrace}"); + } + + // 等一帧, 让 "隐藏文本" 的改动真正反映到画面上 + yield return new WaitForEndOfFrame(); + + // 3. 截取无文本画面 (与 Full 图差分, 可用于判断文本占位/可见性) + try + { + SaveTexture(new Rect(0, 0, width, height), Path.Combine(dirPath, "ScreenShot_NoText.png"), TextureFormat.RGB24); + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 截取无文本画面失败: {e.Message}\n{e.StackTrace}"); + } + + // 还原被隐藏的阴影颜色 (对象可能已销毁, 判空) + foreach (var kvp in shadowColorBackups) + { + if (kvp.Key != null) kvp.Key.effectColor = kvp.Value; + } + + // 还原被隐藏文本 (含 TMP SubMesh) 的 CanvasRenderer alpha (对象可能已销毁, 判空) + foreach (var kvp in textAlphaBackups) + { + if (kvp.Key != null) kvp.Key.SetAlpha(kvp.Value); + } + + // 等一帧, 确保文本还原后再进行后续基于渲染的处理 + yield return new WaitForEndOfFrame(); + + // 4~5 文本 ID 图 / 可见性判定 / 分层截图 / JSON 导出 + try + { + // 创建离屏渲染用的 RenderTexture (带 alpha 通道, 24 位深度) + RenderTexture rt = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32); + // 取场景所有相机 (按 depth 升序), 若场景无相机则创建临时相机兜底 (tempCam) + Camera[] cameras = GetSortedCameras(out Camera tempCam); + // 最上层相机 (depth 最大), 用于承载临时切换为 Camera 模式的 Overlay 画布 + Camera topCamera = cameras[cameras.Length - 1]; + + // 文本 ID 图相关的输出: + // textIdMap —— 常规染色 ID 图逐像素颜色 + // pureTextIdMap —— 隐藏非文本图形后的纯净 ID 图 + // textToId —— 文本 Transform → 分配到的 ID + Color32[] textIdMap = null; + Color32[] pureTextIdMap = null; + Dictionary textToId = null; + try + { + textIdMap = CaptureTextIdMap(cameras, topCamera, rt, width, height, toolCanvas, dumpTexts, dirPath, out textToId, out pureTextIdMap); + } + catch (Exception e) + { + // 染色图捕获失败时: 置空 ID 图, 后续可见性判定会把所有文本按不可见处理 (安全降级) + textIdMap = null; + pureTextIdMap = null; + Debug.LogError($"[LQATool][UIDumpService] 文本 ID 图捕获失败 (本次将无法判定可见性, 所有文本按不可见处理): {e.Message}\n{e.StackTrace}"); + } + + // 基于 ID 图 + 像素差分, 为本场景构建 "文本是否可见" 的判定缓存 + try + { + PixelVisibilityChecker.BuildCacheForScene( + dirPath, + dumpTexts, + textIdMap, + pureTextIdMap, + textToId, + LQAUILayerConfig.PixelDiffColorThreshold, // 像素颜色差异阈值 + LQAUILayerConfig.PixelDiffMaskVisibleRatio, // 判定为可见所需的最小像素占比 + LQAUILayerConfig.PureMaskAlphaThreshold // 纯色掩码有效足迹的最小 alpha + ); + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 像素差分判定失败 (缓存为空, 所有文本按不可见处理): {e.Message}\n{e.StackTrace}"); + } + + // (可选) 输出可见性叠加调试图, 便于人工核对判定结果 + if (LQAUILayerConfig.EmitVisibilityDebug) + { + try + { + PixelVisibilityChecker.SaveVisibilityOverlay(dirPath, width, height); + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 可见性叠加图输出失败: {e.Message}\n{e.StackTrace}"); + } + } + + // 5. (可选) 按图层拆分截图: 每个配置图层单独出一张, 再出一张剩余背景图 + if (LQAUILayerConfig.EmitLayerScreenshots) + { + // 所有有效配置图层的合并掩码 (用于最后反推 "背景" 掩码) + int configuredLayerMask = 0; + // 配置中真实存在于工程的图层列表 (图层名, 单图层掩码) + var validLayers = new List>(); + + // 逐个解析配置的图层名: 存在则加入列表并累加到合并掩码, 不存在则告警跳过 + foreach (string layerName in LQAUILayerConfig.UILayerNames) + { + int layerIndex = LayerMask.NameToLayer(layerName); + if (layerIndex >= 0) + { + int layerMask = 1 << layerIndex; + validLayers.Add(new KeyValuePair(layerName, layerMask)); + configuredLayerMask |= layerMask; + } + else + { + Debug.LogWarning($"[LQATool][UIDumpService] LQAUILayerConfig 中配置的 Layer \"{layerName}\" 在当前工程中不存在, 已跳过"); + } + } + + // 为每个有效图层单独渲染一张 "只含该图层" 的透明截图 + foreach (var layerPair in validLayers) + { + string layerName = layerPair.Key; + int singleLayerMask = layerPair.Value; + + // 配置相机只渲染该图层 + 处理 Overlay 画布, 渲染到 RT 后存 PNG, 再逐一还原 + RenderLayerMaskToPng(cameras, rt, topCamera, toolCanvas, singleLayerMask, + width, height, Path.Combine(dirPath, $"ScreenShot_Only_{layerName}.png")); + } + + // 再输出一张 "背景图": 即所有配置图层以外的内容 + if (configuredLayerMask != 0) + { + // 背景图 = 所有配置图层以外的内容 (掩码按位取反) + int bgMask = ~configuredLayerMask; + RenderLayerMaskToPng(cameras, rt, topCamera, toolCanvas, bgMask, + width, height, Path.Combine(dirPath, "ScreenShot_BG.png")); + } + else + { + // 没有任何有效图层配置时的兜底: 背景图直接渲染全部图层 (layerMask = -1) + Debug.LogWarning("[LQATool][UIDumpService] LQAUILayerConfig.UILayerNames 中没有任何有效的图层配置, ScreenShot_BG.png 将包含所有图层的渲染结果"); + RenderLayerMaskToPng(cameras, rt, topCamera, toolCanvas, -1, + width, height, Path.Combine(dirPath, "ScreenShot_BG.png")); + } + } + + // 销毁离屏 RT, 释放显存 + UnityEngine.Object.Destroy(rt); + // 若使用了兜底临时相机, 连同其 GameObject 一并销毁 + if (tempCam != null) UnityEngine.Object.Destroy(tempCam.gameObject); + + // 6. 遍历 UI 节点树并导出为 JSON (排除工具自身画布) + GenerateJsonData(toolCanvas, dirPath); + } + catch (Exception e) + { + Debug.LogError($"[LQATool][UIDumpService] 转储失败: {e.Message}\n{e.StackTrace}"); + } + finally + { + // 7. 无论成功或失败都必须恢复现场: + // 还原游戏时间流速 + Time.timeScale = originalTimeScale; + // 清理可见性判定缓存, 避免残留影响下次 Dump + PixelVisibilityChecker.ClearCache(); + // 重新显示工具自身 UI + toolCanvas.enabled = true; + // 触发完成回调 (可能为 null) + onComplete?.Invoke(); + + Debug.Log($"[LQATool][UIDumpService] 转储完成! 路径: {dirPath}"); + } + } + } +} \ No newline at end of file diff --git a/timi_hok_game_translator/Unity_LQATool_Plugin/UI/LQAToolUIManager.Builder.cs b/timi_hok_game_translator/Unity_LQATool_Plugin/UI/LQAToolUIManager.Builder.cs new file mode 100644 index 0000000000000000000000000000000000000000..a9a1a8aec0d8477779559936efa9d1492e78bac7 --- /dev/null +++ b/timi_hok_game_translator/Unity_LQATool_Plugin/UI/LQAToolUIManager.Builder.cs @@ -0,0 +1,198 @@ +// ========================================== +// 文件: LQATool\UI\LQAToolUIManager.Builder.cs +// 模块: UI (用户界面) +// ========================================== + +using UnityEngine; +using UnityEngine.UI; + +/// +/// LQATool 用户界面层命名空间 +/// +namespace LQATool.UI +{ + /// + /// 分部类: 与 LQAToolUIManager.cs / .Display.cs / .EventSystem.cs 共同组成同一个类 + /// 本分部专注于 "如何把 UI 画出来", 字段 (_canvas / _infoPanel 等) 在主文件中声明 + /// + public partial class LQAToolUIManager + { + /// + /// 动态构建工具所需的全部 UI 元素 (整棵 UI 树的入口) + /// 调用时机: 由 Initialize() 调用 + /// 构建内容: 主画布 Canvas → Dump 按钮 → GetNode 按钮 → 信息面板 + /// + private void CreateToolUI() + { + // 1. 创建承载所有 UI 的根节点游戏对象 + GameObject canvasObj = new GameObject("LQATool_Canvas"); + // 挂到 UIManager 所在的对象下, 保持层级整洁, 便于随管理器一起被销毁 + canvasObj.transform.SetParent(this.transform); + + // 2. 添加 Canvas 组件并缓存引用 (供 Dump 时临时隐藏工具 UI) + _canvas = canvasObj.AddComponent(); + // 屏幕空间-覆盖模式: 直接叠加在屏幕最外层, 不依赖任何摄像机 + _canvas.renderMode = RenderMode.ScreenSpaceOverlay; + // 排序层级拉到最高 (short.MaxValue), 确保工具 UI 永远压在游戏 UI 之上 + _canvas.sortingOrder = 32767; + + // 3. 添加画布缩放器, 让 UI 在不同分辨率设备上表现一致 + CanvasScaler scaler = canvasObj.AddComponent(); + // 按屏幕尺寸缩放 + scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; + // 设计基准分辨率: 1920×1080 + scaler.referenceResolution = new Vector2(1920, 1080); + // 宽高匹配权重 0.5: 宽度和高度各占一半, 兼顾横竖屏比例变化 + scaler.matchWidthOrHeight = 0.5f; + + // 4. 添加图形射线检测器: UI 元素能够接收点击/触摸事件的前提 + canvasObj.AddComponent(); + + // 5. 创建 Dump 按钮 (锚点左中, 位于最左侧) + Button btnDump = CreateButton(canvasObj.transform, "Btn_Dump", "Dump", new Vector2(10, 0)); + // 绑定点击回调: 点击时向外广播 OnDumpClicked 事件 (?. 防止无人订阅时空引用) + btnDump.onClick.AddListener(() => OnDumpClicked?.Invoke()); + + // 6. 创建 GetNode 按钮 (在 Dump 按钮右侧, x=120), 初始文字为关闭状态 + Button btnGetNode = CreateButton(canvasObj.transform, "Btn_GetNode", "GetNode[off]", new Vector2(120, 0)); + // 缓存按钮上的 Text 组件, 供 ToggleGetNode() 切换文字/颜色时复用, 避免重复查找 + _txtGetNode = btnGetNode.GetComponentInChildren(); + // 绑定点击回调: 切换 GetNode 开关状态 (ToggleGetNode 定义在主文件中) + btnGetNode.onClick.AddListener(ToggleGetNode); + + // 7. 创建长按信息展示面板 (预创建并隐藏, 需要时再显示) + CreateInfoPanel(canvasObj.transform); + } + + /// + /// 通用按钮工厂方法: 用纯代码创建一个 "半透明黑底 + 居中白字" 的按钮 + /// + /// 父节点 (通常是主画布) + /// 按钮游戏对象的名称 + /// 按钮上显示的文字 + /// 相对锚点 (左中) 的偏移位置 + /// 创建好的 Button 组件 + private Button CreateButton(Transform parent, string name, string text, Vector2 position) + { + // 1. 创建按钮根对象并挂到父节点下 (worldPositionStays = false, 保持本地布局) + GameObject btnObj = new GameObject(name); + btnObj.transform.SetParent(parent, false); + + // 2. 添加背景图: 半透明黑色, 作为按钮的可视外观与点击热区 + Image bg = btnObj.AddComponent(); + bg.color = new Color(0, 0, 0, 0.7f); + // 必须开启射线检测, 否则按钮无法被点击 + bg.raycastTarget = true; + + // 3. 添加 Button 组件 (点击交互逻辑) + Button btn = btnObj.AddComponent