diff --git a/.github/workflows/windows-installer.yml b/.github/workflows/windows-installer.yml
new file mode 100644
index 0000000..b83b8a3
--- /dev/null
+++ b/.github/workflows/windows-installer.yml
@@ -0,0 +1,135 @@
+name: Build and sign Windows installer
+
+on:
+ workflow_dispatch:
+ inputs:
+ previous_version:
+ description: Previous signed Windows Setup release for upgrade testing and optional delta
+ type: string
+ required: false
+
+permissions:
+ contents: read
+
+jobs:
+ installer:
+ runs-on: windows-2022
+ if: github.ref_type == 'tag'
+ environment: windows-release-signing
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12.10'
+ - name: Check release tag and install build dependencies
+ id: release
+ shell: pwsh
+ run: |
+ $version = python -c 'from comic_translate_desktop import __version__; print(__version__)'
+ if ($env:GITHUB_REF_NAME -cne "v$version") { throw 'Tag and application version differ.' }
+ "version=$version" >> $env:GITHUB_OUTPUT
+ python -m venv .venv
+ .\.venv\Scripts\python.exe -m pip install -r requirements-build.txt
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ choco install nsis --version=3.13 --yes --no-progress
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ - name: Test and build the application, service and NSIS uninstaller
+ shell: powershell
+ run: |
+ .\.venv\Scripts\python.exe -m unittest -v tests.test_nsis_installer tests.test_release_update
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ .\build_app.ps1
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ .\.venv\Scripts\python.exe installer/build.py --stage-only --include-models --output build/unsigned
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ New-Item -ItemType Directory -Force build/signing | Out-Null
+ foreach ($name in 'ComiTrans.exe', 'ComiTransReleaseService.exe', 'Uninstall.exe') {
+ Copy-Item -LiteralPath "build/unsigned/payload/$name" -Destination build/signing
+ }
+ - name: Stage executables for verified signing
+ id: unsigned
+ uses: actions/upload-artifact@v4
+ with:
+ name: unsigned-windows-payload
+ path: build/signing/*.exe
+ if-no-files-found: error
+ compression-level: 0
+ - name: Sign the application, service and uninstaller
+ uses: signpath/github-action-submit-signing-request@f6d04783b4569d051e0c80105fe66e82819d0092 # v3
+ with:
+ api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
+ organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
+ project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}
+ signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}
+ artifact-configuration-slug: windows-payload
+ parameters: |
+ version: ${{ toJSON(steps.release.outputs.version) }}
+ github-artifact-id: ${{ steps.unsigned.outputs.artifact-id }}
+ wait-for-completion: true
+ output-artifact-directory: build/signed-payload
+ - name: Build NSIS Setup with the signed executables
+ shell: pwsh
+ run: |
+ Copy-Item -Path build/signed-payload/*.exe -Destination build/unsigned/payload -Force
+ .\.venv\Scripts\python.exe installer/build.py --payload build/unsigned/payload --output release/unsigned
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ - uses: actions/upload-artifact@v4
+ id: unsigned-setup
+ with:
+ name: unsigned-windows-setup
+ path: release/unsigned/*-Setup.exe
+ if-no-files-found: error
+ compression-level: 0
+ - name: Sign the final Setup EXE
+ uses: signpath/github-action-submit-signing-request@f6d04783b4569d051e0c80105fe66e82819d0092 # v3
+ with:
+ api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
+ organization-id: ${{ vars.SIGNPATH_ORGANIZATION_ID }}
+ project-slug: ${{ vars.SIGNPATH_PROJECT_SLUG }}
+ signing-policy-slug: ${{ vars.SIGNPATH_SIGNING_POLICY_SLUG }}
+ artifact-configuration-slug: windows-setup
+ parameters: |
+ version: ${{ toJSON(steps.release.outputs.version) }}
+ github-artifact-id: ${{ steps.unsigned-setup.outputs.artifact-id }}
+ wait-for-completion: true
+ output-artifact-directory: release/signed
+ - name: Verify signatures, test Setup and prepare the release files
+ shell: pwsh
+ env:
+ PREVIOUS_VERSION: ${{ inputs.previous_version }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ function Confirm-ComiTransSignature($path) {
+ $signature = Get-AuthenticodeSignature -LiteralPath $path
+ if ($signature.Status -ne 'Valid' -or !$signature.TimeStamperCertificate -or
+ $signature.SignerCertificate.GetNameInfo('SimpleName', $false) -ne 'SignPath Foundation') {
+ throw "Windows could not verify the timestamped SignPath Foundation signature: $path"
+ }
+ }
+ foreach ($name in 'ComiTrans.exe', 'ComiTransReleaseService.exe', 'Uninstall.exe') {
+ Confirm-ComiTransSignature "build/unsigned/payload/$name"
+ }
+ $stem = "ComiTrans-$($env:GITHUB_REF_NAME)-x64"
+ $setup = (Get-Item "release/signed/$stem-Setup.exe").FullName
+ Confirm-ComiTransSignature $setup
+ $test = @{ Setup = $setup; Version = $env:GITHUB_REF_NAME.Substring(1); LogDirectory = $env:RUNNER_TEMP }
+ if ($env:PREVIOUS_VERSION) {
+ if ($env:PREVIOUS_VERSION -notmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { throw 'Invalid base version.' }
+ $name = "ComiTrans-v$env:PREVIOUS_VERSION-x64-Setup.exe"
+ gh release download "v$env:PREVIOUS_VERSION" --pattern $name --dir build/previous
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ Confirm-ComiTransSignature "build/previous/$name"
+ $test.PreviousSetup = (Resolve-Path "build/previous/$name").Path
+ .\.venv\Scripts\python.exe installer/build.py --delta "build/previous/$name" $setup
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ }
+ & installer/Test-Setup.ps1 @test
+ .\.venv\Scripts\python.exe -c "from pathlib import Path; from package_release import write_checksums; p=Path('release/signed'); write_checksums(p, sorted(p.glob('ComiTrans-*')))"
+ - uses: actions/upload-artifact@v4
+ with:
+ name: signed-windows-release
+ path: release/signed/*
+ if-no-files-found: error
+ compression-level: 0
diff --git a/.github/workflows/windows-release-verify.yml b/.github/workflows/windows-release-verify.yml
new file mode 100644
index 0000000..7a2988c
--- /dev/null
+++ b/.github/workflows/windows-release-verify.yml
@@ -0,0 +1,47 @@
+name: Verify Windows release
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: Release tag to verify, including draft releases
+ required: true
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ verify:
+ runs-on: windows-2022
+ steps:
+ - uses: actions/checkout@v4
+ - name: Download and verify release files
+ shell: pwsh
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.tag }}
+ run: |
+ if ($env:RELEASE_TAG -notmatch '^v[0-9]+\.[0-9]+\.[0-9]+$') { throw 'Invalid release tag.' }
+ gh release download $env:RELEASE_TAG --repo $env:GITHUB_REPOSITORY --pattern '*-Setup.exe' --pattern 'SHA256SUMS.txt' --dir package
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ foreach ($line in Get-Content package/SHA256SUMS.txt) {
+ if ($line -notmatch '^([a-fA-F0-9]{64}) ([^/\\]+)$') { throw 'Invalid checksum entry.' }
+ $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path package $Matches[2])).Hash
+ if ($actual -ine $Matches[1]) { throw 'Release checksum mismatch.' }
+ }
+ - name: Install, reinstall and uninstall on a clean Windows runner
+ shell: pwsh
+ env:
+ RELEASE_TAG: ${{ inputs.tag }}
+ run: |
+ $setup = (Resolve-Path "package/ComiTrans-$env:RELEASE_TAG-x64-Setup.exe").Path
+ & installer/Test-Setup.ps1 -Setup $setup -Version $env:RELEASE_TAG.Substring(1) -LogDirectory $env:RUNNER_TEMP
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: windows-release-verification
+ path: |
+ ${{ runner.temp }}/comitrans-nsis-install.log
+ ${{ runner.temp }}/comitrans-installed-smoke/smoke-result.json
+ if-no-files-found: ignore
diff --git a/.gitignore b/.gitignore
index 40bb316..d8dc6af 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,6 +42,7 @@ pip-delete-this-directory.txt
dist/
build/
release/
+/.wix/
# Only the current audited ONNX model set is tracked (weights use Git LFS).
comic-translate-ai/models/*
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ddea69c..cc5ba57 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,12 @@
本文件记录当前源码与发布版本的主要变化。英文摘要见 [README_en.md](README_en.md#changelog)。
+## v2.6.0(2026-11-23)
+
+- Windows x64 安装向导包含桌面程序与默认模型。正式发布包附 SHA-256,未签名版本通过 GitHub 发布页手动安装。
+- 模型在独立进程中预热。启动时按版本号检查正式更新,发现更高版本后在顶栏模型状态左侧显示「有更新」。
+- 新增作品术语库、试译与用量报告。精修支持全书译稿、单气泡重译和 CBZ 导出。[安装与升级说明](docs/RELEASE-v2.6.0.md)
+
## v2.5.2 — 2026-11-17
- 翻译工作流改为 Fork-Join 并行流水线,并用实时拓扑图重绘自动处理页进度面板(支持并发在途页角标、后台修补就绪、上下文统计、断点续传标注及底部逐页状态矩阵,适配纸白/夜墨双主题)。
diff --git a/ComiTrans.spec b/ComiTrans.spec
index 5cf6a10..956d147 100644
--- a/ComiTrans.spec
+++ b/ComiTrans.spec
@@ -6,6 +6,10 @@ from pathlib import Path
import PySide6
import shiboken6
from PyInstaller.utils.hooks import collect_data_files, copy_metadata
+from PyInstaller.utils.win32.versioninfo import (
+ FixedFileInfo, StringFileInfo, StringStruct, StringTable, VarFileInfo, VarStruct, VSVersionInfo,
+)
+from comic_translate_desktop import __version__
# Resolve DLLs from this Python/Qt installation and Windows, not unrelated
# tools on PATH (e.g. Poppler's ICU exports do not match Qt's Windows ICU ABI).
@@ -108,6 +112,18 @@ a.binaries = [entry for entry in a.binaries
pyz = PYZ(a.pure)
+version_tuple = (*map(int, __version__.split('.')), 0)
+version_info = VSVersionInfo(
+ ffi=FixedFileInfo(filevers=version_tuple, prodvers=version_tuple, mask=0x3f,
+ flags=0, OS=0x40004, fileType=1, subtype=0, date=(0, 0)),
+ kids=[StringFileInfo([StringTable('040904B0', [
+ StringStruct('FileDescription', 'ComiTrans'),
+ StringStruct('FileVersion', __version__),
+ StringStruct('ProductName', 'ComiTrans'),
+ StringStruct('ProductVersion', __version__),
+ ])]), VarFileInfo([VarStruct('Translation', [1033, 1200])])],
+)
+
exe = EXE(
pyz,
a.scripts,
@@ -115,6 +131,7 @@ exe = EXE(
exclude_binaries=True,
name="ComiTrans",
icon="assets/ComiTrans.ico",
+ version=version_info,
debug=False,
bootloader_ignore_signals=False,
strip=False,
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 4161dde..9255ed6 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,10 @@
ComiTrans 是一款漫画自动汉化桌面客户端。本地执行文本检测、日语/韩语/英语 OCR、背景修复和中文排版,通过配置的大模型 API 翻译。支持接入自定义 OCR,不依赖 Web 前端。
-从 v2.2.1 开始,检测、OCR、修复全部切换为 **ONNX Runtime 推理**,彻底移除 PyTorch / torchvision / transformers 依赖;主程序和模型拆分发布,更新程序时不再需要重新下载模型。
+从 v2.2.1 开始,检测、OCR 和修复均使用 **ONNX Runtime**,无需 PyTorch / torchvision / transformers。
+
+> [!NOTE]
+> **v2.6.0 Windows x64 版**将程序和模型放进一个安装包。模型在独立进程预热,翻译前可用作品术语库统一译名、先试译几页查看用量。[发布说明与升级步骤](docs/RELEASE-v2.6.0.md)
> [!NOTE]
> **v2.5.2 更新**:滚动上下文记忆与可选缓存保留、OCR 后“按序翻译 ∥ 后台修补”Fork-Join 并行流水线、实时工作流拓扑可视化,以及精修画框、取色与自定义 RGB 填色、9 槽收藏字体、文字拉伸/旋转/描边和 PDF 边缘修复。已有 v2.5.1 模型可复用。[v2.5.2 发布说明](docs/RELEASE-v2.5.2.md) · [更新日志](CHANGELOG.md)。
@@ -113,7 +116,7 @@ ComiTrans 是一款漫画自动汉化桌面客户端。本地执行文本检测
- **多语言源文与自定义 OCR**:选择日语、韩语、英语或“自定义 OCR”,可翻译成简体或繁体中文;支持独立 HTTP OCR 与兼容视觉模型接口。[接入说明与混合语言策略](docs/MULTILINGUAL_OCR.md)。
- **纯本地桌面客户端**:PySide6 桌面应用,抛弃 Web 页面,启动后即可使用。
- **全 ONNX 推理**:漫画文本检测、日/韩/英本地 OCR、LaMa 修复全部为 ONNX 模型,不再依赖 PyTorch。
-- **模型拆包发布**:模型单独一个下载包,更新程序无需重新下载模型。
+- **Windows 一体化安装**:v2.6.0 将程序和本地模型放进一个 Setup。
- **延迟后台预热**:打开客户端先显示界面,模型在低优先级后台准备,开始翻译时直接复用。
- **GPU 推理**:新安装默认优先 NVIDIA CUDA;软件内提供 CUDA/cuDNN 官方安装链接,需兼容的 NVIDIA 驱动,日志明确实际设备。保留旧配置中的 CPU 选择。
- **多模态翻译开关**:勾选后发送整页图片给 AI,结合画面翻译;不勾选则发送 OCR 文本。字体、字号与横竖方向默认由本地算法决定,实验性字体比对需单独启用。
@@ -136,6 +139,12 @@ ComiTrans 是一款漫画自动汉化桌面客户端。本地执行文本检测
### Release 用户(推荐)
+下载 `ComiTrans-v2.6.0-x64-Setup.exe` 和 `SHA256SUMS.txt`,核对 SHA-256 后关闭 ComiTrans 并运行 Setup。首次使用请在设置中填写翻译 API 密钥和模型。[下载 v2.6.0](https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.6.0)
+
+本版安装包未签名,Windows 可能显示「未知发布者」,请从发布页手动下载安装。应用启动时会检查更高的正式版本,点击模型状态左侧的「有更新」可查看版本详情并前往发布页。[安装与迁移说明](docs/WINDOWS_INSTALLER.md)
+
+#### 历史 ZIP 版(v2.5.2)
+
1. 在[发布页](https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.5.2)下载 `ComiTrans-v2.5.2-app.zip`(程序包);首次安装或从 v2.5.0 及更早版本升级请同时下载 `ComiTrans-v2.5.2-models.zip`(模型包,与 v2.5.1 一致,已有 v2.5.1 模型可直接复用)。
2. 所需压缩包解压到同一个父目录,合并顶层同名 `ComiTrans` 文件夹,保留子目录结构。最终模型路径为 `ComiTrans\comic-translate-ai\models\`。
3. 双击合并后的 `ComiTrans.exe`,在“设置”页填写翻译 API Key 和模型。
@@ -204,7 +213,7 @@ Copy-Item comic-translate-ai/main/config.example.yaml comic-translate-ai/main/co
默认启用按页断点续传。网络失败或停止后,使用相同原文件、输出目录和翻译设置再次开始,即可跳过已完成页面并复用已保存译文;重启程序后同样有效。需要全部重译时,取消“翻译偏好 → 断点续传”勾选。[断点续传说明](docs/RESUMABLE_TRANSLATION.md)。
-PDF 会以一个文件任务显示,内部按在途页数上限连续处理,成功后输出 `<原文件名>_translated.pdf`,并保留同名 `.comitrans.json` 索引和独立精修资料目录。点击结果页的精修入口,或在“嵌字精修”导入译文 PDF,即可逐页改字、排版与修补背景;开启“连续长条”可纵向滚动浏览并点击页面原位编辑。精修始终操作逐页图片,“保存图片”和切页不会合成 PDF;需要成书时点击“导出 PDF”,选择文件名后在后台无损合成,支持进度与取消。也可直接导入资料目录中的 `project.json`,不依赖 PDF 本身。输出保留页数、顺序和页面尺寸,页面内容会栅格化;加密或需要密码的 PDF 暂不支持。移动项目时请一起保留 PDF、索引和资料目录。详见 [PDF 精修说明](docs/PDF_EDITING.md)。
+PDF 会以一个文件任务显示,内部按在途页数上限连续处理,成功后输出 `<原文件名>_translated.pdf`,并保留同名 `.comitrans` 索引和独立精修资料目录。点击结果页的精修入口,或在“嵌字精修”导入译文 PDF,即可逐页改字、排版与修补背景;开启“连续长条”可纵向滚动浏览并点击页面原位编辑。精修始终操作逐页图片,“保存图片”和切页不会合成 PDF;需要成书时点击“导出 PDF”,选择文件名后在后台无损合成,支持进度与取消。也可直接导入资料目录中的 `project.json`,不依赖 PDF 本身。输出保留页数、顺序和页面尺寸,页面内容会栅格化;加密或需要密码的 PDF 暂不支持。移动项目时请一起保留 PDF、索引和资料目录。详见 [PDF 精修说明](docs/PDF_EDITING.md)。
### OCR 接口
@@ -309,18 +318,13 @@ v2.5.1 本地预览只随包提供 CharSpot Small 日语 OCR,默认使用 Smal
### 生成发布包
+构建桌面程序并安装 NSIS 后,运行以下命令生成包含默认模型的 Windows 安装包。打包脚本从客户端读取版本号。[Windows 打包说明](docs/WINDOWS_INSTALLER.md)
+
```powershell
-python package_release.py --output release/v2.5.2
+.\.venv\Scripts\python.exe installer/build.py --include-models
```
-本地构建生成两个 v2.5.2 压缩包。
-
-- `ComiTrans-v2.5.2-app.zip`:主程序,不含模型
-- `ComiTrans-v2.5.2-models.zip`:与 v2.5.1 一致的 ONNX 模型包(含日语 CharSpot Small、双检测器、韩语、英语 OCR 与 LaMa);v2.5.1 已有模型可直接复用
-
-不发布 CUDA/cuDNN 运行库包;v2.5.0 修补版与 v2.5.1+ 用户可在设置中点击「下载安装便携 GPU 运行库」,重启后从程序目录加载。发布页同时提供 `SHA256SUMS.txt` 和 `baseline.json`。
-
-版本元数据保存在源码仓库,随发布提交:
+历史 ZIP 版的校验文件
- [docs/releases/v2.5.2/baseline.json](docs/releases/v2.5.2/baseline.json):2.5.2 目标构建基线
- [docs/releases/v2.5.2/SHA256SUMS.txt](docs/releases/v2.5.2/SHA256SUMS.txt):2.5.2 程序包、模型包及目标基线的 SHA256
@@ -361,6 +365,10 @@ ComiTrans
```
## 更新日志
+### v2.6.0(2026-11-23)
+
+Windows 安装包附带默认模型。桌面端支持后台模型预热、作品术语库、试译和顶栏更新提醒。[发布说明](docs/RELEASE-v2.6.0.md)
+
### v2.5.2(2026-11-17)
- 新增滚动上下文记忆与 `.cache/translation-context.json` 原子缓存;偏好新增「保留上下文缓存」(联动锁定断点续传)。
@@ -476,11 +484,11 @@ ComiTrans
**Release 需要安装 Python 或 GPU 运行库吗?**
-不需要 Python。CPU 模式解压程序与模型即可运行;GPU 模式需要兼容的 NVIDIA 驱动、CUDA 12 和 cuDNN 9,软件内提供官方安装链接,已有环境可复用。实际设备可在日志中确认。
+不需要 Python。单文件 Setup 安装完成后即可用 CPU 加载本地模型。GPU 模式需要兼容的 NVIDIA 驱动、CUDA 12 和 cuDNN 9,软件内提供安装指引。
**模型放哪里?**
-模型位于 exe 旁的 `comic-translate-ai/models/`。两个压缩包解压到同一个父目录并合并顶层 `ComiTrans` 文件夹,避免出现 `ComiTrans/ComiTrans` 的嵌套目录。
+v2.6.0 Setup 会自动把模型装到程序目录。v2.5.2 等历史 ZIP 版仍按上方步骤将程序和模型解压到同一目录。
**为什么英文文本没有被翻译?**
@@ -496,7 +504,7 @@ v2.2.1 已全面 ONNX 化并移除 PyTorch。检测、OCR、修复均使用 ONNX
## 开源协议
-- 项目代码遵循相应开源协议发布(详见仓库 LICENSE 文件)。
+- 项目源码采用 [GPL-3.0](LICENSE)。
- 字体:得意黑 Smiley Sans、霞鹜文楷 LXGW WenKai、霞鹜漫黑 LXGW Marker Gothic(SIL OFL 1.1)、Klee One、思源黑体/宋体、setofont(濑户字体)、851手写杂书体 均为可免费商用的开源/免费字体,各自的授权见字体项目说明。
- UI 字体 Skribble 与 Aa今日花晴 春懒猫困使用各自的内嵌版权信息,来源与用途见 [字体说明](assets/ui/fonts/README.md)。
- 模型:CharSpot Small 权重为 CC BY-NC-SA 4.0,各模型的来源、署名与许可见 [docs/ONNX_MODELS.md](docs/ONNX_MODELS.md)。
diff --git a/README_en.md b/README_en.md
index f9cb1d1..759a440 100644
--- a/README_en.md
+++ b/README_en.md
@@ -18,7 +18,10 @@ Source-language selection supports Japanese, Korean, English, and **Custom OCR**
ComiTrans is a manga translation desktop client. Detection, built-in Japanese/Korean/English OCR, inpainting, and Chinese typesetting run locally; translation uses your configured LLM API. No web frontend is required.
-Since v2.2.1, detection, OCR, and inpainting are powered entirely by **ONNX Runtime**, removing PyTorch / torchvision / transformers dependencies. The app and models are released as separate packages: app updates no longer require re-downloading unchanged models.
+Since v2.2.1, detection, OCR, and inpainting have run on **ONNX Runtime**, with no PyTorch, torchvision, or transformers dependencies.
+
+> [!NOTE]
+> **v2.6.0 for Windows x64** bundles the app and models in one installer. Model warm-up runs in a separate process. Project glossaries and trial translations help check a batch before running it. [Release notes and upgrade instructions](docs/RELEASE-v2.6.0.md)
> [!NOTE]
> **v2.5.2 update:** rolling cross-page translation context with optional cache retention, an OCR-forked sequential-translation ∥ background-repair Fork-Join pipeline, a redesigned live workflow graph on the translation page, plus manual bubble boxes, eyedropper & custom RGB fills, 9-slot favorite fonts (`1–9`), lettering stretch/rotation/outline, and fractional-edge PDF export fixes. v2.5.1 models remain reusable. [v2.5.2 release notes](docs/RELEASE-v2.5.2.md) · [Changelog](CHANGELOG.md).
@@ -117,7 +120,7 @@ Logs use the Aa handwriting font and reveal at about 250 characters per second,
- **Native desktop UI**: PySide6 app with a manga magazine design and a clean editing canvas.
- **Source languages and OCR**: Japanese, Korean, English, or a custom language; independent HTTP and compatible vision OCR endpoints.
- **All-ONNX inference**: text detection, Japanese/Korean/English local OCR, and LaMa inpainting all use ONNX; no PyTorch required.
-- **Split release packages**: models ship separately, so app updates do not require re-downloading models.
+- **Single Windows installer**: v2.6.0 bundles the app and local models in one Setup.
- **Startup warmup**: the AI pipeline loads automatically when the app opens.
- **GPU inference**: new installations prefer NVIDIA CUDA. Settings provide official CUDA/cuDNN installation links; a compatible NVIDIA driver is required; logs report the actual device. Existing CPU preferences are preserved.
- **Multimodal translation toggle**: sends the full page image to the AI for visual context; pure-text mode sends OCR results. Font selection, size, and orientation are local by default. Experimental font comparison requires a separate opt-in.
@@ -140,6 +143,12 @@ A fully successful translation batch has a 15% chance of showing a small reposit
### Release users (recommended)
+Download `ComiTrans-v2.6.0-x64-Setup.exe` and `SHA256SUMS.txt`. Verify the SHA-256, close ComiTrans and run Setup. Enter your translation API key and model in Settings. [Download v2.6.0](https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.6.0)
+
+This installer is unsigned. Windows may display “Unknown publisher.” Install this release manually. At startup the app checks GitHub for a newer stable release. Select **Update** beside the model status to view the version and open its release page. [Installation and migration guide](docs/WINDOWS_INSTALLER.md)
+
+#### Earlier ZIP releases (v2.5.2)
+
1. Download `ComiTrans-v2.5.2-app.zip` from the [v2.5.2 release](https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.5.2); for fresh installs or upgrades from v2.5.0 and earlier, also download `ComiTrans-v2.5.2-models.zip` (identical to v2.5.1 models; existing v2.5.1 users can reuse their models folder).
2. Extract the required archives into the same parent directory and merge their top-level `ComiTrans` folders, preserving the subfolder structure. The final model path is `ComiTrans\comic-translate-ai\models\`.
3. Double-click the merged `ComiTrans.exe` and enter your translation API key and model on the "Settings" page.
@@ -208,7 +217,7 @@ The `@ComiTrans` watermark is enabled by default. To disable it, uncheck Add @Co
Per-page resume is enabled by default. After a network failure, cancellation, or restart, use the same source files, output folder, and translation settings to skip completed pages and reuse saved translations. Uncheck Resume in Translation Preferences to start over. [Resume guide](docs/RESUMABLE_TRANSLATION.md).
-A PDF is shown as one file task and processed through a bounded page pipeline. ComiTrans retains the translated PDF, a matching `.comitrans.json` index, and a separate directory of editable pages. Open the result in the Typesetting Editor or import the translated PDF to adjust text, layout, and backgrounds. Continuous Strip mode lets you scroll vertically and click a page to edit it in place. Editing and Save Image operate on individual images. Export PDF explicitly assembles saved pages in the background with lossless compression, progress and cancellation, preserving page count, order, and sizes. You can also import the project directory’s `project.json` without the PDF. Content is rasterized; password-protected PDFs are not supported. Keep the PDF, index, and project directory together when moving them. [PDF editing guide](docs/PDF_EDITING.md).
+A PDF is shown as one file task and processed through a bounded page pipeline. ComiTrans retains the translated PDF, a matching `.comitrans` index, and a separate directory of editable pages. Open the result in the Typesetting Editor or import the translated PDF to adjust text, layout, and backgrounds. Continuous Strip mode lets you scroll vertically and click a page to edit it in place. Editing and Save Image operate on individual images. Export PDF explicitly assembles saved pages in the background with lossless compression, progress and cancellation, preserving page count, order, and sizes. You can also import the project directory’s `project.json` without the PDF. Content is rasterized; password-protected PDFs are not supported. Keep the PDF, index, and project directory together when moving them. [PDF editing guide](docs/PDF_EDITING.md).
### OCR interfaces
@@ -310,18 +319,13 @@ By default the app is built without models. For local testing with models:
### Generate release packages
+After building the desktop app, run the following command with NSIS installed. Setup includes the default models and uses the version declared by the desktop package. [Windows packaging guide](docs/WINDOWS_INSTALLER.md)
+
```powershell
-python package_release.py --output release/v2.5.2
+.\.venv\Scripts\python.exe installer/build.py --include-models
```
-The local build produces two v2.5.2 archives.
-
-- `ComiTrans-v2.5.2-app.zip`: program only, no models
-- `ComiTrans-v2.5.2-models.zip`: ONNX models matching v2.5.1 (Japanese CharSpot Small, dual detectors, Korean & English OCR, LaMa); existing v2.5.1 models can be reused
-
-CUDA/cuDNN libraries are not distributed in this release. GPU users can open official installation links from Settings. The release includes `SHA256SUMS.txt` and `baseline.json`.
-
-Version metadata is stored and committed in the source repository:
+Historical ZIP release metadata
- [docs/releases/v2.5.2/baseline.json](docs/releases/v2.5.2/baseline.json): v2.5.2 target build fingerprint
- [docs/releases/v2.5.2/SHA256SUMS.txt](docs/releases/v2.5.2/SHA256SUMS.txt): v2.5.2 app, models and target baseline checksums
@@ -363,6 +367,10 @@ ComiTrans
## Changelog
+### v2.6.0 (2026-11-23)
+
+Windows Setup includes the default models. The desktop app adds background model warm-up, project glossaries, trial translations and a compact update indicator. [Release notes](docs/RELEASE-v2.6.0.md)
+
### v2.5.2 (2026-11-17)
- Rolling cross-page translation context with atomic `.cache/translation-context.json` persistence and a "Keep context cache" toggle locking per-page resume.
@@ -489,11 +497,11 @@ App and models remain separate packages; v2.3.0 users can reuse their models. Se
**Do releases require Python or GPU libraries?**
-Python is not required. CPU users can extract the app and models and run. GPU users need a compatible NVIDIA driver, CUDA 12 and cuDNN 9; Settings provide official installation links. Existing compatible installations can be reused. Logs show the actual provider.
+Setup includes the CPU runtime and models, so no Python installation is required. CUDA acceleration requires a compatible NVIDIA driver, CUDA 12, and cuDNN 9. See GPU setup in Settings for instructions.
**Where do models go?**
-Beside the exe at `comic-translate-ai/models/`. Extract both archives into the same parent directory and merge their top-level `ComiTrans` folders; avoid nesting `ComiTrans/ComiTrans`.
+The v2.6.0 Setup installs the models with the app. For v2.5.2 and earlier ZIP releases, follow the extraction instructions above.
**Why is English text not translated?**
@@ -509,7 +517,7 @@ Report issues at [GitHub Issues](https://github.com/Aaaaamadeus/ComiTrans/issues
## License
-- Project code is released under the license in the repository.
+- Project source code is licensed under [GPL-3.0](LICENSE).
- Fonts: Smiley Sans, LXGW WenKai, LXGW Marker Gothic (SIL OFL 1.1), Klee One, Source Han Sans/Serif, setofont (SetoFont), and 851tegakizatsu are free for commercial use, each under its own license.
- UI fonts Skribble and Aa retain their embedded copyright information; see [font provenance](assets/ui/fonts/README.md).
- Models: CharSpot Small weights use CC BY-NC-SA 4.0. For attribution, terms, and sources of each model see [docs/ONNX_MODELS.md](docs/ONNX_MODELS.md).
diff --git a/assets/i18n/en.json b/assets/i18n/en.json
index 37bf476..47a4073 100644
--- a/assets/i18n/en.json
+++ b/assets/i18n/en.json
@@ -1,4 +1,19 @@
{
+ "有更新": "Update",
+ "新版本 v{version} 可用,点击查看详情": "Version {version} is available. View update details.",
+ "检查更新失败:{reason}": "Update check failed: {reason}",
+ "发布信息格式无效": "Invalid release information",
+ "发现 ComiTrans 新版本": "ComiTrans update available",
+ "当前版本 v{current},GitHub 已发布 v{latest}。": "Current version v{current}. Version v{latest} is available on GitHub.",
+ "下载并更新": "Download and update",
+ "下载完成后,ComiTrans 将请求关闭并通过 Windows 安装程序更新。": "After the download, ComiTrans will ask to close and update through Windows Installer.",
+ "查看 GitHub 发布": "View GitHub release",
+ "前往发布页下载安装": "Download from releases",
+ "稍后提醒": "Remind me later",
+ "正在下载并验证更新…": "Downloading and verifying the update…",
+ "取消": "Cancel",
+ "更新 ComiTrans": "Update ComiTrans",
+ "更新下载或验证失败。请在 GitHub 发布页重试。": "The download or signature check failed. Try again from the GitHub release page.",
"CUDA 加速": "CUDA",
"检测器与修补说明": "Detector and repair comparison",
"CUDA 快速检测器在 GPU 上检测更快,能用笔画像素限定擦除范围。日漫样本中文字框覆盖较少,漏检处可能留字。\n\n轻量双图检测器在 CPU 上检测更快,日漫样本中文字框覆盖更全。它靠文字框和文字行定位,复杂底纹或描边仍可能漏擦。\n\n两套方案共用背景修补流程,主要区别在于擦除范围。": "The fast CUDA detector runs faster on GPU and identifies stroke pixels to guide erasing. It covered fewer text regions in the Japanese manga sample, so missed text may remain.\n\nThe lightweight dual detector runs faster on CPU and covered more text regions in the sample. It uses text boxes and lines, so it can miss strokes on textured backgrounds or in outlined text.\n\nBoth detectors use the same background repair process. They mainly differ in what gets erased.",
@@ -149,7 +164,7 @@
"修改实时预览 · Ctrl+S 保存图片": "Live preview · Ctrl+S to save image",
"修改待保存…": "Changes pending…",
"修改待保存,收起面板也会立即保存。": "Changes pending. Collapsing this panel also saves them immediately.",
- "修补选区": "Repair selection",
+ "修补选区": "Repair area",
"倾斜": "Oblique",
"偏好已保存;展开状态会记住。": "Preferences saved. The expanded state is remembered.",
"偏好未保存,请重试": "Preferences not saved. Please retry.",
@@ -310,7 +325,7 @@
"接入方式": "Protocol",
"描述报错现象,或直接问:帮我分析当前日志": "Describe the problem, or ask: Analyze the current logs",
"描述遇到的问题,AI 将结合当前日志分析;后续追问会保留上下文。": "Describe the problem. AI analyzes the current logs and keeps context for follow-up questions.",
- "插入换行": "Insert line break",
+ "插入换行": "Line break",
"搜索": "Search",
"搜索名称、中文别名、语言或风格,例如:霞鹜、中文、手写…": "Search font names, aliases, languages or styles, e.g. WenKai, Chinese, handwriting…",
"搜索日志": "Search logs",
@@ -366,7 +381,7 @@
"标准 HTTP OCR": "Standard HTTP OCR",
"标题": "Title",
"标题 / 装饰": "Display / decorative",
- "框选背景": "Select background",
+ "框选背景": "Select area",
"检查结果": "Review results",
"检测": "Detect",
"检测: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\n修复: {_3}": "Detector: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\nInpainting: {_3}",
@@ -412,7 +427,7 @@
"清空日志": "Clear logs",
"已清空页面列表。": "Page list cleared.",
"源语言代码": "Source language code",
- "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)": "Comic files (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json *.comitrans)": "Comic files (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json *.comitrans)",
"漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf)": "Comic files (*.png *.jpg *.jpeg *.webp *.bmp *.pdf)",
"漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf)": "Manga files (*.png *.jpg *.jpeg *.webp *.bmp *.pdf);;Images (*.png *.jpg *.jpeg *.webp *.bmp);;PDF files (*.pdf)",
"漫画文件队列": "Manga file queue",
@@ -629,7 +644,7 @@
"切换后立即生效;夜墨只改变界面与画布周围,不改漫画像素与导出结果。": "Applies immediately. Night ink changes only the UI and the area around the canvas; manga pixels and exports are untouched.",
"跟随系统会随 Windows 深浅色自动切换。": "Follow system tracks the Windows light/dark setting.",
"翻译方向": "Translation direction",
- "全屏编辑": "Full-screen editor",
+ "全屏编辑": "Expand",
"在独立窗口中编辑当前气泡的译文 · F2": "Edit this bubble's translation in its own window · F2",
"全屏编辑 · 第 {_0} 块": "Full-screen editor · Block {_0}",
"修改会实时同步到右侧面板;Ctrl+S 保存图片。": "Edits sync to the inspector live; Ctrl+S saves the image.",
@@ -699,7 +714,7 @@
"纵向拉伸": "Vertical stretch",
"文字旋转": "Text rotation",
"文字变形尺寸过大,请减小字号或拉伸比例。": "The transformed text is too large. Reduce the font size or stretch percentage.",
- "添加气泡框": "Add bubble frame",
+ "添加气泡框": "Add bubble",
"在画布上拖动一个矩形,添加可自由编辑的文字气泡框。": "Drag a rectangle on the canvas to add a freely editable text bubble frame.",
"在画布拖动矩形添加气泡框,添加后可直接输入译文。": "Drag a rectangle on the canvas to add a bubble frame, then enter the translation.",
"手动添加": "Added manually",
@@ -778,5 +793,164 @@
"按阅读顺序调用翻译模型,结合前文上下文并缓存译文": "Translates in reading order with prior-page context and saves checkpoints",
"与翻译并行在独立线程生成擦字掩膜并修补背景": "Generates masks and repairs backgrounds concurrently on a separate thread",
"翻译与修补汇合后,校对空译文并完成横竖排嵌字": "Reconciles joined branches and typesets translations onto the cleaned page",
- "写入译图、清理底图与布局文件,全部完成后合成译文 PDF": "Writes translated images, cleaned pages, layouts, and final PDFs atomically"
+ "写入译图、清理底图与布局文件,全部完成后合成译文 PDF": "Writes translated images, cleaned pages, layouts, and final PDFs atomically",
+ "输出水印": "Output watermark",
+ "便携 GPU 运行库": "Portable GPU runtime",
+ "手动安装步骤": "Manual setup steps",
+ "官方下载": "Official downloads",
+ "喜欢这次翻译?": "Enjoying this translation?",
+ "installer.Require64Bit": "ComiTrans requires 64-bit Windows.",
+ "installer.LegacyInstaller": "An MSI installation of ComiTrans was found. Uninstall it from Windows Settings before installing this version. Your user data will be kept.",
+ "installer.NewerInstalled": "A newer version of ComiTrans is already installed.",
+ "installer.KeepDirectory": "To change the installation folder, uninstall the current version first. Your user data will be kept.",
+ "installer.InvalidDirectory": "Choose an empty folder on a local drive, or the folder of the current NSIS installation. Do not select a drive root or a Windows system folder.",
+ "installer.CloseApplication": "Close ComiTrans before installing or uninstalling, then try again.",
+ "installer.ServiceError": "The ComiTrans update service could not be configured. See the installation log for details.",
+ "installer.InstallError": "Installation did not complete. Check the available disk space and folder permissions, then try again.",
+ "installer.AlreadyRunning": "Another ComiTrans installer or uninstaller is running.",
+ "installer.InvalidUninstall": "This uninstaller does not match the registered ComiTrans installation. Open Windows Settings to uninstall ComiTrans.",
+ "installer.DirectoryHelp": "Choose where to install ComiTrans. Setup creates a ComiTrans subfolder automatically. If the selected folder is already named ComiTrans, it is used directly.",
+ "{_0} / {_1}": "{_0} / {_1}",
+ "不使用术语库": "No terminology library",
+ "作品名称": "Work name",
+ "作品术语库": "Work terminology",
+ "保存失败": "Save failed",
+ "保存并关闭": "Save and close",
+ "删除作品": "Delete work",
+ "删除此作品的术语库?": "Delete the terminology library for this work?",
+ "删除选中词条": "Remove selected terms",
+ "取样式": "Pick style",
+ "固定译名": "Preferred translation",
+ "填写单价以估算费用": "Enter token prices to estimate cost",
+ "币种": "Currency",
+ "开始试译": "Start trial",
+ "撤销样式": "Undo style",
+ "新建作品": "New work",
+ "未启用作品术语库": "No work terminology selected",
+ "本次估算费用:{_0}": "Estimated cost for this run: {_0}",
+ "样式刷": "Style brush",
+ "消耗": "Usage",
+ "添加词条": "Add term",
+ "类型(可选)": "Type (optional)",
+ "精修试译": "Edit trial",
+ "翻译整本": "Translate all",
+ "翻译消耗": "Translation usage",
+ "识别线索(可选)": "Matching clues (optional)",
+ "试译": "Trial",
+ "试译完成": "Trial complete",
+ "试译已结束": "Trial ended",
+ "试译报告": "Trial report",
+ "试译结束,结果已单独保存。": "Trial ended. Results were saved separately.",
+ "试译页数": "Trial pages",
+ "费用未知": "Cost unknown",
+ "输入 / 百万 token": "Input / million tokens",
+ "输出 / 百万 token": "Output / million tokens",
+ "当前作品:{_0} · {_1} 个译名 · AI 自动匹配": "Work: {_0} · {_1} terms · AI matching",
+ "查看本次翻译 token 用量并设置估算单价": "View translation token usage and enter estimated token prices",
+ "先翻译队列开头的 1–3 页,查看效果和消耗": "Translate the first 1–3 queued pages to review quality and usage",
+ "复制当前气泡的字体与排版样式,然后点击或框选目标气泡。": "Copy this bubble’s font and lettering style, then click or box-select target bubbles.",
+ "已取样式,点击或框选目标气泡;Esc 退出样式刷。": "Style picked. Click or box-select target bubbles; Esc exits the brush.",
+ "已选 {_0} / {_1}": "Selected {_0} / {_1}",
+ "已选 {_0} 个气泡:排版修改应用到所选,译文和位置单独保留。": "{_0} bubbles selected: lettering changes apply to the selection; each keeps its text and position.",
+ "点击目标应用样式;Shift 拖动框选,Ctrl 点击多选;Esc 退出。不会复制译文或气泡位置。": "Click to apply style; Shift-drag to box-select, Ctrl-click to toggle selection, Esc to exit. Text and bubble positions are preserved.",
+ "只填写固定译名即可,AI 会根据上下文自动匹配原文。类型和识别线索可帮助区分同名角色;不确定时不会强行套用。": "Enter preferred translations only. AI matches them to the source using context. Optional types and clues help distinguish characters; uncertain matches are not forced.",
+ "试译当前队列开头的 1–3 页,PDF 按页面计数。试译结果单独保存,使用独立上下文,不占用正式任务的断点。": "Try the first 1–3 queued pages, counting PDF pages individually. Trial results and context are separate from the full run and its checkpoints.",
+ "模型:{_0}\n完成 {_1} / {_2} 页 · 用时 {_3} 秒\n翻译响应 {_4} 次 · 已报告用量 {_5} 次\n输入 {_6} token · 输出 {_7} token": "Model: {_0}\nCompleted {_1} / {_2} pages · {_3} seconds\nTranslation responses: {_4} · Usage reported: {_5}\nInput: {_6} tokens · Output: {_7} tokens",
+ "任务已停止或有失败页面,不生成整本预估。": "The task stopped or some pages failed. A full-run estimate is unavailable.",
+ "部分响应未提供用量;以上 token 为已知部分,费用未知。": "Some responses did not report usage. Token counts above are partial; cost is unknown.",
+ "队列共 {_0} 页 · 粗估全量 {_1} 分钟 · {_2}": "Queue: {_0} pages · Rough full-run estimate: {_1} minutes · {_2}",
+ "仅统计翻译 API 返回的用量,包含重试响应,不含字体探测。费用按填写单价估算,缓存折扣等以服务商账单为准。整本预估基于样页平均值,受页面密度、上下文长度和并行度影响。": "Counts usage reported by the translation API, including retry responses, excluding font probes. Costs use your entered prices; provider billing determines cache discounts. Full-run estimates use sample averages and vary with page density, context length and concurrency.",
+ "部分文件无法读取,整本页数未知。": "Some files could not be read; the full page count is unknown.",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)": "Comic files (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)",
+ "视图": "View",
+ "视图与面板选项": "View & panel options",
+ "页面栏": "Pages panel",
+ "快捷字体栏": "Quick font bar",
+ "显示或隐藏画布上方的 1–9 快捷字体栏": "Show or hide the 1–9 quick font bar above the canvas",
+ "实际大小 (100%)": "Actual size (100%)",
+ "文件": "File",
+ "文件与导出操作": "File & export actions",
+ "关联原图…": "Link original…",
+ "背景填色与取色选项": "Background fill & color picking options",
+ "选择填充颜色…": "Choose fill color…",
+ "取色中 · 取消": "Picking · Cancel",
+ "点击退出图片取色,或按 Esc / 右键取消。": "Click to exit color picking, or press Esc / right-click.",
+ "当前气泡更多操作": "More actions for this bubble",
+ "字体管理": "Fonts",
+ "字体库、导入与快捷字体管理": "Font library, local import, and font shortcuts",
+ "字体库与本地字体导入": "Font library and local font import",
+ "字体库…": "Font library…",
+ "导入本地字体…": "Import local fonts…",
+ "将当前字体加入快捷字体": "Add current font to shortcuts",
+ "设置快捷字体…": "Font shortcuts…",
+ "高级样式(描边 · 变形)": "Outline & transform",
+ "高级样式 · 已自定义": "Outline & transform · Custom",
+ "用当前色填充 ({color})": "Fill with {color}",
+ "输出目录不存在或尚未生成。": "The output folder does not exist yet.",
+ "全屏编辑译文": "Full-screen translation editor",
+ "已导入或复用 {_0} 款字体。": "Imported or reused {_0} fonts.",
+ "未导入:{_0}": "Not imported: {_0}",
+ "管理": "Manage",
+ "管理快捷字体槽位与显示": "Manage quick font slots and visibility",
+ "隐藏快捷字体栏": "Hide quick font bar",
+ "任务": "Task",
+ "退出样式刷": "Exit brush",
+ "应用样式到所选气泡": "Apply style to selection",
+ "仅应用字体与排版;保留译文和位置,跳过已还原原图的气泡。": "Apply font and lettering only; keep text and positions, and skip bubbles restored to the original image.",
+ "选择漫画文件": "Select comic files",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf);;CBZ 文件 (*.cbz)": "Comics (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz);;Images (*.png *.jpg *.jpeg *.webp *.bmp);;PDF (*.pdf);;CBZ (*.cbz)",
+ "支持图片、PDF 与 CBZ": "Images, PDF, and CBZ",
+ "精修已生成的结果": "Edit translated results",
+ "请选择已完成且带精修资料的结果": "Select a completed result with editing data",
+ "把上次任务的全部结果加入嵌字精修列表": "Add all results from the last job to the editor",
+ "请先添加漫画文件": "Add comic files first",
+ "导出 CBZ": "Export CBZ",
+ "将已保存的图片按页面顺序打包为 CBZ。": "Package saved images into a CBZ in page order.",
+ "导入译图": "Import results",
+ "导入已翻译的漫画": "Import translated comics",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json)": "Comics (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json)",
+ "正在导出,请完成或取消后再切页或退出。": "Finish or cancel the export before switching pages or exiting.",
+ "正在后台导出 {_0}…": "Exporting {_0} in the background…",
+ "正在导出 {_0}:{_1}/{_2} 页": "Exporting {_0} · {_1}/{_2} pages",
+ "已导出 {_0}:{_1}": "Exported {_0} · {_1}",
+ "导出失败:{_0}。已保存的图片仍然保留。": "Export failed. Saved images were kept. ({_0})",
+ "已取消导出,已保存的图片仍然保留。": "Export cancelled. Saved images were kept.",
+ "导出 {_0}": "Export {_0}",
+ "全书译稿": "Book transcript",
+ "已保存 {_0} 页。替换暂停({_1})": "Saved {_0} pages. Replacement paused ({_1}).",
+ "已保存 {_0} 页的译文替换": "Saved replacements on {_0} pages",
+ "页面内容已更新,请重新预览替换": "The page changed. Preview the replacement again.",
+ "显示 {_0} 个气泡": "Showing {_0} bubbles",
+ "搜索原文或译文": "Search source or translation",
+ "替换为(留空即删除)": "Replace with (empty to remove)",
+ "预览替换": "Preview replacement",
+ "定位气泡": "Go to bubble",
+ "替换并保存": "Replace and save",
+ "正在读取全书译稿…": "Reading the book transcript…",
+ "将修改 {_0} 个气泡(仅匹配译文)": "{_0} bubbles will change (translation matches only)",
+ "{_0} 页缺少可读译稿": "No readable transcript on {_0} pages",
+ "页码与气泡": "Page and bubble",
+ "替换后": "After replacement",
+ "正在保存第 {_0}/{_1} 页…": "Saving page {_0}/{_1}…",
+ "重译气泡": "Retranslate",
+ "重译当前气泡": "Retranslate this bubble",
+ "校正 OCR 原文": "Correct OCR text",
+ "重译要求,如缩短对白或保留反讽": "Instructions, e.g. shorten the dialogue or keep the irony",
+ "请求重译": "Retranslate",
+ "当前译文": "Current translation",
+ "候选译文": "Suggested translation",
+ "应用候选译文": "Use suggested translation",
+ "正在请求单气泡重译…": "Retranslating this bubble…",
+ "重译失败:{_0}": "Retranslation failed ({_0})",
+ "已应用候选译文,保存后写入图片": "Suggested translation applied. Save to update the image.",
+ "翻译服务未返回可用译文": "The service returned no usable translation",
+ "CBZ 打包": "CBZ packaging",
+ "正在打包译文 CBZ · {_0}": "Packaging translated CBZ · {_0}",
+ "读取图片,或按页准备 PDF、CBZ 的原分辨率页图": "Reads images or prepares full-resolution PDF and CBZ pages on demand",
+ "写入译图、底图和布局,全部完成后生成译文 PDF 或 CBZ": "Saves each page and its editing data, then builds the translated PDF or CBZ",
+ "打包译文 CBZ": "Package translated CBZ",
+ "导入带布局数据的译稿,或从自动处理结果进入精修。": "Import translated pages with layout data or open results from the translation workspace.",
+ "CBZ 中没有可读取的漫画图片": "This CBZ contains no readable comic images",
+ "没有可导出的漫画页": "There are no comic pages to export",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json *.comitrans)": "Comics (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json *.comitrans)"
}
diff --git a/assets/i18n/ja.json b/assets/i18n/ja.json
index c95093a..42b6a79 100644
--- a/assets/i18n/ja.json
+++ b/assets/i18n/ja.json
@@ -1,4 +1,19 @@
{
+ "有更新": "更新あり",
+ "新版本 v{version} 可用,点击查看详情": "新しいバージョン v{version} が利用できます。更新の詳細を表示します。",
+ "检查更新失败:{reason}": "更新を確認できませんでした:{reason}",
+ "发布信息格式无效": "リリース情報の形式が正しくありません",
+ "发现 ComiTrans 新版本": "ComiTrans の新しいバージョン",
+ "当前版本 v{current},GitHub 已发布 v{latest}。": "現在のバージョンは v{current} です。GitHub で v{latest} が公開されました。",
+ "下载并更新": "ダウンロードして更新",
+ "下载完成后,ComiTrans 将请求关闭并通过 Windows 安装程序更新。": "ダウンロード後、ComiTrans を閉じるよう求められ、Windows インストーラーで更新します。",
+ "查看 GitHub 发布": "GitHub のリリースを表示",
+ "前往发布页下载安装": "リリースページからダウンロード",
+ "稍后提醒": "後で通知",
+ "正在下载并验证更新…": "更新のダウンロードと検証中…",
+ "取消": "キャンセル",
+ "更新 ComiTrans": "ComiTrans を更新",
+ "更新下载或验证失败。请在 GitHub 发布页重试。": "更新のダウンロードまたは署名の検証に失敗しました。GitHub のリリースページから再試行してください。",
"CUDA 加速": "CUDA 加速",
"检测器与修补说明": "検出器と修復の違い",
"CUDA 快速检测器在 GPU 上检测更快,能用笔画像素限定擦除范围。日漫样本中文字框覆盖较少,漏检处可能留字。\n\n轻量双图检测器在 CPU 上检测更快,日漫样本中文字框覆盖更全。它靠文字框和文字行定位,复杂底纹或描边仍可能漏擦。\n\n两套方案共用背景修补流程,主要区别在于擦除范围。": "高速 CUDA 検出器は GPU での検出が速く、文字の画素を使って消去範囲を絞ります。日本の漫画サンプルでは文字領域のカバー率が低く、検出漏れの文字が残ることがあります。\n\n軽量の二段階検出器は CPU での検出が速く、サンプルではより多くの文字領域をカバーしました。文字枠と行で位置を特定するため、複雑な背景や縁取り文字では一部が残ることがあります。\n\n背景の修復処理は共通で、主な違いは文字を消去する範囲です。",
@@ -412,7 +427,7 @@
"清空日志": "ログを消去",
"已清空页面列表。": "ページ一覧を消去しました。",
"源语言代码": "原文の言語コード",
- "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)": "漫画ファイル (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json *.comitrans)": "漫画ファイル (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json *.comitrans)",
"漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf)": "漫画ファイル (*.png *.jpg *.jpeg *.webp *.bmp *.pdf)",
"漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf)": "漫画ファイル (*.png *.jpg *.jpeg *.webp *.bmp *.pdf);;画像 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF ファイル (*.pdf)",
"漫画文件队列": "漫画ファイルのキュー",
@@ -778,5 +793,164 @@
"按阅读顺序调用翻译模型,结合前文上下文并缓存译文": "読み順で文脈を参照しながら翻訳し、キャッシュへ保存します",
"与翻译并行在独立线程生成擦字掩膜并修补背景": "翻訳と並列して別スレッドでマスク生成と背景修復を行います",
"翻译与修补汇合后,校对空译文并完成横竖排嵌字": "合流後に空訳を調整し、縦横の写植を描画します",
- "写入译图、清理底图与布局文件,全部完成后合成译文 PDF": "翻訳画像・背景画像・レイアウトを保存し、完了後に PDF を書き出します"
+ "写入译图、清理底图与布局文件,全部完成后合成译文 PDF": "翻訳画像・背景画像・レイアウトを保存し、完了後に PDF を書き出します",
+ "输出水印": "出力ウォーターマーク",
+ "便携 GPU 运行库": "ポータブル GPU ランタイム",
+ "手动安装步骤": "手動セットアップ手順",
+ "官方下载": "公式ダウンロード",
+ "喜欢这次翻译?": "今回の翻訳はいかがでしたか?",
+ "installer.Require64Bit": "ComiTrans には 64 ビット版 Windows が必要です。",
+ "installer.LegacyInstaller": "MSI 版の ComiTrans が見つかりました。Windows の設定から旧版をアンインストールしてから、このバージョンをインストールしてください。ユーザーデータは保持されます。",
+ "installer.NewerInstalled": "新しいバージョンの ComiTrans が既にインストールされています。",
+ "installer.KeepDirectory": "インストール先を変更するには、現在のバージョンを先にアンインストールしてください。ユーザーデータは保持されます。",
+ "installer.InvalidDirectory": "ローカルドライブの空のフォルダー、または現在の NSIS 版のインストール先を選択してください。ドライブのルートや Windows のシステムフォルダーは選択できません。",
+ "installer.CloseApplication": "ComiTrans を終了してから、インストールまたはアンインストールをやり直してください。",
+ "installer.ServiceError": "ComiTrans 更新確認サービスを設定できませんでした。インストールログを確認してください。",
+ "installer.InstallError": "インストールが完了しませんでした。空き容量とフォルダーのアクセス権を確認して、やり直してください。",
+ "installer.AlreadyRunning": "別の ComiTrans インストーラーまたはアンインストーラーが実行中です。",
+ "installer.InvalidUninstall": "このアンインストーラーは登録済みの ComiTrans と一致しません。Windows の設定からアンインストールしてください。",
+ "installer.DirectoryHelp": "インストール先を選択してください。ComiTrans サブフォルダーは自動作成されます。選択したフォルダー名が ComiTrans の場合は、そのフォルダーを使用します。",
+ "{_0} / {_1}": "{_0} / {_1}",
+ "不使用术语库": "用語集を使用しない",
+ "作品名称": "作品名",
+ "作品术语库": "作品用語集",
+ "保存失败": "保存に失敗しました",
+ "保存并关闭": "保存して閉じる",
+ "删除作品": "作品を削除",
+ "删除此作品的术语库?": "この作品の用語集を削除しますか?",
+ "删除选中词条": "選択した用語を削除",
+ "取样式": "書式を取得",
+ "固定译名": "指定訳語",
+ "填写单价以估算费用": "単価を入力して費用を概算",
+ "币种": "通貨",
+ "开始试译": "試訳を開始",
+ "撤销样式": "書式を元に戻す",
+ "新建作品": "作品を追加",
+ "未启用作品术语库": "作品用語集は未選択です",
+ "本次估算费用:{_0}": "今回の概算費用:{_0}",
+ "样式刷": "書式ブラシ",
+ "消耗": "使用量",
+ "添加词条": "用語を追加",
+ "类型(可选)": "種類(任意)",
+ "精修试译": "試訳を編集",
+ "翻译整本": "全体を翻訳",
+ "翻译消耗": "翻訳の使用量",
+ "识别线索(可选)": "照合の手がかり(任意)",
+ "试译": "試訳",
+ "试译完成": "試訳が完了しました",
+ "试译已结束": "試訳が終了しました",
+ "试译报告": "試訳レポート",
+ "试译结束,结果已单独保存。": "試訳が終了しました。結果は別に保存されています。",
+ "试译页数": "試訳ページ数",
+ "费用未知": "費用は不明です",
+ "输入 / 百万 token": "入力 / 100万トークン",
+ "输出 / 百万 token": "出力 / 100万トークン",
+ "当前作品:{_0} · {_1} 个译名 · AI 自动匹配": "作品:{_0} · 訳語 {_1} 件 · AI が自動照合",
+ "查看本次翻译 token 用量并设置估算单价": "翻訳トークンの使用量を確認し、概算用の単価を設定",
+ "先翻译队列开头的 1–3 页,查看效果和消耗": "キューの先頭1~3ページで仕上がりと使用量を確認",
+ "复制当前气泡的字体与排版样式,然后点击或框选目标气泡。": "現在の吹き出しのフォントと書式を取得し、対象をクリックまたは範囲選択します。",
+ "已取样式,点击或框选目标气泡;Esc 退出样式刷。": "書式を取得しました。対象をクリックまたは範囲選択してください。Esc でブラシを終了します。",
+ "已选 {_0} / {_1}": "選択 {_0} / {_1}",
+ "已选 {_0} 个气泡:排版修改应用到所选,译文和位置单独保留。": "吹き出し {_0} 個を選択中:書式の変更は選択全体に適用され、訳文と位置はそれぞれ保持されます。",
+ "点击目标应用样式;Shift 拖动框选,Ctrl 点击多选;Esc 退出。不会复制译文或气泡位置。": "クリックで書式を適用。Shift+ドラッグで範囲選択、Ctrl+クリックで複数選択、Esc で終了。訳文と吹き出しの位置は保持されます。",
+ "只填写固定译名即可,AI 会根据上下文自动匹配原文。类型和识别线索可帮助区分同名角色;不确定时不会强行套用。": "指定訳語だけを入力してください。AI が文脈から原文との対応を判断します。種類や手がかりで人物を区別でき、曖昧な場合は無理に適用しません。",
+ "试译当前队列开头的 1–3 页,PDF 按页面计数。试译结果单独保存,使用独立上下文,不占用正式任务的断点。": "キューの先頭1~3ページを試訳します。PDF はページ単位です。結果と文脈は別に保存され、本番タスクの再開データに影響しません。",
+ "模型:{_0}\n完成 {_1} / {_2} 页 · 用时 {_3} 秒\n翻译响应 {_4} 次 · 已报告用量 {_5} 次\n输入 {_6} token · 输出 {_7} token": "モデル:{_0}\n完了 {_1} / {_2} ページ · {_3} 秒\n翻訳応答 {_4} 回 · 使用量報告 {_5} 回\n入力 {_6} トークン · 出力 {_7} トークン",
+ "任务已停止或有失败页面,不生成整本预估。": "タスクが停止したか、失敗したページがあるため、全体の概算は表示しません。",
+ "部分响应未提供用量;以上 token 为已知部分,费用未知。": "一部の応答には使用量情報がありません。上記トークン数は判明分のみで、費用は不明です。",
+ "队列共 {_0} 页 · 粗估全量 {_1} 分钟 · {_2}": "全 {_0} ページ · 全体の目安 {_1} 分 · {_2}",
+ "仅统计翻译 API 返回的用量,包含重试响应,不含字体探测。费用按填写单价估算,缓存折扣等以服务商账单为准。整本预估基于样页平均值,受页面密度、上下文长度和并行度影响。": "翻訳 API が返す使用量を集計します。再試行の応答を含み、フォント判定は含みません。入力単価での概算であり、キャッシュ割引等は提供元の請求に従います。全体の予測はサンプルの平均値に基づき、ページ密度・文脈長・並列数によって変わります。",
+ "部分文件无法读取,整本页数未知。": "一部のファイルを読み込めないため、全体のページ数は不明です。",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)": "漫画ファイル (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)",
+ "视图": "表示",
+ "视图与面板选项": "表示とパネル設定",
+ "页面栏": "ページ一覧",
+ "快捷字体栏": "クイックフォントバー",
+ "显示或隐藏画布上方的 1–9 快捷字体栏": "キャンバス上部の 1–9 クイックフォントバーを表示/非表示",
+ "实际大小 (100%)": "実寸 (100%)",
+ "文件": "ファイル",
+ "文件与导出操作": "ファイルと書き出し操作",
+ "关联原图…": "元画像を関連付け…",
+ "背景填色与取色选项": "背景塗りつぶしと採色オプション",
+ "选择填充颜色…": "塗りつぶし色を選択…",
+ "取色中 · 取消": "採色中 · 解除",
+ "点击退出图片取色,或按 Esc / 右键取消。": "クリックで採色を終了、または Esc / 右クリックでキャンセル。",
+ "当前气泡更多操作": "この吹き出しの追加操作",
+ "字体管理": "フォント管理",
+ "字体库、导入与快捷字体管理": "フォント一覧・読込・キー設定",
+ "字体库与本地字体导入": "フォント一覧とローカル読込",
+ "字体库…": "フォント一覧…",
+ "导入本地字体…": "ローカルフォントを読込…",
+ "将当前字体加入快捷字体": "現在のフォントをキーに追加",
+ "设置快捷字体…": "フォントキー設定…",
+ "高级样式(描边 · 变形)": "詳細スタイル(縁取り・変形)",
+ "高级样式 · 已自定义": "詳細スタイル · 設定済み",
+ "用当前色填充 ({color})": "現在の色で塗る ({color})",
+ "输出目录不存在或尚未生成。": "出力フォルダーが存在しないか、まだ作成されていません。",
+ "全屏编辑译文": "全画面エディターで編集",
+ "已导入或复用 {_0} 款字体。": "{_0} 件のフォントを読み込みまたは再利用しました。",
+ "未导入:{_0}": "未読込:{_0}",
+ "管理": "管理",
+ "管理快捷字体槽位与显示": "クイックフォント枠と表示の管理",
+ "隐藏快捷字体栏": "クイックフォントバーを隠す",
+ "任务": "タスク",
+ "退出样式刷": "書式ブラシを終了",
+ "应用样式到所选气泡": "選択した吹き出しに書式を適用",
+ "仅应用字体与排版;保留译文和位置,跳过已还原原图的气泡。": "フォントと書式のみを適用します。訳文と位置は保持され、原画像に戻した吹き出しは対象外です。",
+ "选择漫画文件": "漫画ファイルを選択",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf);;CBZ 文件 (*.cbz)": "漫画 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz);;画像 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF (*.pdf);;CBZ (*.cbz)",
+ "支持图片、PDF 与 CBZ": "画像・PDF・CBZ に対応",
+ "精修已生成的结果": "翻訳結果を編集",
+ "请选择已完成且带精修资料的结果": "編集データがある完了済みの結果を選択",
+ "把上次任务的全部结果加入嵌字精修列表": "前回の結果をすべて写植エディターに追加",
+ "请先添加漫画文件": "先に漫画ファイルを追加してください",
+ "导出 CBZ": "CBZ を出力",
+ "将已保存的图片按页面顺序打包为 CBZ。": "保存済みの画像をページ順に CBZ にまとめます。",
+ "导入译图": "翻訳結果を読み込む",
+ "导入已翻译的漫画": "翻訳済みの漫画を読み込む",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json)": "漫画 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json)",
+ "正在导出,请完成或取消后再切页或退出。": "ページを切り替えたり終了したりするには、出力を完了するかキャンセルしてください。",
+ "正在后台导出 {_0}…": "バックグラウンドで {_0} を出力中…",
+ "正在导出 {_0}:{_1}/{_2} 页": "{_0} を出力中 · {_1}/{_2} ページ",
+ "已导出 {_0}:{_1}": "{_0} の出力が完了しました · {_1}",
+ "导出失败:{_0}。已保存的图片仍然保留。": "出力に失敗しました。保存済みの画像は保持されています。 ({_0})",
+ "已取消导出,已保存的图片仍然保留。": "出力をキャンセルしました。保存済みの画像は保持されています。",
+ "导出 {_0}": "{_0} を出力",
+ "全书译稿": "全巻の翻訳原稿",
+ "已保存 {_0} 页。替换暂停({_1})": "{_0} ページを保存しました。置換を中断しました({_1})。",
+ "已保存 {_0} 页的译文替换": "{_0} ページの置換を保存しました",
+ "页面内容已更新,请重新预览替换": "ページの内容が更新されました。もう一度置換をプレビューしてください。",
+ "显示 {_0} 个气泡": "吹き出し {_0} 件を表示中",
+ "搜索原文或译文": "原文または訳文を検索",
+ "替换为(留空即删除)": "置換後のテキスト(空欄は削除)",
+ "预览替换": "置換をプレビュー",
+ "定位气泡": "吹き出しへ移動",
+ "替换并保存": "置換して保存",
+ "正在读取全书译稿…": "全巻の翻訳原稿を読み込み中…",
+ "将修改 {_0} 个气泡(仅匹配译文)": "吹き出し {_0} 件を変更します(訳文のみ)",
+ "{_0} 页缺少可读译稿": "{_0} ページの翻訳原稿を読み込めません",
+ "页码与气泡": "ページと吹き出し",
+ "替换后": "置換後",
+ "正在保存第 {_0}/{_1} 页…": "{_0}/{_1} ページを保存中…",
+ "重译气泡": "再翻訳",
+ "重译当前气泡": "この吹き出しを再翻訳",
+ "校正 OCR 原文": "OCR の原文を修正",
+ "重译要求,如缩短对白或保留反讽": "再翻訳の指示(例:台詞を短くする、皮肉を残す)",
+ "请求重译": "再翻訳する",
+ "当前译文": "現在の訳文",
+ "候选译文": "訳文候補",
+ "应用候选译文": "訳文候補を適用",
+ "正在请求单气泡重译…": "吹き出しを再翻訳中…",
+ "重译失败:{_0}": "再翻訳に失敗しました({_0})",
+ "已应用候选译文,保存后写入图片": "訳文候補を適用しました。保存して画像を更新してください。",
+ "翻译服务未返回可用译文": "翻訳サービスから有効な訳文が返りませんでした",
+ "CBZ 打包": "CBZ に格納",
+ "正在打包译文 CBZ · {_0}": "翻訳済みの CBZ を作成中 · {_0}",
+ "读取图片,或按页准备 PDF、CBZ 的原分辨率页图": "画像の読み込み、または PDF・CBZ の原寸ページを順次準備します",
+ "写入译图、底图和布局,全部完成后生成译文 PDF 或 CBZ": "各ページと編集データを保存し、完了後に PDF または CBZ に出力します",
+ "打包译文 CBZ": "翻訳済み CBZ を作成",
+ "导入带布局数据的译稿,或从自动处理结果进入精修。": "レイアウトデータ付きの翻訳結果を読み込むか、自動処理の結果から編集を開始します。",
+ "CBZ 中没有可读取的漫画图片": "この CBZ に読み込める漫画画像がありません",
+ "没有可导出的漫画页": "出力できる漫画ページがありません",
+ "漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json *.comitrans)": "漫画 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json *.comitrans)"
}
diff --git a/assets/ui/icons/close.svg b/assets/ui/icons/close.svg
new file mode 100644
index 0000000..3d7bdc4
--- /dev/null
+++ b/assets/ui/icons/close.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/ui/icons/dark/close.svg b/assets/ui/icons/dark/close.svg
new file mode 100644
index 0000000..8a90d96
--- /dev/null
+++ b/assets/ui/icons/dark/close.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/ui/icons/dark/external-link.svg b/assets/ui/icons/dark/external-link.svg
new file mode 100644
index 0000000..b5b7aab
--- /dev/null
+++ b/assets/ui/icons/dark/external-link.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/ui/icons/dark/star.svg b/assets/ui/icons/dark/star.svg
new file mode 100644
index 0000000..1febc53
--- /dev/null
+++ b/assets/ui/icons/dark/star.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/ui/icons/external-link.svg b/assets/ui/icons/external-link.svg
new file mode 100644
index 0000000..ea7469d
--- /dev/null
+++ b/assets/ui/icons/external-link.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/assets/ui/icons/star.svg b/assets/ui/icons/star.svg
new file mode 100644
index 0000000..a0f48c3
--- /dev/null
+++ b/assets/ui/icons/star.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/build_app.ps1 b/build_app.ps1
index 4966d12..15abc73 100644
--- a/build_app.ps1
+++ b/build_app.ps1
@@ -38,4 +38,4 @@ if ($IncludeModels) {
Write-Host ""
Write-Host "打包完成: dist\ComiTrans\ComiTrans.exe"
-Write-Host "发布时只上传程序和模型两个包;GPU 运行库由软件内的官方安装链接提供,不打包上传。"
+Write-Host "生成 Windows Setup EXE 与 MSI:.\.venv\Scripts\python.exe installer/build.py"
diff --git a/comic-translate-ai/main/manga_lama.py b/comic-translate-ai/main/manga_lama.py
index 15a8086..f7e0be1 100644
--- a/comic-translate-ai/main/manga_lama.py
+++ b/comic-translate-ai/main/manga_lama.py
@@ -35,7 +35,7 @@ def __init__(self, model_path, device=None, cancel_callback=None):
raise ValueError("LaMa 仅支持 ONNX 模型: " + str(model_path))
def _load_onnx(self, model_path):
- from comic_translate_core.onnx_session import create_onnx_session
+ from comic_translate_core.image_session import create_image_session
path = Path(model_path).resolve()
stamp = path.stat()
@@ -45,7 +45,7 @@ def _load_onnx(self, model_path):
with _sessions_lock:
resource = _sessions.get(key)
if resource is None:
- session = create_onnx_session(path, self.device)
+ session = create_image_session(path, self.device)
resource = _SharedSession(session)
_sessions[key] = resource
self._session_resource = resource
diff --git a/comic-translate-ai/main/onnx_split_detector.py b/comic-translate-ai/main/onnx_split_detector.py
index 9c4d96a..d4581f0 100644
--- a/comic-translate-ai/main/onnx_split_detector.py
+++ b/comic-translate-ai/main/onnx_split_detector.py
@@ -8,7 +8,7 @@
from PIL import Image
from comic_translate_core.inference_control import run_inference
-from comic_translate_core.onnx_session import create_onnx_session
+from comic_translate_core.image_session import create_image_session
from comic_translate_core.detector_paths import LINE_FILE
from comic_text_detector.utils.textblock import TextBlock, sort_textblk_list
@@ -116,8 +116,8 @@ def seed_strokes(gray, seed, box, lines):
class SplitTextDetector:
def __init__(self, model_path, device, language):
- self.session = create_onnx_session(model_path, device)
- self.line_session = create_onnx_session(Path(model_path).with_name(LINE_FILE), device)
+ self.session = create_image_session(model_path, device)
+ self.line_session = create_image_session(Path(model_path).with_name(LINE_FILE), device)
self.right_to_left = language == "ja"
def __call__(self, image):
diff --git a/comic-translate-ai/main/onnx_text_detector.py b/comic-translate-ai/main/onnx_text_detector.py
index ff5b646..6ae6ed3 100644
--- a/comic-translate-ai/main/onnx_text_detector.py
+++ b/comic-translate-ai/main/onnx_text_detector.py
@@ -3,7 +3,7 @@
import cv2
import numpy as np
from comic_translate_core.inference_control import run_inference
-from comic_translate_core.onnx_session import create_onnx_session
+from comic_translate_core.image_session import create_image_session
from comic_text_detector.utils.db_utils import SegDetectorRepresenter
from comic_text_detector.utils.imgproc_utils import letterbox
@@ -122,7 +122,7 @@ def create_text_detector(model_path, device="cpu", language="ja", *, cuda_model_
class OnnxTextDetector:
def __init__(self, model_path: str, input_size: int = 1024, device: str = "cpu", conf_thresh: float = 0.4, nms_thresh: float = 0.35, mask_thresh: float = 0.3, *, require_cuda=False):
- self.session = create_onnx_session(model_path, device, require_cuda=True) if require_cuda else create_onnx_session(model_path, device)
+ self.session = create_image_session(model_path, device, require_cuda=require_cuda)
self.input_size = input_size if isinstance(input_size, tuple) else (input_size, input_size)
self.conf_thresh = conf_thresh
self.nms_thresh = nms_thresh
diff --git a/comic-translate-ai/requirements.txt b/comic-translate-ai/requirements.txt
index c1c8e67..305a583 100644
--- a/comic-translate-ai/requirements.txt
+++ b/comic-translate-ai/requirements.txt
@@ -14,3 +14,4 @@ jaconv>=0.3
fonttools>=4.50.0
opencc-python-reimplemented==0.1.7
jieba==0.42.1
+zstandard==0.25.0
diff --git a/comic_translate_core/gpu_install.py b/comic_translate_core/gpu_install.py
index 46db27f..6ed10b5 100644
--- a/comic_translate_core/gpu_install.py
+++ b/comic_translate_core/gpu_install.py
@@ -10,9 +10,13 @@
import requests
+from .windows_install import data_directory
+
def app_directory():
- return Path(sys.executable).resolve().parent if getattr(sys, 'frozen', False) else Path(__file__).resolve().parents[1]
+ if getattr(sys, 'frozen', False):
+ return data_directory(Path(sys.executable).resolve().parent)
+ return Path(__file__).resolve().parents[1]
def install(progress=print, *, root=None, canceled=lambda: False):
@@ -20,7 +24,7 @@ def install(progress=print, *, root=None, canceled=lambda: False):
manifest = (assets / 'gpu-runtime-windows.json').read_bytes()
packages = json.loads(manifest)
parent = (root or app_directory()) / 'gpu-runtime'
- parent.mkdir(exist_ok=True)
+ parent.mkdir(parents=True, exist_ok=True)
target = parent / 'nvidia-cu12-v1'
if target.exists():
if (target / 'manifest.json').read_bytes() == manifest and all((target / 'bin' / f).is_file() for f in REQUIRED):
diff --git a/comic_translate_core/gpu_runtime.py b/comic_translate_core/gpu_runtime.py
index 65f70ce..fa532ea 100644
--- a/comic_translate_core/gpu_runtime.py
+++ b/comic_translate_core/gpu_runtime.py
@@ -3,6 +3,8 @@
import sys
from pathlib import Path
+from .windows_install import data_directory
+
CUDA_DOWNLOAD_URL = 'https://developer.nvidia.com/cuda-12-8-1-download-archive'
CUDNN_DOWNLOAD_URL = 'https://developer.nvidia.com/cudnn-9-10-2-download-archive'
MSVC_DOWNLOAD_URL = 'https://aka.ms/vs/17/release/vc_redist.x64.exe'
@@ -14,7 +16,7 @@ def runtime_directories(environ=None):
env = os.environ if environ is None else environ
candidates = []
if getattr(sys, 'frozen', False):
- portable = Path(sys.executable).resolve().parent / 'gpu-runtime'
+ portable = data_directory(Path(sys.executable).resolve().parent) / 'gpu-runtime'
candidates.extend([portable / 'nvidia-cu12-v1/bin', portable / 'bin'])
for name in ('CUDA_PATH', 'CUDNN_PATH', *sorted(k for k in env if k.startswith('CUDA_PATH_V12_'))):
value = env.get(name, '').strip().strip('"')
diff --git a/comic_translate_core/image_session.py b/comic_translate_core/image_session.py
new file mode 100644
index 0000000..361684d
--- /dev/null
+++ b/comic_translate_core/image_session.py
@@ -0,0 +1,111 @@
+"""Keep desktop image-model sessions outside the Qt interpreter during loading."""
+import io
+import multiprocessing
+import os
+from contextlib import redirect_stdout
+from multiprocessing.managers import BaseManager
+from threading import Lock, Thread
+from types import SimpleNamespace
+
+from .onnx_session import create_onnx_session
+
+
+class _HostedSession:
+ """Lives in the helper. Only tensor data and model metadata cross the pipe."""
+
+ def __init__(self, path, device, require_cuda, options_factory):
+ with redirect_stdout(io.StringIO()) as startup_log:
+ self.session = _open(path, device, require_cuda, options_factory)
+ self.startup_log = startup_log.getvalue()
+
+ def describe(self):
+ def nodes(values):
+ return [SimpleNamespace(name=v.name, type=v.type, shape=v.shape) for v in values]
+ return (self.session.get_providers(), nodes(self.session.get_inputs()),
+ nodes(self.session.get_outputs()), self.startup_log)
+
+ def run(self, outputs, inputs):
+ return self.session.run(outputs, inputs)
+
+
+class _ModelHost(BaseManager):
+ pass
+
+
+_ModelHost.register('open_session', _HostedSession, exposed=('describe', 'run'))
+_host_lock = Lock()
+_host = None
+_desktop = False
+
+
+def enable_desktop_model_host():
+ global _desktop
+ _desktop = True
+
+
+def _watch_desktop():
+ # BaseManager shuts down on a normal exit. Also release VRAM if the
+ # desktop process is killed before its shutdown finalizers can run.
+ parent = multiprocessing.parent_process()
+
+ def watch():
+ parent.join()
+ os._exit(0)
+
+ Thread(target=watch, daemon=True).start()
+
+
+def _open(path, device, require_cuda, options_factory):
+ options = options_factory() if options_factory else None
+ return create_onnx_session(path, device, require_cuda=require_cuda, sess_options=options)
+
+
+class _ImageSession:
+ def __init__(self, path, device, require_cuda, options_factory):
+ self._settings = (str(path), device, require_cuda, options_factory)
+ self._reconnect_lock = Lock()
+ self._connect()
+
+ def _connect(self):
+ remote = _get_host().open_session(*self._settings)
+ self._providers, self._inputs, self._outputs, log = remote.describe()
+ self._remote = remote
+ if log:
+ print(log, end='')
+
+ def get_inputs(self):
+ return self._inputs
+
+ def get_outputs(self):
+ return self._outputs
+
+ def get_providers(self):
+ return self._providers
+
+ def run(self, outputs, inputs):
+ remote = self._remote
+ try:
+ return remote.run(outputs, inputs)
+ except (EOFError, ConnectionError, FileNotFoundError):
+ # Inference has no side effects. Recreate a lost helper session
+ # once, even when concurrent pages discover the disconnect.
+ with self._reconnect_lock:
+ if self._remote is remote:
+ self._connect()
+ return self._remote.run(outputs, inputs)
+
+
+def _get_host():
+ global _host
+ with _host_lock:
+ if _host is None or not _host._process.is_alive():
+ host = _ModelHost(ctx=multiprocessing.get_context('spawn'))
+ host.start(initializer=_watch_desktop)
+ _host = host
+ return _host
+
+
+def create_image_session(path, device='cpu', *, require_cuda=False, options_factory=None):
+ if _desktop:
+ return _ImageSession(path, device, require_cuda, options_factory)
+ return _open(path, device, require_cuda, options_factory)
diff --git a/comic_translate_core/onnx_charspot.py b/comic_translate_core/onnx_charspot.py
index 5fcc66c..9ad95d4 100644
--- a/comic_translate_core/onnx_charspot.py
+++ b/comic_translate_core/onnx_charspot.py
@@ -15,7 +15,7 @@
from PIL import Image
from .inference_control import run_inference
-from .onnx_session import create_onnx_session
+from .image_session import create_image_session
def preprocess(image):
@@ -41,6 +41,13 @@ def preprocess(image):
return np.ascontiguousarray(canvas.transpose(2, 0, 1)[None], dtype=np.float32)
+def _session_options():
+ options = ort.SessionOptions()
+ options.intra_op_num_threads = min(8, os.cpu_count() or 1)
+ options.inter_op_num_threads = 1
+ return options
+
+
class OnnxCharSpot:
def __init__(self, directory):
root = Path(directory)
@@ -53,10 +60,7 @@ def __init__(self, directory):
if len(chars) > config["n_cls"] or config["n_cls"] + len(combos) != config["n_out"]:
raise ValueError("Incompatible CharSpot vocabulary")
self.vocab = chars + [""] * (config["n_cls"] - len(chars)) + combos
- options = ort.SessionOptions()
- options.intra_op_num_threads = min(8, os.cpu_count() or 1)
- options.inter_op_num_threads = 1
- self.session = create_onnx_session(root / "model.onnx", "cpu", sess_options=options)
+ self.session = create_image_session(root / "model.onnx", "cpu", options_factory=_session_options)
if ([v.name for v in self.session.get_inputs()] != ["img"] or
[v.name for v in self.session.get_outputs()] != ["boxes", "scores", "ids", "order"]):
raise ValueError("Incompatible CharSpot ONNX interface")
diff --git a/comic_translate_core/release_update.py b/comic_translate_core/release_update.py
new file mode 100644
index 0000000..3c09c6a
--- /dev/null
+++ b/comic_translate_core/release_update.py
@@ -0,0 +1,214 @@
+"""Discover stable GitHub releases and prepare verified Windows installers."""
+
+from dataclasses import dataclass
+import hashlib
+import os
+from pathlib import Path
+import re
+import struct
+import subprocess
+import tempfile
+
+import requests
+
+
+REPOSITORY_URL = 'https://github.com/Aaaaamadeus/ComiTrans'
+RELEASE_API = 'https://api.github.com/repos/Aaaaamadeus/ComiTrans/releases/latest'
+SIGNPATH_ASSET_LABEL = 'SignPath Foundation signed'
+RESPONSE_LIMIT = 512 * 1024
+DELTA_LIMIT = 768 * 1024 * 1024
+DELTA_BLOCK_SIZE = 256 * 1024
+SETUP_DELTA_BLOCK_SIZE = 8 * 1024
+DELTA_OVERLAP = 1024 * 1024
+DELTA_FRAME = struct.Struct(' asset.size:
+ raise ValueError('Unexpected update size')
+ handle.write(chunk)
+ _check_asset(target, asset)
+
+
+def _expand_delta(delta, base, target, size, canceled, *, setup=False):
+ import zstandard as zstd
+
+ decoder = zstd.ZstdDecompressor()
+ block_size = SETUP_DELTA_BLOCK_SIZE if setup else DELTA_BLOCK_SIZE
+ with delta.open('rb') as source, base.open('rb') as previous, target.open('wb') as handle:
+ for offset in range(0, size, block_size):
+ if canceled():
+ raise InterruptedError('Update canceled')
+ header = source.read(DELTA_FRAME.size)
+ if len(header) != DELTA_FRAME.size:
+ raise ValueError('Incomplete update frame header')
+ frame_info, = DELTA_FRAME.unpack(header)
+ expected = min(block_size, size - offset)
+ if frame_info & DELTA_COPY:
+ previous.seek(frame_info ^ DELTA_COPY)
+ block = previous.read(expected)
+ else:
+ if not 0 < frame_info <= block_size + 65536:
+ raise ValueError('Unexpected update frame size')
+ frame = source.read(frame_info)
+ if len(frame) != frame_info or zstd.frame_content_size(frame) != expected:
+ raise ValueError('Unexpected expanded update size')
+ block = decoder.decompress(frame, allow_extra_data=False)
+ if len(block) != expected:
+ raise ValueError('Unexpected expanded update size')
+ handle.write(block)
+ if source.read(1):
+ raise ValueError('Unexpected data at the end of the update')
+
+
+SIGNATURE_CHECK = r"""
+$signature = Get-AuthenticodeSignature -LiteralPath $env:COMITRANS_INSTALL_PACKAGE
+if ($signature.Status -ne 'Valid' -or
+ $signature.SignerCertificate.GetNameInfo('SimpleName', $false) -ne 'SignPath Foundation') { exit 1 }
+"""
+
+
+def _powershell(command, package, **variables):
+ executable = Path(os.environ['SystemRoot']) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
+ env = dict(os.environ, COMITRANS_INSTALL_PACKAGE=str(package), **variables)
+ return subprocess.Popen([str(executable), '-NoProfile', '-NonInteractive', '-Command', command],
+ env=env, creationflags=subprocess.CREATE_NO_WINDOW)
+
+
+def prepare_update(release, current, cache, base, canceled):
+ installer = release.installer
+ if installer is None:
+ raise ValueError('Missing verified installer asset')
+ cache.mkdir(parents=True, exist_ok=True)
+ target = cache / installer_name(release.version, setup=release.setup)
+ with tempfile.TemporaryDirectory(dir=cache) as directory:
+ stage = Path(directory) / target.name
+ delta = release.delta
+ if delta and delta.size < installer.size <= DELTA_LIMIT and base:
+ import zstandard as zstd
+
+ try:
+ if base.stat().st_size > DELTA_LIMIT:
+ raise ValueError('Base installer exceeds delta size limit')
+ patch = Path(directory) / delta_name(current, release.version, setup=release.setup)
+ _download(delta, patch, canceled)
+ _expand_delta(patch, base, stage, installer.size, canceled, setup=release.setup)
+ _check_asset(stage, installer)
+ except InterruptedError:
+ raise
+ except (requests.RequestException, OSError, ValueError, zstd.ZstdError):
+ stage.unlink(missing_ok=True)
+ if not stage.is_file():
+ _download(installer, stage, canceled)
+ process = _powershell(SIGNATURE_CHECK, stage)
+ try:
+ if process.wait(timeout=30) != 0:
+ raise ValueError('Windows did not verify the SignPath Foundation signature')
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ raise ValueError('Windows signature verification timed out') from None
+ if canceled():
+ raise InterruptedError('Update canceled')
+ stage.replace(target)
+ return target
+
+
+def launch_update(package):
+ _powershell(r"""
+try {
+ Wait-Process -Id ([int]$env:COMITRANS_EXITING_PID) -Timeout 30 -ErrorAction Stop
+} catch {
+ if (Get-Process -Id ([int]$env:COMITRANS_EXITING_PID) -ErrorAction SilentlyContinue) { exit 1 }
+}
+try {
+ $stream = [IO.File]::Open($env:COMITRANS_INSTALL_PACKAGE, 'Open', 'Read', 'Read')
+""" + SIGNATURE_CHECK + r"""
+ $log = Join-Path (Split-Path -Parent $env:COMITRANS_INSTALL_PACKAGE) 'install.log'
+ $quotedLog = '"' + $log + '"'
+ if ([IO.Path]::GetExtension($env:COMITRANS_INSTALL_PACKAGE) -eq '.exe') {
+ $result = Start-Process -FilePath $env:COMITRANS_INSTALL_PACKAGE `
+ -ArgumentList '/quiet', '/norestart', '/log', $quotedLog -PassThru -Wait -ErrorAction Stop
+ } else {
+ $msi = '"' + $env:COMITRANS_INSTALL_PACKAGE + '"'
+ $result = Start-Process -FilePath (Join-Path $env:SystemRoot 'System32\msiexec.exe') -Verb RunAs `
+ -ArgumentList '/i', $msi, '/quiet', '/norestart', '/L*v', $quotedLog -PassThru -Wait -ErrorAction Stop
+ }
+ exit $result.ExitCode
+} finally {
+ if ($stream) { $stream.Dispose() }
+}
+""", package, COMITRANS_EXITING_PID=str(os.getpid()))
diff --git a/comic_translate_core/windows_install.py b/comic_translate_core/windows_install.py
new file mode 100644
index 0000000..f338358
--- /dev/null
+++ b/comic_translate_core/windows_install.py
@@ -0,0 +1,76 @@
+"""Locate a Windows installation without changing portable layouts."""
+
+from dataclasses import dataclass
+import os
+from pathlib import Path
+import sys
+
+
+INSTALL_KEY = r'Software\ComiTrans\Installer'
+
+
+@dataclass(frozen=True)
+class InstalledProduct:
+ code: str
+ setup: bool = False
+ setup_source: Path | None = None
+
+
+def installed_product(root):
+ if sys.platform != 'win32' or not getattr(sys, 'frozen', False):
+ return None
+ import winreg
+
+ try:
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, INSTALL_KEY, 0,
+ winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key:
+ directory, _ = winreg.QueryValueEx(key, 'InstallDir')
+ product, _ = winreg.QueryValueEx(key, 'ProductCode')
+ if Path(directory).resolve() != Path(root).resolve():
+ return None
+ try:
+ managed, _ = winreg.QueryValueEx(key, 'SetupManaged')
+ except FileNotFoundError:
+ return InstalledProduct(product)
+ if managed != '1':
+ return InstalledProduct(product)
+ try:
+ path = Path(winreg.QueryValueEx(key, 'SetupSource')[0])
+ if path.is_absolute() and path.suffix.lower() == '.exe':
+ return InstalledProduct(product, setup=True, setup_source=path)
+ except (OSError, TypeError, ValueError):
+ pass
+ return InstalledProduct(product, setup=True)
+ except (OSError, TypeError, ValueError):
+ pass
+ return None
+
+
+def data_directory(root):
+ local = Path(os.environ.get('LOCALAPPDATA', ''))
+ if local.is_absolute() and installed_product(root):
+ return local / 'ComiTrans'
+ return Path(root)
+
+
+def original_package(product):
+ """Find the original installer when still available for a delta update."""
+ if product.setup:
+ return product.setup_source
+
+ from ctypes import WinDLL, byref, create_unicode_buffer
+ from ctypes.wintypes import DWORD, LPCWSTR, LPWSTR, PDWORD
+
+ info = WinDLL('msi.dll').MsiGetProductInfoW
+ info.argtypes = (LPCWSTR, LPCWSTR, LPWSTR, PDWORD)
+ info.restype = DWORD
+
+ def read(name):
+ buffer = create_unicode_buffer(32768)
+ size = DWORD(len(buffer))
+ return buffer.value if info(product.code, name, buffer, byref(size)) == 0 else ''
+
+ source, name = Path(read('InstallSource')), read('PackageName')
+ if source.is_absolute() and name and Path(name).name == name:
+ return source / name
+ return None
diff --git a/comic_translate_desktop/__init__.py b/comic_translate_desktop/__init__.py
index 1ee6b39..5f29399 100644
--- a/comic_translate_desktop/__init__.py
+++ b/comic_translate_desktop/__init__.py
@@ -1,3 +1,3 @@
"""ComiTrans 本地桌面客户端。"""
-__version__ = "2.5.2"
+__version__ = "2.6.0"
diff --git a/comic_translate_desktop/bubble_translation.py b/comic_translate_desktop/bubble_translation.py
new file mode 100644
index 0000000..1c3992d
--- /dev/null
+++ b/comic_translate_desktop/bubble_translation.py
@@ -0,0 +1,47 @@
+"""Translate one selected bubble through the configured translation service."""
+from dataclasses import replace
+from types import SimpleNamespace
+
+from comic_translate_core.chinese import convert_chinese
+from comic_translate_core.errors import TaskCancelledError, TranslationError
+from comic_translate_core.languages import source_language_name
+from comic_translate_core.pipeline_settings import TranslationSettings
+from comic_translate_core.translation import TranslationClient
+from comic_translate_core.translation_format import ResponseFormatCapabilities
+
+from .i18n import tr
+
+
+_CAPABILITIES = ResponseFormatCapabilities()
+
+
+def retranslate_bubble(config, source_language, source, instruction, context,
+ original_path, box, cancelled):
+ from openai import OpenAI
+
+ def check_cancelled():
+ if cancelled():
+ raise TaskCancelledError()
+
+ check_cancelled()
+ settings = TranslationSettings.from_pipeline(SimpleNamespace(**config))
+ guidance = settings.translation_prompt or ''
+ if instruction.strip():
+ guidance = f'{guidance}\n\n【本次单气泡翻译要求】\n{instruction.strip()}'.strip()
+ image = None
+ if settings.multimodal and original_path is not None:
+ import numpy as np
+ from PIL import Image
+
+ with Image.open(original_path) as original:
+ image = np.asarray(original.crop(tuple(box)).convert('RGB'))[:, :, ::-1]
+ settings = replace(settings, translation_prompt=guidance, multimodal=image is not None,
+ source_language_name=source_language_name(
+ {**config, 'source_language': source_language}))
+ client = TranslationClient(settings, _CAPABILITIES, client_factory=OpenAI,
+ convert_text=convert_chinese, report_progress=lambda *_: None,
+ check_cancelled=check_cancelled, context_prompt=context)
+ candidate, = client.translate([source], image)
+ if not candidate.strip():
+ raise TranslationError(tr('翻译服务未返回可用译文'))
+ return candidate
diff --git a/comic_translate_desktop/cbz.py b/comic_translate_desktop/cbz.py
new file mode 100644
index 0000000..5ec31c3
--- /dev/null
+++ b/comic_translate_desktop/cbz.py
@@ -0,0 +1,108 @@
+"""Read comic archives in page order and package translated pages losslessly."""
+from pathlib import Path, PurePosixPath
+import os
+import re
+import tempfile
+from zipfile import ZipFile, ZIP_STORED
+
+from PIL import Image, ImageOps
+
+from .i18n import tr
+
+
+IMAGE_EXTS = frozenset(('.png', '.jpg', '.jpeg', '.webp', '.bmp'))
+PROJECT_EXTS = frozenset(('.pdf', '.cbz'))
+
+
+def _sort_member(member):
+ name = member.filename.replace('\\', '/')
+ parts = re.split(r'([0-9]+)', name.casefold())
+ return tuple(int(part) if index % 2 else part for index, part in enumerate(parts)), name
+
+
+class CbzReader:
+ def __init__(self, path):
+ self.path = Path(path)
+ self.archive = ZipFile(path)
+ try:
+ self.members = sorted(
+ (member for member in self.archive.infolist() if self._is_page(member)),
+ key=_sort_member)
+ if not self.members:
+ raise ValueError(tr('CBZ 中没有可读取的漫画图片'))
+ except Exception:
+ self.archive.close()
+ raise
+
+ @staticmethod
+ def _is_page(member):
+ path = PurePosixPath(member.filename.replace('\\', '/'))
+ return (not member.is_dir() and path.suffix.lower() in IMAGE_EXTS
+ and not any(part.startswith('.') or part == '__MACOSX' for part in path.parts))
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ self.close()
+
+ def close(self):
+ self.archive.close()
+
+ def page_sizes(self, cancel_callback):
+ sizes = []
+ for member in self.members:
+ cancel_callback()
+ with self.archive.open(member) as stream, Image.open(stream) as image:
+ width, height = image.size
+ if image.getexif().get(274) in (5, 6, 7, 8):
+ width, height = height, width
+ sizes.append((width * 72 / 200, height * 72 / 200))
+ return sizes
+
+ def render(self, index, destination, cancel_callback):
+ cancel_callback()
+ if destination.is_file():
+ try:
+ with Image.open(destination) as cached:
+ cached.verify()
+ return
+ except (OSError, ValueError, SyntaxError):
+ pass
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='.cbz-page-', dir=destination.parent) as directory:
+ staged = Path(directory) / destination.name
+ with self.archive.open(self.members[index]) as stream, Image.open(stream) as image:
+ ImageOps.exif_transpose(image).convert('RGB').save(staged)
+ cancel_callback()
+ os.replace(staged, destination)
+
+ def preview(self, size):
+ from PIL.ImageQt import ImageQt
+ with self.archive.open(self.members[0]) as stream, Image.open(stream) as image:
+ image = ImageOps.exif_transpose(image).convert('RGB')
+ image.thumbnail((size.width(), size.height()))
+ return ImageQt(image).copy()
+
+
+def render_cbz_preview(path, size):
+ with CbzReader(path) as archive:
+ return archive.preview(size)
+
+
+def build_cbz_from_images(images, output, *, progress_callback=lambda *_: None, cancel_callback=lambda: None):
+ output = Path(output)
+ if not images:
+ raise ValueError(tr('没有可导出的漫画页'))
+ output.parent.mkdir(parents=True, exist_ok=True)
+ digits = max(4, len(str(len(images))))
+ with tempfile.TemporaryDirectory(prefix='.cbz-export-', dir=output.parent) as directory:
+ staged = Path(directory) / output.name
+ with ZipFile(staged, 'w', compression=ZIP_STORED) as archive:
+ for number, image in enumerate(images, 1):
+ cancel_callback()
+ archive.write(image, f'page_{number:0{digits}d}{Path(image).suffix.lower()}')
+ progress_callback(number, len(images))
+ cancel_callback()
+ os.replace(staged, output)
+ return output
diff --git a/comic_translate_desktop/checkpoints.py b/comic_translate_desktop/checkpoints.py
index 4386c58..d2e4400 100644
--- a/comic_translate_desktop/checkpoints.py
+++ b/comic_translate_desktop/checkpoints.py
@@ -10,6 +10,7 @@
from PIL import Image
from comic_translate_core.translation_context import CONTEXT_VERSION
+from .productivity import desktop_translation_config
def _digest(value):
@@ -18,11 +19,14 @@ def _digest(value):
def _identity(source, config):
+ config = desktop_translation_config(config)
with source.open('rb') as stream:
source_hash = hashlib.file_digest(stream, 'sha256').hexdigest()
ignored = {'raw', 'api_key', 'max_workers', 'resume_enabled', 'use_gpu',
'retain_translation_context',
'ui_language', 'ui_language_selected', 'issue_url',
+ 'usage_pricing',
+ 'terminology_project', 'terminology_projects',
'page_input_dir', 'page_output_dir', 'page_test_output_dir'}
settings = {key: value for key, value in config.items()
if key not in ignored and not key.endswith(('_key', '_token', '_password'))}
diff --git a/comic_translate_desktop/config.py b/comic_translate_desktop/config.py
index 09eee4c..2ee50bc 100644
--- a/comic_translate_desktop/config.py
+++ b/comic_translate_desktop/config.py
@@ -9,6 +9,7 @@
from comic_translate_core.detector_paths import LEGACY_PATH, SPLIT_PATH, REGION_FILE, LINE_FILE
from comic_translate_core.chinese import normalize_target_language
from comic_translate_core.layout_options import normalize_text_color, normalize_vertical_alignment
+from comic_translate_core.windows_install import data_directory
from .i18n import normalize_ui_language
from comic_translate_core.languages import (
OCR_DEFAULTS, OCR_CONFIG_KEYS, effective_ocr_backend, source_language, validate_ocr_config,
@@ -16,15 +17,17 @@
if getattr(sys, "frozen", False):
- PROJECT_ROOT = Path(sys.executable).resolve().parent
- AI_ROOT = Path(getattr(sys, "_MEIPASS", PROJECT_ROOT)) / "comic-translate-ai"
+ INSTALL_ROOT = Path(sys.executable).resolve().parent
+ PROJECT_ROOT = data_directory(INSTALL_ROOT)
+ AI_ROOT = Path(getattr(sys, "_MEIPASS", INSTALL_ROOT)) / "comic-translate-ai"
else:
PROJECT_ROOT = Path(__file__).resolve().parents[1]
AI_ROOT = PROJECT_ROOT / "comic-translate-ai"
MAIN_DIR = AI_ROOT / "main"
MODELS_ROOT = PROJECT_ROOT / "comic-translate-ai" / "models"
+BUNDLED_MODELS_ROOT = AI_ROOT / "models" if getattr(sys, "frozen", False) else None
PAGE_BASE = PROJECT_ROOT if getattr(sys, "frozen", False) else AI_ROOT
-ICON_PATH = Path(getattr(sys, "_MEIPASS", PROJECT_ROOT)) / "assets" / "ComiTrans.ico" if getattr(sys, "frozen", False) else PROJECT_ROOT / "assets" / "ComiTrans.ico"
+ICON_PATH = Path(getattr(sys, "_MEIPASS", PROJECT_ROOT)) / "assets" / "ComiTrans.ico"
if getattr(sys, "frozen", False):
CONFIG_PATH = PROJECT_ROOT / "config.yaml"
DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "page" / "output_page_output"
@@ -112,7 +115,7 @@ def _clamped_int(value: Any, key: str) -> int:
return max(low, min(high, number))
-def _resolve_path(value: Any, default: str, base: Path | None = None) -> Path:
+def _resolve_path(value: Any, default: str | Path, base: Path | None = None) -> Path:
base = base or AI_ROOT
raw = str(value).strip() if value else ""
if not raw or raw in ("none", "None"):
@@ -125,6 +128,75 @@ def _resolve_path(value: Any, default: str, base: Path | None = None) -> Path:
return path
+def _resolve_model_path(value: Any, default: str | Path) -> Path:
+ """Resolve bundled models after an install moves, preserving custom paths."""
+ path = _resolve_path(value, default, base=MODELS_ROOT)
+ if BUNDLED_MODELS_ROOT is None:
+ return path
+ setting = Path(_clean_text(value))
+ if not setting.is_absolute() and (setting.parts[:1] == ('models',) or setting == LEGACY_PATH):
+ relative = setting if setting == LEGACY_PATH else Path(*setting.parts[1:])
+ if relative != Path('.') and '..' not in relative.parts:
+ bundled = BUNDLED_MODELS_ROOT / relative
+ if bundled.exists():
+ return bundled
+ if path.is_relative_to(MODELS_ROOT):
+ relative = path.relative_to(MODELS_ROOT)
+ else:
+ # Settings pages used to save absolute paths inside the old PyInstaller
+ # bundle. Recognize that layout without redirecting unrelated custom models.
+ parts = path.parts
+ marker = ('_internal', 'comic-translate-ai', 'models')
+ for index in range(len(parts) - 2):
+ if tuple(part.casefold() for part in parts[index:index + 3]) == marker:
+ relative = Path(*parts[index + 3:])
+ break
+ else:
+ return path
+ if relative == Path('.') or '..' in relative.parts:
+ return path
+ bundled = BUNDLED_MODELS_ROOT / relative
+ try:
+ if (not _clean_text(value) or not path.exists()) and bundled.exists():
+ return bundled
+ except OSError:
+ pass
+ return path
+
+
+def _model_path_setting(value: Any, default: str | Path) -> Any:
+ """Persist installed resources relative to the current application's AI root."""
+ text = _clean_text(value)
+ if not text or text.casefold() == 'auto':
+ return value
+ path = Path(text).expanduser()
+ if not path.is_absolute():
+ return path.as_posix()
+
+ def reference(relative):
+ # The historical "models/" spelling means automatic selection.
+ # Keep an explicit legacy detector selection explicit after serialization.
+ if Path(default) == SPLIT_PATH and relative == LEGACY_PATH:
+ return relative.as_posix()
+ return (Path('models') / relative).as_posix()
+
+ for root in (BUNDLED_MODELS_ROOT, AI_ROOT / 'models'):
+ if root is not None and path.is_relative_to(root):
+ relative = path.relative_to(root)
+ if relative != Path('.') and '..' not in relative.parts:
+ return reference(relative)
+ resolved = _resolve_model_path(value, default)
+ if BUNDLED_MODELS_ROOT is not None and resolved.is_relative_to(BUNDLED_MODELS_ROOT):
+ relative = resolved.relative_to(BUNDLED_MODELS_ROOT)
+ if relative != Path('.') and '..' not in relative.parts:
+ return reference(relative)
+ # Missing legacy defaults in the writable profile are still relative settings;
+ # user-selected external models keep their own paths.
+ if path == MODELS_ROOT / default and not path.exists():
+ return (Path('models') / default).as_posix()
+ return value
+
+
def load_ai_config() -> dict[str, Any]:
raw = load_yaml(CONFIG_PATH)
font_map = {}
@@ -155,7 +227,7 @@ def load_ai_config() -> dict[str, Any]:
use_gpu = bool(raw.get("use_gpu", True))
detector_setting = detector_model_setting(raw.get("detector_model"))
detector_path = _detector_path(detector_setting)
- legacy = MODELS_ROOT / LEGACY_PATH
+ legacy = _resolve_model_path(None, LEGACY_PATH)
cuda_detector = (legacy if use_gpu and detector_setting == "auto"
and detector_path != legacy and _model_file_exists(legacy) else None)
@@ -173,6 +245,9 @@ def load_ai_config() -> dict[str, Any]:
"text_color": normalize_text_color(raw.get("text_color")),
"translation_prompt": str(raw.get("translation_prompt") or ""),
"chinese_names": str(raw.get("chinese_names") or ""),
+ "terminology_project": str(raw.get("terminology_project") or ""),
+ "terminology_projects": raw.get("terminology_projects") if isinstance(raw.get("terminology_projects"), dict) else {},
+ "usage_pricing": raw.get("usage_pricing") if isinstance(raw.get("usage_pricing"), dict) else {},
"font_size": _clamped_int(raw.get("font_size"), "font_size"),
"multimodal": bool(raw.get("multimodal", False)),
# 实验开关:多模态下是否让 AI 参与字体族判别(默认关闭,见 docs/FONT_STYLE_STRATEGY.md §4.14)
@@ -195,13 +270,13 @@ def load_ai_config() -> dict[str, Any]:
"detector_model": str(detector_path),
"detector_model_setting": detector_setting,
"cuda_detector_model": str(cuda_detector) if cuda_detector else None,
- "lama_model": str(_resolve_path(raw.get("lama_model"), MODEL_DEFAULTS["lama_model"], base=MODELS_ROOT)),
+ "lama_model": str(_resolve_model_path(raw.get("lama_model"), MODEL_DEFAULTS["lama_model"])),
"ocr_backend": ocr_backend,
- "charspot_ocr_model": str(_resolve_path(raw.get("charspot_ocr_model"), MODEL_DEFAULTS["charspot_ocr_model"], base=MODELS_ROOT)),
- "ocr_model": str(_resolve_path(raw.get("ocr_model"), MODEL_DEFAULTS["ocr_model"], base=MODELS_ROOT)),
- "baberu_ocr_model": str(_resolve_path(raw.get("baberu_ocr_model"), MODEL_DEFAULTS["baberu_ocr_model"], base=MODELS_ROOT)),
- "korean_ocr_model": str(_resolve_path(raw.get("korean_ocr_model"), "ppocr/korean_PP-OCRv5_rec_mobile.onnx", base=MODELS_ROOT)),
- "english_ocr_model": str(_resolve_path(raw.get("english_ocr_model"), "ppocr/en_PP-OCRv5_rec_mobile.onnx", base=MODELS_ROOT)),
+ "charspot_ocr_model": str(_resolve_model_path(raw.get("charspot_ocr_model"), MODEL_DEFAULTS["charspot_ocr_model"])),
+ "ocr_model": str(_resolve_model_path(raw.get("ocr_model"), MODEL_DEFAULTS["ocr_model"])),
+ "baberu_ocr_model": str(_resolve_model_path(raw.get("baberu_ocr_model"), MODEL_DEFAULTS["baberu_ocr_model"])),
+ "korean_ocr_model": str(_resolve_model_path(raw.get("korean_ocr_model"), "ppocr/korean_PP-OCRv5_rec_mobile.onnx")),
+ "english_ocr_model": str(_resolve_model_path(raw.get("english_ocr_model"), "ppocr/en_PP-OCRv5_rec_mobile.onnx")),
"page_input_dir": str(_resolve_path(raw.get("page_input_dir"), "page/test", base=PAGE_BASE)),
"page_output_dir": str(_resolve_path(raw.get("page_output_dir"), "page/output_page_output", base=PAGE_BASE)),
"page_test_output_dir": str(_resolve_path(raw.get("page_test_output_dir"), "page/test_output", base=PAGE_BASE)),
@@ -214,6 +289,12 @@ def save_ai_config(updates: dict[str, Any]) -> dict[str, Any]:
for key, value in updates.items():
if value is not None:
raw[key] = value
+ defaults = {'detector_model': SPLIT_PATH, **MODEL_DEFAULTS,
+ 'korean_ocr_model': 'ppocr/korean_PP-OCRv5_rec_mobile.onnx',
+ 'english_ocr_model': 'ppocr/en_PP-OCRv5_rec_mobile.onnx'}
+ for key, default in defaults.items():
+ if key in raw:
+ raw[key] = _model_path_setting(raw[key], default)
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
yaml.safe_dump(raw, f, allow_unicode=True, sort_keys=False, default_flow_style=False)
@@ -286,20 +367,21 @@ def _model_file_exists(path):
def _detector_path(value):
setting = detector_model_setting(value)
if setting != "auto":
- return _resolve_path(setting, str(SPLIT_PATH), base=MODELS_ROOT)
- new = MODELS_ROOT / SPLIT_PATH
- old = MODELS_ROOT / LEGACY_PATH
- if not (_model_file_exists(new) and _model_file_exists(new.with_name(LINE_FILE))):
- if _model_file_exists(old):
- return old
- return new
+ return _resolve_model_path(setting, SPLIT_PATH)
+ for root in (BUNDLED_MODELS_ROOT, MODELS_ROOT):
+ if root is not None:
+ new = root / SPLIT_PATH
+ if _model_file_exists(new) and _model_file_exists(new.with_name(LINE_FILE)):
+ return new
+ old = _resolve_model_path(None, LEGACY_PATH)
+ return old if _model_file_exists(old) else _resolve_model_path(None, SPLIT_PATH)
def model_defaults() -> dict[str, str]:
"""Absolute built-in model locations, used for path reset and comparisons."""
return {
"detector_model": str(_detector_path(None)),
- **{key: str(_resolve_path(None, path, base=MODELS_ROOT))
+ **{key: str(_resolve_model_path(None, path))
for key, path in MODEL_DEFAULTS.items()},
}
@@ -329,7 +411,7 @@ def _check_model_paths(config: dict[str, Any], missing: list[str]) -> list[str]:
if not Path(config.get(key) or "").is_file():
missing.append(f"{key}: {config.get(key, '')}(请运行 scripts/download_ocr_models.py)")
return missing
- charspot_path = Path(config.get("charspot_ocr_model") or MODELS_ROOT / "charspot-small")
+ charspot_path = Path(config.get("charspot_ocr_model") or _resolve_model_path(None, "charspot-small"))
charspot_ok = all((charspot_path / name).is_file() for name in ("model.onnx", "config.json", "vocab.json"))
if backend == "charspot":
if not charspot_ok:
diff --git a/comic_translate_desktop/desktop_translation.py b/comic_translate_desktop/desktop_translation.py
new file mode 100644
index 0000000..d09a681
--- /dev/null
+++ b/comic_translate_desktop/desktop_translation.py
@@ -0,0 +1,46 @@
+"""Desktop instrumentation around the existing translation client, without model changes."""
+from types import SimpleNamespace
+
+from comic_translate_core.pipeline_settings import TranslationSettings
+from comic_translate_core.translation import TranslationClient
+from comic_translate_core.translation_context import TranslationContext
+from comic_translate_core.translation_format import ResponseFormatCapabilities
+
+
+def metered_client_factory(factory, meter):
+ def create_client(**kwargs):
+ client = factory(**kwargs)
+ class ClientProxy:
+ def __init__(self):
+ def create(**options):
+ response = client.chat.completions.create(**options)
+ if meter is not None:
+ meter.record(response)
+ return response
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=create))
+
+ def __getattr__(self, name):
+ return getattr(client, name)
+ return ClientProxy()
+ return create_client
+
+
+class DesktopTranslationMixin:
+ def translate_page_batch(self, ocr_texts, image_input):
+ from openai import OpenAI
+ from comic_translate_core.chinese import convert_chinese
+ if not hasattr(self, '_translation_capabilities'):
+ self._translation_capabilities = ResponseFormatCapabilities()
+ if not hasattr(self, 'translation_context'):
+ self.translation_context = TranslationContext()
+ settings = TranslationSettings.from_pipeline(self)
+ client = TranslationClient(
+ settings, self._translation_capabilities,
+ client_factory=metered_client_factory(OpenAI, getattr(self, 'usage_meter', None)),
+ convert_text=convert_chinese, report_progress=self._report_progress,
+ check_cancelled=self._check_cancelled,
+ context_prompt=self.translation_context.prompt(settings))
+ result = client.translate(ocr_texts, image_input)
+ if not getattr(self, 'translation_context_managed', False):
+ self.translation_context.record(None, ocr_texts, result, settings)
+ return result
diff --git a/comic_translate_desktop/editor_jobs.py b/comic_translate_desktop/editor_jobs.py
index f16f075..8376fd0 100644
--- a/comic_translate_desktop/editor_jobs.py
+++ b/comic_translate_desktop/editor_jobs.py
@@ -121,6 +121,39 @@ def read_page(path, settings=None, cancelled=lambda: False):
return PageData(preview, None, [], f'缺少或无法读取配套清理底图、布局:{exc}')
+@dataclass(frozen=True)
+class TranscriptEntry:
+ path: Path
+ label: str
+ index: int
+ source: str
+ translation: str
+ restored: bool
+
+
+def read_transcript(pages, current_path, current_items, cancelled):
+ entries, skipped = [], 0
+ for path, label in pages:
+ if cancelled():
+ break
+ if path == current_path:
+ items = current_items
+ else:
+ layout = path.parent.parent / f'{path.parent.name}_layout' / f'{path.stem}_layout.json'
+ try:
+ items = json.loads(layout.read_text(encoding='utf-8'))
+ if not isinstance(items, list):
+ raise ValueError('Expected layout items')
+ except (OSError, ValueError):
+ skipped += 1
+ continue
+ entries.extend(
+ TranscriptEntry(path, label, index, str(item.get('source_text') or ''),
+ str(item.get('text') or ''), bool(item.get('restore_original')))
+ for index, item in enumerate(items) if isinstance(item, dict))
+ return entries, skipped
+
+
def prepare_legacy_regions(data, settings):
legacy = [item for item in data.items if len(item.get('mask_box', [])) < 4]
if not legacy:
diff --git a/comic_translate_desktop/main.py b/comic_translate_desktop/main.py
index 71ca7c8..b2cf944 100644
--- a/comic_translate_desktop/main.py
+++ b/comic_translate_desktop/main.py
@@ -2,9 +2,11 @@
import sys
import argparse
+from pathlib import Path
from PySide6.QtWidgets import QApplication
+from . import __version__
from .i18n import initialize_ui_language
from .config import load_ai_config
from .ui.theme import apply_theme, install_ui_font
@@ -12,12 +14,19 @@
def main() -> int:
+ from comic_translate_core.image_session import enable_desktop_model_host
+
+ enable_desktop_model_host()
parser = argparse.ArgumentParser(description="ComiTrans desktop client")
+ parser.add_argument('project', type=Path, nargs='?', help='Open an editable .comitrans PDF project')
parser.add_argument("--smoke-test", metavar="OUTPUT_DIR", help="Verify startup/resources/models, write evidence, then exit")
parser.add_argument("--smoke-test-require-gpu", action="store_true", help="Fail smoke verification if CUDA is not actually active")
args = parser.parse_args()
- app = QApplication(sys.argv)
+ if args.project and args.project.suffix.lower() != '.comitrans':
+ parser.error('Expected a .comitrans PDF project')
+ app = QApplication(sys.argv[:1])
app.setApplicationName("ComiTrans")
+ app.setApplicationVersion(__version__)
app.setOrganizationName("ComiTrans")
app.setStyle("Fusion")
install_window_chrome(app)
@@ -31,6 +40,12 @@ def main() -> int:
from .ui.main_window import MainWindow
window = MainWindow()
window.show()
+ if args.project:
+ window.tabs.setCurrentWidget(window.editor_page)
+ window.editor_page.request_import([args.project])
+ from .ui.update_notice import UpdateNotice
+ update = UpdateNotice(window)
+ update.start()
return app.exec()
diff --git a/comic_translate_desktop/pdf_export.py b/comic_translate_desktop/pdf_export.py
index 15e218d..c41183d 100644
--- a/comic_translate_desktop/pdf_export.py
+++ b/comic_translate_desktop/pdf_export.py
@@ -1,5 +1,6 @@
-"""Explicit, cancellable image-to-PDF export; never runs on the UI thread."""
+"""Explicit, cancellable comic export; never runs on the UI thread."""
from PySide6.QtCore import QThread, Signal
+from .cbz import build_cbz_from_images
from .pdf_utils import build_pdf_from_images
@@ -24,8 +25,11 @@ def _check_cancel(self):
def run(self):
try:
- result = build_pdf_from_images(self.images, self.sizes, self.output,
- progress_callback=self.progress.emit, cancel_callback=self._check_cancel)
+ options = dict(progress_callback=self.progress.emit, cancel_callback=self._check_cancel)
+ if self.output.suffix.lower() == '.cbz':
+ result = build_cbz_from_images(self.images, self.output, **options)
+ else:
+ result = build_pdf_from_images(self.images, self.sizes, self.output, **options)
self.succeeded.emit(str(result))
except PdfExportCancelled:
self.cancelled.emit()
diff --git a/comic_translate_desktop/pdf_project.py b/comic_translate_desktop/pdf_project.py
index 4d74c4b..dbc70de 100644
--- a/comic_translate_desktop/pdf_project.py
+++ b/comic_translate_desktop/pdf_project.py
@@ -1,4 +1,4 @@
-"""Persistent PDF pages shared by the batch translator and the image editor."""
+"""Persistent comic pages shared by the batch translator and the image editor."""
from __future__ import annotations
import json
@@ -9,6 +9,7 @@
from dataclasses import dataclass
from pathlib import Path
+from .cbz import build_cbz_from_images
from .pdf_utils import PdfProcessingError, build_pdf_from_images
@@ -20,7 +21,12 @@ class PdfProject:
def project_link_path(pdf_path: str | Path) -> Path:
- return Path(pdf_path).with_suffix('.comitrans.json')
+ pdf = Path(pdf_path)
+ if pdf.suffix.lower() == '.cbz':
+ return pdf.with_name(pdf.name + '.comitrans.json')
+ link = pdf.with_suffix('.comitrans')
+ legacy = pdf.with_suffix('.comitrans.json')
+ return legacy if not link.exists() and legacy.is_file() else link
def create_pdf_project(pdf_path: Path) -> Path:
@@ -37,33 +43,33 @@ def write_project_metadata(directory: Path, source_name: str, page_sizes) -> Non
def read_project(directory: Path) -> PdfProject:
- """Only complete, editable generations can be published as a PDF."""
+ """Read a complete, editable generation."""
try:
data = json.loads((directory / 'project.json').read_text(encoding='utf-8'))
if not isinstance(data, dict) or data.get('version') != 1:
- raise ValueError('不支持的 PDF 精修数据版本')
+ raise ValueError('不支持的漫画精修数据版本')
raw_sizes = data.get('page_sizes_points')
if not isinstance(raw_sizes, list) or not raw_sizes:
- raise ValueError('PDF 精修数据没有页面')
+ raise ValueError('漫画精修数据没有页面')
sizes = []
images = []
for number, pair in enumerate(raw_sizes, 1):
if (not isinstance(pair, list) or len(pair) != 2
or any(type(value) not in (int, float) or not math.isfinite(value)
or value <= 0 for value in pair)):
- raise ValueError(f'PDF 第 {number} 页尺寸无效')
+ raise ValueError(f'漫画第 {number} 页尺寸无效')
stem = f'page_{number:04d}'
image = directory / 'translated' / f'{stem}.png'
required = (image, directory / 'translated_cleaned' / f'{stem}_cleaned.png',
directory / 'translated_layout' / f'{stem}_layout.json')
for path in required:
if not path.is_file():
- raise ValueError(f'PDF 第 {number} 页缺少精修文件:{path.name}')
+ raise ValueError(f'漫画第 {number} 页缺少精修文件:{path.name}')
sizes.append(tuple(pair))
images.append(image)
return PdfProject(directory, images, sizes)
except (OSError, ValueError, TypeError) as exc:
- raise PdfProcessingError(f'无法读取 PDF 精修数据:{exc}') from exc
+ raise PdfProcessingError(f'无法读取漫画精修数据:{exc}') from exc
def load_pdf_project(pdf_path: str | Path) -> PdfProject:
@@ -72,29 +78,36 @@ def load_pdf_project(pdf_path: str | Path) -> PdfProject:
try:
data = json.loads(link.read_text(encoding='utf-8'))
if not isinstance(data, dict) or data.get('version') != 1:
- raise ValueError('不支持的 PDF 精修索引版本')
+ raise ValueError('不支持的漫画精修索引版本')
relative = Path(data['project_dir'])
directory = (pdf_path.parent / relative).resolve()
if relative.is_absolute() or directory == pdf_path.parent or not directory.is_relative_to(pdf_path.parent):
- raise ValueError('PDF 精修目录必须位于 PDF 所在文件夹内')
+ raise ValueError('漫画精修目录必须位于译稿所在文件夹内')
return read_project(directory)
except (OSError, ValueError, TypeError, KeyError) as exc:
- raise PdfProcessingError(f'无法打开 PDF 精修资料(请保留同名 .comitrans.json 和配套目录):{exc}') from exc
+ raise PdfProcessingError(f'无法打开 漫画精修资料(请保留项目索引和配套目录):{exc}') from exc
def publish_pdf_project(pdf_path: Path, directory: Path) -> None:
- """Commit the PDF and its index together, rolling back on a write failure."""
- pdf_path = pdf_path.resolve()
+ publish_project(pdf_path, directory)
+
+
+def publish_project(output: Path, directory: Path, *, cancel_callback=None) -> None:
+ """Commit the comic and its editable index together."""
+ output = output.resolve()
project = read_project(directory)
- with tempfile.TemporaryDirectory(prefix='.pdf-publish-', dir=pdf_path.parent) as temporary:
+ with tempfile.TemporaryDirectory(prefix='.comic-publish-', dir=output.parent) as temporary:
staging = Path(temporary)
- staged_pdf = staging / pdf_path.name
- build_pdf_from_images(project.images, project.page_sizes, staged_pdf)
+ staged_output = staging / output.name
+ if output.suffix.lower() == '.cbz':
+ build_cbz_from_images(project.images, staged_output, cancel_callback=cancel_callback or (lambda: None))
+ else:
+ build_pdf_from_images(project.images, project.page_sizes, staged_output)
staged_link = staging / 'index.json'
staged_link.write_text(json.dumps({
- 'version': 1, 'project_dir': directory.relative_to(pdf_path.parent).as_posix(),
+ 'version': 1, 'project_dir': directory.relative_to(output.parent).as_posix(),
}, ensure_ascii=False, indent=2), encoding='utf-8')
- targets = [pdf_path, project_link_path(pdf_path)]
+ targets = [output, project_link_path(output)]
backups = []
for index, target in enumerate(targets):
backup = staging / f'backup-{index}'
@@ -105,7 +118,7 @@ def publish_pdf_project(pdf_path: Path, directory: Path) -> None:
backups.append(None)
committed = []
try:
- for index, (source, target) in enumerate(zip((staged_pdf, staged_link), targets)):
+ for index, (source, target) in enumerate(zip((staged_output, staged_link), targets)):
os.replace(source, target)
committed.append(index)
except Exception:
diff --git a/comic_translate_desktop/productivity.py b/comic_translate_desktop/productivity.py
new file mode 100644
index 0000000..9cbe4f9
--- /dev/null
+++ b/comic_translate_desktop/productivity.py
@@ -0,0 +1,140 @@
+"""Desktop workflow data: target-only terminology, lettering styles and usage."""
+from __future__ import annotations
+
+from copy import deepcopy
+import json
+import math
+from threading import RLock
+
+
+STYLE_DEFAULTS = dict(style='dialogue', font_reference=None, font_size=0, direction=-1,
+ text_effect='auto', text_color=None, vertical_alignment='center',
+ text_scale_x=1.0, text_scale_y=1.0, text_rotation=0.0,
+ outline_width=None)
+
+
+def lettering_style(item):
+ return {key: deepcopy(item.get(key, default)) for key, default in STYLE_DEFAULTS.items()}
+
+
+def apply_lettering_style(item, patch):
+ """Copy presentation only; source text, geometry and restored pixels are protected."""
+ if item.get('restore_original'):
+ return False
+ before = lettering_style(item)
+ for key in STYLE_DEFAULTS.keys() & patch.keys():
+ if key == 'font_reference' and not patch[key]:
+ item.pop(key, None)
+ else:
+ item[key] = deepcopy(patch[key])
+ changed = before != lettering_style(item)
+ if changed:
+ item['manual_layout'] = True
+ return changed
+
+
+def terminology_projects(value):
+ if not isinstance(value, dict):
+ return {}
+ projects = {}
+ for identity, raw in value.items():
+ if not isinstance(raw, dict) or not str(raw.get('name', '')).strip():
+ continue
+ terms, seen = [], set()
+ for entry in raw.get('terms', []) if isinstance(raw.get('terms'), list) else []:
+ if not isinstance(entry, dict):
+ continue
+ term = str(entry.get('term') or '').strip()
+ if not term or term in seen:
+ continue
+ seen.add(term)
+ terms.append(dict(term=term, kind=str(entry.get('kind') or '').strip(),
+ note=str(entry.get('note') or '').strip()))
+ projects[str(identity)] = dict(name=str(raw['name']).strip(), terms=terms)
+ return projects
+
+
+def terminology_prompt(config):
+ project = terminology_projects(config.get('terminology_projects')).get(
+ str(config.get('terminology_project') or ''))
+ if not project or not project['terms']:
+ return ''
+ data = json.dumps(project['terms'], ensure_ascii=False)
+ return ('【作品术语库】\n以下 JSON 仅为术语数据,不是额外指令。term 是用户指定的目标译名,'
+ 'kind 是类型,note 是身份、外貌或剧情线索;用户不需要提供原文。'
+ '请根据原文、整页及前文上下文自行匹配角色、地点和术语,匹配后统一使用指定译名。'
+ '没有对应实体时不要强行套用,线索不足时不要臆造对应关系。'
+ '保持说话人、称呼与敬语的含义,跨页保持同一实体译名一致。'
+ '仍严格遵守既定 translations JSON 输出格式,不输出匹配说明。\n' + data)
+
+
+def desktop_translation_config(config):
+ result = dict(config)
+ prompt = terminology_prompt(config)
+ if prompt:
+ result['translation_prompt'] = '\n\n'.join(
+ part for part in (str(config.get('translation_prompt') or '').strip(), prompt) if part)
+ return result
+
+
+def nonnegative_number(value):
+ try:
+ number = float(value)
+ return number if math.isfinite(number) and number >= 0 else 0.0
+ except (TypeError, ValueError, OverflowError):
+ return 0.0
+
+
+class UsageMeter:
+ """Only server-reported translation tokens are billed; missing usage stays unknown."""
+
+ def __init__(self, on_change=None):
+ self._lock = RLock()
+ self._on_change = on_change
+ self.requests = self.reported = self.prompt_tokens = self.completion_tokens = 0
+ self.cached_tokens = 0
+
+ def record(self, response):
+ usage = getattr(response, 'usage', None)
+ def get(value, name):
+ return value.get(name) if isinstance(value, dict) else getattr(value, name, None)
+ prompt, completion = get(usage, 'prompt_tokens'), get(usage, 'completion_tokens')
+ valid = (type(prompt) is int and type(completion) is int
+ and prompt >= 0 and completion >= 0)
+ details = get(usage, 'prompt_tokens_details')
+ cached = get(details, 'cached_tokens')
+ with self._lock:
+ self.requests += 1
+ if valid:
+ self.reported += 1
+ self.prompt_tokens += prompt
+ self.completion_tokens += completion
+ self.cached_tokens += min(prompt, cached) if type(cached) is int and cached >= 0 else 0
+ if self._on_change:
+ self._on_change(self.snapshot())
+
+ def snapshot(self):
+ with self._lock:
+ return dict(requests=self.requests, reported=self.reported,
+ prompt_tokens=self.prompt_tokens, completion_tokens=self.completion_tokens,
+ cached_tokens=self.cached_tokens)
+
+
+def usage_cost(usage, pricing):
+ if (not pricing.get('enabled') or not usage.get('requests')
+ or usage.get('reported') != usage.get('requests')):
+ return None
+ # Prices are explicitly entered per million tokens; no provider price is assumed.
+ return (usage['prompt_tokens'] * nonnegative_number(pricing.get('input'))
+ + usage['completion_tokens'] * nonnegative_number(pricing.get('output'))) / 1_000_000
+
+
+def trial_projection(report, pricing):
+ sampled, total = report.get('completed_pages', 0), report.get('total_pages', 0)
+ if (not sampled or report.get('cancelled') or report.get('failed')
+ or not report.get('total_pages_known', True)):
+ return None
+ ratio = total / sampled
+ cost = usage_cost(report.get('usage', {}), pricing)
+ return dict(seconds=nonnegative_number(report.get('processing_seconds')) * ratio,
+ cost=None if cost is None else cost * ratio)
diff --git a/comic_translate_desktop/smoke_test.py b/comic_translate_desktop/smoke_test.py
index cb190c0..c878fb3 100644
--- a/comic_translate_desktop/smoke_test.py
+++ b/comic_translate_desktop/smoke_test.py
@@ -19,7 +19,7 @@
from .ui.language_dialog import InterfaceLanguageDialog
from .ui.gpu_setup_dialog import GpuSetupDialog
from .ui.star_prompt import STAR_PROMPT_PROBABILITY, STAR_PROMPT_IDLE_MS
-from .ui.theme import install_ui_font
+from .ui.theme import install_ui_font, log_font
from comic_translate_core.chinese import convert_chinese
@@ -34,6 +34,22 @@ def run_smoke_test(app, output_dir, *, require_gpu=False):
QSettings.setDefaultFormat(QSettings.IniFormat)
QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, str(output / "settings"))
config.save_ai_config({'use_gpu': require_gpu})
+ defaults = config.load_ai_config()
+ # Reproduce a retained profile from a removed installation. No user settings
+ # or credentials are copied into the release verification directory.
+ relocated = {}
+ if config.BUNDLED_MODELS_ROOT is not None:
+ old_models = output / 'removed-install/_internal/comic-translate-ai/models'
+ relatives = {**config.MODEL_DEFAULTS,
+ 'korean_ocr_model': 'ppocr/korean_PP-OCRv5_rec_mobile.onnx',
+ 'english_ocr_model': 'ppocr/en_PP-OCRv5_rec_mobile.onnx'}
+ relocated = {key: str(old_models / relative) for key, relative in relatives.items()
+ if (config.BUNDLED_MODELS_ROOT / relative).exists()}
+ # Write the stale profile directly so load_ai_config itself must recover it.
+ import yaml
+ raw = config.load_yaml(config.CONFIG_PATH)
+ raw.update(relocated)
+ config.CONFIG_PATH.write_text(yaml.safe_dump(raw), encoding='utf-8')
window = MainWindow()
window.setAttribute(Qt.WA_DontShowOnScreen, True)
window.show()
@@ -41,6 +57,7 @@ def run_smoke_test(app, output_dir, *, require_gpu=False):
# verification explicitly requests it so the complete model stack is tested.
window._start_warmup()
result = {"version": __version__, "frozen": bool(getattr(sys, "frozen", False))}
+ result['relocated_models_recovered'] = all(window.config[key] == defaults[key] for key in relocated)
def finish():
if window.warmup_worker is not None:
@@ -231,7 +248,7 @@ def finish():
result["translation_https_client"] = True
result["success"] = all((result['jpeg_paper_fill'], result['white_box_fallback'], result["translation_https_client"], result["pipeline_ready"], result["svg_valid"], result["window_visible"],
result["screenshot_saved"], result["brand_font"] == "Skribble",
- result["log_font"] == "Aa今日花晴 春懒猫困", not result["missing_glyphs"],
+ result["log_font"] == QFontInfo(log_font()).family(), not result["missing_glyphs"],
result['font_imported'], result['font_choice_persisted'], result['font_pipeline_updated'],
result['font_models_reused'], result['font_editor_updated'],
result['catalog_families'] == 2056, result['font_search_enabled'],
@@ -247,7 +264,7 @@ def finish():
value for name, value in result.items()
if name.startswith(('en_', 'ja_', 'onboarding_')) or name == 'star_prompt_behavior')
result['success'] = result['success'] and all(result.get(key, False) for key in (
- 'real_detection_and_ocr', 'native_repair_pixels', 'no_torch_import'))
+ 'real_detection_and_ocr', 'native_repair_pixels', 'no_torch_import', 'relocated_models_recovered'))
if require_gpu:
result['success'] = result['success'] and result.get('gpu_active', False)
except Exception as exc:
diff --git a/comic_translate_desktop/ui/advanced_config.py b/comic_translate_desktop/ui/advanced_config.py
index 2e65db0..c0001d8 100644
--- a/comic_translate_desktop/ui/advanced_config.py
+++ b/comic_translate_desktop/ui/advanced_config.py
@@ -7,6 +7,7 @@
from PySide6.QtWidgets import (
QFileDialog,
QFormLayout,
+ QFrame,
QGridLayout,
QGroupBox,
QHBoxLayout,
@@ -30,13 +31,14 @@ def __init__(self, config: dict, parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(10)
+ layout.setSpacing(14)
performance = QGroupBox(tr('性能与渲染'))
+ performance.setProperty('card', True)
performance_grid = QGridLayout(performance)
- performance_grid.setContentsMargins(0, 0, 0, 0)
- performance_grid.setHorizontalSpacing(24)
- performance_grid.setVerticalSpacing(10)
+ performance_grid.setContentsMargins(0, 4, 0, 0)
+ performance_grid.setHorizontalSpacing(20)
+ performance_grid.setVerticalSpacing(12)
self._workers = self._spin('max_workers')
self._workers.setToolTip(tr(
'同时在途准备、翻译与修补的页数(1–16,默认 4)。数值越大吞吐越高,'
@@ -71,9 +73,10 @@ def __init__(self, config: dict, parent=None):
layout.addWidget(performance)
models = QGroupBox(tr('模型文件'))
+ models.setProperty('card', True)
models_form = QFormLayout(models)
self._style_form(models_form)
- models_form.setVerticalSpacing(8)
+ models_form.setVerticalSpacing(10)
self._path_fields: dict[str, QLineEdit] = {}
self._browse_buttons: dict[str, QPushButton] = {}
for key, label in (
@@ -88,25 +91,31 @@ def __init__(self, config: dict, parent=None):
field.setAccessibleName(tr(label))
field.editingFinished.connect(self._refresh_model_status)
button = QPushButton(tr('浏览...'))
+ button.setProperty('role', 'utility')
button.setProperty('compact', True)
button.clicked.connect(
lambda _checked=False, target=field, name=key: self._browse_model(target, name))
row = QHBoxLayout()
+ row.setSpacing(8)
row.addWidget(field, 1)
row.addWidget(button)
models_form.addRow(tr(label), row)
self._path_fields[key] = field
self._browse_buttons[key] = button
self._model_status = QLabel()
+ self._model_status.setObjectName('statusCallout')
self._model_status.setWordWrap(True)
- self._model_status.setProperty('muted', True)
self._model_status.setTextInteractionFlags(Qt.TextSelectableByMouse)
models_form.addRow(tr('模型检查'), self._model_status)
layout.addWidget(models)
- defaults_row = QHBoxLayout()
- defaults_row.setSpacing(12)
+ defaults_card = QFrame()
+ defaults_card.setObjectName('settingsCard')
+ defaults_row = QHBoxLayout(defaults_card)
+ defaults_row.setContentsMargins(20, 14, 20, 14)
+ defaults_row.setSpacing(14)
self._reset_btn = QPushButton(tr('恢复推荐默认值'))
+ self._reset_btn.setProperty('role', 'utility')
self._reset_btn.setProperty('compact', True)
self._reset_btn.setToolTip(tr('只恢复本页字段,点击「保存配置」后才会写入。'))
self._reset_btn.clicked.connect(self.reset_to_defaults)
@@ -118,7 +127,7 @@ def __init__(self, config: dict, parent=None):
location.setTextInteractionFlags(Qt.TextSelectableByMouse)
location.setToolTip(str(app_config.CONFIG_PATH))
defaults_row.addWidget(location, 1)
- layout.addLayout(defaults_row)
+ layout.addWidget(defaults_card)
layout.addStretch(1)
self.load_config(config)
@@ -127,8 +136,8 @@ def _style_form(form: QFormLayout) -> None:
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
form.setRowWrapPolicy(QFormLayout.WrapLongRows)
- form.setHorizontalSpacing(24)
- form.setVerticalSpacing(14)
+ form.setHorizontalSpacing(22)
+ form.setVerticalSpacing(12)
@staticmethod
def _spin(key: str) -> QSpinBox:
@@ -197,7 +206,7 @@ def reset_to_defaults(self) -> None:
def _model_path(key, value):
if key == 'detector_model':
return app_config._detector_path(value)
- return app_config._resolve_path(value, app_config.MODEL_DEFAULTS[key], app_config.MODELS_ROOT)
+ return app_config._resolve_model_path(value, app_config.MODEL_DEFAULTS[key])
def _refresh_model_status(self) -> None:
existing = 0
diff --git a/comic_translate_desktop/ui/api_config_page.py b/comic_translate_desktop/ui/api_config_page.py
index b3dca06..2036381 100644
--- a/comic_translate_desktop/ui/api_config_page.py
+++ b/comic_translate_desktop/ui/api_config_page.py
@@ -1,8 +1,9 @@
from __future__ import annotations
+
from pathlib import Path
-from ..i18n import tr
from PySide6.QtCore import Qt, Signal
+from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
@@ -10,7 +11,6 @@
QFileDialog,
QFormLayout,
QFrame,
- QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
@@ -22,13 +22,13 @@
QWidget,
)
-from ..config import mask_api_key
-from ..i18n import UI_LANGUAGES
from comic_translate_core.languages import SOURCE_LANGUAGES
+from ..config import mask_api_key
+from ..i18n import UI_LANGUAGES, tr
from .advanced_config import AdvancedConfigSection
from .manga_components import PanelHeading
from .motion import install_tab_motion, set_reduced_motion
-from .theme import apply_theme
+from .theme import apply_theme, set_themed_icon, ui_font
class ApiConfigPage(QWidget):
@@ -43,22 +43,24 @@ def __init__(self, config: dict, parent=None):
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
body = QFrame()
- body.setObjectName('pageBody')
+ body.setObjectName('settingsBody')
body_layout = QVBoxLayout(body)
- body_layout.setContentsMargins(24, 16, 24, 12)
+ body_layout.setContentsMargins(24, 14, 24, 0)
+ body_layout.setSpacing(0)
self._sections = QTabWidget()
self._sections.setDocumentMode(True)
self._sections.setAccessibleName(tr('设置分类'))
install_tab_motion(self._sections)
body_layout.addWidget(self._sections)
outer.addWidget(body, 1)
+
root = self._add_section(tr('01 翻译服务'), tr('连接你的翻译服务'), tr('配置接口、翻译方式和输出水印,保存后将在下一次任务生效。'))
ocr_root = self._add_section(tr('02 文字识别'), tr('选择语言与识别方式'), tr('本地识别和自定义 OCR 均在这里配置。'))
runtime_root = self._add_section(tr('03 运行与输出'), tr('安排输出与运行选项'), tr('设置默认保存位置和硬件加速。'))
advanced_root = self._add_section(tr('04 详细配置'), tr('微调运行与模型细节'), tr('原先需要手动编辑 config.yaml 的选项集中在这里,保存后下一次任务生效。'))
- api_group = QGroupBox(tr('翻译服务'))
- api_form = QFormLayout(api_group)
+ api_card, api_layout = self._make_card('翻译服务')
+ api_form = QFormLayout()
self._style_form(api_form)
self._key_input = QLineEdit()
@@ -68,6 +70,7 @@ def __init__(self, config: dict, parent=None):
self._show_key_check = QCheckBox(tr('显示密钥'))
self._show_key_check.toggled.connect(self._toggle_key_visibility)
key_row = QHBoxLayout()
+ key_row.setSpacing(10)
key_row.addWidget(self._key_input, 1)
key_row.addWidget(self._show_key_check)
@@ -95,12 +98,20 @@ def __init__(self, config: dict, parent=None):
api_form.addRow(tr('多模态'), self._multimodal_check)
api_form.addRow(tr('字体判别'), self._font_probe_check)
api_form.addRow(tr('思考模式'), self._no_thinking_check)
- root.addWidget(api_group)
+ api_layout.addLayout(api_form)
+ root.addWidget(api_card)
+
+ watermark_card, watermark_layout = self._make_card(
+ '输出水印',
+ '在输出图片和 PDF 每页右下角添加小号半透明字标,精修保存时同样生效。取消勾选并保存可关闭。',
+ )
self._watermark_check = QCheckBox(tr('添加 @ComiTrans 水印(默认开启)'))
self._watermark_check.setToolTip(tr('在输出图片和 PDF 每页右下角添加小号半透明字标,精修保存时同样生效。取消勾选并保存可关闭。'))
- root.addWidget(self._watermark_check)
- interface_group = QGroupBox(tr('界面语言'))
- interface_form = QFormLayout(interface_group)
+ watermark_layout.addWidget(self._watermark_check)
+ root.addWidget(watermark_card)
+
+ interface_card, interface_layout = self._make_card('界面语言')
+ interface_form = QFormLayout()
self._style_form(interface_form)
self._ui_language = QComboBox()
self._ui_language.setAccessibleName(tr('界面语言'))
@@ -110,17 +121,32 @@ def __init__(self, config: dict, parent=None):
interface_note = QLabel(tr('保存后下次启动生效,不影响漫画译文语言。'))
interface_note.setWordWrap(True)
interface_note.setProperty('muted', True)
- interface_form.addRow(tr(interface_note))
- root.insertWidget(0, interface_group)
+ interface_layout.addLayout(interface_form)
+ interface_layout.addWidget(interface_note)
+ root.addWidget(interface_card)
root.addStretch(1)
- runtime_group = QGroupBox(tr('运行设置'))
- runtime_form = QFormLayout(runtime_group)
+ runtime_card, runtime_layout = self._make_card('运行设置')
+ runtime_form = QFormLayout()
self._style_form(runtime_form)
self._gpu_check = QCheckBox(tr('使用 GPU(需要本机 CUDA 可用)'))
self._gpu_help = QPushButton(tr('GPU 安装说明与下载'))
+ self._gpu_help.setProperty('role', 'utility')
+ self._gpu_help.setProperty('compact', True)
+ self._gpu_help.setCursor(Qt.PointingHandCursor)
+ set_themed_icon(self._gpu_help, 'external-link', size=13)
self._gpu_help.clicked.connect(self._show_gpu_setup)
+ gpu_col = QVBoxLayout()
+ gpu_col.setContentsMargins(0, 0, 0, 0)
+ gpu_col.setSpacing(8)
+ gpu_col.addWidget(self._gpu_check)
+ gpu_btn_row = QHBoxLayout()
+ gpu_btn_row.setContentsMargins(0, 0, 0, 0)
+ gpu_btn_row.addWidget(self._gpu_help)
+ gpu_btn_row.addStretch(1)
+ gpu_col.addLayout(gpu_btn_row)
+
self._ocr_backend = QComboBox()
self._source_language = QComboBox()
for code, label in SOURCE_LANGUAGES:
@@ -130,8 +156,11 @@ def __init__(self, config: dict, parent=None):
self._output_input = QLineEdit()
browse_btn = QPushButton(tr('浏览...'))
+ browse_btn.setProperty('role', 'utility')
+ browse_btn.setProperty('compact', True)
browse_btn.clicked.connect(self._browse_output)
output_row = QHBoxLayout()
+ output_row.setSpacing(8)
output_row.addWidget(self._output_input, 1)
output_row.addWidget(browse_btn)
@@ -139,16 +168,19 @@ def __init__(self, config: dict, parent=None):
self._issue_input.setPlaceholderText(tr('https://github.com/你的用户名/ComiTrans/issues'))
self._model_info = QLabel()
+ self._model_info.setObjectName('statusCallout')
+ self._model_info.setFont(ui_font(12, mono=True))
self._model_info.setWordWrap(True)
- self._model_info.setProperty("muted", True)
+ self._model_info.setTextInteractionFlags(Qt.TextSelectableByMouse)
- runtime_form.addRow(tr('硬件'), self._gpu_check)
- runtime_form.addRow('', self._gpu_help)
+ runtime_form.addRow(tr('硬件'), gpu_col)
runtime_form.addRow(tr('输出目录'), output_row)
runtime_form.addRow(tr('Issue 链接'), self._issue_input)
- runtime_root.addWidget(runtime_group)
- appearance_group = QGroupBox(tr('外观'))
- appearance_form = QFormLayout(appearance_group)
+ runtime_layout.addLayout(runtime_form)
+ runtime_root.addWidget(runtime_card)
+
+ appearance_card, appearance_layout = self._make_card('外观')
+ appearance_form = QFormLayout()
self._style_form(appearance_form)
self._theme = QComboBox()
self._theme.setAccessibleName(tr('界面主题'))
@@ -165,46 +197,52 @@ def __init__(self, config: dict, parent=None):
appearance_note = QLabel(tr('跟随系统会随 Windows 深浅色自动切换。'))
appearance_note.setWordWrap(True)
appearance_note.setProperty('muted', True)
- appearance_form.addRow(tr(appearance_note))
- runtime_root.addWidget(appearance_group)
+ appearance_layout.addLayout(appearance_form)
+ appearance_layout.addWidget(appearance_note)
+ runtime_root.addWidget(appearance_card)
runtime_root.addStretch(1)
- ocr_group = QGroupBox(tr('语言与引擎'))
- ocr_form = QFormLayout(ocr_group)
+
+ ocr_card, ocr_layout = self._make_card('语言与引擎')
+ ocr_form = QFormLayout()
self._style_form(ocr_form)
ocr_form.addRow(tr('原文语言'), self._source_language)
ocr_form.addRow(tr('OCR 引擎'), self._ocr_backend)
ocr_form.addRow(tr('本地模型'), self._model_info)
- self._model_info.setTextInteractionFlags(Qt.TextSelectableByMouse)
- ocr_root.addWidget(ocr_group)
+ ocr_layout.addLayout(ocr_form)
+ ocr_root.addWidget(ocr_card)
- self._ppocr_group = QGroupBox(tr('韩语 / 英语本地 OCR'))
- ppocr_form = QFormLayout(self._ppocr_group)
+ self._ppocr_group, ppocr_layout = self._make_card('韩语 / 英语本地 OCR')
+ ppocr_form = QFormLayout()
self._style_form(ppocr_form)
self._korean_model = QLineEdit()
self._english_model = QLineEdit()
for label, field in ((tr('韩语模型'), self._korean_model), (tr('英语模型'), self._english_model)):
row = QHBoxLayout()
+ row.setSpacing(8)
button = QPushButton(tr('浏览...'))
+ button.setProperty('role', 'utility')
+ button.setProperty('compact', True)
button.clicked.connect(lambda _checked=False, target=field: self._browse_model(target))
row.addWidget(field, 1)
row.addWidget(button)
ppocr_form.addRow(tr(label), row)
note = QLabel(tr('使用 PP-OCRv5 ONNX 模型。模型包缺失时,按 docs/MULTILINGUAL_OCR.md 下载后选择模型文件。'))
note.setWordWrap(True)
- note.setProperty("muted", True)
- ppocr_form.addRow(tr(note))
+ note.setProperty('muted', True)
+ ppocr_layout.addLayout(ppocr_form)
+ ppocr_layout.addWidget(note)
ocr_root.addWidget(self._ppocr_group)
- self._custom_group = QGroupBox(tr('自定义 OCR'))
- custom_form = QFormLayout(self._custom_group)
+ self._custom_group, custom_layout = self._make_card('自定义 OCR')
+ custom_form = QFormLayout()
self._style_form(custom_form)
self._custom_language = QLineEdit()
self._custom_language.setPlaceholderText(tr('例如 fr、de、th;选择自定义 OCR 语言时必填'))
self._custom_language_name = QLineEdit()
self._custom_language_name.setPlaceholderText(tr('例如 法语(可选)'))
self._custom_protocol = QComboBox()
- self._custom_protocol.addItem(tr('标准 HTTP OCR'), "http")
- self._custom_protocol.addItem(tr('兼容 OpenAI 的视觉模型'), "openai")
+ self._custom_protocol.addItem(tr('标准 HTTP OCR'), 'http')
+ self._custom_protocol.addItem(tr('兼容 OpenAI 的视觉模型'), 'openai')
self._custom_url = QLineEdit()
self._custom_url.setPlaceholderText(tr('HTTP 完整识别地址;视觉模型填写 Base URL'))
self._custom_key = QLineEdit()
@@ -222,10 +260,11 @@ def __init__(self, config: dict, parent=None):
custom_form.addRow('OCR API Key', self._custom_key)
custom_form.addRow(tr('OCR 模型'), self._custom_model)
custom_form.addRow(tr('请求超时'), self._custom_timeout)
- note = QLabel(tr('此模式会将文本区域图片发送到配置的 OCR 服务。标准 HTTP 返回 {"text": "原文"};完整接入协议见 docs/MULTILINGUAL_OCR.md。译文简繁在翻译页选择。'))
- note.setWordWrap(True)
- note.setProperty("muted", True)
- custom_form.addRow(tr(note))
+ custom_note = QLabel(tr('此模式会将文本区域图片发送到配置的 OCR 服务。标准 HTTP 返回 {"text": "原文"};完整接入协议见 docs/MULTILINGUAL_OCR.md。译文简繁在翻译页选择。'))
+ custom_note.setWordWrap(True)
+ custom_note.setProperty('muted', True)
+ custom_layout.addLayout(custom_form)
+ custom_layout.addWidget(custom_note)
ocr_root.addWidget(self._custom_group)
ocr_root.addStretch(1)
@@ -236,10 +275,12 @@ def __init__(self, config: dict, parent=None):
footer.setObjectName('pageActions')
actions = QHBoxLayout(footer)
actions.setContentsMargins(24, 12, 24, 12)
+ actions.setSpacing(10)
self._save_btn = QPushButton(tr('保存配置'))
- self._save_btn.setProperty("role", "primary")
+ self._save_btn.setProperty('role', 'primary')
+ self._save_btn.setCursor(Qt.PointingHandCursor)
self._save_status = QLabel(tr('修改后点击保存,下次任务生效'))
- self._save_status.setProperty("muted", True)
+ self._save_status.setProperty('muted', True)
actions.addWidget(self._save_status)
actions.addStretch(1)
actions.addWidget(self._save_btn)
@@ -259,18 +300,19 @@ def __init__(self, config: dict, parent=None):
def _add_section(self, tab_title, title, description):
scroll = QScrollArea()
+ scroll.setObjectName('settingsScroll')
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
canvas = QFrame()
- canvas.setObjectName('editorPanel')
+ canvas.setObjectName('settingsScrollContent')
centered = QHBoxLayout(canvas)
centered.setContentsMargins(0, 0, 0, 0)
content = QFrame()
- content.setObjectName('editorPanel')
- content.setMaximumWidth(1040)
+ content.setObjectName('settingsScrollContent')
+ content.setMaximumWidth(920)
root = QVBoxLayout(content)
- root.setContentsMargins(20, 24, 20, 24)
- root.setSpacing(16)
+ root.setContentsMargins(16, 22, 16, 24)
+ root.setSpacing(14)
heading = PanelHeading('', title)
root.addWidget(heading)
hint = QLabel(tr(description))
@@ -278,19 +320,37 @@ def _add_section(self, tab_title, title, description):
hint.setWordWrap(True)
root.addWidget(hint)
centered.addStretch(1)
- centered.addWidget(content, 8)
+ centered.addWidget(content, 10)
centered.addStretch(1)
scroll.setWidget(canvas)
self._sections.addTab(scroll, tr(tab_title))
return root
+ @staticmethod
+ def _make_card(title: str, description: str | None = None):
+ card = QFrame()
+ card.setObjectName('settingsCard')
+ layout = QVBoxLayout(card)
+ layout.setContentsMargins(20, 18, 20, 18)
+ layout.setSpacing(12)
+ heading = QLabel(tr(title))
+ heading.setObjectName('cardTitle')
+ heading.setFont(ui_font(14, QFont.Bold))
+ layout.addWidget(heading)
+ if description:
+ hint = QLabel(tr(description))
+ hint.setProperty('muted', True)
+ hint.setWordWrap(True)
+ layout.addWidget(hint)
+ return card, layout
+
@staticmethod
def _style_form(form):
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
form.setRowWrapPolicy(QFormLayout.WrapLongRows)
- form.setHorizontalSpacing(24)
- form.setVerticalSpacing(14)
+ form.setHorizontalSpacing(22)
+ form.setVerticalSpacing(12)
def _mark_unsaved(self, *args):
if not self._loading_config:
@@ -320,20 +380,20 @@ def _refresh_ocr_choices(self) -> None:
self._ocr_backend.blockSignals(True)
self._ocr_backend.clear()
language = self._source_language.currentData()
- if language == "ja":
- choices = [(tr('自动(使用已安装的日语模型)'), "auto")]
- selected = self._config.get("ocr_backend")
- for label, value, key in (("CharSpot Small", "charspot", "charspot_ocr_model"),
- ("Baberu OCR", "baberu", "baberu_ocr_model"),
- ("manga-ocr", "manga-ocr", "ocr_model")):
+ if language == 'ja':
+ choices = [(tr('自动(使用已安装的日语模型)'), 'auto')]
+ selected = self._config.get('ocr_backend')
+ for label, value, key in (('CharSpot Small', 'charspot', 'charspot_ocr_model'),
+ ('Baberu OCR', 'baberu', 'baberu_ocr_model'),
+ ('manga-ocr', 'manga-ocr', 'ocr_model')):
directory = self._config.get(key)
- if (directory and Path(directory).is_dir()) or selected == value or (value == "manga-ocr" and selected == "manga"):
+ if (directory and Path(directory).is_dir()) or selected == value or (value == 'manga-ocr' and selected == 'manga'):
choices.append((label, value))
- elif language in ("ko", "en"):
- choices = [(tr('自动(PP-OCRv5 本地识别)'), "auto")]
+ elif language in ('ko', 'en'):
+ choices = [(tr('自动(PP-OCRv5 本地识别)'), 'auto')]
else:
choices = []
- for label, value in choices + [(tr('自定义 OCR'), "custom")]:
+ for label, value in choices + [(tr('自定义 OCR'), 'custom')]:
self._ocr_backend.addItem(tr(label), value)
index = self._ocr_backend.findData(previous)
self._ocr_backend.setCurrentIndex(max(0, index))
@@ -341,92 +401,95 @@ def _refresh_ocr_choices(self) -> None:
self._refresh_custom_visibility()
def _refresh_custom_visibility(self) -> None:
- if not hasattr(self, "_custom_group"):
+ if not hasattr(self, '_custom_group'):
return
- self._custom_group.setVisible(self._ocr_backend.currentData() == "custom")
- custom_language = self._source_language.currentData() == "custom"
+ self._custom_group.setVisible(self._ocr_backend.currentData() == 'custom')
+ custom_language = self._source_language.currentData() == 'custom'
self._custom_language.setEnabled(custom_language)
self._custom_language_name.setEnabled(custom_language)
- self._ppocr_group.setVisible(self._source_language.currentData() in ("ko", "en") and self._ocr_backend.currentData() != "custom")
+ self._ppocr_group.setVisible(self._source_language.currentData() in ('ko', 'en') and self._ocr_backend.currentData() != 'custom')
def load_config(self, config: dict) -> None:
self._loading_config = True
self._config = config
self._key_input.clear()
self._ui_language.setCurrentIndex(max(0, self._ui_language.findData(config.get('ui_language', 'zh-CN'))))
- if config.get("api_key"):
+ if config.get('api_key'):
self._key_input.setPlaceholderText(tr('当前密钥: {_0}', _0=mask_api_key(config['api_key'])))
- self._base_input.setText(config.get("api_base_url", ""))
- self._model_input.setText(config.get("translation_model", ""))
- self._multimodal_check.setChecked(bool(config.get("multimodal", False)))
- self._font_probe_check.setChecked(bool(config.get("multimodal_font_probe", False)))
- self._no_thinking_check.setChecked(bool(config.get("disable_thinking", True)))
- self._gpu_check.setChecked(bool(config.get("use_gpu", True)))
- self._source_language.setCurrentIndex(max(0, self._source_language.findData(config.get("source_language", "ja"))))
+ self._base_input.setText(config.get('api_base_url', ''))
+ self._model_input.setText(config.get('translation_model', ''))
+ self._multimodal_check.setChecked(bool(config.get('multimodal', False)))
+ self._font_probe_check.setChecked(bool(config.get('multimodal_font_probe', False)))
+ self._no_thinking_check.setChecked(bool(config.get('disable_thinking', True)))
+ self._gpu_check.setChecked(bool(config.get('use_gpu', True)))
+ self._source_language.setCurrentIndex(max(0, self._source_language.findData(config.get('source_language', 'ja'))))
self._refresh_ocr_choices()
- backend = str(config.get("ocr_backend") or "auto")
- backend = {"manga": "manga-ocr", "ppocr": "auto"}.get(backend, backend)
+ backend = str(config.get('ocr_backend') or 'auto')
+ backend = {'manga': 'manga-ocr', 'ppocr': 'auto'}.get(backend, backend)
backend_index = self._ocr_backend.findData(backend)
self._ocr_backend.setCurrentIndex(max(0, backend_index))
- self._korean_model.setText(config.get("korean_ocr_model", ""))
- self._english_model.setText(config.get("english_ocr_model", ""))
- self._custom_language.setText(config.get("custom_source_language") or "")
- self._custom_language_name.setText(config.get("custom_source_language_name") or "")
- self._custom_protocol.setCurrentIndex(max(0, self._custom_protocol.findData(config.get("custom_ocr_protocol", "http"))))
- self._custom_url.setText(config.get("custom_ocr_url") or "")
- self._custom_key.setText(config.get("custom_ocr_api_key") or "")
- self._custom_model.setText(config.get("custom_ocr_model") or "")
- self._custom_timeout.setValue(int(config.get("custom_ocr_timeout") or 60))
+ self._korean_model.setText(config.get('korean_ocr_model', ''))
+ self._english_model.setText(config.get('english_ocr_model', ''))
+ self._custom_language.setText(config.get('custom_source_language') or '')
+ self._custom_language_name.setText(config.get('custom_source_language_name') or '')
+ self._custom_protocol.setCurrentIndex(max(0, self._custom_protocol.findData(config.get('custom_ocr_protocol', 'http'))))
+ self._custom_url.setText(config.get('custom_ocr_url') or '')
+ self._custom_key.setText(config.get('custom_ocr_api_key') or '')
+ self._custom_model.setText(config.get('custom_ocr_model') or '')
+ self._custom_timeout.setValue(int(config.get('custom_ocr_timeout') or 60))
self._advanced.load_config(config)
self._refresh_custom_visibility()
- self._output_input.setText(config.get("page_output_dir", ""))
- self._watermark_check.setChecked(bool(config.get("watermark_enabled", True)))
+ self._output_input.setText(config.get('page_output_dir', ''))
+ self._watermark_check.setChecked(bool(config.get('watermark_enabled', True)))
self._output_input.setToolTip(self._output_input.text())
self._output_input.setCursorPosition(len(self._output_input.text()))
- self._issue_input.setText(config.get("issue_url", ""))
+ self._issue_input.setText(config.get('issue_url', ''))
self._theme.blockSignals(True)
- self._theme.setCurrentIndex(max(0, self._theme.findData(config.get("ui_theme", "auto"))))
+ self._theme.setCurrentIndex(max(0, self._theme.findData(config.get('ui_theme', 'auto'))))
self._theme.blockSignals(False)
self._reduced_motion.blockSignals(True)
- self._reduced_motion.setChecked(bool(config.get("ui_reduced_motion", False)))
+ self._reduced_motion.setChecked(bool(config.get('ui_reduced_motion', False)))
self._reduced_motion.blockSignals(False)
self._model_info.setText(
- tr('CharSpot Small: {_4}\n检测: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\n修复: {_3}', _4=config.get('charspot_ocr_model', ''), _0=config.get('detector_model', ''), _1=config.get('baberu_ocr_model', ''), _2=config.get('ocr_model', ''), _3=config.get('lama_model', ''))
+ tr('CharSpot Small: {_4}\n检测: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\n修复: {_3}',
+ _4=config.get('charspot_ocr_model', ''), _0=config.get('detector_model', ''),
+ _1=config.get('baberu_ocr_model', ''), _2=config.get('ocr_model', ''),
+ _3=config.get('lama_model', ''))
)
self._loading_config = False
self._save_status.setText(tr('修改后点击保存,下次任务生效'))
def values(self) -> dict:
data = {
- "ui_language": self._ui_language.currentData(),
- "ui_language_selected": True,
- "api_base_url": self._base_input.text().strip(),
- "translation_model": self._model_input.text().strip(),
- "multimodal": self._multimodal_check.isChecked(),
- "multimodal_font_probe": self._font_probe_check.isChecked(),
- "disable_thinking": self._no_thinking_check.isChecked(),
- "watermark_enabled": self._watermark_check.isChecked(),
- "use_gpu": self._gpu_check.isChecked(),
- "ocr_backend": self._ocr_backend.currentData(),
- "source_language": self._source_language.currentData(),
- "korean_ocr_model": self._korean_model.text().strip(),
- "english_ocr_model": self._english_model.text().strip(),
- "custom_source_language": self._custom_language.text().strip(),
- "custom_source_language_name": self._custom_language_name.text().strip(),
- "custom_ocr_protocol": self._custom_protocol.currentData(),
- "custom_ocr_url": self._custom_url.text().strip(),
- "custom_ocr_api_key": self._custom_key.text().strip(),
- "custom_ocr_model": self._custom_model.text().strip(),
- "custom_ocr_timeout": self._custom_timeout.value(),
- "page_output_dir": self._output_input.text().strip(),
- "issue_url": self._issue_input.text().strip(),
- "ui_theme": self._theme.currentData(),
- "ui_reduced_motion": self._reduced_motion.isChecked(),
+ 'ui_language': self._ui_language.currentData(),
+ 'ui_language_selected': True,
+ 'api_base_url': self._base_input.text().strip(),
+ 'translation_model': self._model_input.text().strip(),
+ 'multimodal': self._multimodal_check.isChecked(),
+ 'multimodal_font_probe': self._font_probe_check.isChecked(),
+ 'disable_thinking': self._no_thinking_check.isChecked(),
+ 'watermark_enabled': self._watermark_check.isChecked(),
+ 'use_gpu': self._gpu_check.isChecked(),
+ 'ocr_backend': self._ocr_backend.currentData(),
+ 'source_language': self._source_language.currentData(),
+ 'korean_ocr_model': self._korean_model.text().strip(),
+ 'english_ocr_model': self._english_model.text().strip(),
+ 'custom_source_language': self._custom_language.text().strip(),
+ 'custom_source_language_name': self._custom_language_name.text().strip(),
+ 'custom_ocr_protocol': self._custom_protocol.currentData(),
+ 'custom_ocr_url': self._custom_url.text().strip(),
+ 'custom_ocr_api_key': self._custom_key.text().strip(),
+ 'custom_ocr_model': self._custom_model.text().strip(),
+ 'custom_ocr_timeout': self._custom_timeout.value(),
+ 'page_output_dir': self._output_input.text().strip(),
+ 'issue_url': self._issue_input.text().strip(),
+ 'ui_theme': self._theme.currentData(),
+ 'ui_reduced_motion': self._reduced_motion.isChecked(),
}
data.update(self._advanced.values())
key = self._key_input.text().strip()
if key:
- data["api_key"] = key
+ data['api_key'] = key
return data
def mark_saved(self) -> None:
diff --git a/comic_translate_desktop/ui/editor_page.py b/comic_translate_desktop/ui/editor_page.py
index c5a19d8..cea89ef 100644
--- a/comic_translate_desktop/ui/editor_page.py
+++ b/comic_translate_desktop/ui/editor_page.py
@@ -5,22 +5,24 @@
from collections import OrderedDict
from copy import deepcopy
from pathlib import Path
-from PySide6.QtCore import Qt, QRect, QSize, QSettings, QTimer, QEvent, QPoint, QVariantAnimation
-from PySide6.QtGui import QColor, QFont, QPainter, QPixmap, QIcon, QImageReader, QShortcut, QKeySequence
-from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QFrame, QLabel, QListWidget, QListWidgetItem, QPushButton, QScrollArea, QSplitter, QComboBox, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QFileDialog, QMessageBox, QSizePolicy, QTabWidget, QCheckBox, QToolButton, QApplication, QLineEdit, QTextEdit, QAbstractSpinBox, QAbstractButton, QAbstractItemView, QStyledItemDelegate, QStyle)
+from PySide6.QtCore import Qt, QRect, QSize, QSettings, QTimer, QEvent, QPoint, QVariantAnimation, QItemSelectionModel, QUrl
+from PySide6.QtGui import QAction, QDesktopServices, QColor, QFont, QPainter, QPixmap, QIcon, QImageReader, QShortcut, QKeySequence
+from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QFrame, QLabel, QListWidget, QListWidgetItem, QMenu, QPushButton, QScrollArea, QSplitter, QComboBox, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QFileDialog, QMessageBox, QSizePolicy, QTabWidget, QCheckBox, QToolButton, QApplication, QLineEdit, QTextEdit, QAbstractSpinBox, QAbstractButton, QAbstractItemView, QStyledItemDelegate, QStyle)
from ..config import load_ai_config, MAIN_DIR
-from ..font_library import available_fonts, font_description, font_display_name, font_reference, inspect_font, resolve_font_reference
-from comic_translate_core.page_compositor import compose_page, layer_bounds
+from ..font_library import available_fonts, font_description, font_display_name, font_reference, import_font, inspect_font, resolve_font_reference
+from comic_translate_core.page_compositor import compose_page, intersection, layer_bounds
from comic_translate_core.restoration import (
find_original, save_original, original_snapshot_path, legacy_region, protected_region,
intersects_restored_region,
)
from comic_translate_core.layout_options import VERTICAL_ALIGNMENTS, normalize_text_color
from ..background_repair import BackgroundRepair, RepairWorker, save_editor_files
+from ..cbz import PROJECT_EXTS
from ..pdf_export import PdfExportWorker
from ..pdf_utils import PdfProcessingError
-from ..editor_jobs import LatestJobQueue, read_page, read_project_pages, SaveRequest
+from ..editor_jobs import LatestJobQueue, read_page, read_project_pages, read_transcript, SaveRequest
from ..lettering_transform import text_transform, transform_layer, outline_width
+from ..productivity import STYLE_DEFAULTS, lettering_style, apply_lettering_style
from .color_picker import TextColorPicker
from .strip_preview import StripPreview
from .thumbnail_loader import ThumbnailLoader
@@ -126,6 +128,13 @@ def __init__(self, parent=None):
self.cleaned_path = self.output_path = None
self._source_expanded = QSettings().value('ui/editorSourceExpanded', True, type=bool)
self._source_compact_override = False
+ raw_fav_pref = QSettings().value('ui/editorFavoriteBarVisible', None)
+ if isinstance(raw_fav_pref, bool):
+ self._favorite_bar_pref = raw_fav_pref
+ elif isinstance(raw_fav_pref, str) and raw_fav_pref.lower() in ('true', 'false'):
+ self._favorite_bar_pref = raw_fav_pref.lower() == 'true'
+ else:
+ self._favorite_bar_pref = None
self._desired_panels = [True, True]
self._panel_priority = 1
self._wide_splitter_state = None
@@ -136,6 +145,7 @@ def __init__(self, parent=None):
self._import_jobs = LatestJobQueue(self)
self._save_jobs = LatestJobQueue(self)
self._after_save = None
+ self._save_failure_callback = None
self._save_again = False
self._requesting_page = False
self._indexing = False
@@ -154,6 +164,10 @@ def __init__(self, parent=None):
self._last_available_width = None
self._row_dirty = False
self._font_choice_dirty = False
+ self._pending_style_keys = set()
+ self._pending_style_rows = []
+ self._style_clipboard = None
+ self._style_history = []
self._cleaned_image = None
self._original_image = None
self._repair_history = []
@@ -308,20 +322,73 @@ def _build_ui(self):
toolbar.setContentsMargins(0, 0, 0, 8)
toolbar.setSpacing(6)
self._toolbar_layout = toolbar
- self._pages_toggle = QPushButton(tr('页面'))
- self._properties_toggle = QPushButton(tr('编辑面板'))
+
+ self._pages_toggle = QPushButton(tr('页面'), self)
+ self._properties_toggle = QPushButton(tr('编辑面板'), self)
for button in (self._pages_toggle, self._properties_toggle):
button.setCheckable(True)
button.setChecked(True)
button.setProperty('compact', True)
button.setProperty('role', 'utility')
- toolbar.addWidget(button)
- self._focus_btn = QPushButton(tr('专注画布'))
+ button.hide()
+
+ self._zoom_tool_btn = QPushButton(tr('缩放工具'), self)
+ self._zoom_tool_btn.setCheckable(True)
+ self._zoom_tool_btn.setProperty('role', 'utility')
+ self._zoom_tool_btn.setProperty('compact', True)
+ self._zoom_tool_btn.hide()
+
+ self._strip_toggle = QPushButton(tr('连续长条'), self)
+ self._strip_toggle.setCheckable(True)
+ self._strip_toggle.setProperty('role', 'utility')
+ self._strip_toggle.setProperty('compact', True)
+ self._strip_toggle.hide()
+
+ self._view_menu_btn = QToolButton()
+ self._view_menu_btn.setText(tr('视图'))
+ self._view_menu_btn.setProperty('role', 'utility')
+ self._view_menu_btn.setProperty('compact', True)
+ self._view_menu_btn.setProperty('menuButton', True)
+ self._view_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._view_menu_btn.setToolTip(tr('视图与面板选项'))
+ self._view_menu = QMenu(self._view_menu_btn)
+ self._view_menu.setToolTipsVisible(True)
+ self._pages_action = self._view_menu.addAction(tr('页面栏'))
+ self._pages_action.setCheckable(True)
+ self._pages_action.setChecked(True)
+ self._properties_action = self._view_menu.addAction(tr('编辑面板'))
+ self._properties_action.setCheckable(True)
+ self._properties_action.setChecked(True)
+ self._focus_action = self._view_menu.addAction(tr('专注画布') + '\tCtrl+Shift+F')
+ self._focus_action.setCheckable(True)
+ self._focus_action.setToolTip(tr('收起侧栏与辅助信息,专注查看作品 · Ctrl+Shift+F'))
+ self._view_menu.addSeparator()
+ self._strip_action = self._view_menu.addAction(tr('连续长条'))
+ self._strip_action.setCheckable(True)
+ self._strip_action.setToolTip(tr('纵向滚动浏览所有页面,点击页面后原位精修。'))
+ self._zoom_tool_action = self._view_menu.addAction(tr('缩放工具') + '\tZ')
+ self._zoom_tool_action.setCheckable(True)
+ self._zoom_tool_action.setToolTip(tr('点击放大,Alt+点击缩小 · Z'))
+ self._view_menu.addSeparator()
+ self._favorite_bar_action = self._view_menu.addAction(tr('快捷字体栏'))
+ self._favorite_bar_action.setCheckable(True)
+ self._favorite_bar_action.setToolTip(tr('显示或隐藏画布上方的 1–9 快捷字体栏'))
+ self._view_menu.addSeparator()
+ self._view_menu.addAction(tr('适应页面') + '\tCtrl+0', lambda: self.preview.set_zoom(None))
+ self._view_menu.addAction(tr('实际大小 (100%)') + '\tCtrl+1', lambda: self.preview.set_zoom(1.0))
+ self._view_menu.addAction(tr('适应宽度') + '\tCtrl+2', lambda: self.preview.set_fit_width())
+ self._view_menu_btn.setMenu(self._view_menu)
+ toolbar.addWidget(self._view_menu_btn)
+
+ self._focus_btn = QPushButton(tr('退出专注'))
self._focus_btn.setCheckable(True)
self._focus_btn.setProperty('role', 'utility')
self._focus_btn.setProperty('compact', True)
+ self._focus_btn.setAccessibleName(tr('专注画布'))
self._focus_btn.setToolTip(tr('收起侧栏与辅助信息,专注查看作品 · Ctrl+Shift+F'))
+ self._focus_btn.hide()
toolbar.addWidget(self._focus_btn)
+
toolbar_div = QFrame()
toolbar_div.setObjectName('toolbarDivider')
toolbar_div.setFrameShape(QFrame.VLine)
@@ -358,26 +425,40 @@ def _build_ui(self):
self._zoom_in_btn.setToolTip(tr('放大 · Ctrl+='))
self._zoom_in_btn.clicked.connect(lambda: self.preview.zoom_by(1.25))
toolbar.addWidget(self._zoom_in_btn)
- self._zoom_tool_btn = QPushButton(tr('缩放工具'))
- self._zoom_tool_btn.setCheckable(True)
- self._zoom_tool_btn.setProperty('role', 'utility')
- self._zoom_tool_btn.setProperty('compact', True)
- self._zoom_tool_btn.setToolTip(tr('点击放大,Alt+点击缩小 · Z'))
- toolbar.addWidget(self._zoom_tool_btn)
- self._strip_toggle = QPushButton(tr('连续长条'))
- self._strip_toggle.setCheckable(True)
- self._strip_toggle.setProperty('role', 'utility')
- self._strip_toggle.setProperty('compact', True)
- self._strip_toggle.setToolTip(tr('纵向滚动浏览所有页面,点击页面后原位精修。'))
- toolbar.addWidget(self._strip_toggle)
toolbar.addStretch()
- self._export_pdf_btn = QPushButton(tr('导出 PDF'))
+
+ self._export_pdf_btn = QPushButton(tr('导出 PDF'), self)
self._export_pdf_btn.setProperty('role', 'chip')
self._export_pdf_btn.setProperty('compact', True)
self._export_pdf_btn.setToolTip(tr('将已保存的图片按页面顺序导出为 PDF;编辑时不会合成 PDF。'))
self._export_pdf_btn.setEnabled(False)
self._export_pdf_btn.clicked.connect(self._export_action)
- toolbar.addWidget(self._export_pdf_btn)
+ self._export_pdf_btn.hide()
+
+ self._file_menu_btn = QToolButton()
+ self._file_menu_btn.setText(tr('文件'))
+ self._file_menu_btn.setProperty('role', 'utility')
+ self._file_menu_btn.setProperty('compact', True)
+ self._file_menu_btn.setProperty('menuButton', True)
+ self._file_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._file_menu_btn.setToolTip(tr('文件与导出操作'))
+ self._file_menu = QMenu(self._file_menu_btn)
+ self._file_menu.setToolTipsVisible(True)
+ self._import_pages_action = self._file_menu.addAction(tr('导入译图 / PDF'), self._import_pages)
+ self._export_pdf_action = self._file_menu.addAction(tr('导出 PDF'), self._export_action)
+ self._export_pdf_action.setToolTip(tr('将已保存的图片按页面顺序导出为 PDF;编辑时不会合成 PDF。'))
+ self._export_pdf_action.setEnabled(False)
+ self._export_cbz_action = self._file_menu.addAction(tr('导出 CBZ'), lambda: self._export_action('cbz'))
+ self._export_cbz_action.setToolTip(tr('将已保存的图片按页面顺序打包为 CBZ。'))
+ self._export_cbz_action.setEnabled(False)
+ self._file_menu.addSeparator()
+ self._open_output_action = self._file_menu.addAction(tr('打开输出目录'), self._open_output_dir)
+ self._link_original_action = self._file_menu.addAction(tr('关联原图…'), self.link_original)
+ self._link_original_action.setToolTip(tr('旧结果缺少原图时,选择该页处理前的同尺寸原图。'))
+ self._link_original_action.setEnabled(False)
+ self._file_menu_btn.setMenu(self._file_menu)
+ toolbar.addWidget(self._file_menu_btn)
+
self._save_btn = QPushButton(tr('保存图片'))
self._save_btn.setProperty('role', 'primary')
toolbar.addWidget(self._save_btn)
@@ -386,9 +467,11 @@ def _build_ui(self):
self._favorite_fonts = FavoriteFontBar(self.config)
self._favorite_fonts.font_selected.connect(self._apply_favorite_font)
self._favorite_fonts.add_current_requested.connect(self._add_favorite_font)
+ self._favorite_fonts.hide_requested.connect(lambda: self._set_favorite_bar_visible(False))
+ self._favorite_fonts.slots_changed.connect(self._on_favorite_slots_changed)
root.addWidget(self._favorite_fonts)
- self._status = QLabel(tr('导入带布局数据的已翻译图片或 PDF,或从自动处理结果进入精修。'))
+ self._status = QLabel(tr('导入带布局数据的译稿,或从自动处理结果进入精修。'))
self._status.setWordWrap(True)
self._status.setTextInteractionFlags(Qt.TextSelectableByMouse)
self._status.setObjectName('editorStatus')
@@ -415,11 +498,17 @@ def _build_ui(self):
self._page_count_label.setFont(ui_font(12, mono=True))
page_head.addWidget(self._page_count_label)
left.addLayout(page_head)
- add = QPushButton(tr('导入译图 / PDF'))
+ add = QPushButton(tr('导入译图'))
set_themed_icon(add, 'plus')
add.setProperty('role', 'chip')
add.clicked.connect(self._import_pages)
left.addWidget(add)
+ self._transcript_btn = QPushButton(tr('全书译稿'))
+ self._transcript_btn.setProperty('role', 'chip')
+ self._transcript_btn.setProperty('compact', True)
+ self._transcript_btn.setEnabled(False)
+ self._transcript_btn.clicked.connect(self.open_transcript)
+ left.addWidget(self._transcript_btn)
self.page_list = QListWidget()
self.page_list.setObjectName('pageList')
self.page_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
@@ -462,12 +551,13 @@ def _build_ui(self):
self._strip_toggle.toggled.connect(self.preview.set_continuous)
self.preview.page_requested.connect(self._request_canvas_page)
self.preview.clear(tr('选择一页,开始精修'))
- self.preview._hint.setText(tr('导入带布局数据的已翻译图片或 PDF,或从自动处理结果进入精修。'))
- self.preview.import_button.setText(tr('导入已翻译图片或 PDF'))
+ self.preview._hint.setText(tr('导入带布局数据的译稿,或从自动处理结果进入精修。'))
+ self.preview.import_button.setText(tr('导入已翻译的漫画'))
self.preview.import_requested.connect(self._import_pages)
self.preview.region_edited.connect(self._resize_region_from_canvas)
self.preview.region_edit_finished.connect(self.apply_changes)
self.preview.region_clicked.connect(self._select_block)
+ self.preview.region_context_menu.connect(self._show_canvas_bubble_context_menu)
self.preview.bubble_created.connect(self._add_bubble_from_canvas)
self.preview.color_picked.connect(self._accept_fill_color)
self.preview.color_pick_canceled.connect(lambda: self._pick_fill_btn.setChecked(False))
@@ -497,7 +587,7 @@ def _build_ui(self):
self._repair_btn = QPushButton(tr('修补选区'))
self._repair_undo = QPushButton(tr('撤回修补'))
self._repair_undo.setToolTip(tr('优先撤回手动修补;没有手动记录时,还原选中气泡的自动修补与嵌字。旧结果请先关联原图。'))
- for button in (self._repair_mode, self._add_bubble_btn, self._repair_btn, self._repair_undo):
+ for button in (self._repair_mode, self._add_bubble_btn):
button.setProperty('compact', True)
button.setProperty('role', 'chip')
canvas_tools.addWidget(button)
@@ -513,19 +603,61 @@ def _build_ui(self):
tools_div.setFixedSize(1, 18)
canvas_tools.addWidget(tools_div)
- self._fill_white_btn = QPushButton(tr('填白'))
+ self._repair_btn.setProperty('compact', True)
+ self._repair_btn.setProperty('role', 'chip')
+ canvas_tools.addWidget(self._repair_btn)
+
+ self._fill_menu_btn = QToolButton()
+ self._fill_menu_btn.setText(tr('填色'))
+ self._fill_menu_btn.setProperty('compact', True)
+ self._fill_menu_btn.setProperty('role', 'chip')
+ self._fill_menu_btn.setProperty('menuButton', True)
+ self._fill_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._fill_menu_btn.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ self._fill_menu_btn.setToolTip(tr('背景填色与取色选项'))
+ self._fill_menu = QMenu(self._fill_menu_btn)
+ self._fill_menu.setToolTipsVisible(True)
+ self._fill_white_action = self._fill_menu.addAction(
+ tr('填白'), lambda: self._fill_repair_region((255, 255, 255)))
+ self._fill_black_action = self._fill_menu.addAction(
+ tr('填黑'), lambda: self._fill_repair_region((0, 0, 0)))
+ self._fill_custom_action = self._fill_menu.addAction(
+ tr('填色'), lambda: self._fill_repair_region(self._fill_color.getRgb()[:3]))
+ self._fill_menu.addSeparator()
+ self._fill_color_action = self._fill_menu.addAction(
+ tr('选择填充颜色…'), self._choose_fill_color)
+ self._fill_color_action.setToolTip(tr('点击选择颜色,支持 RGB 与十六进制色值。'))
+ self._pick_fill_action = self._fill_menu.addAction(tr('图片取色'))
+ self._pick_fill_action.setCheckable(True)
+ self._pick_fill_action.setToolTip(tr('点击图片取色;Esc 或右键取消,不会修改图片。'))
+ self._fill_menu_btn.setMenu(self._fill_menu)
+ canvas_tools.addWidget(self._fill_menu_btn)
+
+ self._pick_cancel_btn = QPushButton(tr('取色中 · 取消'))
+ self._pick_cancel_btn.setProperty('compact', True)
+ self._pick_cancel_btn.setProperty('role', 'utility')
+ self._pick_cancel_btn.setToolTip(tr('点击退出图片取色,或按 Esc / 右键取消。'))
+ self._pick_cancel_btn.clicked.connect(lambda: self._pick_fill_btn.setChecked(False))
+ self._pick_cancel_btn.hide()
+ canvas_tools.addWidget(self._pick_cancel_btn)
+
+ self._repair_undo.setProperty('compact', True)
+ self._repair_undo.setProperty('role', 'chip')
+ canvas_tools.addWidget(self._repair_undo)
+
+ self._fill_white_btn = QPushButton(tr('填白'), self)
self._fill_white_btn.setToolTip(tr('把框选区域整块填成白色(可撤回)。'))
- self._fill_black_btn = QPushButton(tr('填黑'))
+ self._fill_black_btn = QPushButton(tr('填黑'), self)
self._fill_black_btn.setToolTip(tr('把框选区域整块填成黑色(可撤回)。'))
- self._fill_color_btn = QPushButton()
+ self._fill_color_btn = QPushButton(self)
self._fill_color_btn.setAccessibleName(tr('选择填充颜色'))
self._fill_color_btn.setToolTip(tr('点击选择颜色,支持 RGB 与十六进制色值。'))
self._fill_color_btn.clicked.connect(self._choose_fill_color)
- self._pick_fill_btn = QPushButton(tr('图片取色'))
+ self._pick_fill_btn = QPushButton(tr('图片取色'), self)
self._pick_fill_btn.setCheckable(True)
self._pick_fill_btn.setToolTip(tr('点击图片取色;Esc 或右键取消,不会修改图片。'))
self._pick_fill_btn.toggled.connect(self._toggle_fill_color_pick)
- self._fill_custom_btn = QPushButton(tr('填色'))
+ self._fill_custom_btn = QPushButton(tr('填色'), self)
self._fill_white_btn.clicked.connect(lambda: self._fill_repair_region((255, 255, 255)))
self._fill_black_btn.clicked.connect(lambda: self._fill_repair_region((0, 0, 0)))
self._fill_custom_btn.clicked.connect(lambda: self._fill_repair_region(self._fill_color.getRgb()[:3]))
@@ -533,7 +665,7 @@ def _build_ui(self):
self._pick_fill_btn, self._fill_custom_btn):
button.setProperty('compact', True)
button.setProperty('role', 'chip')
- canvas_tools.addWidget(button)
+ button.hide()
self._refresh_fill_color()
canvas_layout.addWidget(canvas_tools_frame)
canvas_layout.addWidget(self.preview, 1)
@@ -589,12 +721,30 @@ def _build_ui(self):
self._restore_bubble_btn.setToolTip(tr('撤销所选气泡的修补与嵌字,恢复处理前的原始像素;可再次恢复处理结果。'))
self._restore_bubble_btn.clicked.connect(self.toggle_bubble_original)
bubble_bar.addWidget(self._restore_bubble_btn)
- self._link_original_btn = QPushButton(tr('关联原图'))
+ self._brush_cancel_btn = QPushButton(tr('退出样式刷'))
+ self._brush_cancel_btn.setProperty('compact', True)
+ self._brush_cancel_btn.setProperty('role', 'chip')
+ self._brush_cancel_btn.clicked.connect(self._stop_style_brush)
+ self._brush_cancel_btn.hide()
+ bubble_bar.addWidget(self._brush_cancel_btn)
+ self._bubble_menu_btn = QToolButton()
+ self._bubble_menu_btn.setText('⋯')
+ self._bubble_menu_btn.setProperty('compact', True)
+ self._bubble_menu_btn.setProperty('role', 'chip')
+ self._bubble_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._bubble_menu_btn.setAccessibleName(tr('当前气泡更多操作'))
+ self._bubble_menu_btn.setToolTip(tr('当前气泡更多操作'))
+ self._bubble_menu = QMenu(self._bubble_menu_btn)
+ self._bubble_menu.setToolTipsVisible(True)
+ self._bubble_menu.aboutToShow.connect(lambda: self._populate_bubble_menu(self._bubble_menu))
+ self._bubble_menu_btn.setMenu(self._bubble_menu)
+ bubble_bar.addWidget(self._bubble_menu_btn)
+ self._link_original_btn = QPushButton(tr('关联原图'), self)
self._link_original_btn.setProperty('compact', True)
self._link_original_btn.setProperty('role', 'chip')
self._link_original_btn.setToolTip(tr('旧结果缺少原图时,选择该页处理前的同尺寸原图。'))
self._link_original_btn.clicked.connect(self.link_original)
- bubble_bar.addWidget(self._link_original_btn)
+ self._link_original_btn.hide()
header_layout.addLayout(bubble_bar)
inspector_layout.addWidget(inspector_header)
@@ -609,8 +759,34 @@ def _build_ui(self):
self.block_list.setMinimumHeight(40)
self.block_list.setUniformItemSizes(True)
self.block_list.setMouseTracking(True)
+ self.block_list.setContextMenuPolicy(Qt.CustomContextMenu)
+ self.block_list.customContextMenuRequested.connect(self._show_block_list_context_menu)
self.block_list.setItemDelegate(_BlockItemDelegate(self.block_list))
+ self.block_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.block_list.currentRowChanged.connect(self._load_properties)
+ self.block_list.itemSelectionChanged.connect(self._selection_changed)
+ self.block_list.itemClicked.connect(self._brush_list_clicked)
+ self.preview.regions_selected.connect(self._select_blocks)
+ self._copy_style_btn = QPushButton(tr('取样式'), self)
+ self._copy_style_btn.setToolTip(tr('复制当前气泡的字体与排版样式,然后点击或框选目标气泡。'))
+ self._copy_style_btn.clicked.connect(self.copy_style)
+ self._style_brush_btn = QPushButton(tr('样式刷'), self)
+ self._style_brush_btn.setCheckable(True)
+ self._style_brush_btn.setToolTip(tr('点击目标应用样式;Shift 拖动框选,Ctrl 点击多选;Esc 退出。不会复制译文或气泡位置。'))
+ self._undo_style_btn = QPushButton(tr('撤销样式'), self)
+ self._undo_style_btn.clicked.connect(self.undo_style)
+ for button in (self._copy_style_btn, self._style_brush_btn, self._undo_style_btn):
+ button.setProperty('compact', True)
+ button.setProperty('role', 'chip')
+ button.hide()
+ self._brush_escape = QShortcut(QKeySequence('Escape'), self)
+ self._brush_escape.setContext(Qt.WidgetWithChildrenShortcut)
+ self._brush_escape.setEnabled(False)
+ self._brush_escape.activated.connect(self._stop_style_brush)
+ self._style_brush_btn.toggled.connect(self._brush_escape.setEnabled)
+ self._style_brush_btn.toggled.connect(self._sync_style_brush_ui)
+ for button in (self._repair_mode, self._add_bubble_btn, self._pick_fill_btn):
+ button.toggled.connect(self._stop_style_brush_for_tool)
install_list_motion(self.block_list)
self._inspector_tabs = QTabWidget()
self._inspector_tabs.setDocumentMode(True)
@@ -634,6 +810,9 @@ def _build_ui(self):
self._text_props_layout = text_props
self._inspector_tabs.addTab(text_panel, tr('译文编辑'))
+ source_row = QHBoxLayout()
+ source_row.setContentsMargins(0, 0, 0, 0)
+ source_row.setSpacing(6)
self._source_toggle = QToolButton()
self._source_toggle.setText(tr('原文'))
self._source_toggle.setCheckable(True)
@@ -641,7 +820,27 @@ def _build_ui(self):
self._source_toggle.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self._source_toggle.setProperty('role', 'quiet')
self._source_toggle.setProperty('compact', True)
- text_props.addWidget(self._source_toggle)
+ source_row.addWidget(self._source_toggle)
+ self._retranslate_btn = QPushButton(tr('重译气泡'))
+ self._retranslate_btn.setProperty('compact', True)
+ self._retranslate_btn.setProperty('role', 'chip')
+ self._retranslate_btn.setEnabled(False)
+ self._retranslate_btn.clicked.connect(self.open_retranslation)
+ source_row.addWidget(self._retranslate_btn)
+ source_row.addStretch(1)
+ quick_size_label = QLabel(tr('字号'))
+ quick_size_label.setProperty('muted', True)
+ source_row.addWidget(quick_size_label)
+ self._quick_size_spin = QSpinBox()
+ self._quick_size_spin.setObjectName('quickSizeSpin')
+ self._quick_size_spin.setRange(0, 200)
+ self._quick_size_spin.setSpecialValueText(tr('自动'))
+ self._quick_size_spin.setToolTip(tr('手动字号按实际像素绘制;0 为自动适配蒙版'))
+ self._quick_size_spin.setAccessibleName(tr('字号'))
+ self._quick_size_spin.setMinimumWidth(72)
+ self._quick_size_spin.setMaximumWidth(86)
+ source_row.addWidget(self._quick_size_spin)
+ text_props.addLayout(source_row)
self._source_text = QPlainTextEdit()
self._source_text.setObjectName('textSource')
self._source_text.setReadOnly(True)
@@ -700,7 +899,7 @@ def _build_ui(self):
layout_tab_root.addWidget(self._properties_scroll, 1)
props = QVBoxLayout(scroll_content)
- props.setContentsMargins(0, 2, 4, 6)
+ props.setContentsMargins(0, 2, 2, 6)
props.setSpacing(10)
self._style_combo = SearchableFontCombo()
@@ -747,11 +946,26 @@ def _build_ui(self):
self._text_color = TextColorPicker()
self._text_color.setAccessibleName(tr('当前文本块文字颜色'))
self._text_color.setToolTip(tr('只修改当前文本块;默认黑字,空心效果默认白字。自选颜色保留描边效果。'))
+ self._text_scale_x, self._text_scale_y = QSpinBox(), QSpinBox()
+ for spin in (self._text_scale_x, self._text_scale_y):
+ spin.setRange(10, 400)
+ spin.setValue(100)
+ spin.setSuffix(' %')
+ spin.setToolTip(tr('以文字中心拉伸;100% 保持原样,不改变换行与蒙版。'))
+ self._text_rotation = QDoubleSpinBox()
+ self._text_rotation.setRange(-180, 180)
+ self._text_rotation.setDecimals(1)
+ self._text_rotation.setSuffix('°')
+ self._text_rotation.setToolTip(tr('以文字中心旋转;正数顺时针,负数逆时针。'))
+ self._reset_transform_btn = QPushButton(tr('重置文字变形'))
+ self._reset_transform_btn.setProperty('compact', True)
+ self._reset_transform_btn.setProperty('role', 'chip')
+ self._reset_transform_btn.clicked.connect(self._reset_text_transform)
type_card = QFrame()
type_card.setObjectName('inspectorCard')
type_layout = QVBoxLayout(type_card)
- type_layout.setContentsMargins(10, 8, 10, 8)
+ type_layout.setContentsMargins(8, 8, 8, 8)
type_layout.setSpacing(6)
type_title = QLabel(tr('字体与排版'))
type_title.setObjectName('cardTitle')
@@ -762,11 +976,29 @@ def _build_ui(self):
font_label.setProperty('muted', True)
font_row.addWidget(font_label)
font_row.addStretch(1)
- self._font_library_btn = QPushButton(tr('字体库'))
+ self._font_menu_btn = QToolButton()
+ self._font_menu_btn.setText(tr('字体管理'))
+ self._font_menu_btn.setProperty('compact', True)
+ self._font_menu_btn.setProperty('role', 'chip')
+ self._font_menu_btn.setProperty('menuButton', True)
+ self._font_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._font_menu_btn.setToolTip(tr('字体库、导入与快捷字体管理'))
+ self._font_menu = QMenu(self._font_menu_btn)
+ self._font_menu.setToolTipsVisible(True)
+ self._font_library_action = self._font_menu.addAction(tr('字体库…'), self._open_font_library)
+ self._import_font_action = self._font_menu.addAction(tr('导入本地字体…'), self._import_local_fonts)
+ self._font_menu.addSeparator()
+ self._add_favorite_action = self._font_menu.addAction(tr('将当前字体加入快捷字体'), self._add_favorite_font)
+ self._configure_favorites_action = self._font_menu.addAction(tr('设置快捷字体…'), self._favorite_fonts.configure)
+ self._font_menu_show_bar_action = self._font_menu.addAction(tr('快捷字体栏'))
+ self._font_menu_show_bar_action.setCheckable(True)
+ self._font_menu_btn.setMenu(self._font_menu)
+ font_row.addWidget(self._font_menu_btn)
+ self._font_library_btn = QPushButton(tr('字体库'), self)
self._font_library_btn.setProperty('compact', True)
self._font_library_btn.setProperty('role', 'chip')
self._font_library_btn.clicked.connect(self._open_font_library)
- font_row.addWidget(self._font_library_btn)
+ self._font_library_btn.hide()
type_layout.addLayout(font_row)
type_layout.addWidget(self._style_combo)
type_layout.addWidget(self._font_name_label)
@@ -779,8 +1011,24 @@ def _build_ui(self):
type_grid.addWidget(self._field_cell('字号', self._size_spin), 0, 0)
type_grid.addWidget(self._field_cell('排版方向', self._direction_combo), 0, 1)
type_layout.addLayout(type_grid)
- type_layout.addWidget(self._field_cell('文字效果', self._effect_combo))
type_layout.addWidget(self._field_cell('文字颜色', self._text_color))
+
+ self._advanced_style_toggle = QToolButton()
+ self._advanced_style_toggle.setText(tr('高级样式(描边 · 变形)'))
+ self._advanced_style_toggle.setCheckable(True)
+ self._advanced_style_toggle.setChecked(False)
+ self._advanced_style_toggle.setArrowType(Qt.RightArrow)
+ self._advanced_style_toggle.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
+ self._advanced_style_toggle.setProperty('role', 'quiet')
+ self._advanced_style_toggle.setProperty('compact', True)
+ self._advanced_style_toggle.toggled.connect(self._toggle_advanced_style)
+ type_layout.addWidget(self._advanced_style_toggle)
+
+ self._advanced_style_panel = QWidget()
+ adv_layout = QVBoxLayout(self._advanced_style_panel)
+ adv_layout.setContentsMargins(0, 2, 0, 0)
+ adv_layout.setSpacing(6)
+ adv_layout.addWidget(self._field_cell('文字效果', self._effect_combo))
outline_grid = QGridLayout()
outline_grid.setContentsMargins(0, 1, 0, 1)
outline_grid.setHorizontalSpacing(10)
@@ -789,11 +1037,30 @@ def _build_ui(self):
outline_grid.setColumnStretch(1, 1)
outline_grid.addWidget(self._field_cell('竖排列对齐', self._vertical_alignment_combo), 0, 0)
outline_grid.addWidget(self._field_cell('描边大小', self._outline_width), 0, 1)
- type_layout.addLayout(outline_grid)
+ adv_layout.addLayout(outline_grid)
preset_row = QHBoxLayout()
preset_row.addWidget(self._hollow_preset_btn)
preset_row.addStretch(1)
- type_layout.addLayout(preset_row)
+ adv_layout.addLayout(preset_row)
+ transform_grid = QGridLayout()
+ transform_grid.setContentsMargins(0, 1, 0, 1)
+ transform_grid.setHorizontalSpacing(10)
+ transform_grid.setVerticalSpacing(4)
+ transform_grid.setColumnStretch(0, 1)
+ transform_grid.setColumnStretch(1, 1)
+ transform_grid.addWidget(self._field_cell('横向拉伸', self._text_scale_x), 0, 0)
+ transform_grid.addWidget(self._field_cell('纵向拉伸', self._text_scale_y), 0, 1)
+ transform_grid.addWidget(self._field_cell('文字旋转', self._text_rotation), 1, 0)
+ reset_cell = QWidget()
+ reset_cell_layout = QVBoxLayout(reset_cell)
+ reset_cell_layout.setContentsMargins(0, 0, 0, 0)
+ reset_cell_layout.setSpacing(3)
+ reset_cell_layout.addStretch(1)
+ reset_cell_layout.addWidget(self._reset_transform_btn)
+ transform_grid.addWidget(reset_cell, 1, 1)
+ adv_layout.addLayout(transform_grid)
+ self._advanced_style_panel.setVisible(False)
+ type_layout.addWidget(self._advanced_style_panel)
props.addWidget(type_card)
self._offset_x, self._offset_y = QSpinBox(), QSpinBox()
@@ -805,21 +1072,6 @@ def _build_ui(self):
spin.setRange(1, 100000)
spin.setSuffix(' px')
spin.setToolTip(tr('调整译文排版蒙版,以当前中心向两侧改变大小'))
- self._text_scale_x, self._text_scale_y = QSpinBox(), QSpinBox()
- for spin in (self._text_scale_x, self._text_scale_y):
- spin.setRange(10, 400)
- spin.setValue(100)
- spin.setSuffix(' %')
- spin.setToolTip(tr('以文字中心拉伸;100% 保持原样,不改变换行与蒙版。'))
- self._text_rotation = QDoubleSpinBox()
- self._text_rotation.setRange(-180, 180)
- self._text_rotation.setDecimals(1)
- self._text_rotation.setSuffix('°')
- self._text_rotation.setToolTip(tr('以文字中心旋转;正数顺时针,负数逆时针。'))
- self._reset_transform_btn = QPushButton(tr('重置文字变形'))
- self._reset_transform_btn.setProperty('compact', True)
- self._reset_transform_btn.setProperty('role', 'chip')
- self._reset_transform_btn.clicked.connect(self._reset_text_transform)
self._show_mask = QCheckBox(tr('显示蒙版范围'))
self._show_mask.setChecked(True)
self._show_mask.setToolTip(tr('画布辅助线仅用于精修,不写入导出图片'))
@@ -830,7 +1082,7 @@ def _build_ui(self):
geo_card = QFrame()
geo_card.setObjectName('inspectorCard')
geo_layout = QVBoxLayout(geo_card)
- geo_layout.setContentsMargins(10, 8, 10, 8)
+ geo_layout.setContentsMargins(8, 8, 8, 8)
geo_layout.setSpacing(5)
geo_title = QLabel(tr('位置与蒙版'))
geo_title.setObjectName('cardTitle')
@@ -845,16 +1097,17 @@ def _build_ui(self):
geo_grid.addWidget(self._field_cell('Y 偏移', self._offset_y), 0, 1)
geo_grid.addWidget(self._field_cell('蒙版宽度', self._mask_width), 1, 0)
geo_grid.addWidget(self._field_cell('蒙版高度', self._mask_height), 1, 1)
- geo_grid.addWidget(self._field_cell('横向拉伸', self._text_scale_x), 2, 0)
- geo_grid.addWidget(self._field_cell('纵向拉伸', self._text_scale_y), 2, 1)
- geo_grid.addWidget(self._field_cell('文字旋转', self._text_rotation), 3, 0)
- reset_cell = QWidget()
- reset_cell_layout = QVBoxLayout(reset_cell)
- reset_cell_layout.setContentsMargins(0, 0, 0, 0)
- reset_cell_layout.setSpacing(3)
- reset_cell_layout.addStretch(1)
- reset_cell_layout.addWidget(self._reset_transform_btn)
- geo_grid.addWidget(reset_cell, 3, 1)
+ for spin in (self._size_spin, self._offset_x, self._offset_y, self._mask_width, self._mask_height,
+ self._text_scale_x, self._text_scale_y, self._text_rotation, self._outline_width):
+ spin.setMinimumWidth(64)
+ spin.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
+ for combo in (self._direction_combo, self._vertical_alignment_combo, self._effect_combo):
+ combo.setMinimumWidth(64)
+ combo.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
+ type_grid.setHorizontalSpacing(6)
+ outline_grid.setHorizontalSpacing(6)
+ transform_grid.setHorizontalSpacing(6)
+ geo_grid.setHorizontalSpacing(6)
geo_layout.addLayout(geo_grid)
geo_layout.addWidget(self._show_mask)
geo_layout.addWidget(self._box_label)
@@ -893,21 +1146,53 @@ def _build_ui(self):
root.addWidget(self._status)
self._pages_toggle.toggled.connect(lambda checked: self._choose_panel(0, checked))
self._properties_toggle.toggled.connect(lambda checked: self._choose_panel(1, checked))
+ self._pages_action.toggled.connect(self._pages_toggle.setChecked)
+ self._properties_action.toggled.connect(self._properties_toggle.setChecked)
self._focus_btn.toggled.connect(self._toggle_canvas_focus)
+ self._focus_action.toggled.connect(self._focus_btn.setChecked)
+ self._strip_toggle.toggled.connect(self._sync_strip_action)
+ self._strip_action.toggled.connect(self._strip_toggle.setChecked)
+ self._zoom_tool_btn.toggled.connect(self._sync_zoom_tool_action)
+ self._zoom_tool_action.toggled.connect(self._zoom_tool_btn.setChecked)
+ self._favorite_bar_action.toggled.connect(self._set_favorite_bar_visible)
+ self._font_menu_show_bar_action.toggled.connect(self._set_favorite_bar_visible)
+ self._pick_fill_btn.toggled.connect(self._sync_pick_fill_ui)
+ self._pick_fill_action.toggled.connect(self._pick_fill_btn.setChecked)
self._zoom.currentIndexChanged.connect(self._zoom_selected)
self.preview.zoom_changed.connect(self._sync_zoom_display)
self._apply_btn.clicked.connect(self.apply_changes)
self._save_btn.clicked.connect(self.request_save)
self._text_input.textChanged.connect(self._schedule_preview)
self._style_combo.currentIndexChanged.connect(self._font_selection_changed)
+ self._size_spin.valueChanged.connect(self._sync_quick_size)
+ self._quick_size_spin.valueChanged.connect(self._size_spin.setValue)
self._direction_combo.currentIndexChanged.connect(self._schedule_preview)
self._direction_combo.currentIndexChanged.connect(self._update_vertical_alignment_enabled)
self._vertical_alignment_combo.currentIndexChanged.connect(self._schedule_preview)
+ self._vertical_alignment_combo.currentIndexChanged.connect(self._update_advanced_style_badge)
self._effect_combo.currentIndexChanged.connect(self._schedule_preview)
self._effect_combo.currentIndexChanged.connect(self._update_color_default)
+ self._effect_combo.currentIndexChanged.connect(self._update_advanced_style_badge)
self._text_color.color_changed.connect(self._schedule_preview)
for spin in self._layout_spins():
spin.valueChanged.connect(self._schedule_preview)
+ style_controls = (
+ (self._style_combo, self._style_combo.currentIndexChanged, ('style', 'font_reference')),
+ (self._size_spin, self._size_spin.valueChanged, ('font_size',)),
+ (self._direction_combo, self._direction_combo.currentIndexChanged, ('direction',)),
+ (self._effect_combo, self._effect_combo.currentIndexChanged, ('text_effect',)),
+ (self._vertical_alignment_combo, self._vertical_alignment_combo.currentIndexChanged, ('vertical_alignment',)),
+ (self._text_color, self._text_color.color_changed, ('text_color',)),
+ (self._text_scale_x, self._text_scale_x.valueChanged, ('text_scale_x',)),
+ (self._text_scale_y, self._text_scale_y.valueChanged, ('text_scale_y',)),
+ (self._text_rotation, self._text_rotation.valueChanged, ('text_rotation',)),
+ (self._outline_width, self._outline_width.valueChanged, ('outline_width',)),
+ )
+ self._style_control_fields = {widget: keys for widget, signal, keys in style_controls}
+ for widget, signal, keys in style_controls:
+ signal.connect(self._note_style_control_changed)
+ for widget in (self._outline_width, self._text_scale_x, self._text_scale_y, self._text_rotation):
+ widget.valueChanged.connect(self._update_advanced_style_badge)
self._show_mask.toggled.connect(self._update_region_guide)
self._save_shortcut = QShortcut(QKeySequence.Save, self)
self._save_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
@@ -953,6 +1238,7 @@ def _build_ui(self):
self._desired_panels = [settings.value('ui/editorPages', True, type=bool),
settings.value('ui/editorProperties', True, type=bool)]
self._apply_panel_layout()
+ self._sync_favorite_bar_visibility()
self._zoom.setCurrentIndex(max(0, min(self._zoom.count() - 1, int(settings.value('ui/editorZoom', 0)))))
self._strip_toggle.setChecked(settings.value('ui/editorContinuous', False, type=bool))
@@ -998,9 +1284,166 @@ def _toggle_zoom_tool(self):
return
self._zoom_tool_btn.toggle()
+ def _sync_strip_action(self, checked):
+ self._strip_action.blockSignals(True)
+ self._strip_action.setChecked(checked)
+ self._strip_action.blockSignals(False)
+
+ def _sync_zoom_tool_action(self, checked):
+ self._zoom_tool_action.blockSignals(True)
+ self._zoom_tool_action.setChecked(checked)
+ self._zoom_tool_action.blockSignals(False)
+
+ def _sync_pick_fill_ui(self, checked):
+ self._pick_fill_action.blockSignals(True)
+ self._pick_fill_action.setChecked(checked)
+ self._pick_fill_action.blockSignals(False)
+ self._pick_cancel_btn.setVisible(bool(checked))
+
+ def _sync_quick_size(self, value):
+ self._quick_size_spin.blockSignals(True)
+ self._quick_size_spin.setValue(value)
+ self._quick_size_spin.blockSignals(False)
+
+ def _set_favorite_bar_visible(self, visible):
+ self._favorite_bar_pref = bool(visible)
+ QSettings().setValue('ui/editorFavoriteBarVisible', self._favorite_bar_pref)
+ self._sync_favorite_bar_visibility()
+
+ def _on_favorite_slots_changed(self, has_active):
+ if has_active and self._favorite_bar_pref is False:
+ return
+ self._sync_favorite_bar_visibility()
+
+ def _sync_favorite_bar_visibility(self):
+ focused = self._focus_btn.isChecked()
+ preferred = (
+ self._favorite_bar_pref
+ if self._favorite_bar_pref is not None
+ else self._favorite_fonts.has_active_slots()
+ )
+ self._favorite_fonts.setVisible(bool(preferred) and not focused)
+ for action in (self._favorite_bar_action, self._font_menu_show_bar_action):
+ action.blockSignals(True)
+ action.setChecked(bool(preferred))
+ action.blockSignals(False)
+
+ def _toggle_advanced_style(self, expanded):
+ self._advanced_style_toggle.setArrowType(Qt.DownArrow if expanded else Qt.RightArrow)
+ self._advanced_style_panel.setVisible(bool(expanded))
+
+ def _update_advanced_style_badge(self):
+ customized = (
+ self._effect_combo.currentData() not in (None, 'auto')
+ or self._vertical_alignment_combo.currentData() not in (None, 'center')
+ or self._outline_width.value() >= 0
+ or self._text_scale_x.value() != 100
+ or self._text_scale_y.value() != 100
+ or abs(self._text_rotation.value()) > 1e-6
+ )
+ self._advanced_style_toggle.setText(
+ tr('高级样式 · 已自定义') if customized else tr('高级样式(描边 · 变形)')
+ )
+
+ def _sync_export_pdf_state(self, *, enabled=None, text=None, tooltip=None):
+ if enabled is not None:
+ self._export_pdf_btn.setEnabled(enabled)
+ self._export_pdf_action.setEnabled(enabled)
+ if text is not None:
+ self._export_pdf_btn.setText(text)
+ self._export_pdf_action.setText(text)
+ if tooltip is not None:
+ self._export_pdf_btn.setToolTip(tooltip)
+ self._export_pdf_action.setToolTip(tooltip)
+
+ def _open_output_dir(self):
+ target = None
+ if self.output_path is not None and self.output_path.parent.is_dir():
+ target = self.output_path.parent
+ else:
+ configured = Path(str(self.config.get('page_output_dir', '') or ''))
+ if str(configured) and configured.is_dir():
+ target = configured
+ if target is None:
+ self._status.setText(tr('输出目录不存在或尚未生成。'))
+ return
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(target)))
+
+ def _show_block_list_context_menu(self, pos):
+ item = self.block_list.itemAt(pos)
+ if item is not None:
+ row = self.block_list.row(item)
+ self._focus_context_bubble(row)
+ if 0 <= self._loaded_row < len(self.items):
+ self._show_bubble_context_menu(self.block_list.viewport().mapToGlobal(pos))
+
+ def _show_canvas_bubble_context_menu(self, index, global_pos):
+ if not 0 <= index < len(self.items):
+ return
+ self._focus_context_bubble(index)
+ self._show_bubble_context_menu(global_pos)
+
+ def _focus_context_bubble(self, index):
+ # Right-clicking an existing member keeps the batch selection and never paints.
+ if index in self.selected_blocks():
+ self.block_list.setCurrentRow(index, QItemSelectionModel.NoUpdate)
+ else:
+ self.block_list.setCurrentRow(index)
+
+ def _show_bubble_context_menu(self, global_pos):
+ if not 0 <= self._loaded_row < len(self.items):
+ return
+ menu = QMenu(self)
+ menu.setToolTipsVisible(True)
+ self._populate_bubble_menu(menu)
+ menu.exec(global_pos)
+
+ def _populate_bubble_menu(self, menu):
+ menu.clear()
+ busy = (self._repair_worker is not None or self._export_worker is not None
+ or self._save_jobs.busy or self.page_io_busy)
+ ready = self._cleaned_image is not None and not busy
+ selected = 0 <= self._loaded_row < len(self.items)
+ restored = selected and bool(self.items[self._loaded_row].get('restore_original'))
+ editable = ready and selected and not restored
+
+ edit_act = menu.addAction(tr('全屏编辑译文') + '\tF2', self.open_text_editor)
+ edit_act.setEnabled(editable)
+ restore_label = tr('恢复处理结果') if restored else tr('还原此气泡')
+ restore_act = menu.addAction(restore_label, self.toggle_bubble_original)
+ restore_act.setEnabled(ready and selected)
+ menu.addSeparator()
+ lib_act = menu.addAction(tr('字体库…'), self._open_font_library)
+ lib_act.setEnabled(editable)
+ fav_act = menu.addAction(tr('将当前字体加入快捷字体'), self._add_favorite_font)
+ fav_act.setEnabled(editable)
+ hollow_act = menu.addAction(tr('白字黑边竖排'), self._apply_hollow_preset)
+ hollow_act.setEnabled(editable)
+ reset_act = menu.addAction(tr('重置文字变形'), self._reset_text_transform)
+ reset_act.setEnabled(editable)
+ menu.addSeparator()
+ style_copy = menu.addAction(tr('取样式'), self.copy_style)
+ style_copy.setEnabled(editable)
+ rows = self.selected_blocks() or ([self._loaded_row] if selected else [])
+ paste_style = menu.addAction(tr('应用样式到所选气泡'), self._paste_selected_style)
+ paste_style.setEnabled(ready and self._style_clipboard is not None
+ and any(not self.items[row].get('restore_original') for row in rows))
+ paste_style.setToolTip(tr('仅应用字体与排版;保留译文和位置,跳过已还原原图的气泡。'))
+ brush_style = menu.addAction(tr('样式刷'))
+ brush_style.setCheckable(True)
+ brush_style.setChecked(self._style_brush_btn.isChecked())
+ brush_style.setEnabled(ready and self._style_clipboard is not None)
+ brush_style.toggled.connect(self._style_brush_btn.setChecked)
+ undo_style = menu.addAction(tr('撤销样式'), self.undo_style)
+ undo_style.setEnabled(ready and bool(self._style_history))
+ menu.addSeparator()
+ link_act = menu.addAction(tr('关联原图…'), self.link_original)
+ link_act.setEnabled(ready)
+
def save_ui_state(self):
settings = QSettings()
- settings.setValue('ui/editorSplitter', self._wide_splitter_state or (self._focus_splitter_state if self._focus_btn.isChecked() else self.splitter.saveState()))
+ focus_state = self._focus_splitter_state if (self._focus_btn.isChecked() and hasattr(self, '_focus_splitter_state')) else self.splitter.saveState()
+ settings.setValue('ui/editorSplitter', self._wide_splitter_state or focus_state)
settings.setValue('ui/editorInspectorSplitter', self._inspector_splitter.saveState())
panels = self._desired_panels
settings.setValue('ui/editorPages', panels[0])
@@ -1016,7 +1459,7 @@ def _choose_panel(self, index, checked):
settings.setValue('ui/editorPages' if index == 0 else 'ui/editorProperties', checked)
self._apply_panel_layout()
- def _apply_panel_layout(self):
+ def _apply_panel_layout(self, *, animate=True):
focused = self._focus_btn.isChecked()
compact = self.isVisible() and self.width() < 1120
if compact and not self._was_compact and not focused:
@@ -1026,14 +1469,19 @@ def _apply_panel_layout(self):
effective = [False, False]
elif compact and all(effective):
effective[1 - self._panel_priority] = False
- for index, (button, panel) in enumerate(((self._pages_toggle, self._pages_panel),
- (self._properties_toggle, self._properties_panel))):
+ for index, (button, action, panel) in enumerate((
+ (self._pages_toggle, self._pages_action, self._pages_panel),
+ (self._properties_toggle, self._properties_action, self._properties_panel),
+ )):
button.blockSignals(True)
button.setChecked(effective[index])
button.blockSignals(False)
+ action.blockSignals(True)
+ action.setChecked(effective[index])
+ action.blockSignals(False)
was_visible = panel.isVisible()
want_visible = effective[index]
- if self.isVisible() and was_visible != want_visible:
+ if animate and self.isVisible() and was_visible != want_visible:
edge = 'left' if index == 0 else 'right'
if want_visible:
panel.setVisible(True)
@@ -1043,9 +1491,17 @@ def _apply_panel_layout(self):
panel.setVisible(False)
else:
panel.setVisible(want_visible)
- button.setToolTip(tr('窗口较窄时暂时收起;展开此栏会让出另一个侧栏的位置。')
- if self._desired_panels[index] and not effective[index] and not focused else '')
- if not compact and self._was_compact and not focused and self._wide_splitter_state is not None:
+ tip = (tr('窗口较窄时暂时收起;展开此栏会让出另一个侧栏的位置。')
+ if self._desired_panels[index] and not effective[index] and not focused else '')
+ button.setToolTip(tip)
+ action.setToolTip(tip)
+ if compact and not focused:
+ avail = max(400, self.width() - 36)
+ left_w = 210 if effective[0] else 0
+ right_w = min(328, max(310, avail // 3)) if effective[1] else 0
+ center_w = max(280, avail - left_w - right_w)
+ self.splitter.setSizes([left_w, center_w, right_w])
+ elif not compact and self._was_compact and not focused and self._wide_splitter_state is not None:
self.splitter.restoreState(self._wide_splitter_state)
self._wide_splitter_state = None
self._was_compact = compact
@@ -1055,15 +1511,18 @@ def _toggle_canvas_focus(self, focused):
self._focus_splitter_state = self.splitter.saveState()
self._apply_panel_layout()
else:
- self.splitter.restoreState(self._focus_splitter_state)
+ if hasattr(self, '_focus_splitter_state'):
+ self.splitter.restoreState(self._focus_splitter_state)
self._apply_panel_layout()
+ self._focus_action.blockSignals(True)
+ self._focus_action.setChecked(focused)
+ self._focus_action.blockSignals(False)
+ self._focus_btn.setVisible(focused)
for widget, edge, slide_hide in (
(self._canvas_heading, 'top', True),
(self._status, 'bottom', True),
- (self._pages_toggle, 'top', False),
- (self._properties_toggle, 'top', False),
):
- want_visible = not focused
+ want_visible = not focused and (widget is not self._canvas_heading or self.height() >= 680)
was_visible = widget.isVisible()
if self.isVisible() and was_visible != want_visible:
if want_visible:
@@ -1075,26 +1534,19 @@ def _toggle_canvas_focus(self, focused):
widget.setVisible(False)
else:
widget.setVisible(want_visible)
+ self._sync_favorite_bar_visibility()
self._update_toolbar_labels()
def _update_toolbar_labels(self):
- compact = self.width() < 1120
- for button, full, short in (
- (self._properties_toggle, tr('编辑面板'), tr('面板')),
- (self._zoom_tool_btn, tr('缩放工具'), tr('缩放')),
- (self._strip_toggle, tr('连续长条'), tr('长条')),
- (self._export_pdf_btn, tr('导出 PDF'), 'PDF'),
- (self._save_btn, tr('保存图片'), tr('保存')),
- ):
- button.setText(short if compact else full)
- button.setAccessibleName(full)
- self._focus_btn.setText(tr('退出专注') if self._focus_btn.isChecked()
- else tr('专注') if compact else tr('专注画布'))
+ narrow = self.width() < 920
+ self._save_btn.setText(tr('保存') if narrow else tr('保存图片'))
+ self._save_btn.setAccessibleName(tr('保存图片'))
+ self._focus_btn.setText(tr('退出专注'))
self._focus_btn.setAccessibleName(tr('专注画布'))
def _toggle_source_text(self, expanded):
self._source_expanded = expanded
- self._source_compact_override = expanded and self.height() < 700
+ self._source_compact_override = expanded and self.height() < 680
QSettings().setValue('ui/editorSourceExpanded', expanded)
self._apply_source_layout()
@@ -1106,35 +1558,39 @@ def _reveal_text_editor(self):
self._sync_inspector_split()
def _sync_inspector_split(self):
- short = self.height() < 560
+ compact_h = self.height() < 680
+ very_short = self.height() < 500
if hasattr(self, '_canvas_heading'):
- self._canvas_heading.setVisible(not short)
+ self._canvas_heading.setVisible(not compact_h and not self._focus_btn.isChecked())
if hasattr(self, '_inspector_heading'):
- self._inspector_heading.setVisible(not short)
+ self._inspector_heading.setVisible(not compact_h)
if hasattr(self, '_root_layout'):
- self._root_layout.setContentsMargins(10 if short else 14, 4 if short else 10, 10 if short else 14, 4 if short else 8)
- self._root_layout.setSpacing(4 if short else 8)
- self._toolbar_layout.setContentsMargins(0, 0, 0, 4 if short else 8)
- self._header_layout.setContentsMargins(10 if short else 12, 3 if short else 6, 10 if short else 12, 3 if short else 6)
- self._inspector_body_layout.setContentsMargins(8 if short else 10, 2 if short else 6, 8 if short else 10, 2 if short else 6)
- self._text_props_layout.setContentsMargins(0, 4 if short else 8, 0, 0)
- self._text_props_layout.setSpacing(4 if short else 6)
- self._layout_tab_root.setContentsMargins(0, 2 if short else 6, 0, 0)
- self._inspector_actions_layout.setContentsMargins(10 if short else 12, 3 if short else 8, 10 if short else 12, 3 if short else 8)
- self._break_hint.setVisible(not short)
- self._inspector_hint.setVisible(not short)
- self._inspector_spacer.setVisible(short)
- self._text_input.setMinimumHeight(42 if short else 80)
- self._inspector_splitter.setHandleWidth(4 if short else 6)
- self.block_list.setMinimumHeight(38 if short else 108)
+ self._root_layout.setContentsMargins(10 if compact_h else 14, 4 if compact_h else 10, 10 if compact_h else 14, 4 if compact_h else 8)
+ self._root_layout.setSpacing(4 if compact_h else 8)
+ self._toolbar_layout.setContentsMargins(0, 0, 0, 4 if compact_h else 8)
+ self._header_layout.setContentsMargins(10 if compact_h else 12, 3 if compact_h else 6, 10 if compact_h else 12, 3 if compact_h else 6)
+ self._inspector_body_layout.setContentsMargins(8 if compact_h else 10, 2 if compact_h else 6, 8 if compact_h else 10, 2 if compact_h else 6)
+ self._text_props_layout.setContentsMargins(0, 4 if compact_h else 8, 0, 0)
+ self._text_props_layout.setSpacing(4 if compact_h else 6)
+ self._layout_tab_root.setContentsMargins(0, 2 if compact_h else 6, 0, 0)
+ self._inspector_actions_layout.setContentsMargins(10 if compact_h else 12, 3 if compact_h else 8, 10 if compact_h else 12, 3 if compact_h else 8)
+ self._break_hint.setVisible(not compact_h)
+ self._inspector_hint.setVisible(not compact_h)
+ self._inspector_spacer.setVisible(compact_h)
+ self._text_input.setMinimumHeight(42 if very_short else 72 if compact_h else 88)
+ self._inspector_splitter.setHandleWidth(4 if very_short else 6)
+ self.block_list.setMinimumHeight(38 if very_short else 68 if compact_h else 104)
total = sum(self._inspector_splitter.sizes())
if total <= 0:
return
- if short:
- list_h = 38 if self.height() < 520 else 42
+ if very_short:
+ list_h = 38 if self.height() < 460 else 42
self._inspector_splitter.setSizes([list_h, max(120, total - list_h)])
- elif self._inspector_splitter.sizes()[0] < 108:
- list_h = min(150, max(108, total // 4))
+ elif compact_h:
+ list_h = min(92, max(68, total // 4))
+ self._inspector_splitter.setSizes([list_h, max(180, total - list_h)])
+ elif self._inspector_splitter.sizes()[0] < 104 or self._inspector_splitter.sizes()[0] > total // 2:
+ list_h = min(148, max(104, total // 4))
self._inspector_splitter.setSizes([list_h, max(200, total - list_h)])
def _step_block(self, delta):
@@ -1156,7 +1612,9 @@ def _refresh_block_counter(self):
if not hasattr(self, '_block_counter'):
return
total = len(self.items)
- if total and 0 <= self._loaded_row < total:
+ if len(self.selected_blocks()) > 1:
+ self._block_counter.setText(tr('已选 {_0} / {_1}', _0=len(self.selected_blocks()), _1=total))
+ elif total and 0 <= self._loaded_row < total:
self._block_counter.setText(tr('{_0} / {_1}', _0=self._loaded_row + 1, _1=total))
elif total:
self._block_counter.setText(tr('{_0} 块', _0=total))
@@ -1165,8 +1623,10 @@ def _refresh_block_counter(self):
self._prev_block_btn.setEnabled(total > 1 and self._loaded_row > 0)
self._next_block_btn.setEnabled(total > 1 and 0 <= self._loaded_row < total - 1)
- def _apply_source_layout(self):
- expanded = self._source_expanded and (not self.isVisible() or self.height() >= 700 or self._source_compact_override)
+ def _apply_source_layout(self, *, animate=True):
+ compact_h = self.isVisible() and self.height() < 680
+ target_h = 52 if compact_h else 84
+ expanded = self._source_expanded and (not compact_h or self._source_compact_override)
self._source_toggle.blockSignals(True)
self._source_toggle.setChecked(expanded)
self._source_toggle.blockSignals(False)
@@ -1178,18 +1638,18 @@ def _apply_source_layout(self):
self._source_anim_gen += 1
gen = self._source_anim_gen
- if not self.isVisible() or reduced_motion():
+ if not animate or not self.isVisible() or reduced_motion():
self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
- self._source_text.setFixedHeight(92 if expanded else 0)
+ self._source_text.setFixedHeight(target_h if expanded else 0)
self._source_text.setVisible(expanded)
return
was_visible = self._source_text.isVisible()
- if was_visible == expanded and self._source_text.height() == (92 if expanded else 0):
+ if was_visible == expanded and self._source_text.height() == (target_h if expanded else 0):
return
start_h = self._source_text.height() if was_visible else 0
- end_h = 92 if expanded else 0
+ end_h = target_h if expanded else 0
self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._source_text.setVisible(True)
self._source_text.setFixedHeight(start_h)
@@ -1211,7 +1671,7 @@ def _on_done():
self._source_anim = None
self._source_text.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
if expanded:
- self._source_text.setFixedHeight(92)
+ self._source_text.setFixedHeight(target_h)
self._source_text.setVisible(True)
else:
self._source_text.setFixedHeight(0)
@@ -1224,9 +1684,19 @@ def _on_done():
def _set_editable(self, enabled):
restored = 0 <= self._loaded_row < len(self.items) and self.items[self._loaded_row].get('restore_original', False)
- for widget in (self._text_input, self._line_break_btn, self._style_combo, self._font_library_btn, self._direction_combo, self._vertical_alignment_combo, self._effect_combo, self._text_color, self._hollow_preset_btn, self._reset_transform_btn, *self._layout_spins(), self._show_mask, self._apply_btn, self._save_btn):
- widget.setEnabled(enabled and not restored)
+ active = enabled and not restored
+ for widget in (self._text_input, self._line_break_btn, self._quick_size_spin, self._style_combo,
+ self._font_menu_btn, self._font_library_btn, self._direction_combo,
+ self._vertical_alignment_combo, self._effect_combo, self._text_color,
+ self._hollow_preset_btn, self._reset_transform_btn, *self._layout_spins(),
+ self._show_mask, self._apply_btn, self._save_btn):
+ widget.setEnabled(active)
+ for action in (self._font_library_action, self._import_font_action, self._add_favorite_action):
+ action.setEnabled(active)
self._show_mask.setEnabled(enabled)
+ self._copy_style_btn.setEnabled(enabled and not restored)
+ self._style_brush_btn.setEnabled(enabled and self._style_clipboard is not None)
+ self._undo_style_btn.setEnabled(enabled and bool(self._style_history))
self._update_vertical_alignment_enabled()
self._update_repair_controls()
@@ -1248,9 +1718,31 @@ def _open_font_library(self):
except Exception as exc:
self._status.setText(tr('字体库未能打开:{_0}', _0=exc))
+ def _import_local_fonts(self):
+ paths, _ = QFileDialog.getOpenFileNames(
+ self, tr('导入漫画译文字体'), '', tr('字体 (*.ttf *.otf *.ttc *.otc)'))
+ if not paths:
+ return []
+ imported, failures = [], []
+ for path in paths:
+ try:
+ imported.append(import_font(path))
+ except Exception as exc:
+ failures.append(f'{Path(path).name}:{exc}')
+ if imported:
+ reference = font_reference(imported[-1].path)
+ self._refresh_font_choices()
+ index = self._style_combo.findData(reference)
+ if index >= 0:
+ self._style_combo.setCurrentIndex(index)
+ self._status.setText(tr('已导入或复用 {_0} 款字体。', _0=len({font.path for font in imported})))
+ elif failures:
+ self._status.setText(tr('未导入:{_0}', _0=';'.join(failures)))
+ return imported
+
def _import_pages(self):
- paths, _ = QFileDialog.getOpenFileNames(self, tr('导入已翻译图片或 PDF'),
- str(self.config.get('page_output_dir', '')), tr('漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.json)'))
+ paths, _ = QFileDialog.getOpenFileNames(self, tr('导入已翻译的漫画'),
+ str(self.config.get('page_output_dir', '')), tr('漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz *.json *.comitrans)'))
if paths:
self.request_import(paths)
@@ -1272,7 +1764,9 @@ def read(cancelled):
raise RuntimeError('页面索引已取消')
try:
path = Path(raw).resolve()
- if path.suffix.lower() == '.pdf' or path.name == 'project.json':
+ if path.suffix.lower() == '.comitrans':
+ path = path.with_suffix('.pdf')
+ if path.suffix.lower() in PROJECT_EXTS or path.name == 'project.json':
result.append((path, read_project_pages(path, cancelled)))
else:
reader = QImageReader(str(path))
@@ -1420,6 +1914,8 @@ def _add_favorite_font(self):
return
if not self._favorite_fonts.add_font(reference):
self._status.setText(tr('常用字体已满(9 个),请在“设置快捷字体”中替换。'))
+ elif self._favorite_bar_pref is False:
+ self._set_favorite_bar_visible(True)
def _apply_favorite_font(self, reference):
if (not self._style_combo.isEnabled() or self.page_io_busy or self._save_jobs.busy
@@ -1552,6 +2048,9 @@ def _clear_loaded_page(self):
self._repair_box = None
self._repair_mode.setChecked(False)
self._add_bubble_btn.setChecked(False)
+ self._style_history.clear()
+ self._pending_style_keys.clear()
+ self._style_brush_btn.setChecked(False)
self.output_path = self.cleaned_path = self.layout_path = None
self.items = []
self._loaded_row = -1
@@ -1564,7 +2063,7 @@ def _clear_loaded_page(self):
self._layer_cache.clear()
self.block_list.clear()
self._refresh_block_counter()
- self._export_pdf_btn.setEnabled(False)
+ self._sync_export_pdf_state(enabled=False)
self.preview.clear(tr('选择一页,开始精修'))
self._set_editable(False)
self._status.setText(tr('已清空页面列表。'))
@@ -1593,27 +2092,29 @@ def _allow_navigation(self, action):
return True
return False
- def request_page(self, output_path):
+ def request_page(self, output_path, *, block=None):
path = Path(output_path).resolve()
self._import_jobs.invalidate()
self._page_jobs.invalidate()
self._indexing = self._requesting_page = False
- if path.suffix.lower() == '.pdf' or path.name == 'project.json':
+ if path.suffix.lower() in PROJECT_EXTS or path.suffix.lower() == '.comitrans' or path.name == 'project.json':
return self.request_import([path])
if path == self.output_path:
self._page_jobs.invalidate()
self._requesting_page = False
self._restore_page_selection()
self._update_repair_controls()
+ if block is not None:
+ self._jump_to_block(block)
return True
self._restore_page_selection()
- if not self._allow_navigation(lambda: self.request_page(path)):
+ if not self._allow_navigation(lambda: self.request_page(path, block=block)):
self._update_repair_controls()
return False
- self._begin_page_load(path)
+ self._begin_page_load(path, after=None if block is None else lambda: self._jump_to_block(block))
return True
- def _begin_page_load(self, path, *, import_notice=''):
+ def _begin_page_load(self, path, *, import_notice='', after=None, failed=None):
revision, previous = self._edit_revision, self.output_path
settings = deepcopy(self.config)
self._requesting_page = True
@@ -1623,14 +2124,106 @@ def _begin_page_load(self, path, *, import_notice=''):
def accept(data):
self._requesting_page = False
if self.output_path != previous or self._edit_revision != revision:
- self._status.setText(tr('加载期间当前页有新修改,已保留当前页;请重新选择目标页。'))
+ message = tr('加载期间当前页有新修改,已保留当前页;请重新选择目标页。')
+ self._status.setText(message)
self._update_repair_controls()
+ if failed:
+ failed(message)
return
- if self.load_page(path, _payload=data, _approved=True) and import_notice:
- self._status.setText(f'{self._status.text()} · {import_notice}')
- self._page_jobs.submit(lambda cancelled: read_page(path, settings, cancelled), accept, self._page_load_failed, cancellable=True)
+ if self.load_page(path, _payload=data, _approved=True):
+ if import_notice:
+ self._status.setText(f'{self._status.text()} · {import_notice}')
+ if after:
+ after()
+ elif failed:
+ failed(self._status.text())
+ def reject(message):
+ self._page_load_failed(message)
+ if failed:
+ failed(message)
+ self._page_jobs.submit(lambda cancelled: read_page(path, settings, cancelled), accept, reject, cancellable=True)
self._update_repair_controls()
+ def open_transcript(self):
+ from .transcript_dialog import TranscriptDialog
+ if not self._transcript_btn.isEnabled():
+ return
+ if self._text_dialog is not None:
+ self._text_dialog.close()
+ project = self._pdf_projects.get(str(self.output_path))
+ dialog = TranscriptDialog(lambda jobs, loaded, failed: self._index_transcript(
+ jobs, loaded, failed, project), self._replace_transcript, self)
+ if dialog.exec() and dialog.selection is not None:
+ self.request_page(dialog.selection.path, block=dialog.selection.index)
+ dialog.deleteLater()
+
+ def _index_transcript(self, jobs, loaded, failed, project):
+ self._store_properties()
+ keys = [str(path) for path in project.images] if project else [
+ self.page_list.item(row).data(Qt.UserRole) for row in range(self.page_list.count())]
+ pages = [(Path(key), self._page_items[key].data(Qt.UserRole + 1))
+ for key in keys if key in self._page_items]
+ current = self.output_path if self._cleaned_image is not None else None
+ items = deepcopy(self.items)
+ jobs.submit(lambda cancelled: read_transcript(pages, current, items, cancelled),
+ loaded, failed, cancellable=True)
+
+ def _replace_transcript(self, replacements, complete, progress):
+ grouped = {}
+ for entry, text in replacements:
+ grouped.setdefault(entry.path, []).append((entry, text))
+ pages = list(grouped.items())
+ starting_page = self.output_path
+ saved_start = starting_page
+ completed = 0
+
+ def finish(error=''):
+ if error:
+ complete(tr('已保存 {_0} 页。替换暂停({_1})', _0=completed, _1=error))
+ else:
+ complete(tr('已保存 {_0} 页的译文替换', _0=completed))
+
+ def save_next():
+ if completed == len(pages):
+ finish()
+ return
+ path, changes = pages[completed]
+ if path == starting_page:
+ path = saved_start
+ progress(completed + 1, len(pages))
+
+ def apply():
+ if any(entry.index >= len(self.items)
+ or self.items[entry.index].get('restore_original')
+ or str(self.items[entry.index].get('source_text') or '') != entry.source
+ or str(self.items[entry.index].get('text') or '') != entry.translation
+ for entry, _text in changes):
+ finish(tr('页面内容已更新,请重新预览替换'))
+ return
+ for entry, text in changes:
+ self.items[entry.index]['text'] = text
+ self._refresh_block_item(entry.index)
+ self._load_properties(self._loaded_row)
+ self._mark_dirty(properties=False)
+ self.request_save(after=saved, on_error=finish)
+
+ if path == self.output_path:
+ apply()
+ else:
+ self._begin_page_load(path, after=apply, failed=finish)
+
+ def saved():
+ nonlocal completed
+ completed += 1
+ save_next()
+
+ def start():
+ nonlocal saved_start
+ saved_start = self.output_path
+ save_next()
+
+ self.request_save(after=start, on_error=finish)
+
def _page_load_failed(self, error):
self._requesting_page = False
self._restore_page_selection()
@@ -1643,7 +2236,7 @@ def _page_load_failed(self, error):
def confirm_discard(self):
if self._export_worker is not None:
- self._status.setText(tr('正在导出 PDF,请完成或取消导出后再切页或退出。'))
+ self._status.setText(tr('正在导出,请完成或取消后再切页或退出。'))
return False
if self._repair_worker is not None:
self._status.setText(tr('正在修补背景,请稍候再保存或切换页面。'))
@@ -1660,7 +2253,7 @@ def confirm_discard(self):
def load_page(self, output_path, *, _payload=None, _approved=False):
path = Path(output_path).resolve()
- if path.suffix.lower() == '.pdf' or path.name == 'project.json':
+ if path.suffix.lower() in PROJECT_EXTS or path.name == 'project.json':
try:
pages = self._register_pdf(path)
except Exception as exc:
@@ -1668,7 +2261,7 @@ def load_page(self, output_path, *, _payload=None, _approved=False):
return False
path = self.output_path if self.output_path in pages else pages[0]
if self.output_path == path:
- self._export_pdf_btn.setEnabled(True)
+ self._sync_export_pdf_state(enabled=True)
return True
if not _approved and not self.confirm_discard():
return False
@@ -1684,6 +2277,9 @@ def load_page(self, output_path, *, _payload=None, _approved=False):
self._repair_box = None
self._repair_mode.setChecked(False)
self._edit_revision = 0
+ self._style_history.clear()
+ self._pending_style_keys.clear()
+ self._style_brush_btn.setChecked(False)
self._loading = True
self._loaded_row = -1
self._row_dirty = False
@@ -1700,7 +2296,7 @@ def load_page(self, output_path, *, _payload=None, _approved=False):
self._text_input.clear()
self._set_editable(False)
self.output_path = path
- self._export_pdf_btn.setEnabled(self._export_worker is None)
+ self._sync_export_pdf_state(enabled=self._export_worker is None)
self.cleaned_path = path.parent.parent / f'{path.parent.name}_cleaned' / f'{path.stem}_cleaned.png'
self.layout_path = path.parent.parent / f'{path.parent.name}_layout' / f'{path.stem}_layout.json'
page_item = self._add_page(path, _payload.preview.size())
@@ -1838,12 +2434,12 @@ def toggle_bubble_original(self):
else tr('此气泡已还原为原图 · 未保存,点击保存图片后保留。'))
return True
- def _mark_dirty(self):
+ def _mark_dirty(self, *, properties=True):
if self._loading or not self.items:
return
self._edit_revision += 1
self._dirty = True
- self._row_dirty = True
+ self._row_dirty = self._row_dirty or properties
self._preview_dirty = True
self._status.setText(tr('● 未保存修改 · {_0}', _0=self.output_path.name))
self._refresh_page_dirty_label()
@@ -1875,6 +2471,92 @@ def _apply_dialog_text(self, text):
return
self._text_input.setPlainText(text)
+ def open_retranslation(self):
+ from ..bubble_translation import retranslate_bubble
+ from .retranslate_dialog import RetranslateDialog
+
+ if not self._retranslate_btn.isEnabled() or not self.apply_changes():
+ return
+ if self._text_dialog is not None:
+ self._text_dialog.close()
+ index = self._loaded_row
+ item = self.items[index]
+ config = load_ai_config()
+ language = item.get('source_language') or config.get('source_language', 'ja')
+ original = find_original(self.output_path)
+ bounds = (0, 0, *self._cleaned_image.size)
+ box = intersection(item['box'][:4], bounds)
+ source = str(item.get('source_text') or '')
+ current = str(item.get('text') or '')
+ neighbors = [
+ {'原文': row.get('source_text', ''), '译文': row.get('text', '')}
+ for row in self.items[max(0, index - 2):index + 3] if row is not item]
+ context = '相邻气泡,仅供参考:\n' + json.dumps(neighbors, ensure_ascii=False) if neighbors else ''
+ def translate(text, instruction, cancelled):
+ return retranslate_bubble(config, language, text, instruction, context,
+ original if box else None, box, cancelled)
+ dialog = RetranslateDialog(source, current, translate,
+ lambda candidate: self._preview_retranslation(index, candidate), self)
+ try:
+ if dialog.exec() and dialog.result_text is not None:
+ revised_source = dialog.source.toPlainText().strip()
+ if revised_source != source:
+ item.setdefault('ocr_raw_text', source)
+ item['source_text'] = revised_source
+ item['text'] = dialog.result_text
+ self._load_properties(index)
+ self._mark_dirty(properties=False)
+ self._preview_timer.start()
+ self._status.setText(tr('已应用候选译文,保存后写入图片'))
+ finally:
+ dialog.deleteLater()
+
+ def _preview_retranslation(self, index, candidate):
+ from PIL.ImageQt import ImageQt
+
+ item = self.items[index]
+ box = self._mask_box(item)
+ rectangles = [box]
+ cached = self._layer_cache.get(index)
+ if cached:
+ rectangles.append(layer_bounds(cached[1:4]))
+ layer = None
+ if candidate is not None:
+ revised = {**item, 'text': candidate}
+ typesetter = self._typesetter_for_item(item)
+ size = item.get('font_size') if item.get('manual_layout') else item.get('rendered_font_size') or item.get('font_size')
+ layer = self._draw_lettering(self._cleaned_image, revised, typesetter, box, int(size or 0))
+ if layer is not None:
+ rectangles.append(layer_bounds(layer))
+ left = min(rect[0] for rect in rectangles)
+ top = min(rect[1] for rect in rectangles)
+ right = max(rect[2] for rect in rectangles)
+ bottom = max(rect[3] for rect in rectangles)
+ padding = max(12, round(max(right - left, bottom - top) * .12))
+ bounds = (0, 0, *self._rendered.size)
+ crop = intersection((left - padding, top - padding, right + padding, bottom + padding), bounds) or bounds
+
+ def preview(image):
+ sample = image.crop(crop)
+ sample.thumbnail((600, 280))
+ return ImageQt(sample).copy()
+
+ current = preview(self._rendered)
+ if candidate is None:
+ return current, None
+ layers = []
+ for row in range(len(self.items)):
+ if row == index:
+ if layer is not None:
+ layers.append(layer)
+ elif row in self._layer_cache:
+ layers.append(self._layer_cache[row][1:4])
+ original = self._get_original_image() if any(i.get('restore_original') for i in self.items) else None
+ revised_image, _ = compose_page(self._cleaned_image, self._rendered, layers, [crop],
+ watermark=bool(self.config.get('watermark_enabled', True)),
+ original=original, items=self.items, copy_previous=True)
+ return current, preview(revised_image)
+
def _layout_spins(self):
return (self._size_spin, self._offset_x, self._offset_y, self._mask_width, self._mask_height,
self._text_scale_x, self._text_scale_y, self._text_rotation, self._outline_width)
@@ -1926,6 +2608,7 @@ def _mask_box(item, *, width=None, height=None, offset_x=None, offset_y=None):
return [left, top, left + width, top + height]
def _update_region_guide(self):
+ self.preview.set_selected_regions(self.selected_blocks())
self.preview.set_regions(
[(index, tuple(self._mask_box(item))) for index, item in enumerate(self.items)],
visible=self._show_mask.isChecked() and not self._repair_mode.isChecked())
@@ -1942,17 +2625,160 @@ def _update_region_guide(self):
if restored:
box = list(self.items[self._loaded_row]['box'][:4])
self._box_label.setText(tr('原图区域:{_0}', _0=', '.join(map(str, box))))
- self.preview.set_region(box if self._show_mask.isChecked() else None, editable=box is not None and not restored)
+ self.preview.set_region(box if self._show_mask.isChecked() else None,
+ editable=box is not None and not restored and len(self.selected_blocks()) <= 1
+ and not self._style_brush_btn.isChecked())
def _select_block(self, index):
"""A click on a box in the canvas is the same as picking it in the list."""
- if not 0 <= index < len(self.items) or index == self._loaded_row:
+ if not 0 <= index < len(self.items):
+ return
+ if self._style_brush_btn.isChecked():
+ self.block_list.setCurrentRow(index)
+ self.paste_style([index])
return
self.block_list.setCurrentRow(index)
item = self.block_list.item(index)
if item is not None:
self.block_list.scrollToItem(item, QAbstractItemView.PositionAtCenter)
+ def selected_blocks(self):
+ return sorted(self.block_list.row(item) for item in self.block_list.selectedItems())
+
+ def _selection_changed(self):
+ if self._loading or not hasattr(self, '_show_mask'):
+ return
+ rows = self.selected_blocks()
+ if rows and self._loaded_row not in rows:
+ self.block_list.setCurrentRow(rows[0], QItemSelectionModel.NoUpdate)
+ self._refresh_block_counter()
+ self._update_region_guide()
+ if len(rows) > 1:
+ self._status.setText(tr('已选 {_0} 个气泡:排版修改应用到所选,译文和位置单独保留。', _0=len(rows)))
+
+ def _select_blocks(self, indices, mode='replace'):
+ self._store_properties()
+ rows = set(self.selected_blocks()) if mode in ('toggle', 'add') else set()
+ targets = {int(index) for index in indices if 0 <= int(index) < len(self.items)}
+ rows = rows ^ targets if mode == 'toggle' else rows | targets
+ blocked = self.block_list.blockSignals(True)
+ try:
+ for row in range(self.block_list.count()):
+ self.block_list.item(row).setSelected(row in rows)
+ if rows:
+ self.block_list.setCurrentRow(min(rows), QItemSelectionModel.NoUpdate)
+ finally:
+ self.block_list.blockSignals(blocked)
+ if rows:
+ self._load_properties(min(rows))
+ self._selection_changed()
+ if self._style_brush_btn.isChecked() and rows:
+ self.paste_style(sorted(rows))
+
+ def _note_style_change(self, keys):
+ if self._loading or self._loaded_row < 0:
+ return
+ if not self._pending_style_keys:
+ self._pending_style_rows = self.selected_blocks()
+ self._pending_style_keys.update(keys)
+
+ def _note_style_control_changed(self, *_args):
+ self._note_style_change(self._style_control_fields.get(self.sender(), ()))
+
+ def _stop_style_brush(self):
+ self._style_brush_btn.setChecked(False)
+ self.preview.cancel_region_drag()
+
+ def _sync_style_brush_ui(self, enabled):
+ self._brush_cancel_btn.setVisible(enabled)
+ self._restore_bubble_btn.setVisible(not enabled)
+ if enabled:
+ self._repair_mode.setChecked(False)
+ self._add_bubble_btn.setChecked(False)
+ self._pick_fill_btn.setChecked(False)
+ self._update_region_guide()
+
+ def _stop_style_brush_for_tool(self, enabled):
+ if enabled:
+ self._stop_style_brush()
+
+ def _paste_selected_style(self):
+ return self.paste_style(self.selected_blocks() or [self._loaded_row])
+
+ def _brush_list_clicked(self, *_args):
+ if self._style_brush_btn.isChecked():
+ self.paste_style()
+
+ def _remember_style_change(self, before):
+ changed = {row: item for row, item in before.items()
+ if lettering_style(item) != lettering_style(self.items[row])}
+ if changed:
+ self._style_history.append(changed)
+ self._style_history = self._style_history[-20:]
+ self._undo_style_btn.setEnabled(True)
+
+ def copy_style(self):
+ if not 0 <= self._loaded_row < len(self.items) or self.items[self._loaded_row].get('restore_original'):
+ return False
+ self._store_properties()
+ self._style_clipboard = lettering_style(self.items[self._loaded_row])
+ self._style_brush_btn.setEnabled(True)
+ self._style_brush_btn.setChecked(True)
+ self._status.setText(tr('已取样式,点击或框选目标气泡;Esc 退出样式刷。'))
+ return True
+
+ def paste_style(self, rows=None):
+ if self._style_clipboard is None or self.page_io_busy or self._save_jobs.busy or self._repair_worker is not None or self._export_worker is not None:
+ return False
+ self._store_properties()
+ rows = self.selected_blocks() if rows is None else rows
+ before = {row: deepcopy(self.items[row]) for row in rows if 0 <= row < len(self.items)}
+ for row in before:
+ apply_lettering_style(self.items[row], self._style_clipboard)
+ self._remember_style_change(before)
+ if not any(lettering_style(self.items[row]) != lettering_style(item) for row, item in before.items()):
+ return False
+ self._finish_style_edit()
+ return True
+
+ def _finish_style_edit(self):
+ self._edit_revision += 1
+ self._dirty = self._preview_dirty = True
+ self._row_dirty = False
+ self._refresh_page_dirty_label()
+ for row in self.selected_blocks():
+ self._refresh_block_item(row)
+ if self._loaded_row >= 0:
+ self._load_properties(self._loaded_row)
+ self.apply_changes()
+
+ def undo_style(self):
+ self._store_properties()
+ if not self._style_history or self.page_io_busy or self._save_jobs.busy or self._repair_worker is not None or self._export_worker is not None:
+ return False
+ before = self._style_history.pop()
+ for row, previous in before.items():
+ if row >= len(self.items):
+ continue
+ for key in (*STYLE_DEFAULTS, 'manual_layout', 'rendered_font_size'):
+ if key in previous:
+ self.items[row][key] = deepcopy(previous[key])
+ else:
+ self.items[row].pop(key, None)
+ self._refresh_block_item(row)
+ self._finish_style_edit()
+ self._undo_style_btn.setEnabled(bool(self._style_history))
+ return True
+
+ def _jump_to_block(self, index):
+ if not 0 <= index < len(self.items):
+ return
+ self._select_block(index)
+ self._inspector_tabs.setCurrentIndex(0)
+ item = self.items[index]
+ box = item['box'][:4] if item.get('restore_original') else self._mask_box(item)
+ self.preview.reveal_region(box)
+
def _resize_region_from_canvas(self, box):
if self._repair_mode.isChecked():
self._repair_box = tuple(box) if box is not None else None
@@ -2042,6 +2868,9 @@ def _store_properties(self):
if not self._row_dirty or self._loaded_row < 0 or self._loaded_row >= len(self.items):
return
item = self.items[self._loaded_row]
+ keys = set(self._pending_style_keys)
+ rows = list(self._pending_style_rows)
+ before = {row: deepcopy(self.items[row]) for row in set(rows + [self._loaded_row])} if keys else {}
if self._font_choice_dirty:
choice = self._style_combo.currentData()
if choice in STYLE_LABELS:
@@ -2063,6 +2892,16 @@ def _store_properties(self):
text_scale_y=self._text_scale_y.value() / 100,
text_rotation=self._text_rotation.value(),
outline_width=None if self._outline_width.value() < 0 else self._outline_width.value())
+ if keys:
+ old_style, new_style = lettering_style(before[self._loaded_row]), lettering_style(item)
+ patch = {key: new_style[key] for key in keys if old_style[key] != new_style[key]}
+ for row in rows:
+ if row != self._loaded_row:
+ apply_lettering_style(self.items[row], patch)
+ self._refresh_block_item(row)
+ self._remember_style_change(before)
+ self._pending_style_keys.clear()
+ self._pending_style_rows = []
self._refresh_block_item(self._loaded_row)
self._row_dirty = False
@@ -2082,6 +2921,7 @@ def _load_properties(self, row):
self._store_properties()
self._loading = True
self._loaded_row = row
+ self._pending_style_keys.clear()
item = self.items[row]
self._source_text.setFont(ui_font(japanese=item.get('source_language', 'ja') == 'ja'))
self._source_text.setPlainText(str(item.get('source_text', '')))
@@ -2108,6 +2948,7 @@ def _load_properties(self, row):
self._mask_width.setValue(box[2] - box[0])
self._mask_height.setValue(box[3] - box[1])
self._update_region_guide()
+ self._update_advanced_style_badge()
self._set_editable(True)
if self._text_dialog is not None and self._text_dialog.isVisible():
self._text_dialog.set_block(row + 1, item.get('source_text', ''),
@@ -2192,21 +3033,42 @@ def _update_repair_controls(self):
self._fill_custom_btn.setEnabled(fills_enabled)
self._fill_color_btn.setEnabled(ready)
self._pick_fill_btn.setEnabled(ready)
+ self._fill_menu_btn.setEnabled(ready)
+ self._fill_white_action.setEnabled(fills_enabled)
+ self._fill_black_action.setEnabled(fills_enabled)
+ self._fill_custom_action.setEnabled(fills_enabled)
+ self._fill_color_action.setEnabled(ready)
+ self._pick_fill_action.setEnabled(ready)
if not ready:
self._pick_fill_btn.setChecked(False)
fill_tip = tr('选区包含已还原气泡,请先恢复该气泡的处理结果再填色。') if protected else ''
- self._fill_white_btn.setToolTip(fill_tip or tr('把框选区域整块填成白色(可撤回)。'))
- self._fill_black_btn.setToolTip(fill_tip or tr('把框选区域整块填成黑色(可撤回)。'))
- self._fill_custom_btn.setToolTip(fill_tip or tr('用当前颜色填充框选区域(可撤回)。'))
+ for target, default_tip in (
+ (self._fill_white_btn, tr('把框选区域整块填成白色(可撤回)。')),
+ (self._fill_white_action, tr('把框选区域整块填成白色(可撤回)。')),
+ (self._fill_black_btn, tr('把框选区域整块填成黑色(可撤回)。')),
+ (self._fill_black_action, tr('把框选区域整块填成黑色(可撤回)。')),
+ (self._fill_custom_btn, tr('用当前颜色填充框选区域(可撤回)。')),
+ (self._fill_custom_action, tr('用当前颜色填充框选区域(可撤回)。')),
+ ):
+ target.setToolTip(fill_tip or default_tip)
selected = 0 <= self._loaded_row < len(self.items)
+ self._retranslate_btn.setEnabled(ready and selected and not self.items[self._loaded_row].get('restore_original'))
self._restore_bubble_btn.setEnabled(ready and selected)
self._restore_bubble_btn.setText(tr('恢复处理结果') if selected and self.items[self._loaded_row].get('restore_original') else tr('还原此气泡'))
+ self._bubble_menu_btn.setEnabled(ready and selected)
self._link_original_btn.setEnabled(ready)
+ self._link_original_action.setEnabled(ready)
can_restore = (selected and not self.items[self._loaded_row].get('restore_original')
and (self._original_image is not None or find_original(self.output_path) is not None))
self._repair_undo.setEnabled(ready and (bool(self._repair_history) or can_restore))
self._save_btn.setEnabled(ready)
+ if self._export_worker is None:
+ can_export = self.output_path is not None and not busy and not self.page_io_busy
+ self._sync_export_pdf_state(enabled=can_export)
+ self._export_cbz_action.setEnabled(can_export)
page_list_busy = (busy or self._export_worker is not None or self.page_io_busy)
+ self._transcript_btn.setEnabled(not page_list_busy and not self._save_jobs.busy
+ and self.page_list.count() > 0)
self.page_list.setEnabled(not page_list_busy)
self._remove_pages_btn.setEnabled(not page_list_busy and bool(self.page_list.selectedItems()))
self._clear_pages_btn.setEnabled(not page_list_busy and self.page_list.count() > 0)
@@ -2234,8 +3096,13 @@ def _refresh_fill_color(self):
painter.setBrush(self._fill_color)
painter.drawRoundedRect(1, 1, 16, 16, 3, 3)
painter.end()
- self._fill_color_btn.setIcon(QIcon(swatch))
- self._fill_color_btn.setText(self._fill_color.name().upper())
+ icon = QIcon(swatch)
+ hex_color = self._fill_color.name().upper()
+ self._fill_color_btn.setIcon(icon)
+ self._fill_color_btn.setText(hex_color)
+ self._fill_menu_btn.setIcon(icon)
+ self._fill_custom_action.setIcon(icon)
+ self._fill_custom_action.setText(tr('用当前色填充 ({color})', color=hex_color))
def _choose_fill_color(self):
self._pick_fill_btn.setChecked(False)
@@ -2371,6 +3238,20 @@ def _refresh_page_dirty_label(self):
label = item.data(Qt.UserRole + 1)
item.setText(tr('● 未保存\n{_0}', _0=label) if self._dirty else label)
+ @staticmethod
+ def _draw_lettering(image, item, typesetter, box, size):
+ typesetter.draw_text(
+ image, box, item['text'], item.get('style', 'dialogue'),
+ direction=int(item.get('direction', 1)),
+ target_font_size=size if size > 0 else None,
+ non_bubble=bool(item.get('non_bubble', False)), manual_layout=True,
+ text_effect=item.get('text_effect', 'auto'),
+ source_outline_ratio=item.get('source_outline_ratio'),
+ vertical_alignment=item.get('vertical_alignment', 'center'),
+ text_color=normalize_text_color(item.get('text_color')),
+ outline_width=outline_width(item), composite=False)
+ return transform_layer(typesetter.last_render_layer, text_transform(item))
+
def render(self) -> None:
if self._cleaned_image is None:
raise ValueError(tr('缺少配套清理底图,请重新导入页面'))
@@ -2405,24 +3286,8 @@ def render(self) -> None:
layers.append(layer)
signatures[index] = (key, layer_bounds(layer))
continue
- typesetter.draw_text(
- image,
- box,
- text,
- item.get("style", "dialogue"),
- direction=int(item.get("direction", 1)),
- target_font_size=size if size > 0 else None,
- non_bubble=bool(item.get("non_bubble", False)),
- manual_layout=True,
- text_effect=item.get('text_effect', 'auto'),
- source_outline_ratio=item.get('source_outline_ratio'),
- vertical_alignment=item.get('vertical_alignment', 'center'),
- text_color=normalize_text_color(item.get('text_color')),
- outline_width=outline_width(item),
- composite=False,
- )
+ layer = self._draw_lettering(image, item, typesetter, box, size)
item['rendered_font_size'] = typesetter.last_font_size
- layer = transform_layer(typesetter.last_render_layer, text_transform(item))
if layer is not None:
surface, left, top = layer
layers.append(layer)
@@ -2453,45 +3318,55 @@ def render(self) -> None:
if 0 <= self._loaded_row < len(self.items):
self._refresh_block_item(self._loaded_row)
- def _export_action(self):
+ def _export_action(self, kind='pdf'):
if self._export_worker is not None:
self._cancel_pdf_export()
else:
- self.export_pdf()
+ self._export_comic(kind if isinstance(kind, str) else 'pdf')
def export_pdf(self, output_path=None):
+ return self._export_comic('pdf', output_path)
+
+ def export_cbz(self, output_path=None):
+ return self._export_comic('cbz', output_path)
+
+ def _export_comic(self, kind, output_path=None):
if self._export_worker is not None or self.output_path is None or self._repair_worker is not None:
return False
+ suffix = f'.{kind}'
+ sizes = []
project = self._pdf_projects.get(str(self.output_path))
if project is not None:
images, sizes = project.images, project.page_sizes
source = self._pdf_sources[str(self.output_path)]
- default = (source.parent / f'{source.stem}_edited.pdf') if source.suffix.lower() == '.pdf' else source.parent / 'edited.pdf'
+ filename = f'{source.stem}_edited{suffix}' if source.suffix.lower() in PROJECT_EXTS else f'edited{suffix}'
+ default = source.parent / filename
else:
images = [Path(self.page_list.item(i).data(Qt.UserRole)) for i in range(self.page_list.count())]
- sizes = []
- for path in images:
- reader = QImageReader(str(path))
- size = reader.size()
- if reader.transformation().value & 4:
- size.transpose()
- if not size.isValid():
- self._status.setText(tr('无法读取译图:{_0}', _0=path.name))
- return False
- sizes.append((size.width() * 72 / 200, size.height() * 72 / 200))
- default = self.output_path.with_name('edited.pdf')
+ if kind == 'pdf':
+ for path in images:
+ reader = QImageReader(str(path))
+ size = reader.size()
+ if reader.transformation().value & 4:
+ size.transpose()
+ if not size.isValid():
+ self._status.setText(tr('无法读取译图:{_0}', _0=path.name))
+ return False
+ sizes.append((size.width() * 72 / 200, size.height() * 72 / 200))
+ default = self.output_path.with_name(f'edited{suffix}')
+ format_name = kind.upper()
if output_path is None:
- chosen, _ = QFileDialog.getSaveFileName(self, tr('导出 PDF'), str(default), 'PDF (*.pdf)')
+ chosen, _ = QFileDialog.getSaveFileName(self, tr('导出 {_0}', _0=format_name),
+ str(default), f'{format_name} (*{suffix})')
if not chosen:
return False
output_path = Path(chosen)
- output_path = Path(output_path).with_suffix('.pdf')
+ output_path = Path(output_path).with_suffix(suffix)
# Flush pending spin-box text even before it has marked the page dirty.
# Plain images without editing metadata can be exported directly.
- for spin in self._layout_spins():
- spin.interpretText()
+ self._commit_spin_inputs()
if self._dirty or self._save_jobs.busy:
- return self.request_save(after=lambda: self.export_pdf(output_path))
+ return self.request_save(after=lambda: self._export_comic(kind, output_path))
worker = PdfExportWorker(images, sizes, output_path, self)
self._export_worker = worker
worker.progress.connect(self._pdf_export_progress)
@@ -2500,36 +3375,52 @@ def export_pdf(self, output_path=None):
worker.cancelled.connect(self._pdf_export_cancelled)
worker.finished.connect(self._pdf_export_finished)
self._update_repair_controls()
- self._export_pdf_btn.setText(tr('取消导出'))
- self._export_pdf_btn.setToolTip(tr('取消导出'))
- self._status.setText(tr('正在后台导出 PDF…'))
+ self._sync_export_pdf_state(enabled=kind == 'pdf')
+ self._export_cbz_action.setEnabled(kind == 'cbz')
+ if kind == 'pdf':
+ self._sync_export_pdf_state(text=tr('取消导出'), tooltip=tr('取消导出'))
+ else:
+ self._export_cbz_action.setText(tr('取消导出'))
+ self._export_cbz_action.setToolTip(tr('取消导出'))
+ self._status.setText(tr('正在后台导出 {_0}…', _0=format_name))
worker.start()
return True
def _pdf_export_progress(self, done, total):
- self._status.setText(tr('正在导出 PDF:{_0}/{_1} 页', _0=done, _1=total))
+ self._status.setText(tr('正在导出 {_0}:{_1}/{_2} 页',
+ _0=self._export_worker.output.suffix[1:].upper(), _1=done, _2=total))
def _pdf_export_succeeded(self, path):
- self._status.setText(tr('已导出 PDF:{_0}', _0=path))
+ self._status.setText(tr('已导出 {_0}:{_1}', _0=Path(path).suffix[1:].upper(), _1=path))
def _pdf_export_failed(self, message):
- self._status.setText(tr('PDF 导出失败:{_0}。已保存的图片仍然保留。', _0=message))
+ self._status.setText(tr('导出失败:{_0}。已保存的图片仍然保留。', _0=message))
def _pdf_export_cancelled(self):
- self._status.setText(tr('已取消 PDF 导出,已保存的图片仍然保留。'))
+ self._status.setText(tr('已取消导出,已保存的图片仍然保留。'))
def _cancel_pdf_export(self):
if self._export_worker is not None:
self._export_worker.requestInterruption()
+ def _commit_spin_inputs(self):
+ if self._quick_size_spin.hasFocus():
+ self._quick_size_spin.interpretText()
+ for spin in self._layout_spins():
+ spin.interpretText()
+
def _pdf_export_finished(self):
worker = self._export_worker
self._export_worker = None
if worker is not None:
worker.deleteLater()
- self._export_pdf_btn.setEnabled(self.output_path is not None)
- self._export_pdf_btn.setText(tr('导出 PDF'))
- self._export_pdf_btn.setToolTip(tr('将已保存的图片按页面顺序导出为 PDF;编辑时不会合成 PDF。'))
+ self._sync_export_pdf_state(
+ enabled=self.output_path is not None,
+ text=tr('导出 PDF'),
+ tooltip=tr('将已保存的图片按页面顺序导出为 PDF;编辑时不会合成 PDF。'),
+ )
+ self._export_cbz_action.setText(tr('导出 CBZ'))
+ self._export_cbz_action.setToolTip(tr('将已保存的图片按页面顺序打包为 CBZ。'))
self._update_repair_controls()
def _save_request(self):
@@ -2538,8 +3429,7 @@ def _save_request(self):
return None
if self.output_path is None or self._cleaned_image is None:
return None
- for spin in self._layout_spins():
- spin.interpretText()
+ self._commit_spin_inputs()
if not self.apply_changes() or self._rendered is None:
return None
output, layout, cleaned = self.output_path, self.layout_path, self.cleaned_path
@@ -2580,21 +3470,25 @@ def _saved(self, request, previous, revision):
tr('✓ 已保存图片与布局 · {_0}', _0=self.output_path.name))
def _save_failed(self, message):
+ callback, self._save_failure_callback = self._save_failure_callback, None
self._saving_image = None
self._after_save = None
self._save_again = False
self._update_repair_controls()
self._status.setText(tr('保存失败:{_0}。修改仍保留,请检查输出目录后重试。', _0=message))
+ if callback:
+ callback(message)
- def request_save(self, checked=False, *, after=None):
+ def request_save(self, checked=False, *, after=None, on_error=None):
if after is not None:
self._after_save = after
+ self._save_failure_callback = on_error
if self._save_jobs.busy:
self._save_again = True
return True
- for spin in self._layout_spins():
- spin.interpretText()
+ self._commit_spin_inputs()
if not self._dirty:
+ self._save_failure_callback = None
action, self._after_save = self._after_save, None
if action:
action()
@@ -2605,7 +3499,7 @@ def request_save(self, checked=False, *, after=None):
self._save_failed(str(exc))
return False
if request is None:
- self._after_save = None
+ self._save_failed(self._status.text())
return False
previous, revision = self.output_path, self._edit_revision
def saved(result):
@@ -2615,6 +3509,7 @@ def saved(result):
if self._dirty and (again or self._after_save is not None):
self.request_save()
else:
+ self._save_failure_callback = None
action, self._after_save = self._after_save, None
if action:
action()
@@ -2628,8 +3523,7 @@ def save_image(self):
"""Synchronous entry for scripts; interactive actions use request_save."""
if self._save_jobs.busy or self._export_worker is not None or self._repair_worker is not None:
return False
- for spin in self._layout_spins():
- spin.interpretText()
+ self._commit_spin_inputs()
if not self._dirty:
return self.output_path is not None and self._cleaned_image is not None
try:
@@ -2681,18 +3575,18 @@ def showEvent(self, event):
super().showEvent(event)
self._store_properties()
self._refresh_font_choices()
+ if self.width() > 0:
+ self._adapt_width(animate=False)
self._adapt_timer.start(0)
def hideEvent(self, event):
self.preview.set_space_pan(False)
super().hideEvent(event)
- def _adapt_width(self):
+ def _adapt_width(self, *, animate=True):
if self.isVisible():
self._update_toolbar_labels()
- compact_h = self.height() < 700
- self._source_text.setFixedHeight(56 if compact_h else 92)
- self._apply_source_layout()
- self._apply_panel_layout()
+ self._apply_source_layout(animate=False)
+ self._apply_panel_layout(animate=animate)
self._sync_inspector_split()
self._reveal_timer.start(0)
diff --git a/comic_translate_desktop/ui/error_log_page.py b/comic_translate_desktop/ui/error_log_page.py
index a335e95..9eb081c 100644
--- a/comic_translate_desktop/ui/error_log_page.py
+++ b/comic_translate_desktop/ui/error_log_page.py
@@ -1,5 +1,4 @@
from __future__ import annotations
-from ..i18n import tr
from PySide6.QtCore import QThread, QUrl, Qt, Signal
from PySide6.QtGui import QDesktopServices
@@ -16,9 +15,10 @@
)
from ..ai_diagnosis import AiDiagnosis
-from .theme import ui_font
+from ..i18n import tr
from .manga_components import PanelHeading
from .motion import install_tab_motion
+from .theme import ui_font
class DiagnosisWorker(QThread):
@@ -50,22 +50,24 @@ def __init__(self, diagnostics, parent=None):
root.setSpacing(0)
body = QFrame()
- body.setObjectName('pageBody')
+ body.setObjectName('settingsBody')
content = QVBoxLayout(body)
- content.setContentsMargins(24, 16, 24, 16)
- content.setSpacing(12)
+ content.setContentsMargins(24, 14, 24, 14)
+ content.setSpacing(10)
self._file_label = QLabel(tr('日志文件: {_0}', _0=self._diagnostics.log_path))
- self._file_label.setProperty("muted", True)
+ self._file_label.setObjectName('statusCallout')
+ self._file_label.setFont(ui_font(12, mono=True))
self._file_label.setWordWrap(True)
self._file_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
- self._file_label.setMaximumHeight(48)
+ self._file_label.setMaximumHeight(54)
+
self._sections = QTabWidget()
self._sections.setDocumentMode(True)
self._sections.setAccessibleName(tr('诊断工作区'))
+ install_tab_motion(self._sections)
self._sections.addTab(self._build_prompt_panel(), tr('01 诊断资料'))
self._sections.addTab(self._build_ai_panel(), tr('02 AI 对话'))
- install_tab_motion(self._sections)
content.addWidget(self._sections, 1)
content.addWidget(self._file_label)
root.addWidget(body, 1)
@@ -74,9 +76,9 @@ def __init__(self, diagnostics, parent=None):
def _build_prompt_panel(self) -> QWidget:
panel = QFrame()
- panel.setObjectName('editorPanel')
+ panel.setObjectName('settingsBody')
layout = QVBoxLayout(panel)
- layout.setContentsMargins(16, 16, 16, 12)
+ layout.setContentsMargins(4, 16, 4, 4)
layout.setSpacing(12)
layout.addWidget(PanelHeading('01', tr('诊断资料')))
hint = QLabel(tr('复制诊断资料用于分析问题,或切换到 AI 对话继续追问。'))
@@ -85,29 +87,36 @@ def _build_prompt_panel(self) -> QWidget:
layout.addWidget(hint)
self.prompt_view = QPlainTextEdit()
+ self.prompt_view.setObjectName('logSurface')
self.prompt_view.setReadOnly(True)
self.prompt_view.setPlaceholderText(tr('暂无报错日志'))
self.prompt_view.setFont(ui_font(13, mono=True))
layout.addWidget(self.prompt_view, 1)
buttons = QHBoxLayout()
+ buttons.setSpacing(8)
self._copy_prompt_btn = QPushButton(tr('复制诊断提示词'))
+ self._copy_prompt_btn.setProperty('role', 'primary')
self._copy_raw_btn = QPushButton(tr('复制原始日志'))
self._open_log_btn = QPushButton(tr('打开日志文件'))
self._clear_btn = QPushButton(tr('清空日志'))
- self._clear_btn.setProperty("role", "danger")
+ self._clear_btn.setProperty('role', 'danger')
+ for button in (self._copy_raw_btn, self._open_log_btn):
+ button.setProperty('role', 'utility')
+ for button in (self._copy_prompt_btn, self._copy_raw_btn, self._open_log_btn, self._clear_btn):
+ button.setProperty('compact', True)
+ button.setCursor(Qt.PointingHandCursor)
+
self._status_label = QLabel('')
- self._status_label.setProperty("muted", True)
+ self._status_label.setProperty('muted', True)
buttons.addWidget(self._copy_prompt_btn)
buttons.addWidget(self._copy_raw_btn)
buttons.addWidget(self._open_log_btn)
- buttons.addWidget(self._clear_btn)
buttons.addStretch(1)
+ buttons.addWidget(self._status_label)
+ buttons.addWidget(self._clear_btn)
layout.addLayout(buttons)
- layout.addWidget(self._status_label)
- for button in (self._copy_prompt_btn, self._copy_raw_btn, self._open_log_btn, self._clear_btn):
- button.setProperty('compact', True)
self._copy_prompt_btn.clicked.connect(self.copy_prompt)
self._copy_raw_btn.clicked.connect(self.copy_raw_logs)
@@ -117,9 +126,9 @@ def _build_prompt_panel(self) -> QWidget:
def _build_ai_panel(self) -> QWidget:
group = QFrame()
- group.setObjectName('editorPanel')
+ group.setObjectName('settingsBody')
layout = QVBoxLayout(group)
- layout.setContentsMargins(16, 16, 16, 12)
+ layout.setContentsMargins(4, 16, 4, 4)
layout.setSpacing(12)
layout.addWidget(PanelHeading('02', tr('AI 对话')))
hint = QLabel(tr('描述遇到的问题,AI 将结合当前日志分析;后续追问会保留上下文。'))
@@ -128,31 +137,40 @@ def _build_ai_panel(self) -> QWidget:
layout.addWidget(hint)
self.history_view = QPlainTextEdit()
+ self.history_view.setObjectName('logSurface')
self.history_view.setReadOnly(True)
self.history_view.setPlaceholderText(tr('在这里发起 AI 诊断,后续问题会保留上下文。'))
self.history_view.setFont(ui_font(14))
layout.addWidget(self.history_view, 1)
self._input_view = QPlainTextEdit()
+ self._input_view.setObjectName('logInput')
self._input_view.setPlaceholderText(tr('描述报错现象,或直接问:帮我分析当前日志'))
- self._input_view.setMaximumHeight(80)
+ self._input_view.setMaximumHeight(82)
self._input_view.setMinimumHeight(56)
layout.addWidget(self._input_view)
buttons = QHBoxLayout()
+ buttons.setSpacing(8)
self._send_btn = QPushButton(tr('发送诊断'))
- self._send_btn.setProperty("role", "primary")
+ self._send_btn.setProperty('role', 'primary')
+ self._send_btn.setCursor(Qt.PointingHandCursor)
self._copy_result_btn = QPushButton(tr('复制诊断结果'))
+ self._copy_result_btn.setProperty('role', 'utility')
+ self._copy_result_btn.setProperty('compact', True)
+ self._copy_result_btn.setCursor(Qt.PointingHandCursor)
self._clear_context_btn = QPushButton(tr('清空上下文'))
+ self._clear_context_btn.setProperty('role', 'utility')
+ self._clear_context_btn.setProperty('compact', True)
+ self._clear_context_btn.setCursor(Qt.PointingHandCursor)
self._ai_status = QLabel('')
- self._ai_status.setProperty("muted", True)
+ self._ai_status.setProperty('muted', True)
buttons.addWidget(self._copy_result_btn)
buttons.addWidget(self._clear_context_btn)
- buttons.addStretch(1)
+ buttons.addWidget(self._ai_status, 1)
buttons.addWidget(self._send_btn)
layout.addLayout(buttons)
- layout.addWidget(self._ai_status)
self._send_btn.clicked.connect(self._send_diagnosis)
self._copy_result_btn.clicked.connect(self.copy_diagnosis_result)
@@ -214,7 +232,7 @@ def _send_diagnosis(self) -> None:
self._worker.start()
def _on_diagnosis_finished(self, answer: str) -> None:
- self._append_history("AI", answer)
+ self._append_history('AI', answer)
self._send_btn.setEnabled(True)
self._ai_status.setText(tr('诊断完成,上下文已保留'))
@@ -224,7 +242,7 @@ def _on_diagnosis_failed(self, message: str) -> None:
self._ai_status.setText(tr('诊断失败'))
def _append_history(self, role: str, content: str) -> None:
- self.history_view.appendPlainText(f"【{role}】\n{content}\n")
+ self.history_view.appendPlainText(f'【{role}】\n{content}\n')
def shutdown(self) -> None:
if self._worker is not None and self._worker.isRunning():
diff --git a/comic_translate_desktop/ui/favorite_fonts.py b/comic_translate_desktop/ui/favorite_fonts.py
index f7a4fb1..6fc7182 100644
--- a/comic_translate_desktop/ui/favorite_fonts.py
+++ b/comic_translate_desktop/ui/favorite_fonts.py
@@ -4,20 +4,24 @@
import json
from PySide6.QtCore import Qt, QSettings, Signal
+from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
QDialog, QDialogButtonBox, QFormLayout, QFrame, QGridLayout, QHBoxLayout,
- QLabel, QPushButton, QSizePolicy, QVBoxLayout,
+ QLabel, QMenu, QPushButton, QScrollArea, QSizePolicy, QToolButton, QVBoxLayout, QWidget,
)
from ..font_library import available_fonts, font_description, font_display_name, font_reference, inspect_font, resolve_font_reference
from ..i18n import tr
+from .manga_components import PanelHeading
from .searchable_combo import SearchableFontCombo
-from .theme import set_themed_icon
+from .theme import set_themed_icon, ui_font
class FavoriteFontBar(QFrame):
font_selected = Signal(str)
add_current_requested = Signal()
+ hide_requested = Signal()
+ slots_changed = Signal(bool)
SETTINGS_KEY = 'ui/editorFavoriteFonts'
def __init__(self, config, parent=None):
@@ -41,13 +45,27 @@ def __init__(self, config, parent=None):
title = QLabel(tr('常用字体'))
title.setObjectName('barCaption')
heading.addWidget(title)
- self.add_button = QPushButton(tr('加入当前字体'))
+ self.manage_button = QToolButton(self)
+ self.manage_button.setText(tr('管理'))
+ self.manage_button.setProperty('compact', True)
+ self.manage_button.setProperty('role', 'chip')
+ self.manage_button.setProperty('menuButton', True)
+ self.manage_button.setPopupMode(QToolButton.InstantPopup)
+ self.manage_button.setToolTip(tr('管理快捷字体槽位与显示'))
+ self.manage_menu = QMenu(self.manage_button)
+ self._add_action = self.manage_menu.addAction(tr('加入当前字体'), self.add_current_requested.emit)
+ self._settings_action = self.manage_menu.addAction(tr('设置快捷字体…'), self.configure)
+ self.manage_menu.addSeparator()
+ self._hide_action = self.manage_menu.addAction(tr('隐藏快捷字体栏'), self.hide_requested.emit)
+ self.manage_button.setMenu(self.manage_menu)
+ heading.addWidget(self.manage_button)
+ self.add_button = QPushButton(tr('加入当前字体'), self)
set_themed_icon(self.add_button, 'plus', size=12)
self.add_button.clicked.connect(self.add_current_requested)
- heading.addWidget(self.add_button)
- self.settings_button = QPushButton(tr('设置快捷字体'))
+ self.add_button.hide()
+ self.settings_button = QPushButton(tr('设置快捷字体'), self)
self.settings_button.clicked.connect(self.configure)
- heading.addWidget(self.settings_button)
+ self.settings_button.hide()
for button in (self.add_button, self.settings_button):
button.setProperty('compact', True)
button.setProperty('role', 'chip')
@@ -77,10 +95,14 @@ def __init__(self, config, parent=None):
self.setToolTip(tr('数字键 1–9 切换当前文本块字体;输入文字时不触发。'))
self._refresh()
+ def has_active_slots(self):
+ return any(bool(slot) for slot in self.slots)
+
def set_slots(self, slots):
self.slots = (list(slots) + [''] * 9)[:9]
QSettings().setValue(self.SETTINGS_KEY, json.dumps(self.slots, ensure_ascii=False))
self._refresh()
+ self.slots_changed.emit(self.has_active_slots())
def add_font(self, reference):
if reference in self.slots:
@@ -101,6 +123,7 @@ def activate(self, index):
def set_apply_enabled(self, enabled):
self._can_apply = bool(enabled)
self.add_button.setEnabled(self._can_apply)
+ self._add_action.setEnabled(self._can_apply)
for index, button in enumerate(self.buttons):
button.setEnabled(self._can_apply and self._available[index])
@@ -128,7 +151,7 @@ def _reflow(self):
has_active = bool(active_indices)
self._empty_hint.setVisible(not has_active)
columns = max(1, len(active_indices))
- available = max(0, self.width() - self._heading.sizeHint().width() - 40)
+ available = max(0, self.width() - self._heading.sizeHint().width() - 36)
for button in self.buttons:
self._grid.removeWidget(button)
for column in range(9):
@@ -150,14 +173,52 @@ def resizeEvent(self, event):
def configure(self):
dialog = QDialog(self)
dialog.setWindowTitle(tr('设置快捷字体'))
- layout = QVBoxLayout(dialog)
+ dialog.setMinimumSize(460, 360)
+ dialog.resize(560, 560)
+ dialog.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
+
+ root = QVBoxLayout(dialog)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(0)
+
+ header = QFrame()
+ header.setObjectName('dialogHeader')
+ header_layout = QVBoxLayout(header)
+ header_layout.setContentsMargins(24, 18, 24, 14)
+ header_layout.setSpacing(6)
+ header_layout.addWidget(PanelHeading('', '设置快捷字体'))
hint = QLabel(tr('最多 9 个字体,对应数字键 1–9;留空可清除该快捷键。'))
+ hint.setProperty('muted', True)
hint.setWordWrap(True)
- layout.addWidget(hint)
- form = QFormLayout()
+ header_layout.addWidget(hint)
+ root.addWidget(header)
+
+ scroll = QScrollArea()
+ scroll.setObjectName('dialogScroll')
+ scroll.setWidgetResizable(True)
+ scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
+ container = QWidget()
+ container.setObjectName('dialogScrollContent')
+ container_layout = QVBoxLayout(container)
+ container_layout.setContentsMargins(24, 16, 24, 16)
+ container_layout.setSpacing(12)
+
+ card = QFrame()
+ card.setObjectName('dialogCard')
+ form = QFormLayout(card)
+ form.setContentsMargins(20, 16, 20, 16)
+ form.setHorizontalSpacing(14)
+ form.setVerticalSpacing(10)
+ form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
fonts = available_fonts(self.config)
choices = []
for index, reference in enumerate(self.slots):
+ badge = QLabel(f'{index + 1:02d}')
+ badge.setObjectName('stepBadge')
+ badge.setFont(ui_font(11, QFont.Bold, mono=True))
+ badge.setAlignment(Qt.AlignCenter)
+ badge.setFixedSize(28, 24)
+
combo = SearchableFontCombo()
combo.addItem(tr('未设置'), '')
for font in fonts:
@@ -168,13 +229,29 @@ def configure(self):
combo.addItem(tr('不可用:{_0}', _0=reference), reference)
row = combo.count() - 1
combo.setCurrentIndex(row)
- form.addRow(str(index + 1), combo)
+ form.addRow(badge, combo)
choices.append(combo)
- layout.addLayout(form)
+ container_layout.addWidget(card)
+ container_layout.addStretch(1)
+ scroll.setWidget(container)
+ root.addWidget(scroll, 1)
+
+ footer = QFrame()
+ footer.setObjectName('pageActions')
+ footer_layout = QHBoxLayout(footer)
+ footer_layout.setContentsMargins(24, 12, 24, 12)
actions = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
+ ok_btn = actions.button(QDialogButtonBox.Ok)
+ cancel_btn = actions.button(QDialogButtonBox.Cancel)
+ if ok_btn is not None:
+ ok_btn.setProperty('role', 'primary')
+ ok_btn.setDefault(True)
+ if cancel_btn is not None:
+ cancel_btn.setProperty('role', 'utility')
actions.accepted.connect(dialog.accept)
actions.rejected.connect(dialog.reject)
- layout.addWidget(actions)
- dialog.resize(540, dialog.sizeHint().height())
+ footer_layout.addWidget(actions)
+ root.addWidget(footer)
+
if dialog.exec() == QDialog.Accepted:
self.set_slots([combo.currentData() or '' for combo in choices])
diff --git a/comic_translate_desktop/ui/font_library_dialog.py b/comic_translate_desktop/ui/font_library_dialog.py
index 20215c8..531659e 100644
--- a/comic_translate_desktop/ui/font_library_dialog.py
+++ b/comic_translate_desktop/ui/font_library_dialog.py
@@ -1,16 +1,22 @@
"""Search the complete offline catalog and download a chosen font face."""
from __future__ import annotations
-from ..i18n import tr
from PIL import Image
from PIL.ImageQt import ImageQt
-from PySide6.QtCore import QThread, Signal, Qt
-from PySide6.QtGui import QPixmap
-from PySide6.QtWidgets import (QComboBox, QDialog, QHBoxLayout, QLabel, QLineEdit,
- QListWidget, QListWidgetItem, QProgressBar, QPushButton, QVBoxLayout)
+from PySide6.QtCore import QThread, Qt, Signal
+from PySide6.QtGui import QFont, QPixmap
+from PySide6.QtWidgets import (
+ QComboBox, QDialog, QFrame, QHBoxLayout, QLabel, QLineEdit, QListWidget,
+ QListWidgetItem, QProgressBar, QPushButton, QVBoxLayout,
+)
+from shiboken6 import isValid
from ..font_catalog import CATEGORY_LABELS, LANGUAGE_LABELS, download_face, installed_faces, load_catalog, search_text
from ..font_library import font_alias, resolve_font_reference
+from ..i18n import tr
+from .manga_components import PanelHeading
+from .theme import theme, theme_changed, ui_font
+from .window_chrome import apply_window_chrome
class FontDownloadThread(QThread):
@@ -35,28 +41,52 @@ class FontLibraryDialog(QDialog):
def __init__(self, settings, parent=None):
super().__init__(parent)
self.setWindowTitle(tr('开源字体库'))
- self.resize(820, 660)
+ self.resize(840, 680)
self.setMinimumSize(560, 480)
+ self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
self.reference = None
self._settings = settings
self._worker = None
self._closing = False
self._downloaded = None
+ self._preview_reference = None
self._installed = installed_faces()
catalog = load_catalog()
self._families = [(family, search_text(family)) for family in catalog['families']]
- root = QVBoxLayout(self)
- root.setContentsMargins(20, 18, 20, 18)
- root.setSpacing(12)
+
+ outer = QVBoxLayout(self)
+ outer.setContentsMargins(0, 0, 0, 0)
+ outer.setSpacing(0)
+
+ header = QFrame()
+ header.setObjectName('dialogHeader')
+ header_layout = QVBoxLayout(header)
+ header_layout.setContentsMargins(24, 18, 24, 14)
+ header_layout.setSpacing(6)
+ header_layout.addWidget(PanelHeading('', '开源字体库'))
intro = QLabel(tr('Google Fonts · {_0:,} 款字体族\n完整目录离线检索,按需下载;下载后离线使用。', _0=len(self._families)))
+ intro.setProperty('muted', True)
intro.setWordWrap(True)
- root.addWidget(intro)
+ header_layout.addWidget(intro)
+ outer.addWidget(header)
+
+ body = QVBoxLayout()
+ body.setContentsMargins(24, 16, 24, 16)
+ body.setSpacing(12)
+
+ filter_card = QFrame()
+ filter_card.setObjectName('dialogCard')
+ filter_layout = QVBoxLayout(filter_card)
+ filter_layout.setContentsMargins(16, 14, 16, 14)
+ filter_layout.setSpacing(10)
self.search = QLineEdit()
self.search.setPlaceholderText(tr('搜索名称、中文别名、语言或风格,例如:霞鹜、中文、手写…'))
self.search.setClearButtonEnabled(True)
self.search.setAccessibleName(tr('检索开源字体库'))
- root.addWidget(self.search)
+ filter_layout.addWidget(self.search)
+
filters = QHBoxLayout()
+ filters.setSpacing(8)
self.language = QComboBox()
self.language.addItem(tr('全部语言'), '')
for subset, label in LANGUAGE_LABELS.items():
@@ -69,51 +99,95 @@ def __init__(self, settings, parent=None):
self.availability.addItem(tr('全部字体'), False)
self.availability.addItem(tr('已下载'), True)
for widget in (self.language, self.category, self.availability):
- filters.addWidget(widget)
- root.addLayout(filters)
+ filters.addWidget(widget, 1)
self.count = QLabel()
- self.count.setProperty('muted', True)
- root.addWidget(self.count)
+ self.count.setObjectName('badgePill')
+ self.count.setFont(ui_font(11, mono=True))
+ filters.addWidget(self.count)
+ filter_layout.addLayout(filters)
+ body.addWidget(filter_card)
+
self.font_list = QListWidget()
+ self.font_list.setObjectName('catalogList')
self.font_list.setAccessibleName(tr('开源字体检索结果'))
- root.addWidget(self.font_list, 1)
+ body.addWidget(self.font_list, 1)
+
+ inspector_card = QFrame()
+ inspector_card.setObjectName('dialogCard')
+ inspector_layout = QVBoxLayout(inspector_card)
+ inspector_layout.setContentsMargins(16, 14, 16, 14)
+ inspector_layout.setSpacing(10)
+
+ meta_row = QHBoxLayout()
+ meta_row.setSpacing(12)
self.details = QLabel()
self.details.setWordWrap(True)
self.details.setProperty('muted', True)
- root.addWidget(self.details)
+ meta_row.addWidget(self.details, 1)
self.face = QComboBox()
- self.face.setMinimumContentsLength(20)
+ self.face.setMinimumContentsLength(18)
+ self.face.setMinimumWidth(200)
+ self.face.setMaximumWidth(320)
self.face.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.face.setAccessibleName(tr('字体款式与字重'))
- root.addWidget(self.face)
+ meta_row.addWidget(self.face)
+ inspector_layout.addLayout(meta_row)
+
+ preview_frame = QFrame()
+ preview_frame.setObjectName('fontPreviewFrame')
+ preview_layout = QVBoxLayout(preview_frame)
+ preview_layout.setContentsMargins(12, 8, 12, 8)
self.preview = QLabel(tr('下载后显示实际字体预览'))
self.preview.setAlignment(Qt.AlignCenter)
self.preview.setMinimumHeight(52)
self.preview.setWordWrap(True)
- root.addWidget(self.preview)
+ self.preview.setProperty('muted', True)
+ preview_layout.addWidget(self.preview)
+ inspector_layout.addWidget(preview_frame)
+
self.progress = QProgressBar()
self.progress.hide()
- root.addWidget(self.progress)
+ inspector_layout.addWidget(self.progress)
self.status = QLabel()
self.status.setWordWrap(True)
- root.addWidget(self.status)
- actions = QHBoxLayout()
+ self.status.setProperty('muted', True)
+ inspector_layout.addWidget(self.status)
+ body.addWidget(inspector_card)
+ outer.addLayout(body, 1)
+
+ footer = QFrame()
+ footer.setObjectName('pageActions')
+ actions = QHBoxLayout(footer)
+ actions.setContentsMargins(24, 12, 24, 12)
+ actions.setSpacing(10)
actions.addStretch()
self.cancel_button = QPushButton(tr('关闭'))
+ self.cancel_button.setProperty('role', 'utility')
self.cancel_button.clicked.connect(self.reject)
actions.addWidget(self.cancel_button)
self.use_button = QPushButton(tr('下载并使用'))
self.use_button.setProperty('role', 'primary')
+ self.use_button.setCursor(Qt.PointingHandCursor)
self.use_button.clicked.connect(self._use_font)
actions.addWidget(self.use_button)
- root.addLayout(actions)
+ outer.addWidget(footer)
+
self.search.textChanged.connect(self._filter)
for widget in (self.language, self.category, self.availability):
widget.currentIndexChanged.connect(self._filter)
self.font_list.currentItemChanged.connect(self._family_changed)
self.face.currentIndexChanged.connect(self._face_changed)
+ theme_changed.changed.connect(self._refresh_theme_preview)
self._filter()
+ def _refresh_theme_preview(self, _mode):
+ if isValid(self) and self._preview_reference:
+ self._show_preview(self._preview_reference)
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+
def _filter(self):
tokens = self.search.text().casefold().split()
language, category = self.language.currentData(), self.category.currentData()
@@ -155,6 +229,7 @@ def _family_changed(self, item, previous=None):
def _face_changed(self):
self.preview.clear()
+ self._preview_reference = None
face = self.face.currentData()
family = self.font_list.currentItem().data(Qt.UserRole) if self.font_list.currentItem() else None
reference = self._installed.get(face['sha1']) if face else None
@@ -171,13 +246,16 @@ def _face_changed(self):
def _show_preview(self, reference):
from vertical_typesetter import VerticalTypesetter
+ self._preview_reference = reference
+ palette = theme()
path = str(resolve_font_reference(reference))
typesetter = VerticalTypesetter({style: path for style in self._settings['font_map']}, 24,
fallback_fonts=self._settings.get('font_fallbacks'))
dpr = self.devicePixelRatioF()
- image = Image.new('RGB', (round(500 * dpr), round(52 * dpr)), 'white')
+ image = Image.new('RGB', (round(500 * dpr), round(52 * dpr)), palette['paper'])
typesetter.draw_text(image, [0, 0, image.width, image.height], '故事,从这里开始。Aa 0123',
- 'dialogue', direction=0, target_font_size=round(24 * dpr), manual_layout=True)
+ 'dialogue', direction=0, target_font_size=round(24 * dpr),
+ manual_layout=True, text_color=palette['ink'], outline_width=0)
pixmap = QPixmap.fromImage(ImageQt(image))
pixmap.setDevicePixelRatio(dpr)
self.preview.setPixmap(pixmap)
diff --git a/comic_translate_desktop/ui/font_picker.py b/comic_translate_desktop/ui/font_picker.py
index bfebf8b..8b170c7 100644
--- a/comic_translate_desktop/ui/font_picker.py
+++ b/comic_translate_desktop/ui/font_picker.py
@@ -9,7 +9,7 @@
from PIL.ImageQt import ImageQt
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QPixmap
-from PySide6.QtWidgets import QFileDialog, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QVBoxLayout, QWidget
+from PySide6.QtWidgets import QFileDialog, QHBoxLayout, QLabel, QMenu, QPushButton, QSizePolicy, QToolButton, QVBoxLayout, QWidget
from .. import config
from comic_translate_core.chinese import convert_chinese
@@ -41,18 +41,30 @@ def __init__(self, settings: dict, parent=None):
self.combo.setToolTip(tr('指定字体用于全部译文;自动匹配保留漫画风格。缺字自动回退到内置中文字体。'))
self.combo.setAccessibleName(tr('翻译默认字体'))
row.addWidget(self.combo, 1)
- self.import_button = QPushButton(tr('导入字体'))
+ self.manage_button = QToolButton(self)
+ self.manage_button.setText(tr('字体管理'))
+ self.manage_button.setProperty('role', 'chip')
+ self.manage_button.setProperty('compact', True)
+ self.manage_button.setProperty('menuButton', True)
+ self.manage_button.setPopupMode(QToolButton.InstantPopup)
+ self.manage_button.setToolTip(tr('字体库与本地字体导入'))
+ self.manage_menu = QMenu(self.manage_button)
+ self._library_action = self.manage_menu.addAction(tr('字体库…'), self._open_library)
+ self._import_action = self.manage_menu.addAction(tr('导入本地字体…'), self._choose_fonts)
+ self.manage_button.setMenu(self.manage_menu)
+ row.addWidget(self.manage_button)
+ self.import_button = QPushButton(tr('导入字体'), self)
set_themed_icon(self.import_button, 'plus')
self.import_button.setProperty('role', 'quiet')
self.import_button.setProperty('compact', True)
self.import_button.setToolTip(tr('导入 TTF、OTF、TTC 或 OTC;字体集合使用第一个款式'))
- row.addWidget(self.import_button)
- self.library_button = QPushButton(tr('字体库'))
+ self.import_button.hide()
+ self.library_button = QPushButton(tr('字体库'), self)
self.library_button.setProperty('role', 'quiet')
self.library_button.setProperty('compact', True)
self.library_button.setToolTip(tr('检索完整开源字体目录,按需下载后离线使用'))
self.library_button.clicked.connect(self._open_library)
- row.addWidget(self.library_button)
+ self.library_button.hide()
self.preview = QLabel()
self.preview.setFixedHeight(34)
self.preview.setMaximumWidth(300)
diff --git a/comic_translate_desktop/ui/gpu_setup_dialog.py b/comic_translate_desktop/ui/gpu_setup_dialog.py
index 964ba2b..2e5f262 100644
--- a/comic_translate_desktop/ui/gpu_setup_dialog.py
+++ b/comic_translate_desktop/ui/gpu_setup_dialog.py
@@ -1,11 +1,17 @@
"""Install the portable CUDA runtime or open the official driver and SDK instructions."""
-from PySide6.QtCore import QUrl, QThread, Signal
-from PySide6.QtGui import QDesktopServices
-from PySide6.QtWidgets import QDialog, QLabel, QPushButton, QScrollArea, QVBoxLayout, QWidget
+from PySide6.QtCore import QThread, QUrl, Qt, Signal
+from PySide6.QtGui import QDesktopServices, QFont
+from PySide6.QtWidgets import (
+ QApplication, QDialog, QFrame, QGridLayout, QHBoxLayout, QLabel, QPushButton, QScrollArea, QVBoxLayout, QWidget,
+)
+from comic_translate_core.gpu_install import install
from comic_translate_core.gpu_runtime import CUDA_DOWNLOAD_URL, CUDNN_DOWNLOAD_URL, MSVC_DOWNLOAD_URL
from ..i18n import tr
-from comic_translate_core.gpu_install import install
+from .manga_components import PanelHeading
+from .motion import MonochromeShimmerBar
+from .theme import set_themed_icon, ui_font
+from .window_chrome import apply_window_chrome
class RuntimeInstall(QThread):
@@ -14,7 +20,7 @@ class RuntimeInstall(QThread):
def run(self):
try:
path = install(self.status.emit, canceled=self.isInterruptionRequested)
- self.status.emit(tr("运行库已就绪,请重启 ComiTrans。") + str(path))
+ self.status.emit(tr('运行库已就绪,请重启 ComiTrans。') + str(path))
except Exception as exc:
self.status.emit(str(exc))
@@ -23,56 +29,166 @@ class GpuSetupDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle(tr('GPU 安装说明与下载'))
- self.resize(660, 560)
- layout = QVBoxLayout(self)
+ screen = QApplication.primaryScreen().availableGeometry() if QApplication.primaryScreen() else None
+ target_w = min(780, int(screen.width() * 0.9)) if screen else 780
+ target_h = min(750, int(screen.height() * 0.9)) if screen else 750
+ self.resize(target_w, target_h)
+ self.setMinimumSize(520, 440)
+ self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
+
+ root = QVBoxLayout(self)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(0)
+
+ header = QFrame()
+ header.setObjectName('dialogHeader')
+ header_layout = QVBoxLayout(header)
+ header_layout.setContentsMargins(24, 12, 24, 10)
+ header_layout.setSpacing(4)
+ header_layout.addWidget(PanelHeading('', 'GPU 安装说明与下载'))
+ intro = QLabel(tr('程序包不附带 CUDA/cuDNN。已有兼容环境无需重复安装;CPU 用户可以关闭“使用 GPU”。以下链接打开 NVIDIA 或 Microsoft 官方网站。'))
+ intro.setProperty('muted', True)
+ intro.setWordWrap(True)
+ header_layout.addWidget(intro)
+ root.addWidget(header)
+
scroll = QScrollArea()
+ scroll.setObjectName('dialogScroll')
scroll.setWidgetResizable(True)
+ scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
content = QWidget()
+ content.setObjectName('dialogScrollContent')
body = QVBoxLayout(content)
- body.setSpacing(16)
+ body.setContentsMargins(20, 10, 20, 10)
+ body.setSpacing(8)
+
+ self.installer = RuntimeInstall(self)
+
+ runtime_card = QFrame()
+ runtime_card.setObjectName('dialogCard')
+ runtime_layout = QVBoxLayout(runtime_card)
+ runtime_layout.setContentsMargins(16, 10, 16, 10)
+ runtime_layout.setSpacing(6)
+ runtime_title = QLabel(tr('便携 GPU 运行库'))
+ runtime_title.setObjectName('cardTitle')
+ runtime_title.setFont(ui_font(14, QFont.Bold))
+ runtime_layout.addWidget(runtime_title)
+ self.install_status = QLabel(tr('从 NVIDIA 发布的 PyPI 软件包下载至程序目录。需要兼容的 NVIDIA 驱动,下载后重启生效。'))
+ self.install_status.setObjectName('statusCallout')
+ self.install_status.setWordWrap(True)
+ runtime_layout.addWidget(self.install_status)
+ self.install_progress = MonochromeShimmerBar()
+ self.install_progress.setFixedHeight(6)
+ self.install_progress.setTextVisible(False)
+ self.install_progress.setRange(0, 0)
+ self.install_progress.hide()
+ runtime_layout.addWidget(self.install_progress)
+ action_row = QHBoxLayout()
+ action_row.setContentsMargins(0, 2, 0, 0)
+ self.install_button = QPushButton(tr('下载安装便携 GPU 运行库(约 1.53 GB)'))
+ self.install_button.setProperty('role', 'primary')
+ self.install_button.setCursor(Qt.PointingHandCursor)
+ self.install_button.clicked.connect(self.start_install)
+ action_row.addWidget(self.install_button)
+ action_row.addStretch(1)
+ runtime_layout.addLayout(action_row)
+ self.installer.status.connect(self.install_status.setText)
+ self.installer.finished.connect(self._install_finished)
+ body.addWidget(runtime_card)
+
+ steps_card = QFrame()
+ steps_card.setObjectName('dialogCard')
+ steps_layout = QVBoxLayout(steps_card)
+ steps_layout.setContentsMargins(16, 10, 16, 10)
+ steps_layout.setSpacing(6)
+ steps_title = QLabel(tr('手动安装步骤'))
+ steps_title.setObjectName('cardTitle')
+ steps_title.setFont(ui_font(14, QFont.Bold))
+ steps_layout.addWidget(steps_title)
paragraphs = (
- '程序包不附带 CUDA/cuDNN。已有兼容环境无需重复安装;CPU 用户可以关闭“使用 GPU”。以下链接打开 NVIDIA 或 Microsoft 官方网站。',
'1. 确认有支持 CUDA 的 NVIDIA 显卡及兼容驱动。安装 CUDA 12.8 Update 1,选择 Windows / x86_64 与对应系统版本。',
'2. 安装 cuDNN 9.10.2,选择适用于 CUDA 12 的 Windows x86_64 版本。CUDA Toolkit 不包含 cuDNN,两个都需要。',
'3. 将 CUDA 和 cuDNN 中实际存放 DLL 的 bin 目录加入系统 PATH。默认安装目录会自动识别;自定义目录也可通过 CUDA_PATH、CUDNN_PATH 指定。',
'4. 完全退出并重新打开 ComiTrans,勾选“使用 GPU”并保存。模型加载日志应显示 CUDA;显示“实际使用 CPU”说明加速未生效。若提示缺少 MSVCP140/VCRUNTIME140,安装下方 Microsoft 运行库。',
)
- for paragraph in paragraphs:
+ for index, paragraph in enumerate(paragraphs, 1):
+ row = QHBoxLayout()
+ row.setSpacing(12)
+ badge = QLabel(f'{index:02d}')
+ badge.setObjectName('stepBadge')
+ badge.setFont(ui_font(11, QFont.Bold, mono=True))
+ badge.setAlignment(Qt.AlignCenter)
+ badge.setFixedSize(28, 22)
label = QLabel(tr(paragraph))
label.setWordWrap(True)
- body.addWidget(label)
- self.installer = RuntimeInstall(self)
- self.install_button = QPushButton(tr("下载安装便携 GPU 运行库(约 1.53 GB)"))
- self.install_status = QLabel(tr("从 NVIDIA 发布的 PyPI 软件包下载至程序目录。需要兼容的 NVIDIA 驱动,下载后重启生效。"))
- self.install_status.setWordWrap(True)
- self.install_button.clicked.connect(self.start_install)
- self.installer.status.connect(self.install_status.setText)
- self.installer.finished.connect(lambda: self.install_button.setEnabled(True))
- body.insertWidget(0, self.install_button)
- body.insertWidget(1, self.install_status)
+ row.addWidget(badge, 0, Qt.AlignTop)
+ row.addWidget(label, 1)
+ steps_layout.addLayout(row)
+ body.addWidget(steps_card)
+
+ links_card = QFrame()
+ links_card.setObjectName('dialogCard')
+ links_layout = QVBoxLayout(links_card)
+ links_layout.setContentsMargins(16, 10, 16, 10)
+ links_layout.setSpacing(6)
+ links_title = QLabel(tr('官方下载'))
+ links_title.setObjectName('cardTitle')
+ links_title.setFont(ui_font(14, QFont.Bold))
+ links_layout.addWidget(links_title)
+ links_grid = QGridLayout()
+ links_grid.setContentsMargins(0, 0, 0, 0)
+ links_grid.setSpacing(8)
self.download_buttons = []
- for title, url in ((tr('打开 CUDA 12.8 官方下载'), CUDA_DOWNLOAD_URL),
- (tr('打开 cuDNN 9.10.2 官方下载'), CUDNN_DOWNLOAD_URL),
- (tr('下载 Microsoft VC++ x64 运行库'), MSVC_DOWNLOAD_URL)):
+ for idx, (title, url) in enumerate((
+ (tr('打开 CUDA 12.8 官方下载'), CUDA_DOWNLOAD_URL),
+ (tr('打开 cuDNN 9.10.2 官方下载'), CUDNN_DOWNLOAD_URL),
+ (tr('下载 Microsoft VC++ x64 运行库'), MSVC_DOWNLOAD_URL),
+ )):
button = QPushButton(title)
+ button.setProperty('role', 'utility')
+ button.setCursor(Qt.PointingHandCursor)
+ set_themed_icon(button, 'external-link', size=14)
button.clicked.connect(lambda checked=False, link=url: QDesktopServices.openUrl(QUrl(link)))
- body.addWidget(button)
+ if idx < 2:
+ links_grid.addWidget(button, 0, idx)
+ else:
+ links_grid.addWidget(button, 1, 0, 1, 2)
self.download_buttons.append(button)
+ links_layout.addLayout(links_grid)
+ body.addWidget(links_card)
body.addStretch(1)
scroll.setWidget(content)
- layout.addWidget(scroll)
+ root.addWidget(scroll, 1)
+
+ footer = QFrame()
+ footer.setObjectName('pageActions')
+ footer_layout = QHBoxLayout(footer)
+ footer_layout.setContentsMargins(24, 10, 24, 10)
+ footer_layout.addStretch(1)
close = QPushButton(tr('关闭'))
+ close.setProperty('role', 'utility')
+ close.setCursor(Qt.PointingHandCursor)
close.clicked.connect(self.accept)
- layout.addWidget(close)
+ footer_layout.addWidget(close)
+ root.addWidget(footer)
def start_install(self):
self.install_button.setEnabled(False)
+ self.install_progress.show()
self.installer.start()
+ def _install_finished(self):
+ self.install_progress.hide()
+ self.install_button.setEnabled(True)
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+
def reject(self):
if self.installer.isRunning():
self.installer.requestInterruption()
- self.install_status.setText(tr("正在取消下载…"))
+ self.install_status.setText(tr('正在取消下载…'))
return
super().reject()
diff --git a/comic_translate_desktop/ui/language_dialog.py b/comic_translate_desktop/ui/language_dialog.py
index 6bafa33..88c5de2 100644
--- a/comic_translate_desktop/ui/language_dialog.py
+++ b/comic_translate_desktop/ui/language_dialog.py
@@ -1,89 +1,157 @@
"""First-launch language choice, before loading models or constructing the main UI."""
-from PySide6.QtCore import Qt
-from PySide6.QtGui import QFont
+from PySide6.QtCore import QRectF, Qt
+from PySide6.QtGui import QColor, QFont, QPainter
from PySide6.QtWidgets import (
- QButtonGroup, QDialog, QHBoxLayout, QLabel, QPushButton, QRadioButton, QVBoxLayout,
+ QButtonGroup, QDialog, QFrame, QHBoxLayout, QLabel, QPushButton, QRadioButton, QVBoxLayout,
)
from ..i18n import UI_LANGUAGES, normalize_ui_language, tr
-from .theme import brand_font, theme, ui_font
+from .halftone import draw_tone
+from .theme import brand_font, color, refresh_style, ui_font
from .window_chrome import apply_window_chrome
+_HEADINGS = {
+ 'zh-CN': '选择界面语言',
+ 'en': 'Choose your interface language',
+ 'ja': '表示言語を選択してください',
+}
+
+_CARD_PREVIEWS = {
+ 'zh-CN': '自动处理 · 嵌字精修',
+ 'en': 'Translate · Typesetting',
+ 'ja': '自動翻訳 · 写植調整',
+}
+
+
+class _LanguageCard(QFrame):
+ """Clickable monochrome card wrapping each language radio option."""
+
+ def __init__(self, radio, preview_text, *, japanese=False, parent=None):
+ super().__init__(parent)
+ self.radio = radio
+ self.setObjectName('langCard')
+ self.setCursor(Qt.PointingHandCursor)
+ row = QHBoxLayout(self)
+ row.setContentsMargins(16, 13, 16, 13)
+ row.setSpacing(12)
+ row.addWidget(radio)
+ row.addStretch(1)
+ preview = QLabel(preview_text)
+ preview.setProperty('muted', True)
+ preview.setFont(ui_font(12, japanese=japanese))
+ preview.setAttribute(Qt.WA_TransparentForMouseEvents)
+ row.addWidget(preview)
+ radio.toggled.connect(self._sync_selected)
+ self._sync_selected(radio.isChecked())
+
+ def _sync_selected(self, checked):
+ self.setProperty('selected', bool(checked))
+ refresh_style(self)
+
+ def mousePressEvent(self, event):
+ if event.button() == Qt.LeftButton:
+ self.radio.click()
+ super().mousePressEvent(event)
+
+
class InterfaceLanguageDialog(QDialog):
def __init__(self, language='zh-CN', parent=None):
super().__init__(parent)
+ self.setObjectName('paperDialog')
self.setWindowTitle('ComiTrans')
self.setModal(True)
- self.setFixedWidth(560)
+ self.setMinimumWidth(460)
+ self.resize(520, 470)
self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
- palette = theme()
- self.setStyleSheet(f'QDialog {{ background: {palette["paper"]}; }}')
+
layout = QVBoxLayout(self)
- layout.setContentsMargins(36, 30, 36, 26)
+ layout.setContentsMargins(32, 28, 32, 24)
layout.setSpacing(14)
+ brand_row = QHBoxLayout()
+ brand_row.setSpacing(10)
brand = QLabel('ComiTrans')
brand.setObjectName('brandTitle')
- brand.setFont(brand_font(40))
- layout.addWidget(brand)
+ brand.setFont(brand_font(38))
+ brand_row.addWidget(brand)
+ brand_row.addStretch(1)
+ lang_pill = QLabel('中文 · EN · 日本語')
+ lang_pill.setObjectName('badgePill')
+ lang_pill.setFont(ui_font(11, mono=True))
+ brand_row.addWidget(lang_pill, 0, Qt.AlignVCenter)
+ layout.addLayout(brand_row)
+
+ self._heading = QLabel()
+ self._heading.setFont(ui_font(20, QFont.Bold))
+ self._heading.setWordWrap(True)
+ layout.addWidget(self._heading)
kicker = QLabel('首次启动 · First launch · 初回起動')
kicker.setProperty('muted', True)
layout.addWidget(kicker)
-
- heading = QLabel('选择界面语言\nChoose your language\n表示言語を選ぶ')
- heading.setFont(ui_font(20, QFont.Bold))
- heading.setWordWrap(True)
- layout.addWidget(heading)
- layout.addSpacing(6)
+ layout.addSpacing(4)
self._group = QButtonGroup(self)
- card_style = (
- f'QRadioButton {{ padding: 12px 14px; border: 1px solid {palette["rule"]}; '
- f'border-radius: 10px; background: {palette["paper"]}; spacing: 10px; }}'
- f'QRadioButton:hover {{ background: {palette["muted"]}; }}'
- f'QRadioButton:checked {{ border: 1px solid {palette["ink"]}; '
- f'background: {palette["muted"]}; font-weight: 700; }}'
- f'QRadioButton::indicator {{ width: 16px; height: 16px; }}'
- )
current = normalize_ui_language(language)
self._radios = {}
+ cards_layout = QVBoxLayout()
+ cards_layout.setSpacing(10)
for code, name in UI_LANGUAGES:
radio = QRadioButton(name)
- radio.setStyleSheet(card_style)
+ radio.setObjectName('langRadio')
+ radio.setFont(ui_font(15, QFont.Bold, japanese=(code == 'ja')))
radio.setCursor(Qt.PointingHandCursor)
radio.setAccessibleName(name)
radio.setChecked(code == current)
radio.toggled.connect(lambda checked, value=code: checked and self._set_language(value))
self._group.addButton(radio)
self._radios[code] = radio
- layout.addWidget(radio)
+ card = _LanguageCard(radio, _CARD_PREVIEWS[code], japanese=(code == 'ja'), parent=self)
+ cards_layout.addWidget(card)
+ layout.addLayout(cards_layout)
layout.addSpacing(4)
+ divider = QFrame()
+ divider.setObjectName('hairlineRule')
+ layout.addWidget(divider)
+
+ actions = QHBoxLayout()
+ actions.setSpacing(16)
self.note = QLabel()
self.note.setWordWrap(True)
self.note.setProperty('muted', True)
- layout.addWidget(self.note)
-
- actions = QHBoxLayout()
- actions.addStretch(1)
+ actions.addWidget(self.note, 1)
self.continue_button = QPushButton()
self.continue_button.setProperty('role', 'primary')
self.continue_button.setDefault(True)
+ self.continue_button.setCursor(Qt.PointingHandCursor)
self.continue_button.clicked.connect(self.accept)
- actions.addWidget(self.continue_button)
+ actions.addWidget(self.continue_button, 0, Qt.AlignVCenter)
layout.addLayout(actions)
self._language = current
self._preview_language()
+ def paintEvent(self, event):
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.Antialiasing)
+ painter.fillRect(self.rect(), QColor(color('paper')))
+ tone_width = min(160.0, self.width() * 0.32)
+ tone_height = 84.0
+ painter.setOpacity(0.24)
+ draw_tone(painter, QRectF(self.width() - tone_width - 12, 10, tone_width, tone_height),
+ profile='quiet', direction='right')
+ painter.end()
+
def _set_language(self, code):
self._language = code
self._preview_language()
def _preview_language(self):
code = self._language
+ self._heading.setText(_HEADINGS.get(code, _HEADINGS['zh-CN']))
+ self._heading.setFont(ui_font(20, QFont.Bold, japanese=(code == 'ja')))
self.note.setText(tr('以后可在设置中更改。界面语言不影响漫画译文语言。', language=code))
self.continue_button.setText(tr('继续', language=code))
self.continue_button.setAccessibleName(tr('继续', language=code))
diff --git a/comic_translate_desktop/ui/main_window.py b/comic_translate_desktop/ui/main_window.py
index cd3fde9..d9fde3e 100644
--- a/comic_translate_desktop/ui/main_window.py
+++ b/comic_translate_desktop/ui/main_window.py
@@ -5,6 +5,8 @@
from pathlib import Path
import json
import random
+import hashlib
+import uuid
from PySide6.QtCore import (
QEasingCurve,
@@ -26,6 +28,7 @@
QIcon,
QImageReader,
QPixmap,
+ QFontMetrics,
)
from PySide6.QtWidgets import (
QApplication,
@@ -34,6 +37,7 @@
QAbstractItemView,
QComboBox,
QCheckBox,
+ QDialog,
QFileDialog,
QFrame,
QHBoxLayout,
@@ -55,15 +59,19 @@
QVBoxLayout,
QWidget,
)
+from shiboken6 import isValid
from comic_translate_core.pipeline_settings import apply_runtime_settings
from .. import config as app_config
from ..config import config_fingerprint, missing_models, save_ai_config
+from ..productivity import nonnegative_number, terminology_projects
+from .workflow_dialogs import TerminologyDialog, TrialDialog, UsageDialog
from comic_translate_core.languages import SOURCE_LANGUAGES, validate_ocr_config
from comic_translate_core.chinese import TARGET_LANGUAGES, target_language_name
from comic_translate_core.layout_options import VERTICAL_ALIGNMENTS
from ..diagnostics import Diagnostics
from ..pdf_utils import render_pdf_preview
+from ..cbz import PROJECT_EXTS, render_cbz_preview
from ..pdf_project import project_link_path
from ..worker import BatchWorker
from .api_config_page import ApiConfigPage
@@ -96,7 +104,7 @@
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
-DOCUMENT_EXTS = IMAGE_EXTS | {".pdf"}
+DOCUMENT_EXTS = IMAGE_EXTS | PROJECT_EXTS
class MainWindow(QMainWindow):
@@ -179,6 +187,12 @@ def _build_ui(self) -> None:
button.setProperty("role", "nav")
header.addWidget(button)
header.addStretch()
+ self.update_button = QPushButton(tr('有更新'))
+ self.update_button.setObjectName('updateIndicator')
+ self.update_button.setProperty('role', 'primary')
+ self.update_button.setCursor(Qt.PointingHandCursor)
+ self.update_button.hide()
+ header.addWidget(self.update_button, 0, Qt.AlignVCenter)
self.status_pill = QFrame()
self.status_pill.setObjectName('statusPill')
self.status_pill.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
@@ -289,7 +303,7 @@ def _build_file_panel(self) -> QWidget:
heading = PanelHeading("01", tr('漫画队列'), sidebar=True)
layout.addWidget(heading)
self._file_count_label = QLabel(tr('0 个文件'))
- self._file_selection_label = QLabel(tr('支持图片与 PDF'))
+ self._file_selection_label = QLabel(tr('支持图片、PDF 与 CBZ'))
self._file_selection_label.setProperty("muted", True)
layout.addWidget(self._file_count_label)
layout.addWidget(self._file_selection_label)
@@ -311,7 +325,7 @@ def _build_file_panel(self) -> QWidget:
self._folder_btn.setProperty("role", "chip")
drop.addWidget(self._add_btn)
drop.addWidget(self._folder_btn)
- hint = QLabel('PNG / JPG / WEBP / BMP / PDF')
+ hint = QLabel('PNG / JPG / WEBP / BMP / PDF / CBZ')
hint.setObjectName("dropHint")
hint.setWordWrap(True)
self._drop_hint = hint
@@ -350,10 +364,14 @@ def _build_work_panel(self) -> QWidget:
self._elapsed_label.setProperty("muted", True)
control_card = QFrame()
control_card.setObjectName("controlCard")
+ control_card.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
+ self._control_card = control_card
control_layout = QVBoxLayout(control_card)
control_layout.setContentsMargins(0, 0, 0, 6)
control_layout.setSpacing(4)
- self._control_grid = QGridLayout()
+ self._control_bar = QWidget()
+ self._control_bar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
+ self._control_grid = QGridLayout(self._control_bar)
self._control_grid.setContentsMargins(0, 0, 0, 0)
self._control_grid.setHorizontalSpacing(10)
self._control_grid.setVerticalSpacing(4)
@@ -429,6 +447,42 @@ def _build_work_panel(self) -> QWidget:
self._language_stacked = False
self._start_btn = QPushButton(tr('开始翻译'))
self._start_btn.setProperty("role", "primary")
+ self._last_usage_report = None
+ self._trial_outputs = []
+ self._usage_report_timer = QTimer(self)
+ self._usage_report_timer.setSingleShot(True)
+ self._usage_report_timer.timeout.connect(self._show_usage)
+ self._trial_btn = QPushButton(tr('试译'))
+ self._trial_btn.setProperty('compact', True)
+ self._trial_btn.setToolTip(tr('先翻译队列开头的 1–3 页,查看效果和消耗'))
+ self._trial_btn.clicked.connect(self._start_trial)
+ self._usage_btn = QPushButton(tr('消耗'), self)
+ self._usage_btn.setProperty('compact', True)
+ self._usage_btn.setToolTip(tr('查看本次翻译 token 用量并设置估算单价'))
+ self._usage_btn.clicked.connect(self._show_usage)
+ self._usage_btn.setEnabled(False)
+ self._usage_btn.hide()
+ self._task_menu_btn = QToolButton()
+ self._task_menu_btn.setText(tr('任务'))
+ self._task_menu_btn.setProperty('compact', True)
+ self._task_menu_btn.setProperty('role', 'utility')
+ self._task_menu_btn.setProperty('menuButton', True)
+ self._task_menu_btn.setPopupMode(QToolButton.InstantPopup)
+ self._task_menu = QMenu(self._task_menu_btn)
+ self._task_menu.setToolTipsVisible(True)
+ self._task_work_info = self._task_menu.addAction(tr('未启用作品术语库'))
+ self._task_work_info.setEnabled(False)
+ self._task_terms_action = self._task_menu.addAction(tr('作品术语库'), self._edit_terminology)
+ self._task_menu.addSeparator()
+ self._task_usage_action = self._task_menu.addAction(tr('翻译消耗'), self._show_usage)
+ self._task_usage_action.setEnabled(False)
+ self._task_menu_btn.setMenu(self._task_menu)
+ self._run_controls = QWidget()
+ run_row = QHBoxLayout(self._run_controls)
+ run_row.setContentsMargins(0, 0, 0, 0)
+ run_row.setSpacing(6)
+ for button in (self._task_menu_btn, self._trial_btn, self._start_btn):
+ run_row.addWidget(button)
self._output_controls = QWidget()
output_row = QHBoxLayout(self._output_controls)
output_row.setContentsMargins(0, 0, 0, 0)
@@ -445,18 +499,21 @@ def _build_work_panel(self) -> QWidget:
self._browse_output_btn.clicked.connect(self._browse_output_dir)
output_row.addWidget(self._output_dir_input, 1)
output_row.addWidget(self._browse_output_btn)
- control_layout.addLayout(self._control_grid)
+ control_layout.addWidget(self._control_bar)
self._font_picker = TranslationFontPicker(self.config)
self._font_picker.selection_changed.connect(self._change_translation_font)
self._pref_container = QScrollArea()
+ self._pref_container.setObjectName('prefContainer')
self._pref_container.setWidgetResizable(True)
self._pref_container.setFrameShape(QFrame.NoFrame)
self._pref_container.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._pref_container.setVisible(False)
pref_content = QWidget()
+ pref_content.setObjectName('prefContent')
+ self._pref_content = pref_content
self._pref_container.setWidget(pref_content)
pref_layout = QVBoxLayout(pref_content)
- pref_layout.setContentsMargins(0, 0, 0, 0)
+ pref_layout.setContentsMargins(0, 10, 0, 4)
pref_layout.setSpacing(10)
pref_layout.addWidget(self._font_picker)
@@ -549,13 +606,25 @@ def _build_work_panel(self) -> QWidget:
names_panel.setSpacing(4)
names_label = QLabel(tr('中文人名(每行一个,AI 会自动对照)'))
names_label.setProperty("muted", True)
+ names_label.setWordWrap(True)
self._names_input = QPlainTextEdit()
self._names_input.setObjectName('prefInput')
self._names_input.setPlaceholderText(tr('例如:\n路飞\n娜美\n索隆'))
self._names_input.setMinimumHeight(62)
self._names_input.setMaximumHeight(72)
- names_panel.addWidget(names_label)
+ names_header = QHBoxLayout()
+ names_header.addWidget(names_label, 1)
+ self._terminology_btn = QPushButton(tr('作品术语库'))
+ self._terminology_btn.setProperty('compact', True)
+ self._terminology_btn.clicked.connect(self._edit_terminology)
+ names_header.addWidget(self._terminology_btn)
+ names_panel.addLayout(names_header)
names_panel.addWidget(self._names_input)
+ self._terminology_summary = QLabel()
+ self._terminology_summary.setWordWrap(True)
+ self._terminology_summary.setProperty('muted', True)
+ self._refresh_terminology_summary()
+ names_panel.addWidget(self._terminology_summary)
right_layout.addLayout(prompt_panel)
right_layout.addLayout(names_panel)
right_layout.addStretch(1)
@@ -823,9 +892,11 @@ def _add_paths(self, paths) -> None:
self._update_actions()
def _thumbnail_icon(self, path: Path) -> QIcon:
- if path.suffix.lower() == ".pdf":
+ suffix = path.suffix.lower()
+ if suffix in PROJECT_EXTS:
try:
- return QIcon(QPixmap.fromImage(render_pdf_preview(path, QSize(96, 96))))
+ preview = render_cbz_preview if suffix == '.cbz' else render_pdf_preview
+ return QIcon(QPixmap.fromImage(preview(path, QSize(96, 96))))
except Exception:
return QIcon()
reader = QImageReader(str(path))
@@ -839,9 +910,9 @@ def _thumbnail_icon(self, path: Path) -> QIcon:
def _choose_files(self) -> None:
paths, _ = QFileDialog.getOpenFileNames(
self,
- tr('选择漫画图片或 PDF'),
+ tr('选择漫画文件'),
"",
- tr('漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf)'),
+ tr('漫画文件 (*.png *.jpg *.jpeg *.webp *.bmp *.pdf *.cbz);;图片文件 (*.png *.jpg *.jpeg *.webp *.bmp);;PDF 文件 (*.pdf);;CBZ 文件 (*.cbz)'),
)
self._add_paths(paths)
@@ -973,7 +1044,7 @@ def _on_warmup_finished(self, success: int, failed: int) -> None:
self._set_status(tr('模型已就绪'), "ready")
self._update_actions()
- def _start_translation(self) -> None:
+ def _start_translation(self, checked=False, *, trial_pages=0) -> None:
if self.worker is not None or self.warmup_worker is not None:
return
self._warmup_timer.stop()
@@ -1019,7 +1090,13 @@ def _start_translation(self) -> None:
if self.pipeline is None or self.pipeline_fingerprint != fingerprint:
self.pipeline = None
- for index in range(self.file_list.count()):
+ self._trial_outputs = []
+ worker_config = dict(self.config)
+ if trial_pages:
+ worker_config.update(trial_page_limit=trial_pages, resume_enabled=False,
+ retain_translation_context=False)
+ output_dir = output_dir / 'trial' / uuid.uuid4().hex[:12]
+ for index in range(self.file_list.count() if not trial_pages else 0):
item = self.file_list.item(index)
key = item.data(Qt.UserRole)
item.setText(tr('○ 等待\n{_0}', _0=item.data(Qt.UserRole + 1) or Path(key).name))
@@ -1028,7 +1105,7 @@ def _start_translation(self) -> None:
self.worker = BatchWorker(
files,
output_dir,
- self.config,
+ worker_config,
pipeline=self.pipeline,
parent=self,
)
@@ -1052,6 +1129,62 @@ def _start_translation(self) -> None:
self.stage_label.setText(tr('任务已创建,正在准备第一份文件'))
self._set_running(True)
+ def _start_trial(self):
+ if self.worker is not None or self.warmup_worker is not None or not self._all_files():
+ return
+ dialog = TrialDialog(self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ self._start_translation(trial_pages=dialog.pages.value())
+ dialog.deleteLater()
+
+ def _refresh_terminology_summary(self):
+ project = terminology_projects(self.config.get('terminology_projects')).get(
+ self.config.get('terminology_project', ''))
+ self._terminology_summary.setText(
+ tr('当前作品:{_0} · {_1} 个译名 · AI 自动匹配', _0=project['name'], _1=len(project['terms']))
+ if project else tr('未启用作品术语库'))
+ summary = self._terminology_summary.text()
+ self._task_work_info.setText(QFontMetrics(self._task_menu.font()).elidedText(summary, Qt.ElideRight, 420))
+ self._task_work_info.setToolTip(summary)
+ self._task_menu_btn.setToolTip(summary)
+
+ def _edit_terminology(self):
+ if self.worker is not None:
+ return
+ dialog = TerminologyDialog(self.config, self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ try:
+ self.config = save_ai_config(dialog.values())
+ self._refresh_terminology_summary()
+ except OSError as exc:
+ QMessageBox.warning(self, tr('保存失败'), str(exc))
+ dialog.deleteLater()
+
+ def _pricing_scope(self):
+ return hashlib.sha256((str(self.config.get('api_base_url', '')) + '\n'
+ + str(self.config.get('translation_model', ''))).encode()).hexdigest()
+
+ def _show_usage(self):
+ if not self._last_usage_report:
+ return
+ report = self._last_usage_report
+ raw = self.config.get('usage_pricing', {})
+ pricing = raw if raw.get('scope') == report.get('scope') else {}
+ pricing = {**pricing, 'input': nonnegative_number(pricing.get('input')),
+ 'output': nonnegative_number(pricing.get('output'))}
+ dialog = UsageDialog(report, pricing, self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ try:
+ self.config = save_ai_config({'usage_pricing': {**dialog.pricing(), 'scope': report.get('scope')}})
+ except OSError as exc:
+ QMessageBox.warning(self, tr('保存失败'), str(exc))
+ if dialog.action == 'edit':
+ self._nav_editor.click()
+ self.editor_page.request_import(report.get('outputs', []))
+ elif dialog.action == 'full':
+ self._start_translation()
+ dialog.deleteLater()
+
def _stop_translation(self) -> None:
if self.worker and self.worker.isRunning():
self._stop_requested = True
@@ -1074,6 +1207,11 @@ def _update_actions(self) -> None:
selected_count = len(self.file_list.selectedItems())
self._start_btn.setText(tr('开始翻译({_0})', _0=count) if count else tr('开始翻译'))
self._start_btn.setEnabled(not running and not warming and count > 0)
+ self._trial_btn.setEnabled(not running and not warming and count > 0)
+ self._usage_btn.setEnabled(not running and bool(self._last_usage_report))
+ self._task_menu_btn.setEnabled(not running)
+ self._task_terms_action.setEnabled(not running)
+ self._task_usage_action.setEnabled(not running and bool(self._last_usage_report))
self._stop_btn.setVisible(running)
self._stop_btn.setEnabled(running and not self._stop_requested)
self._add_btn.setEnabled(not running)
@@ -1099,22 +1237,22 @@ def _update_actions(self) -> None:
self._page_progress_label.setVisible((count > 0 or running) and not compact_pref)
self._progress_label.setVisible((count > 0 or running) and not compact_pref)
self._file_selection_label.setText(
- tr('已选 {_0} 个', _0=selected_count) if selected_count else tr('支持图片与 PDF')
+ tr('已选 {_0} 个', _0=selected_count) if selected_count else tr('支持图片、PDF 与 CBZ')
)
selected = self.file_list.selectedItems()
output = self.results.get(selected[-1].data(Qt.UserRole)) if selected else None
self._edit_result_btn.setEnabled(bool(output and (
- Path(output).suffix.lower() != ".pdf" or project_link_path(output).is_file())))
- self._edit_result_btn.setToolTip(tr('精修已生成的图片或 PDF') if self._edit_result_btn.isEnabled() else tr('请选择已完成且带精修资料的图片或 PDF'))
+ Path(output).suffix.lower() not in PROJECT_EXTS or project_link_path(output).is_file())))
+ self._edit_result_btn.setToolTip(tr('精修已生成的结果') if self._edit_result_btn.isEnabled() else tr('请选择已完成且带精修资料的结果'))
editable = self._editable_outputs()
self._edit_all_btn.setEnabled(bool(editable) and not running)
self._edit_all_btn.setToolTip(
- tr('把上次任务生成的全部图片或 PDF 加入嵌字精修列表') if editable
+ tr('把上次任务的全部结果加入嵌字精修列表') if editable
else tr('上次任务还没有可精修的结果'))
if warming:
self._start_btn.setToolTip(tr('本地模型正在准备,完成后即可开始'))
elif not count:
- self._start_btn.setToolTip(tr('请先添加漫画图片或 PDF'))
+ self._start_btn.setToolTip(tr('请先添加漫画文件'))
else:
self._start_btn.setToolTip(tr('开始处理当前列表中的 {_0} 个文件', _0=count))
@@ -1143,7 +1281,8 @@ def _on_workflow_event(self, event) -> None:
return
self.step_panel.consume_workflow_event(event)
if event.get('type') == 'publish' and event.get('state') == 'running':
- self.stage_focus.set_stage('07', tr('合成译文 PDF'), event.get('document_name', ''))
+ title = tr('打包译文 CBZ') if event.get('output_format') == 'CBZ' else tr('合成译文 PDF')
+ self.stage_focus.set_stage('07', title, event.get('document_name', ''))
def _on_stage_event(self, event) -> None:
if self.worker is None or event['task_id'] != self.worker.task_id:
@@ -1161,7 +1300,7 @@ def _on_stage_event(self, event) -> None:
self.stage_label.setText(detail)
self.stage_label.setToolTip(tr(event['message']))
index = event['document_index']
- if 0 < index <= self.file_list.count():
+ if not self.worker._trial_limit and 0 < index <= self.file_list.count():
item = self.file_list.item(index - 1)
state = {'failed': tr('⊠ 失败'), 'cancelled': tr('— 已取消')}.get(event['state'], tr('◉ 处理中'))
item.setText(f'{state}\n{item.data(Qt.UserRole + 1)}')
@@ -1175,6 +1314,11 @@ def _on_pipeline_ready(self, pipeline) -> None:
self._append_log(tr('AI 模型初始化完成。'))
def _on_image_done(self, input_path: str, output_path: str) -> None:
+ if self.worker is not None and self.worker._trial_limit:
+ self._trial_outputs.append(output_path)
+ self.result_view.set_image(output_path)
+ self.preview_tabs.setCurrentWidget(self.result_view)
+ return
key = str(Path(input_path).resolve())
self.results[key] = output_path
current = self._current_result_paths()
@@ -1197,6 +1341,9 @@ def _on_image_done(self, input_path: str, output_path: str) -> None:
def _on_image_failed(self, name: str, message: str) -> None:
self.step_panel.mark_failed()
+ if self.worker is not None and self.worker._trial_limit:
+ self._append_log(tr('[失败] {_0}: {_1}', _0=name, _1=message))
+ return
for index in range(self.file_list.count()):
item = self.file_list.item(index)
original_name = item.data(Qt.UserRole + 1) or Path(item.data(Qt.UserRole)).name
@@ -1207,6 +1354,10 @@ def _on_image_failed(self, name: str, message: str) -> None:
self._append_log(tr('[失败] {_0}: {_1}', _0=name, _1=message))
def _on_finished(self, success: int, failed: int) -> None:
+ trial = bool(self.worker is not None and self.worker._trial_limit)
+ if self.worker is not None and self.worker.usage_report:
+ self._last_usage_report = {**self.worker.usage_report, 'scope': self._pricing_scope()}
+ self._usage_btn.setEnabled(True)
# The terminal signal is emitted as run() returns. Keep the worker until it exits.
if self.worker is not None:
self._stop_requested = self._stop_requested or self.worker._is_stopped()
@@ -1220,6 +1371,19 @@ def _on_finished(self, success: int, failed: int) -> None:
self._elapsed_timer.stop()
self._update_elapsed()
self._set_running(False)
+ if trial:
+ self.stage_label.setText(tr('试译结束,结果已单独保存。'))
+ self._set_status(tr('试译完成') if not failed and not self._stop_requested else tr('试译已结束'),
+ 'ready' if not failed and not self._stop_requested else 'warning')
+ self._sync_step_panel_queue()
+ if failed:
+ self.step_panel.mark_failed()
+ elif self._stop_requested:
+ self.step_panel.mark_cancelled()
+ else:
+ self.step_panel.mark_done()
+ self._usage_report_timer.start(0)
+ return
total_done = success + failed
if self._stop_requested and total_done < self.file_list.count():
summary = tr('已停止,完成 {_0} 个文件,失败 {_1} 个文件。', _0=success, _1=failed)
@@ -1278,7 +1442,11 @@ def _show_issue_prompt(self) -> None:
)
copy_btn = box.addButton(tr('复制诊断提示词'), QMessageBox.ActionRole)
issue_btn = box.addButton(tr('打开 Issue 页面'), QMessageBox.ActionRole)
- box.addButton(tr('关闭'), QMessageBox.RejectRole)
+ close_btn = box.addButton(tr('关闭'), QMessageBox.RejectRole)
+ copy_btn.setProperty('role', 'primary')
+ issue_btn.setProperty('role', 'utility')
+ close_btn.setProperty('role', 'quiet')
+ box.setDefaultButton(copy_btn)
box.exec()
clicked = box.clickedButton()
if clicked is copy_btn:
@@ -1346,7 +1514,7 @@ def _editable_outputs(self) -> list[str]:
key = str(path)
if key in seen or not path.exists():
continue
- if path.suffix.lower() == '.pdf' and not project_link_path(path).is_file():
+ if path.suffix.lower() in PROJECT_EXTS and not project_link_path(path).is_file():
continue
seen.add(key)
outputs.append(key)
@@ -1368,96 +1536,142 @@ def _open_all_in_editor(self) -> None:
def _toggle_preferences(self, checked: bool) -> None:
if not checked:
- self._pref_scroll_value = self._pref_container.verticalScrollBar().value()
+ if self._pref_animation is None:
+ self._pref_scroll_value = self._pref_container.verticalScrollBar().value()
if self._pref_save_timer.isActive():
self._save_translation_preferences()
self._pref_toggle.setArrowType(Qt.DownArrow if checked else Qt.RightArrow)
self._ui_settings.setValue('ui/preferencesVisible', checked)
- # Animate the foldout height and leave the log alone. Hiding the log in
- # one step (and fading the scroll area through a QGraphicsOpacityEffect)
- # is what made the old transition stutter instead of animate.
- self._pref_animating = True
self._animate_preferences(checked)
- self._apply_compact_layout()
+
+ def _sync_pref_columns(self) -> None:
+ if not hasattr(self, '_pref_columns'):
+ return
+ control_layout = self._control_card.layout()
+ margins = control_layout.contentsMargins()
+ available_width = (
+ self._control_card.contentsRect().width()
+ - margins.left()
+ - margins.right()
+ )
+ if available_width <= 0:
+ available_width = max(0, self.width() - 320)
+ direction = (
+ QHBoxLayout.LeftToRight
+ if available_width >= 680
+ else QHBoxLayout.TopToBottom
+ )
+ if self._pref_columns.direction() == direction:
+ return
+ self._pref_columns.setDirection(direction)
+ self._pref_content.layout().invalidate()
+ self._pref_content.updateGeometry()
def _pref_target_height(self) -> int:
- if self.height() >= 760:
- # Keep the log panel visible so nothing jumps when the foldout opens.
- return min(280, max(220, self.height() - 620))
- # The scroll viewport must fit its card in short windows; a 160px
- # minimum otherwise lets the card clip controls that Qt reports visible.
- reserve = 396 + (40 if hasattr(self, 'stage_focus') and self.stage_focus.isVisible() else 0)
- available = max(56, self.height() - reserve)
- return min(240, available)
+ self._sync_pref_columns()
+ self._pref_content.layout().activate()
+ content_height = self._pref_content.sizeHint().height()
+ if content_height <= 0:
+ content_height = 276
+ if self.height() < 760:
+ stage_visible = (
+ hasattr(self, 'stage_focus')
+ and not self.stage_focus.isHidden()
+ )
+ reserve = 392 + (40 if stage_visible else 0)
+ available = max(56, self.height() - reserve)
+ return min(max(240, min(content_height + 6, 300)), available)
+
+ cap = min(320, max(220, self.height() - 500))
+ return max(220, min(content_height + 6, cap))
+
+ def _unfreeze_pref_content(self) -> None:
+ if hasattr(self, '_pref_content'):
+ self._pref_content.setMinimumSize(0, 0)
+ self._pref_content.setMaximumSize(16777215, 16777215)
+ self._pref_container.setWidgetResizable(True)
def _animate_preferences(self, expand: bool) -> None:
container = self._pref_container
previous = self._pref_animation
if previous is not None:
+ self._pref_animation = None
previous.stop()
previous.deleteLater()
- self._pref_animation = None
- target = self._pref_target_height() if expand else 0
- duration = 230 if expand else 195
- if reduced_motion() or self.height() < 680:
- # Short windows hide the log and stage focus while the foldout is open;
- # apply compact visibility first so _pref_target_height sees freed space.
- self._pref_animating = False
- self._apply_compact_layout()
- target = self._pref_target_height() if expand else 0
- container.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
- container.setVisible(expand)
- container.setMinimumHeight(target)
- container.setMaximumHeight(target)
- if expand:
- self._restore_preferences_scroll()
- return
- start = container.height() if container.isVisible() else 0
+
+ start = 0 if container.isHidden() else container.height()
if start > 10000:
start = 0
+ self._unfreeze_pref_content()
+ self._pref_animating = True
+ self._apply_compact_layout()
+ target = self._pref_target_height() if expand else 0
+
+ if (
+ not self.isVisible()
+ or reduced_motion()
+ or self.height() < 680
+ or start == target
+ ):
+ self._finish_preferences_animation(expand, None)
+ return
+
+ container.setFixedHeight(start)
container.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- container.setVisible(True)
+ container.show()
if expand:
container.verticalScrollBar().setValue(self._pref_scroll_value)
- container.setFixedHeight(start)
+
+ control_layout = self._control_card.layout()
+ work_layout = getattr(self, '_work_layout', None)
animation = QVariantAnimation(self)
- animation.setDuration(duration)
+ animation.setDuration(230 if expand else 195)
animation.setStartValue(float(start))
animation.setEndValue(float(target))
animation.setEasingCurve(STANDARD)
- def _on_val(value) -> None:
- container.setFixedHeight(max(0, int(round(float(value)))))
+ def apply_height(value) -> None:
+ if self._pref_animation is not animation:
+ return
+ container.setFixedHeight(max(0, round(float(value))))
+ control_layout.activate()
+ if work_layout is not None:
+ work_layout.activate()
- animation.valueChanged.connect(_on_val)
+ animation.valueChanged.connect(apply_height)
animation.finished.connect(
- lambda: self._finish_preferences_animation(expand, target))
+ lambda: self._finish_preferences_animation(expand, animation)
+ )
self._pref_animation = animation
animation.start()
- def _finish_preferences_animation(self, expand: bool, target: int) -> None:
- self._pref_animating = False
+ def _finish_preferences_animation(self, expand: bool, animation) -> None:
+ if self._pref_animation is not animation:
+ return
self._pref_animation = None
- if expand:
- target = self._pref_target_height()
- else:
- target = 0
+ self._pref_animating = False
+ if animation is not None:
+ animation.deleteLater()
+
container = self._pref_container
+ self._unfreeze_pref_content()
container.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
- container.setMinimumHeight(target)
- container.setMaximumHeight(target)
- if expand:
- bar = container.verticalScrollBar()
- if bar.value() != self._pref_scroll_value:
- bar.setValue(self._pref_scroll_value)
- else:
- container.setVisible(False)
+ container.setVisible(expand)
self._apply_compact_layout()
+ self._control_card.layout().activate()
+ work_layout = getattr(self, '_work_layout', None)
+ if work_layout is not None:
+ work_layout.activate()
+ if expand:
+ self._restore_preferences_scroll()
def _restore_preferences_scroll(self) -> None:
- QTimer.singleShot(
- 0, lambda: self._pref_container.verticalScrollBar().setValue(self._pref_scroll_value))
+ QTimer.singleShot(0, self, self._apply_preferences_scroll)
+
+ def _apply_preferences_scroll(self) -> None:
+ if isValid(self) and isValid(self._pref_container):
+ self._pref_container.verticalScrollBar().setValue(self._pref_scroll_value)
def _toggle_log_panel(self, visible: bool) -> None:
was_visible = self._log_panel.isVisible()
@@ -1487,13 +1701,11 @@ def _apply_compact_layout(self):
self.stage_focus.setVisible((active_items or warming) and not compact_pref)
self._page_progress_label.setVisible(active_items and not compact_pref)
self._progress_label.setVisible(active_items and not compact_pref)
- wide = self._pref_container.width() >= 680
- if not self._pref_animating:
+ if self._pref_animating:
+ self._sync_pref_columns()
+ else:
wanted = self._pref_target_height() if expanded else 0
- self._pref_container.setMinimumHeight(wanted)
- self._pref_container.setMaximumHeight(wanted)
- if hasattr(self, '_pref_columns'):
- self._pref_columns.setDirection(QHBoxLayout.LeftToRight if wide else QHBoxLayout.TopToBottom)
+ self._pref_container.setFixedHeight(wanted)
self._brand_title.setFont(brand_font(28 if self.width() < 960 else 36 if self.width() < 1180 else 40))
self._header_layout.setContentsMargins(12 if self.width() < 1120 else 20, 8, 12 if self.width() < 1120 else 20, 8)
self._nav_auto.setText(tr('自动处理') if (self.width() < 1120 or ui_language() != 'zh-CN') else tr('01 自动处理'))
@@ -1504,7 +1716,7 @@ def _apply_compact_layout(self):
self._issue_btn.setVisible(not narrow)
self._settings_btn.setVisible(self.width() >= 960)
self._logs_btn.setVisible(self.width() >= 960)
- inline = self.width() >= (1400 if ui_language() == 'en' else 1280 if ui_language() == 'ja' else 1180)
+ inline = self.width() >= (1580 if ui_language() == 'en' else 1500 if ui_language() == 'ja' else 1420)
controls_mode = 'inline' if inline else 'narrow' if self.width() < 880 else 'split'
stacked = controls_mode == 'split' and ui_language() != 'zh-CN'
if stacked != self._language_stacked:
@@ -1529,7 +1741,7 @@ def _apply_compact_layout(self):
self._language_grid.setColumnStretch(5, 1)
if controls_mode != self._controls_mode:
self._controls_mode = controls_mode
- for widget in (self._language_controls, self._output_controls, self._start_btn,
+ for widget in (self._language_controls, self._output_controls, self._run_controls,
self._quick_options, self._control_divider):
self._control_grid.removeWidget(widget)
if inline:
@@ -1537,19 +1749,19 @@ def _apply_compact_layout(self):
self._control_grid.addWidget(self._control_divider, 0, 1)
self._control_grid.addWidget(self._output_controls, 0, 2)
self._control_grid.addWidget(self._quick_options, 0, 3)
- self._control_grid.addWidget(self._start_btn, 0, 4)
+ self._control_grid.addWidget(self._run_controls, 0, 4)
self._control_divider.setVisible(True)
elif controls_mode == 'narrow':
self._control_grid.addWidget(self._language_controls, 0, 0, 1, 5)
self._control_grid.addWidget(self._quick_options, 1, 0, 1, 3, Qt.AlignLeft)
- self._control_grid.addWidget(self._start_btn, 1, 3, 1, 2, Qt.AlignRight)
+ self._control_grid.addWidget(self._run_controls, 1, 3, 1, 2, Qt.AlignRight)
self._control_grid.addWidget(self._output_controls, 2, 0, 1, 5)
self._control_divider.setVisible(False)
else:
self._control_grid.addWidget(self._language_controls, 0, 0, 1, 3)
self._control_grid.addWidget(self._quick_options, 0, 3, 1, 2, Qt.AlignRight)
self._control_grid.addWidget(self._output_controls, 1, 0, 1, 3)
- self._control_grid.addWidget(self._start_btn, 1, 3, 1, 2, Qt.AlignRight)
+ self._control_grid.addWidget(self._run_controls, 1, 3, 1, 2, Qt.AlignRight)
self._control_divider.setVisible(False)
self._control_grid.setColumnStretch(1, 0)
self._control_grid.setColumnStretch(2, 1)
@@ -1579,10 +1791,16 @@ def _apply_compact_layout(self):
def showEvent(self, event):
super().showEvent(event)
apply_window_chrome(self)
+ self._apply_compact_layout()
+ QTimer.singleShot(0, self, self._apply_deferred_compact_layout)
if not self._warmup_scheduled and self.pipeline is None:
self._warmup_scheduled = True
self._warmup_timer.start()
+ def _apply_deferred_compact_layout(self) -> None:
+ if isValid(self) and isValid(self._pref_container):
+ self._apply_compact_layout()
+
def resizeEvent(self, event):
super().resizeEvent(event)
self._apply_compact_layout()
@@ -1732,13 +1950,22 @@ def dropEvent(self, event: QDropEvent) -> None:
self._add_paths(paths)
event.acceptProposedAction()
+ def close_for_update(self, launch) -> None:
+ self._launch_after_close = launch
+ try:
+ self.close()
+ finally:
+ self._launch_after_close = None
+
def closeEvent(self, event) -> None:
self._warmup_timer.stop()
if (self._pref_save_timer.isActive() or self._pref_save_error) and not self._save_translation_preferences():
self._set_status(tr('偏好未保存,请重试'), 'error')
event.ignore()
return
- if not self.editor_page._allow_navigation(self.close):
+ launch = getattr(self, '_launch_after_close', None)
+ retry_close = (lambda: self.close_for_update(launch)) if launch else self.close
+ if not self.editor_page._allow_navigation(retry_close):
event.ignore()
return
if self.worker and self.worker.isRunning():
@@ -1769,3 +1996,5 @@ def closeEvent(self, event) -> None:
self._star_prompt.dismiss()
self.editor_page.shutdown_jobs()
event.accept()
+ if launch:
+ launch()
diff --git a/comic_translate_desktop/ui/motion.py b/comic_translate_desktop/ui/motion.py
index f25596c..4e400d9 100644
--- a/comic_translate_desktop/ui/motion.py
+++ b/comic_translate_desktop/ui/motion.py
@@ -12,6 +12,7 @@
from PySide6.QtCore import (
QAbstractAnimation,
+ QBasicTimer,
QElapsedTimer,
QEasingCurve,
QEvent,
@@ -245,22 +246,23 @@ class _RippleOverlay(QWidget):
_FADE_MS = 240.0
def __init__(self, target: QAbstractButton) -> None:
- super().__init__(target)
+ # Qt may dispatch paint while the native widget is being constructed.
+ # Establish the idle paint state before any QWidget calls can re-enter us.
self._target = target
- self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
- self.setGeometry(target.rect())
-
self._hover_alpha = 0.0
self._hover_target = 0.0
self._last_ms = 0.0
self._ripples: list[dict] = []
+ super().__init__(target)
+ self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
+ self.setGeometry(target.rect())
+
self._clock = QElapsedTimer()
self._clock.start()
- self._timer = QTimer(self)
- self._timer.setInterval(16)
- self._timer.timeout.connect(self._step)
+ # Deliver frames to the widget itself, including inside modal dialogs.
+ self._timer = QBasicTimer()
self.show()
def set_hovered(self, hovered: bool) -> None:
@@ -308,10 +310,22 @@ def release_ripples(self) -> None:
def _ensure_running(self) -> None:
self._last_ms = float(self._clock.elapsed())
if not self._timer.isActive():
- self._timer.start()
+ self._timer.start(16, self)
- def _step(self) -> None:
- if not isValid(self) or not isValid(self._target):
+ def hideEvent(self, event) -> None:
+ timer = getattr(self, '_timer', None)
+ if timer is not None:
+ timer.stop()
+ self._ripples.clear()
+ self._hover_alpha = self._hover_target = 0.0
+ super().hideEvent(event)
+
+ def timerEvent(self, event) -> None:
+ timer = getattr(self, '_timer', None)
+ if timer is None or event.timerId() != timer.timerId():
+ super().timerEvent(event)
+ return
+ if not isValid(self._target):
self._timer.stop()
return
now = float(self._clock.elapsed())
@@ -341,6 +355,9 @@ def _step(self) -> None:
self.update()
def paintEvent(self, event) -> None:
+ # Qt can request paint before the Python animation state is available.
+ if getattr(self, '_timer', None) is None:
+ return
if not isValid(self._target) or (self._hover_alpha <= 0.004 and not self._ripples):
return
r = QRectF(self.rect())
@@ -405,15 +422,16 @@ class _FocusLineOverlay(QWidget):
"""Draws Google AI Studio center-out expanding monochrome focus underline."""
def __init__(self, target: QWidget) -> None:
- super().__init__(target)
+ # Keep early native paint callbacks safe, as with the ripple overlay.
self._target = target
- self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
- self.setGeometry(target.rect())
-
self._progress = 0.0
self._target_progress = 0.0
self._last_ms = 0.0
+ super().__init__(target)
+ self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
+ self.setGeometry(target.rect())
+
self._clock = QElapsedTimer()
self._clock.start()
self._timer = QTimer(self)
@@ -453,6 +471,8 @@ def _step(self) -> None:
self.update()
def paintEvent(self, event) -> None:
+ if getattr(self, '_timer', None) is None:
+ return
if self._progress <= 0.004 or not isValid(self._target):
return
r = QRectF(self.rect())
diff --git a/comic_translate_desktop/ui/preview.py b/comic_translate_desktop/ui/preview.py
index ab4620e..c7cd7d7 100644
--- a/comic_translate_desktop/ui/preview.py
+++ b/comic_translate_desktop/ui/preview.py
@@ -3,10 +3,12 @@
from pathlib import Path
from functools import lru_cache
+import time
from PySide6.QtCore import Qt, QElapsedTimer, QRectF, QPointF, QSize, QTimer, Signal, QEvent
from PySide6.QtGui import QColor, QPainter, QPen, QPixmap, QImageReader, QRegion
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QScrollArea, QStackedLayout, QPushButton, QSizePolicy, QProgressBar
from ..pdf_utils import render_pdf_preview
+from ..cbz import render_cbz_preview
from ..config import ICON_PATH
from .halftone import COMPACT_BREAKPOINT, draw_corner_tones, draw_tone
from .theme import color, display_font, theme_name, ui_font
@@ -78,6 +80,8 @@ class PageCanvas(QLabel):
region_edited = Signal(object)
region_edit_finished = Signal()
region_clicked = Signal(int)
+ regions_selected = Signal(object, str)
+ region_context_menu = Signal(int, object)
bubble_created = Signal(object)
def __init__(self, parent=None):
@@ -263,12 +267,28 @@ def _region_cursor(self, hit):
def cancel_region_drag(self):
self._region_drag = None
+ self._selection_start = self._selection_rect = None
if self.mouseGrabber() is self:
self.releaseMouse()
self.unsetCursor()
def mousePressEvent(self, event):
hit = self._region_hit(event.position())
+ if (event.button() == Qt.LeftButton and not self.region_creation and not self.bubble_creation
+ and self.page_rect().contains(event.position())):
+ if event.modifiers() & Qt.ShiftModifier:
+ self._selection_start = QPointF(event.position())
+ self._selection_rect = QRectF(self._selection_start, self._selection_start)
+ self.setFocus(Qt.MouseFocusReason)
+ self.grabMouse()
+ event.accept()
+ return
+ if event.modifiers() & Qt.ControlModifier:
+ index = self._region_at(event.position())
+ if index is not None:
+ self.regions_selected.emit([index], 'toggle')
+ event.accept()
+ return
if (self.bubble_creation and event.button() == Qt.LeftButton
and self.page_rect().contains(event.position())):
self._region_drag = ('bubble_create', QPointF(event.position()), self.region)
@@ -302,6 +322,17 @@ def mousePressEvent(self, event):
return
super().mousePressEvent(event)
+ def contextMenuEvent(self, event):
+ if self._region_drag is not None or self.region_creation or self.bubble_creation:
+ event.ignore()
+ return
+ index = self._region_at(QPointF(event.pos()))
+ if index is not None:
+ self.region_context_menu.emit(index, event.globalPos())
+ event.accept()
+ return
+ super().contextMenuEvent(event)
+
def _drag_region_to(self, point):
hit, start, original = self._region_drag
page = self.page_rect()
@@ -343,6 +374,11 @@ def image_point(position):
self.region_edited.emit(box)
def mouseMoveEvent(self, event):
+ if getattr(self, '_selection_start', None) is not None:
+ self._selection_rect = QRectF(self._selection_start, event.position()).normalized().intersected(self.page_rect())
+ self.update()
+ event.accept()
+ return
if self._region_drag is not None:
self._drag_region_to(event.position())
event.accept()
@@ -364,6 +400,16 @@ def mouseMoveEvent(self, event):
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
+ if event.button() == Qt.LeftButton and getattr(self, '_selection_start', None) is not None:
+ rect = self._selection_rect
+ indices = [index for index, box in self.regions if rect.intersects(self._box_rect(box))]
+ self._selection_start = self._selection_rect = None
+ if self.mouseGrabber() is self:
+ self.releaseMouse()
+ self.regions_selected.emit(indices, 'add' if event.modifiers() & Qt.ControlModifier else 'replace')
+ self.update()
+ event.accept()
+ return
if event.button() == Qt.LeftButton and self._region_drag is not None:
self._drag_region_to(event.position())
drag = self._region_drag
@@ -383,6 +429,13 @@ def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
def keyPressEvent(self, event):
+ if event.key() == Qt.Key_Escape and getattr(self, '_selection_start', None) is not None:
+ self._selection_start = self._selection_rect = None
+ if self.mouseGrabber() is self:
+ self.releaseMouse()
+ self.update()
+ event.accept()
+ return
if event.key() == Qt.Key_Escape and self._region_drag is not None:
if self._region_drag[0] == 'bubble_create':
self.cancel_region_drag()
@@ -477,6 +530,13 @@ def _paint_canvas_overlay(self):
painter.setPen(edge)
painter.setBrush(Qt.NoBrush)
painter.drawRect(page.adjusted(.5, .5, -.5, -.5))
+ rubber = getattr(self, '_selection_rect', None)
+ if rubber is not None:
+ painter.setPen(QPen(QColor(color('guide')), 1, Qt.DashLine))
+ tint = QColor(color('guide'))
+ tint.setAlpha(25)
+ painter.setBrush(tint)
+ painter.drawRect(rubber)
selected_index = None
if self.regions_visible and self.regions:
painter.setClipping(False)
@@ -490,7 +550,12 @@ def _paint_canvas_overlay(self):
selected_index = index
continue
guide = QColor(color('guide'))
- if index == self._hover_index:
+ if index in getattr(self, 'selected_indices', set()):
+ pen = QPen(QColor(color('guide')), 2, Qt.SolidLine)
+ pen.setCosmetic(True)
+ painter.setPen(pen)
+ painter.setBrush(Qt.NoBrush)
+ elif index == self._hover_index:
hs = max(0.25, min(1.0, self._hover_strength if self._hover_strength > 0 else 1.0))
halo = QColor(color('guideHalo'))
halo.setAlpha(int(round(180 * hs)))
@@ -569,6 +634,8 @@ class ImagePreview(QWidget):
region_edited = Signal(object)
region_edit_finished = Signal()
region_clicked = Signal(int)
+ regions_selected = Signal(object, str)
+ region_context_menu = Signal(int, object)
bubble_created = Signal(object)
zoom_changed = Signal(object)
color_picked = Signal(object)
@@ -586,6 +653,7 @@ def __init__(self, parent=None, *, import_action=False, illustration='studio-imp
self._space_pan = False
self._zoom_tool = False
self._color_picking = False
+ self._suppress_context_until = 0.0
self.setMinimumSize(120, 100)
self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
self._stack = QStackedLayout(self)
@@ -660,7 +728,9 @@ def __init__(self, parent=None, *, import_action=False, illustration='studio-imp
self._label.region_edited.connect(self.region_edited)
self._label.region_edit_finished.connect(self.region_edit_finished)
self._label.region_clicked.connect(self.region_clicked)
+ self._label.region_context_menu.connect(self.region_context_menu)
self._label.bubble_created.connect(self.bubble_created)
+ self._label.regions_selected.connect(self.regions_selected)
self._label.installEventFilter(self)
self._label.setObjectName('previewLabel')
self._label.setAlignment(Qt.AlignCenter)
@@ -682,9 +752,16 @@ def eventFilter(self, watched, event):
return super().eventFilter(watched, event)
elif watched is not self._label:
return super().eventFilter(watched, event)
+ if event.type() == QEvent.ContextMenu and (
+ self._color_picking or time.monotonic() <= self._suppress_context_until):
+ self._suppress_context_until = 0.0
+ event.accept()
+ return True
if self._color_picking:
if (event.type() == QEvent.KeyPress and event.key() == Qt.Key_Escape
or event.type() == QEvent.MouseButtonPress and event.button() == Qt.RightButton):
+ if event.type() == QEvent.MouseButtonPress and event.button() == Qt.RightButton:
+ self._suppress_context_until = time.monotonic() + 0.25
self.cancel_color_picking()
return True
if (event.type() == QEvent.MouseButtonPress and event.button() == Qt.LeftButton
@@ -706,6 +783,8 @@ def eventFilter(self, watched, event):
if event.type() == QEvent.MouseMove and not self._space_pan and self._pan is None:
self._label.setCursor(Qt.CrossCursor)
return True
+ elif event.type() == QEvent.MouseButtonPress:
+ self._suppress_context_until = 0.0
if event.type() == QEvent.Wheel:
if event.modifiers() & (Qt.ControlModifier | Qt.AltModifier):
step = 1.12 if event.angleDelta().y() > 0 else 1 / 1.12
@@ -768,8 +847,11 @@ def _wheel_scroll(self, event):
def set_image(self, path):
try:
- if Path(path).suffix.lower() == '.pdf':
+ suffix = Path(path).suffix.lower()
+ if suffix == '.pdf':
self.set_pixmap(QPixmap.fromImage(render_pdf_preview(path, QSize(1600, 1600))))
+ elif suffix == '.cbz':
+ self.set_pixmap(QPixmap.fromImage(render_cbz_preview(path, QSize(1600, 1600))))
else:
reader = QImageReader(str(path))
reader.setAutoTransform(True)
@@ -935,6 +1017,11 @@ def set_regions(self, regions, visible=True):
"""All text boxes of the page, in image coordinates; click to select."""
self._label.set_regions(regions, visible)
+ def set_selected_regions(self, indices):
+ self._selected_regions = set(indices)
+ self._label.selected_indices = self._selected_regions
+ self._label.update()
+
def set_region(self, box=None, *, editable=False):
"""Canvas-only selection guide; never alter the rendered/exported pixels."""
prev_box = self._label.region
diff --git a/comic_translate_desktop/ui/retranslate_dialog.py b/comic_translate_desktop/ui/retranslate_dialog.py
new file mode 100644
index 0000000..5dad909
--- /dev/null
+++ b/comic_translate_desktop/ui/retranslate_dialog.py
@@ -0,0 +1,135 @@
+"""Edit OCR, request a candidate, and compare both readings before applying."""
+from PySide6.QtCore import Qt
+from PySide6.QtGui import QPixmap
+from PySide6.QtWidgets import (
+ QDialog, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QPlainTextEdit,
+ QPushButton, QVBoxLayout,
+)
+
+from ..editor_jobs import LatestJobQueue
+from ..i18n import tr
+from .window_chrome import apply_window_chrome
+
+
+class RetranslateDialog(QDialog):
+ def __init__(self, source, current, translate, preview, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('重译当前气泡'))
+ self.resize(720, 500)
+ self._translate = translate
+ self._preview = preview
+ self._jobs = LatestJobQueue(self)
+ self.result_text = None
+ self._busy = False
+
+ root = QVBoxLayout(self)
+ inputs = QGridLayout()
+ inputs.addWidget(QLabel(tr('校正 OCR 原文')), 0, 0, 1, 2)
+ self.source = QPlainTextEdit(source)
+ self.source.setAccessibleName(tr('校正 OCR 原文'))
+ self.source.setMaximumHeight(70)
+ inputs.addWidget(self.source, 1, 0, 1, 2)
+ self.instruction = QLineEdit()
+ self.instruction.setPlaceholderText(tr('重译要求,如缩短对白或保留反讽'))
+ self.instruction.setAccessibleName(tr('重译要求,如缩短对白或保留反讽'))
+ inputs.addWidget(self.instruction, 2, 0)
+ self.request_button = QPushButton(tr('请求重译'))
+ self.request_button.clicked.connect(self._request)
+ inputs.addWidget(self.request_button, 2, 1)
+ root.addLayout(inputs)
+
+ comparison = QGridLayout()
+ comparison.setColumnStretch(0, 1)
+ comparison.setColumnStretch(1, 1)
+ comparison.addWidget(QLabel(tr('当前译文')), 0, 0)
+ comparison.addWidget(QLabel(tr('候选译文')), 0, 1)
+ self.current_image = QLabel()
+ self.candidate_image = QLabel()
+ for column, label in enumerate((self.current_image, self.candidate_image)):
+ label.setAlignment(Qt.AlignCenter)
+ label.setMinimumHeight(105)
+ comparison.addWidget(label, 1, column)
+ current_text = QPlainTextEdit(current)
+ current_text.setReadOnly(True)
+ current_text.setAccessibleName(tr('当前译文'))
+ self.candidate = QPlainTextEdit()
+ self.candidate.setReadOnly(True)
+ self.candidate.setAccessibleName(tr('候选译文'))
+ comparison.addWidget(current_text, 2, 0)
+ comparison.addWidget(self.candidate, 2, 1)
+ root.addLayout(comparison, 1)
+
+ footer = QHBoxLayout()
+ self.status = QLabel()
+ self.status.setTextFormat(Qt.PlainText)
+ self.status.setWordWrap(True)
+ footer.addWidget(self.status, 1)
+ self.apply_button = QPushButton(tr('应用候选译文'))
+ self.apply_button.setProperty('role', 'primary')
+ self.apply_button.clicked.connect(self.accept)
+ close = QPushButton(tr('关闭'))
+ close.clicked.connect(self.reject)
+ for button in (self.apply_button, close):
+ button.setAutoDefault(False)
+ footer.addWidget(button)
+ root.addLayout(footer)
+ self.source.textChanged.connect(self._reset_candidate)
+ self.instruction.textChanged.connect(self._reset_candidate)
+ self._reset_candidate()
+ current_preview, _ = self._preview(None)
+ self._show_image(self.current_image, current_preview)
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+
+ def done(self, result):
+ self._jobs.close()
+ super().done(result)
+
+ @staticmethod
+ def _show_image(label, image):
+ label.setPixmap(QPixmap.fromImage(image).scaled(300, 140, Qt.KeepAspectRatio,
+ Qt.SmoothTransformation))
+
+ def _reset_candidate(self):
+ self.result_text = None
+ self.candidate.clear()
+ self.candidate_image.clear()
+ self.status.clear()
+ self.request_button.setEnabled(not self._busy and bool(self.source.toPlainText().strip()))
+ self.apply_button.setEnabled(False)
+
+ def _request(self):
+ source, instruction = self.source.toPlainText().strip(), self.instruction.text()
+ if not source or self._busy:
+ return
+ self._reset_candidate()
+ self._set_busy(True)
+ self.status.setText(tr('正在请求单气泡重译…'))
+ self._jobs.submit(lambda cancelled: self._translate(source, instruction, cancelled),
+ self._ready, self._error, cancellable=True)
+
+ def _set_busy(self, busy):
+ self._busy = busy
+ self.request_button.setEnabled(not busy and bool(self.source.toPlainText().strip()))
+ self.source.setReadOnly(busy)
+ self.instruction.setReadOnly(busy)
+
+ def _ready(self, candidate):
+ try:
+ current, revised = self._preview(candidate)
+ self._show_image(self.current_image, current)
+ self._show_image(self.candidate_image, revised)
+ except Exception as exc:
+ self._error(str(exc))
+ return
+ self._set_busy(False)
+ self.status.clear()
+ self.candidate.setPlainText(candidate)
+ self.result_text = candidate
+ self.apply_button.setEnabled(True)
+
+ def _error(self, message):
+ self._set_busy(False)
+ self.status.setText(tr('重译失败:{_0}', _0=message))
diff --git a/comic_translate_desktop/ui/star_prompt.py b/comic_translate_desktop/ui/star_prompt.py
index 72e7b67..fd62a42 100644
--- a/comic_translate_desktop/ui/star_prompt.py
+++ b/comic_translate_desktop/ui/star_prompt.py
@@ -1,10 +1,14 @@
"""A non-modal, idle-dismissed repository support prompt."""
from __future__ import annotations
-from ..i18n import tr
-from PySide6.QtCore import QEvent, QTimer, Qt, QUrl
-from PySide6.QtGui import QDesktopServices
+from PySide6.QtCore import QEvent, QRectF, QTimer, Qt, QUrl
+from PySide6.QtGui import QDesktopServices, QPainter, QPainterPath
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QToolButton, QVBoxLayout, QWidget
+from shiboken6 import isValid
+
+from ..i18n import tr
+from .halftone import draw_tone
+from .theme import apply_card_shadow, set_themed_icon, set_themed_pixmap, theme_changed, ui_font
from .motion import fade_in
@@ -21,35 +25,74 @@ def __init__(self, parent, *, idle_timeout_ms=STAR_PROMPT_IDLE_MS):
self.setAccessibleName(tr('支持 ComiTrans 仓库'))
self.setAttribute(Qt.WA_StyledBackground, True)
self.setFocusPolicy(Qt.NoFocus)
+
layout = QVBoxLayout(self)
- layout.setContentsMargins(18, 14, 14, 16)
+ layout.setContentsMargins(16, 14, 14, 14)
layout.setSpacing(10)
+
heading = QHBoxLayout()
- title = QLabel(tr('☆ 喜欢这次翻译?'))
+ heading.setSpacing(10)
+ badge = QFrame()
+ badge.setObjectName('starBadge')
+ badge.setFixedSize(30, 30)
+ badge_layout = QHBoxLayout(badge)
+ badge_layout.setContentsMargins(0, 0, 0, 0)
+ badge_icon = QLabel()
+ badge_icon.setAlignment(Qt.AlignCenter)
+ set_themed_pixmap(badge_icon, 'star', size=16)
+ badge_layout.addWidget(badge_icon)
+ heading.addWidget(badge, 0, Qt.AlignTop)
+
+ title_col = QVBoxLayout()
+ title_col.setSpacing(3)
+ title = QLabel(tr('喜欢这次翻译?'))
title.setObjectName('starPromptTitle')
- heading.addWidget(title, 1)
+ title_col.addWidget(title)
+ repo_tag = QLabel('GitHub · ComiTrans')
+ repo_tag.setObjectName('starRepoTag')
+ repo_tag.setFont(ui_font(11, mono=True))
+ repo_tag.setFixedHeight(20)
+ title_col.addWidget(repo_tag, 0, Qt.AlignLeft)
+ heading.addLayout(title_col, 1)
+
self.close_button = QToolButton()
- self.close_button.setText('×')
+ self.close_button.setObjectName('starCloseBtn')
self.close_button.setAccessibleName(tr('关闭求 Star 提示'))
self.close_button.setToolTip(tr('关闭'))
self.close_button.setProperty('role', 'quiet')
+ self.close_button.setFixedSize(26, 26)
+ self.close_button.setCursor(Qt.PointingHandCursor)
+ set_themed_icon(self.close_button, 'close', size=14)
self.close_button.clicked.connect(self.dismiss)
- heading.addWidget(self.close_button)
+ heading.addWidget(self.close_button, 0, Qt.AlignTop)
layout.addLayout(heading)
+
body = QLabel(tr('如果 ComiTrans 帮到了你,欢迎给仓库点个 Star,支持后续更新。'))
body.setWordWrap(True)
layout.addWidget(body)
+
+ divider = QFrame()
+ divider.setObjectName('hairlineRule')
+ layout.addWidget(divider)
+
actions = QHBoxLayout()
+ actions.setSpacing(8)
self.star_button = QPushButton(tr('去 GitHub 点 Star ↗'))
self.star_button.setProperty('role', 'primary')
+ self.star_button.setCursor(Qt.PointingHandCursor)
self.star_button.setAccessibleName(tr('打开 ComiTrans GitHub 仓库'))
self.star_button.clicked.connect(self._open_repository)
actions.addWidget(self.star_button)
actions.addStretch(1)
- layout.addLayout(actions)
hint = QLabel(tr('8 秒无操作后自动收起'))
hint.setProperty('muted', True)
- layout.addWidget(hint)
+ hint.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
+ actions.addWidget(hint)
+ layout.addLayout(actions)
+
+ apply_card_shadow(self, blur=20, y_offset=4)
+ theme_changed.changed.connect(self._on_theme_changed)
+
self._idle_timer = QTimer(self)
self._idle_timer.setSingleShot(True)
self._idle_timer.setInterval(idle_timeout_ms)
@@ -59,6 +102,25 @@ def __init__(self, parent, *, idle_timeout_ms=STAR_PROMPT_IDLE_MS):
widget.installEventFilter(self)
self.hide()
+ def _on_theme_changed(self, _mode):
+ if not isValid(self):
+ return
+ apply_card_shadow(self, blur=20, y_offset=4)
+ self.update()
+
+ def paintEvent(self, event):
+ super().paintEvent(event)
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.Antialiasing)
+ clip = QPainterPath()
+ clip.addRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 13, 13)
+ painter.setClipPath(clip)
+ tone_width = min(116.0, self.width() * 0.34)
+ painter.setOpacity(0.16)
+ draw_tone(painter, QRectF(self.width() - tone_width, 0, tone_width, 54),
+ profile='quiet', direction='right')
+ painter.end()
+
def show_prompt(self):
self.reposition()
self.show()
@@ -69,7 +131,7 @@ def show_prompt(self):
def reposition(self):
parent = self.parentWidget()
margin = 16
- self.setFixedWidth(min(344, max(1, parent.width() - 2 * margin)))
+ self.setFixedWidth(min(368, max(1, parent.width() - 2 * margin)))
self.adjustSize()
self.move(max(margin, parent.width() - self.width() - margin),
max(margin, parent.height() - self.height() - margin))
diff --git a/comic_translate_desktop/ui/step_panel.py b/comic_translate_desktop/ui/step_panel.py
index 0c1cede..208b7d7 100644
--- a/comic_translate_desktop/ui/step_panel.py
+++ b/comic_translate_desktop/ui/step_panel.py
@@ -25,13 +25,13 @@
}
STAGE_COMPACT_LABELS = dict(zip(STAGE_ORDER, ('读取', '检测', '识别', '翻译', '修复', '排版', '保存')))
STAGE_DESCRIPTIONS = {
- "start": "读取原始图片或按页渲染原分辨率 PDF 页图",
+ "start": "读取图片,或按页准备 PDF、CBZ 的原分辨率页图",
"detect": "检测漫画气泡与文字框范围",
"ocr": "识别框内原文并测量字号与排向",
"translate": "按阅读顺序调用翻译模型,结合前文上下文并缓存译文",
"inpaint": "与翻译并行在独立线程生成擦字掩膜并修补背景",
"typeset": "翻译与修补汇合后,校对空译文并完成横竖排嵌字",
- "save": "写入译图、清理底图与布局文件,全部完成后合成译文 PDF",
+ "save": "写入译图、底图和布局,全部完成后生成译文 PDF 或 CBZ",
}
PENDING = 0
@@ -321,11 +321,13 @@ def consume_workflow_event(self, event: dict) -> None:
if state == 'running':
self._publishing_pdf = {
'name': event.get('document_name', ''),
+ 'format': event.get('output_format') or 'PDF',
'state': 'running',
}
elif state == 'failed':
self._publishing_pdf = {
'name': event.get('document_name', ''),
+ 'format': event.get('output_format') or 'PDF',
'state': 'failed',
}
self._task_phase = 'failed'
@@ -468,15 +470,13 @@ def _compute_stage_views(self) -> dict[str, _StageView]:
detail_line = tr(STAGE_DESCRIPTIONS[stage])
if stage == "save" and self._publishing_pdf:
+ badge = self._publishing_pdf['format']
+ sublabel = tr('CBZ 打包') if badge == 'CBZ' else tr('PDF 合成')
if self._publishing_pdf.get('state') == 'failed':
state = FAILED
- badge = "PDF"
- sublabel = tr('PDF 合成')
else:
state = RUNNING
- badge = "PDF"
- sublabel = tr('PDF 合成')
- detail_line = tr('正在合成译文 PDF · {_0}', _0=self._publishing_pdf.get('name', ''))
+ detail_line = self._publish_status()
elif failed:
pid = failed[0]
state = FAILED
@@ -654,6 +654,12 @@ def _compute_dag_geometry(self, bounds: QRectF) -> tuple[dict[str, QRectF], QPoi
join_pt = QPointF(rects["typeset"].left() - fork_gap * 0.34, cy)
return rects, fork_pt, join_pt
+ def _publish_status(self):
+ name = self._publishing_pdf['name']
+ if self._publishing_pdf['format'] == 'CBZ':
+ return tr('正在打包译文 CBZ · {_0}', _0=name)
+ return tr('正在合成译文 PDF · {_0}', _0=name)
+
def _header_texts(self, views: dict[str, _StageView]) -> tuple[str, list[str]]:
work_ids = self._work_page_ids()
total_pages = len(self._page_order)
@@ -661,7 +667,7 @@ def _header_texts(self, views: dict[str, _StageView]) -> tuple[str, list[str]]:
resumed = self._resumed_count()
if self._publishing_pdf and self._publishing_pdf.get('state') == 'running':
- headline = tr('正在合成译文 PDF · {_0}', _0=self._publishing_pdf.get('name', ''))
+ headline = self._publish_status()
elif self._task_phase == 'failed' or any(v.state == FAILED for v in views.values()):
headline = tr('流程中断 · 请查看报错日志')
elif self._task_phase == 'cancelled':
diff --git a/comic_translate_desktop/ui/strip_preview.py b/comic_translate_desktop/ui/strip_preview.py
index 8ce6318..438e6a8 100644
--- a/comic_translate_desktop/ui/strip_preview.py
+++ b/comic_translate_desktop/ui/strip_preview.py
@@ -104,6 +104,8 @@ def _mount(self, key):
label.region_edited.connect(self.region_edited)
label.region_edit_finished.connect(self.region_edit_finished)
label.region_clicked.connect(self.region_clicked)
+ label.regions_selected.connect(self.regions_selected)
+ label.region_context_menu.connect(self.region_context_menu)
label.bubble_created.connect(self.bubble_created)
label.setToolTip(Path(key).name)
self._pages[key][0] = label
@@ -184,6 +186,7 @@ def _apply_regions(self):
regions, visible = getattr(self, '_regions', ([], True))
if self._label is not None:
self._label.set_regions(regions, visible)
+ self._label.selected_indices = getattr(self, '_selected_regions', set())
def set_image(self, path):
self.activate_page(path)
@@ -211,6 +214,18 @@ def reveal_active(self):
if self._active_path:
self.reveal_page(self._active_path)
+ def reveal_region(self, box):
+ self.reveal_active()
+ rect = self._label._box_rect(box)
+ if rect.isEmpty():
+ return
+ scroll = self._strip_scroll if self._continuous else self._scroll
+ viewport = scroll.viewport()
+ center = self._label.mapTo(viewport, rect.center().toPoint())
+ horizontal, vertical = scroll.horizontalScrollBar(), scroll.verticalScrollBar()
+ horizontal.setValue(horizontal.value() + center.x() - viewport.width() // 2)
+ vertical.setValue(vertical.value() + center.y() - viewport.height() // 2)
+
def reveal_page(self, key):
if not self._continuous or key not in self._indices:
return
diff --git a/comic_translate_desktop/ui/text_editor_dialog.py b/comic_translate_desktop/ui/text_editor_dialog.py
index 0a8b761..f45ab41 100644
--- a/comic_translate_desktop/ui/text_editor_dialog.py
+++ b/comic_translate_desktop/ui/text_editor_dialog.py
@@ -27,7 +27,7 @@ def __init__(self, parent=None):
self._title.setObjectName('sectionTitle')
header.addWidget(self._title, 1)
self._stats = QLabel()
- self._stats.setProperty('muted', True)
+ self._stats.setObjectName('badgePill')
self._stats.setFont(ui_font(12, mono=True))
header.addWidget(self._stats)
layout.addLayout(header)
@@ -79,7 +79,7 @@ def __init__(self, parent=None):
hint.setWordWrap(True)
footer.addWidget(hint, 1)
close_btn = QPushButton(tr('关闭'))
- close_btn.setProperty('role', 'chip')
+ close_btn.setProperty('role', 'utility')
close_btn.clicked.connect(self.close)
footer.addWidget(close_btn)
layout.addLayout(footer)
diff --git a/comic_translate_desktop/ui/theme.py b/comic_translate_desktop/ui/theme.py
index c4cd151..a47b427 100644
--- a/comic_translate_desktop/ui/theme.py
+++ b/comic_translate_desktop/ui/theme.py
@@ -4,6 +4,7 @@
from weakref import ref as weakref
from PySide6.QtCore import QObject, QSize, Qt, Signal
from PySide6.QtGui import QColor, QFont, QFontDatabase, QFontInfo, QIcon, QPalette
+from PySide6.QtWidgets import QGraphicsDropShadowEffect
from shiboken6 import isValid
from ..config import AI_ROOT, ICON_PATH
from ..i18n import ui_language
@@ -232,6 +233,13 @@ def set_themed_icon(button, name, size=14):
_icon_buttons.append(weakref(button))
+def set_themed_pixmap(label, name, size=16):
+ label.setProperty('themedPixmap', name)
+ label.setProperty('themedPixmapSize', size)
+ label.setPixmap(themed_icon(name, theme_name()).pixmap(size, size))
+ _icon_buttons.append(weakref(label))
+
+
def refresh_themed_icons():
alive = []
for reference in _icon_buttons:
@@ -239,8 +247,12 @@ def refresh_themed_icons():
if widget is None or not isValid(widget):
continue
name = widget.property('themedIcon')
+ pixmap_name = widget.property('themedPixmap')
if name:
widget.setIcon(themed_icon(name, theme_name()))
+ elif pixmap_name:
+ size = int(widget.property('themedPixmapSize') or 16)
+ widget.setPixmap(themed_icon(pixmap_name, theme_name()).pixmap(size, size))
alive.append(reference)
_icon_buttons[:] = alive
@@ -248,8 +260,23 @@ def refresh_themed_icons():
theme_changed.changed.connect(lambda *_: refresh_themed_icons())
+def apply_card_shadow(widget, *, blur=22, y_offset=4):
+ """Apply subtle elevation to floating overlays without altering geometry."""
+ effect = widget.graphicsEffect()
+ if not isinstance(effect, QGraphicsDropShadowEffect):
+ effect = QGraphicsDropShadowEffect(widget)
+ widget.setGraphicsEffect(effect)
+ effect.setBlurRadius(blur)
+ effect.setOffset(0, y_offset)
+ alpha = 120 if theme_name() == 'dark' else 32
+ effect.setColor(QColor(0, 0, 0, alpha))
+ return effect
+
+
APP_STYLESHEET_TEMPLATE = '''
QMainWindow, QWidget#appRoot { background: @workspace; color: @ink; }
+QDialog { background: @workspace; color: @ink; }
+QDialog#paperDialog { background: @paper; color: @ink; }
QWidget { color: @ink; }
QFrame#topBar { background: @paper; border: none; border-bottom: 1px solid @rule; }
QLabel#brandTitle { color: @black; }
@@ -262,6 +289,7 @@ def refresh_themed_icons():
QLabel#cardTitle { font-size: 13px; font-weight: 700; color: @ink; }
QLabel#fontChoiceName { color: @secondary; font-size: 12px; padding: 2px 0 2px 0; }
QFrame#statusPill { background: transparent; border: none; }
+QPushButton#updateIndicator { font-size: 12px; font-weight: 700; min-height: 18px; padding: 2px 9px; border-radius: 8px; }
QFrame#statusPill[active="true"] { background: @muted; border-radius: 10px; }
QLabel#statusText { font-size: 12px; color: @secondary; background: transparent; }
QLabel#statusText[state="running"], QLabel#statusText[state="warming"],
@@ -300,16 +328,43 @@ def refresh_themed_icons():
QToolButton#blockNavBtn:disabled, QPushButton#zoomStepBtn:disabled { border: 1px solid @rule; background: transparent; }
QPushButton[role="retry"] { border: 1px solid @ruleStrong; border-radius: 10px; padding: 6px 16px; background: @paper; }
QPushButton[role="retry"]:hover { background: @muted; }
+QPushButton[role="danger"] { border: 1px solid @rule; background: @paper; color: @ink; padding: 5px 12px; border-radius: 8px; }
+QPushButton[role="danger"]:hover { background: @muted; border-color: @ink; }
+QPushButton[role="danger"]:focus { border: 1.5px solid @focusRing; }
QPushButton[role="quiet"]:hover, QToolButton[role="quiet"]:hover { background: @muted; }
QPushButton[role="quiet"]:focus, QToolButton[role="quiet"]:focus { border-color: @ruleStrong; }
QPushButton[role="nav"]:focus { border-bottom-color: @ink; }
QPushButton[compact="true"], QToolButton[compact="true"] { min-height: 22px; padding: 3px 9px; }
+QToolButton[menuButton="true"] { padding-right: 22px; }
+QToolButton[menuButton="true"]::menu-indicator { subcontrol-origin: padding; subcontrol-position: center right; right: 6px; width: 12px; height: 12px; image: url("@icons/chevron-down.svg"); }
QPushButton:disabled, QToolButton:disabled { background: transparent; color: @disabled; border-color: transparent; }
QPushButton[role="primary"]:disabled { background: @muted; color: @disabled; border-color: transparent; }
QGroupBox { margin-top: 24px; padding: 16px 0 0 0; border: none; background: transparent; font-weight: 700; }
QGroupBox::title { subcontrol-origin: margin; subcontrol-position: top left; padding: 0 12px 0 0; background: transparent; }
+QGroupBox[card="true"] { background: @paper; border: 1px solid @rule; border-radius: 12px; margin-top: 0px; padding: 44px 20px 18px 20px; font-size: 14px; font-weight: 700; }
+QGroupBox[card="true"]::title { subcontrol-origin: padding; subcontrol-position: top left; left: 20px; top: 15px; padding: 0px; background: transparent; color: @ink; }
QFrame#queuePanel, QFrame#workPanel, QFrame#editorPanel { background: @paper; }
QFrame#pageBody, QFrame#editorToolbar, QFrame#canvasPanel { background: @paper; }
+QFrame#settingsBody, QWidget#settingsScrollContent, QWidget#dialogScrollContent { background: @workspace; }
+QScrollArea#settingsScroll, QScrollArea#dialogScroll { background: @workspace; border: none; }
+QFrame#settingsHeader, QFrame#dialogHeader { background: @paper; border: none; border-bottom: 1px solid @rule; }
+QFrame#settingsCard, QFrame#dialogCard { background: @paper; border: 1px solid @rule; border-radius: 12px; }
+QFrame#langCard { background: @paper; border: 1px solid @rule; border-radius: 10px; }
+QFrame#langCard:hover { background: @muted; border-color: @ruleStrong; }
+QFrame#langCard[selected="true"] { background: @muted; border: 1.5px solid @ink; }
+QRadioButton#langRadio { background: transparent; border: none; spacing: 10px; font-weight: 700; padding: 0px; }
+QRadioButton#langRadio::indicator { width: 15px; height: 15px; border-radius: 9px; border: 1.5px solid @ruleStrong; background: @paper; }
+QRadioButton#langRadio::indicator:hover { border-color: @ink; }
+QRadioButton#langRadio::indicator:checked { width: 8px; height: 8px; border-radius: 9px; border: 5px solid @ink; background: @paper; }
+QLabel#badgePill { background: @muted; border: 1px solid @rule; border-radius: 6px; padding: 2px 8px; color: @secondary; font-size: 11px; font-weight: 600; }
+QLabel#stepBadge { background: @muted; border: 1px solid @rule; border-radius: 6px; color: @ink; font-size: 11px; font-weight: 700; }
+QLabel#statusCallout { background: @workspace; border: 1px solid @rule; border-radius: 8px; padding: 8px 12px; color: @secondary; font-size: 12px; }
+QFrame#hairlineRule { background: @rule; border: none; max-height: 1px; min-height: 1px; }
+QFrame#fontPreviewFrame { background: @paper; border: 1px solid @rule; border-radius: 10px; }
+QListWidget#catalogList { background: @paper; border: 1px solid @rule; border-radius: 10px; padding: 4px; }
+QListWidget#catalogList::item { border-radius: 6px; padding: 8px 10px; border: none; border-left: 3px solid transparent; }
+QListWidget#catalogList::item:selected { background: @muted; color: @ink; border-left: 3px solid @ink; }
+QListWidget#catalogList::item:hover:!selected { background: @workspace; }
QFrame#editorToolbar { border-bottom: 1px solid @rule; }
QFrame#favoriteFontsBar, QFrame#canvasToolBar { background: @workspace; border: 1px solid @rule; border-radius: 10px; }
QFrame#toolbarDivider { background: @rule; border: none; }
@@ -325,10 +380,16 @@ def refresh_themed_icons():
QLabel#editorStatus { background: @workspace; border: 1px solid @rule; border-radius: 8px; padding: 5px 12px; color: @secondary; font-size: 12px; }
QFrame#queuePanel { background: @workspace; border: none; }
QFrame#controlCard { background: @paper; border: none; }
-QFrame#starPrompt { background: @elevated; border: 1px solid @rule; border-radius: 14px; }
+QScrollArea#prefContainer { background: @paper; border: none; border-top: 1px solid @rule; }
+QWidget#prefContent { background: @paper; }
+QFrame#starPrompt { background: @elevated; border: 1.5px solid @ruleStrong; border-radius: 14px; }
QFrame#starPrompt QLabel { background: transparent; border: none; }
-QLabel#starPromptTitle { font-weight: 700; font-size: 15px; }
-QFrame#starPrompt QToolButton { padding: 0; min-width: 24px; min-height: 24px; font-size: 20px; }
+QFrame#starBadge { background: @muted; border: 1px solid @rule; border-radius: 8px; }
+QLabel#starPromptTitle { font-weight: 700; font-size: 14px; color: @ink; }
+QLabel#starRepoTag { background: @muted; border: 1px solid @rule; border-radius: 5px; padding: 1px 6px; font-size: 11px; color: @secondary; }
+QFrame#starPrompt QToolButton#starCloseBtn { padding: 0; min-width: 24px; min-height: 24px; border-radius: 6px; border: 1px solid transparent; }
+QFrame#starPrompt QToolButton#starCloseBtn:hover { background: @muted; border-color: @rule; }
+QFrame#starPrompt QPushButton[role="primary"] { border-radius: 10px; padding: 6px 14px; min-height: 28px; }
QFrame#logPanel { background: @paper; border-top: 1px solid @rule; }
QTabWidget::pane { border: none; background: transparent; }
QTabBar::tab { padding: 7px 14px; min-height: 24px; border: none; border-bottom: 2px solid transparent; background: transparent; color: @secondary; font-weight: 500; }
@@ -351,13 +412,30 @@ def refresh_themed_icons():
QComboBox QAbstractItemView::item, QCompleter QAbstractItemView::item { min-height: 28px; padding: 4px 10px; border-radius: 6px; color: @ink; background: transparent; }
QComboBox QAbstractItemView::item:hover, QCompleter QAbstractItemView::item:hover { background: @muted; color: @ink; }
QComboBox QAbstractItemView::item:selected, QCompleter QAbstractItemView::item:selected { background: @ink; color: @paper; }
-QFrame#inspectorCard QSpinBox, QFrame#inspectorCard QDoubleSpinBox { min-height: 18px; padding: 2px 7px; border: 1px solid @rule; border-bottom: 1px solid @ruleStrong; background: @workspace; }
-QFrame#inspectorCard QSpinBox:focus, QFrame#inspectorCard QDoubleSpinBox:focus { border: 1px solid @focusRing; background: @paper; }
+QFrame#inspectorCard QSpinBox, QFrame#inspectorCard QDoubleSpinBox,
+QFrame#settingsCard QLineEdit, QFrame#settingsCard QSpinBox, QFrame#settingsCard QDoubleSpinBox,
+QFrame#dialogCard QLineEdit, QFrame#dialogCard QSpinBox, QFrame#dialogCard QDoubleSpinBox,
+QGroupBox[card="true"] QLineEdit, QGroupBox[card="true"] QSpinBox, QGroupBox[card="true"] QDoubleSpinBox { min-height: 22px; padding: 4px 9px; border: 1px solid @rule; border-bottom: 1px solid @ruleStrong; background: @workspace; }
+QFrame#settingsCard QComboBox, QFrame#dialogCard QComboBox, QGroupBox[card="true"] QComboBox { min-height: 22px; padding: 4px 6px 4px 9px; border: 1px solid @rule; border-radius: 8px; background: @workspace; }
+QFrame#settingsCard QComboBox:hover, QFrame#dialogCard QComboBox:hover, QGroupBox[card="true"] QComboBox:hover { border-color: @ruleStrong; background: @paper; }
+QFrame#settingsCard QComboBox:focus, QFrame#settingsCard QComboBox:on,
+QFrame#dialogCard QComboBox:focus, QFrame#dialogCard QComboBox:on,
+QGroupBox[card="true"] QComboBox:focus, QGroupBox[card="true"] QComboBox:on { border: 1.5px solid @ink; background: @paper; }
+QFrame#inspectorCard QSpinBox, QFrame#inspectorCard QDoubleSpinBox { min-height: 18px; padding: 2px 7px; }
+QFrame#inspectorCard QSpinBox:focus, QFrame#inspectorCard QDoubleSpinBox:focus,
+QFrame#settingsCard QLineEdit:focus, QFrame#settingsCard QSpinBox:focus, QFrame#settingsCard QDoubleSpinBox:focus,
+QFrame#dialogCard QLineEdit:focus, QFrame#dialogCard QSpinBox:focus, QFrame#dialogCard QDoubleSpinBox:focus,
+QGroupBox[card="true"] QLineEdit:focus, QGroupBox[card="true"] QSpinBox:focus, QGroupBox[card="true"] QDoubleSpinBox:focus { border: 1px solid @focusRing; background: @paper; }
+QFrame#editorInspector QSpinBox#quickSizeSpin { min-height: 20px; padding: 1px 6px; border: 1px solid @rule; border-bottom: 1px solid @ruleStrong; background: @workspace; }
+QFrame#editorInspector QSpinBox#quickSizeSpin:focus { border: 1px solid @focusRing; background: @paper; }
QFrame#inspectorCard QComboBox { min-height: 22px; padding: 3px 4px 3px 8px; border: 1px solid @rule; border-radius: 7px; background: @workspace; }
QFrame#inspectorCard QComboBox:hover { border-color: @ruleStrong; background: @paper; }
QFrame#inspectorCard QComboBox:focus, QFrame#inspectorCard QComboBox:on { border: 1.5px solid @ink; background: @paper; }
QPlainTextEdit[readOnly="true"] { border: none; background: transparent; }
QPlainTextEdit[readOnly="true"]:focus { border: none; background: transparent; }
+QPlainTextEdit#logSurface, QPlainTextEdit#logSurface:focus { background: @paper; border: 1px solid @rule; border-radius: 10px; padding: 10px 12px; }
+QPlainTextEdit#logInput { background: @paper; border: 1px solid @rule; border-radius: 10px; padding: 8px 10px; }
+QPlainTextEdit#logInput:focus { border: 1.5px solid @focusRing; background: @paper; }
QPlainTextEdit#logContent, QPlainTextEdit#logContent:focus { border: none; background: @paper; padding: 8px 10px; }
QPlainTextEdit#prefInput { background: @workspace; border: 1px solid @rule; border-radius: 8px; padding: 6px 8px; }
QPlainTextEdit#prefInput:focus { border-color: @ruleStrong; background: @paper; }
@@ -365,7 +443,11 @@ def refresh_themed_icons():
QPlainTextEdit#textInput:focus { border: 1.5px solid @focusRing; background: @paper; }
QPlainTextEdit#textSource { background: @paper; border: 1px solid @rule; border-radius: 8px; padding: 7px 10px; font-size: 14px; }
QLineEdit:disabled, QSpinBox:disabled, QDoubleSpinBox:disabled, QPlainTextEdit:disabled { background: @workspace; color: @disabled; border-color: transparent; }
-QFrame#inspectorCard QComboBox:disabled, QFrame#inspectorCard QSpinBox:disabled, QFrame#inspectorCard QDoubleSpinBox:disabled { background: @workspace; color: @disabled; border-color: @rule; }
+QFrame#inspectorCard QComboBox:disabled, QFrame#inspectorCard QSpinBox:disabled, QFrame#inspectorCard QDoubleSpinBox:disabled,
+QFrame#settingsCard QLineEdit:disabled, QFrame#settingsCard QComboBox:disabled, QFrame#settingsCard QSpinBox:disabled,
+QFrame#dialogCard QLineEdit:disabled, QFrame#dialogCard QComboBox:disabled, QFrame#dialogCard QSpinBox:disabled,
+QGroupBox[card="true"] QLineEdit:disabled, QGroupBox[card="true"] QComboBox:disabled, QGroupBox[card="true"] QSpinBox:disabled { background: @workspace; color: @disabled; border-color: @rule; }
+QFrame#editorInspector QSpinBox#quickSizeSpin:disabled { background: @workspace; color: @disabled; border-color: @rule; }
QFrame#controlCard QLineEdit { min-height: 28px; padding: 4px 10px; border-color: transparent; font-size: 13px; }
QFrame#controlCard QLineEdit:focus { border-color: @ruleStrong; }
QFrame#controlCard QComboBox { min-height: 28px; padding: 4px 6px 4px 10px; border: 1px solid @rule; border-radius: 8px; background: @workspace; font-size: 13px; }
@@ -384,6 +466,9 @@ def refresh_themed_icons():
QSpinBox::up-arrow, QDoubleSpinBox::up-arrow { image: url("@icons/chevron-up.svg"); width: 12px; height: 12px; }
QSpinBox::down-arrow, QDoubleSpinBox::down-arrow { image: url("@icons/chevron-down.svg"); width: 12px; height: 12px; }
QListWidget, QTreeView { padding: 0; border: none; background: transparent; }
+QTableView#transcriptTable { border: 1px solid @rule; border-radius: 8px; background: @paper; color: @ink; gridline-color: @rule; selection-background-color: @muted; selection-color: @ink; }
+QTableView#transcriptTable::item { padding: 6px; }
+QTableView#transcriptTable QHeaderView::section { padding: 6px; border: none; border-bottom: 1px solid @rule; background: @workspace; color: @ink; }
QListWidget::item { padding: 8px 6px; border: none; border-left: 2px solid transparent; }
QListWidget::item:selected { background: @muted; color: @ink; border-left: 2px solid @ink; }
QListWidget::item:hover:!selected { background: @workspace; }
@@ -417,9 +502,22 @@ def refresh_themed_icons():
QCheckBox::indicator:checked { background: @ink; image: url("@icons/check.svg"); }
QCheckBox:focus { color: @black; }
QToolTip { padding: 6px 8px; border: 1px solid @rule; border-radius: 6px; background: @elevated; color: @ink; }
-QMenu { background: @elevated; border: 1px solid @rule; padding: 4px; }
-QMenu::item { padding: 8px 20px; }
+QMenu { background: @elevated; border: 1px solid @ruleStrong; border-radius: 10px; padding: 4px; }
+QMenu::item { padding: 6px 26px 6px 14px; border-radius: 6px; color: @ink; }
QMenu::item:selected { background: @ink; color: @paper; }
+QMessageBox, QProgressDialog { background: @paper; color: @ink; }
+QMessageBox QLabel, QProgressDialog QLabel { color: @ink; background: transparent; }
+QMessageBox QPushButton, QProgressDialog QPushButton, QDialogButtonBox QPushButton { min-height: 26px; padding: 5px 14px; border: 1px solid @rule; border-radius: 8px; background: @paper; color: @ink; }
+QMessageBox QPushButton:hover, QProgressDialog QPushButton:hover, QDialogButtonBox QPushButton:hover { background: @muted; border-color: @ruleStrong; }
+QMessageBox QPushButton:default, QDialogButtonBox QPushButton:default { background: @ink; color: @paper; border: 1px solid @ink; border-radius: 10px; font-weight: 700; }
+QMessageBox QPushButton:default:hover, QDialogButtonBox QPushButton:default:hover { background: @black; }
+QProgressBar { background: @muted; border: 1px solid @rule; border-radius: 4px; min-height: 8px; max-height: 8px; text-align: center; color: transparent; }
+QProgressBar::chunk { background: @ink; border-radius: 3px; }
+QMenu::item:disabled { color: @disabled; background: transparent; }
+QMenu::separator { height: 1px; background: @rule; margin: 4px 8px; }
+QMenu::indicator { width: 14px; height: 14px; margin-left: 6px; }
+QMenu::indicator:checked { background: @ink; border-radius: 3px; image: url("@icons/check.svg"); }
+QMenu::indicator:unchecked { border: 1px solid @ruleStrong; border-radius: 3px; background: @paper; }
'''
APP_STYLESHEET = build_stylesheet(PALETTES['light'])
diff --git a/comic_translate_desktop/ui/tool_flow.py b/comic_translate_desktop/ui/tool_flow.py
index 967f116..654f02d 100644
--- a/comic_translate_desktop/ui/tool_flow.py
+++ b/comic_translate_desktop/ui/tool_flow.py
@@ -53,6 +53,8 @@ def _item_size(self, item):
if widget is not None and hasattr(widget, 'text') and not widget.property('toolDivider'):
# Some styles reserve less than the compact button's text padding.
width = widget.fontMetrics().horizontalAdvance(widget.text()) + 20
+ if widget.property('menuButton'):
+ width += 14
if hasattr(widget, 'icon') and not widget.icon().isNull():
width += widget.iconSize().width() + 4
size.setWidth(max(size.width(), width))
diff --git a/comic_translate_desktop/ui/transcript_dialog.py b/comic_translate_desktop/ui/transcript_dialog.py
new file mode 100644
index 0000000..c053bda
--- /dev/null
+++ b/comic_translate_desktop/ui/transcript_dialog.py
@@ -0,0 +1,175 @@
+"""Search a book's saved and current dialogue, with a reviewable replacement."""
+from html import escape
+import re
+
+from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
+from PySide6.QtWidgets import (
+ QAbstractItemView, QDialog, QHeaderView, QHBoxLayout, QLabel, QLineEdit,
+ QPushButton, QTableView, QVBoxLayout,
+)
+
+from ..editor_jobs import LatestJobQueue
+from ..i18n import tr
+from .window_chrome import apply_window_chrome
+
+
+class TranscriptModel(QAbstractTableModel):
+ def __init__(self, parent):
+ super().__init__(parent)
+ self.rows = []
+ self.preview = False
+
+ def rowCount(self, parent=QModelIndex()):
+ return 0 if parent.isValid() else len(self.rows)
+
+ def columnCount(self, parent=QModelIndex()):
+ return 0 if parent.isValid() else 4 if self.preview else 3
+
+ def headerData(self, section, orientation, role=Qt.DisplayRole):
+ if role == Qt.DisplayRole and orientation == Qt.Horizontal:
+ return (tr('页码与气泡'), tr('原文'), tr('译文'), tr('替换后'))[section]
+ return None
+
+ def data(self, index, role=Qt.DisplayRole):
+ if not index.isValid() or role not in (Qt.DisplayRole, Qt.ToolTipRole):
+ return None
+ entry, replacement = self.rows[index.row()]
+ values = (f'{entry.label} · #{entry.index + 1}', entry.source, entry.translation, replacement)
+ text = values[index.column()]
+ if role == Qt.ToolTipRole and text:
+ return '' + escape(text).replace('\n', '
') + ''
+ return text
+
+ def set_rows(self, rows, *, preview=False):
+ self.beginResetModel()
+ self.rows, self.preview = rows, preview
+ self.endResetModel()
+
+
+class TranscriptDialog(QDialog):
+ def __init__(self, index_book, apply_replacements, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('全书译稿'))
+ self.resize(760, 500)
+ self._index_book = index_book
+ self._apply_replacements = apply_replacements
+ self._jobs = LatestJobQueue(self)
+ self._entries = []
+ self._skipped = 0
+ self._busy = False
+ self.selection = None
+
+ root = QVBoxLayout(self)
+ inputs = QHBoxLayout()
+ self.search = QLineEdit()
+ self.search.setPlaceholderText(tr('搜索原文或译文'))
+ self.search.setAccessibleName(tr('搜索原文或译文'))
+ self.replace = QLineEdit()
+ self.replace.setPlaceholderText(tr('替换为(留空即删除)'))
+ self.replace.setAccessibleName(tr('替换为(留空即删除)'))
+ self.preview_button = QPushButton(tr('预览替换'))
+ self.preview_button.clicked.connect(self._preview)
+ for widget in (self.search, self.replace, self.preview_button):
+ inputs.addWidget(widget)
+ root.addLayout(inputs)
+
+ self.model = TranscriptModel(self)
+ self.table = QTableView()
+ self.table.setObjectName('transcriptTable')
+ self.table.setModel(self.model)
+ self.table.setWordWrap(True)
+ self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
+ self.table.setSelectionMode(QAbstractItemView.SingleSelection)
+ self.table.verticalHeader().hide()
+ self.table.verticalHeader().setDefaultSectionSize(3 * self.table.fontMetrics().lineSpacing() + 10)
+ self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
+ self.table.doubleClicked.connect(self._jump)
+ self.table.selectionModel().selectionChanged.connect(self._refresh_actions)
+ root.addWidget(self.table, 1)
+
+ footer = QHBoxLayout()
+ self.status = QLabel()
+ self.status.setTextFormat(Qt.PlainText)
+ self.status.setWordWrap(True)
+ footer.addWidget(self.status, 1)
+ self.jump_button = QPushButton(tr('定位气泡'))
+ self.jump_button.clicked.connect(lambda: self._jump(self.table.currentIndex()))
+ self.apply_button = QPushButton(tr('替换并保存'))
+ self.apply_button.clicked.connect(self._apply)
+ self.close_button = QPushButton(tr('关闭'))
+ self.close_button.clicked.connect(self.reject)
+ for button in (self.jump_button, self.apply_button, self.close_button):
+ button.setAutoDefault(False)
+ footer.addWidget(button)
+ root.addLayout(footer)
+ self.search.textChanged.connect(self._filter)
+ self.replace.textChanged.connect(self._filter)
+ self._reload()
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+
+ def done(self, result):
+ if not self._busy:
+ self._jobs.close()
+ super().done(result)
+
+ def _reload(self, notice=''):
+ self._set_busy(True)
+ self.status.setText(tr('正在读取全书译稿…'))
+ def loaded(entries):
+ self._entries, self._skipped = entries
+ self._set_busy(False)
+ self._filter()
+ if notice:
+ self.status.setText(notice)
+ def failed(message):
+ loaded(([], 0))
+ self.status.setText(message)
+ self._index_book(self._jobs, loaded, failed)
+
+ def _set_busy(self, busy):
+ self._busy = busy
+ for widget in (self.search, self.replace, self.table, self.close_button):
+ widget.setEnabled(not busy)
+ self._refresh_actions()
+
+ def _refresh_actions(self):
+ self.jump_button.setEnabled(not self._busy and self.table.currentIndex().isValid())
+ self.preview_button.setEnabled(not self._busy and bool(self.search.text().strip()))
+ self.apply_button.setEnabled(not self._busy and self.model.preview and bool(self.model.rows))
+
+ def _filter(self):
+ query = self.search.text().strip().casefold()
+ rows = [(entry, None) for entry in self._entries
+ if query in entry.source.casefold() or query in entry.translation.casefold()]
+ self.model.set_rows(rows)
+ message = tr('显示 {_0} 个气泡', _0=len(rows))
+ if self._skipped:
+ message += ' · ' + tr('{_0} 页缺少可读译稿', _0=self._skipped)
+ self.status.setText(message)
+ self._refresh_actions()
+
+ def _preview(self):
+ query, replacement = self.search.text().strip(), self.replace.text()
+ if not query:
+ return
+ pattern = re.compile(re.escape(query), re.IGNORECASE)
+ rows = [(entry, after) for entry in self._entries if not entry.restored
+ and (after := pattern.sub(lambda _: replacement, entry.translation)) != entry.translation]
+ self.model.set_rows(rows, preview=True)
+ self.status.setText(tr('将修改 {_0} 个气泡(仅匹配译文)', _0=len(rows)))
+ self._refresh_actions()
+
+ def _jump(self, index):
+ if index.isValid() and not self._busy:
+ self.selection = self.model.rows[index.row()][0]
+ self.accept()
+
+ def _apply(self):
+ rows = list(self.model.rows)
+ self._set_busy(True)
+ self._apply_replacements(
+ rows, self._reload,
+ lambda done, total: self.status.setText(tr('正在保存第 {_0}/{_1} 页…', _0=done, _1=total)))
diff --git a/comic_translate_desktop/ui/update_notice.py b/comic_translate_desktop/ui/update_notice.py
new file mode 100644
index 0000000..8e3768a
--- /dev/null
+++ b/comic_translate_desktop/ui/update_notice.py
@@ -0,0 +1,349 @@
+"""Check once per launch and offer an update after the main window is shown."""
+
+import json
+from pathlib import Path
+from queue import Empty, SimpleQueue
+import sys
+from threading import Event, Thread
+
+from PySide6.QtCore import QIODevice, QObject, QTimer, Qt, QUrl, Signal
+from PySide6.QtGui import QDesktopServices, QFont
+from PySide6.QtNetwork import QLocalSocket, QNetworkAccessManager, QNetworkReply, QNetworkRequest
+from PySide6.QtWidgets import (
+ QDialog, QFrame, QHBoxLayout, QLabel, QMessageBox, QPushButton, QVBoxLayout,
+)
+
+from comic_translate_core.release_update import (
+ RELEASE_API, RESPONSE_LIMIT, installer_name, latest_stable, launch_update, prepare_update,
+)
+from comic_translate_core.windows_install import installed_product, original_package
+from .. import __version__, config
+from ..i18n import tr
+
+from .manga_components import PanelHeading
+from .motion import MonochromeShimmerBar
+from .theme import set_themed_icon, ui_font
+from .window_chrome import apply_window_chrome
+
+SERVICE_PIPE = 'ComiTrans.ReleaseCheck'
+
+
+class UpdateProgressDialog(QDialog):
+ """Themed monochrome indeterminate progress modal for update downloads."""
+
+ canceled = Signal()
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('更新 ComiTrans'))
+ self.setWindowModality(Qt.WindowModality.WindowModal)
+ self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
+ self.setMinimumWidth(400)
+
+ root = QVBoxLayout(self)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(0)
+
+ header = QFrame(self)
+ header.setObjectName('dialogHeader')
+ header_layout = QVBoxLayout(header)
+ header_layout.setContentsMargins(24, 16, 24, 12)
+ header_layout.addWidget(PanelHeading('', '更新 ComiTrans'))
+ root.addWidget(header)
+
+ body = QVBoxLayout()
+ body.setContentsMargins(24, 16, 24, 16)
+ card = QFrame(self)
+ card.setObjectName('dialogCard')
+ card_layout = QVBoxLayout(card)
+ card_layout.setContentsMargins(18, 16, 18, 16)
+ card_layout.setSpacing(10)
+
+ status = QLabel(tr('正在下载并验证更新…'), card)
+ status.setWordWrap(True)
+ card_layout.addWidget(status)
+
+ self.progress = MonochromeShimmerBar(card)
+ self.progress.setAccessibleName(status.text())
+ self.progress.setTextVisible(False)
+ self.progress.setRange(0, 0)
+ self.progress.setFixedHeight(6)
+ card_layout.addWidget(self.progress)
+ body.addWidget(card)
+ root.addLayout(body, 1)
+
+ actions = QFrame(self)
+ actions.setObjectName('pageActions')
+ actions_layout = QHBoxLayout(actions)
+ actions_layout.setContentsMargins(24, 12, 24, 12)
+ actions_layout.addStretch(1)
+
+ cancel_button = QPushButton(tr('取消'), actions)
+ cancel_button.setProperty('role', 'utility')
+ cancel_button.setCursor(Qt.PointingHandCursor)
+ cancel_button.clicked.connect(self.reject)
+ actions_layout.addWidget(cancel_button)
+ root.addWidget(actions)
+
+ self.rejected.connect(self.canceled.emit)
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+
+ def dismiss(self) -> None:
+ self.accept()
+
+
+class UpdateOfferDialog(QDialog):
+ """Non-modal monochrome update prompt matched to the app palette."""
+
+ def __init__(self, current_version: str, update, *, can_install: bool, on_release, on_install, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('发现 ComiTrans 新版本'))
+ self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
+ self.setWindowModality(Qt.WindowModality.NonModal)
+ self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
+ self.setMinimumWidth(440)
+ self.resize(480, 260)
+
+ root = QVBoxLayout(self)
+ root.setContentsMargins(0, 0, 0, 0)
+ root.setSpacing(0)
+
+ header = QFrame()
+ header.setObjectName('dialogHeader')
+ header_layout = QVBoxLayout(header)
+ header_layout.setContentsMargins(24, 18, 24, 14)
+ header_layout.setSpacing(8)
+ top_row = QHBoxLayout()
+ top_row.setSpacing(10)
+ top_row.addWidget(PanelHeading('', '发现 ComiTrans 新版本'), 1)
+ version_pill = QLabel(f'v{current_version} → v{update.version}')
+ version_pill.setObjectName('badgePill')
+ version_pill.setFont(ui_font(12, QFont.Bold, mono=True))
+ top_row.addWidget(version_pill, 0, Qt.AlignVCenter)
+ header_layout.addLayout(top_row)
+ root.addWidget(header)
+
+ body = QVBoxLayout()
+ body.setContentsMargins(24, 16, 24, 16)
+ body.setSpacing(10)
+ card = QFrame()
+ card.setObjectName('dialogCard')
+ card_layout = QVBoxLayout(card)
+ card_layout.setContentsMargins(18, 16, 18, 16)
+ card_layout.setSpacing(8)
+ summary = QLabel(tr('当前版本 v{current},GitHub 已发布 v{latest}。',
+ current=current_version, latest=update.version))
+ summary.setFont(ui_font(14, QFont.Bold))
+ summary.setWordWrap(True)
+ card_layout.addWidget(summary)
+ if can_install:
+ detail = QLabel(tr('下载完成后,ComiTrans 将请求关闭并通过 Windows 安装程序更新。'))
+ detail.setProperty('muted', True)
+ detail.setWordWrap(True)
+ card_layout.addWidget(detail)
+ body.addWidget(card)
+ root.addLayout(body, 1)
+
+ footer = QFrame()
+ footer.setObjectName('pageActions')
+ actions = QHBoxLayout(footer)
+ actions.setContentsMargins(24, 12, 24, 12)
+ actions.setSpacing(8)
+ self.later_button = QPushButton(tr('稍后提醒'))
+ self.later_button.setProperty('role', 'quiet')
+ self.later_button.setCursor(Qt.PointingHandCursor)
+ self.later_button.clicked.connect(self.reject)
+ actions.addWidget(self.later_button)
+ actions.addStretch(1)
+
+ release_action = '查看 GitHub 发布' if can_install else '前往发布页下载安装'
+ self.release_button = QPushButton(tr(release_action))
+ self.release_button.setProperty('role', 'utility' if can_install else 'primary')
+ self.release_button.setCursor(Qt.PointingHandCursor)
+ if can_install:
+ set_themed_icon(self.release_button, 'external-link', size=13)
+ self.release_button.clicked.connect(lambda: (on_release(), self.accept()))
+ actions.addWidget(self.release_button)
+
+ self.install_button = None
+ if can_install:
+ self.install_button = QPushButton(tr('下载并更新'))
+ self.install_button.setProperty('role', 'primary')
+ self.install_button.setDefault(True)
+ self.install_button.setCursor(Qt.PointingHandCursor)
+ self.install_button.clicked.connect(lambda: (on_install(), self.accept()))
+ actions.addWidget(self.install_button)
+ self._initial_focus = self.install_button
+ else:
+ self.release_button.setDefault(True)
+ self._initial_focus = self.release_button
+ root.addWidget(footer)
+
+ def showEvent(self, event):
+ super().showEvent(event)
+ apply_window_chrome(self)
+ self._initial_focus.setFocus()
+
+
+class UpdateNotice(QObject):
+ def __init__(self, window):
+ super().__init__(window)
+ self.window = window
+ self.product = installed_product(Path(sys.executable).parent)
+ self.pipe = QLocalSocket(self)
+ self.pipe_data = bytearray()
+ self.pipe.readyRead.connect(self._read_service)
+ self.pipe.errorOccurred.connect(self._service_error)
+ self.pipe.disconnected.connect(self._service_finished)
+ self.timer = QTimer(self, singleShot=True, interval=5500)
+ self.timer.timeout.connect(self._request_github)
+ self.network = QNetworkAccessManager(self)
+ self.requested_directly = False
+ self.poll = QTimer(self, interval=100)
+ self.poll.timeout.connect(self._download_finished)
+ self.available_update = None
+ self.window.update_button.clicked.connect(self._show_offer)
+ self.notice_dialog = None
+
+ def start(self):
+ if self.product:
+ self.timer.start()
+ self.pipe.connectToServer(SERVICE_PIPE, QIODevice.OpenModeFlag.ReadOnly)
+ else:
+ self._request_github()
+
+ def _read_service(self):
+ self.pipe_data.extend(bytes(self.pipe.readAll()))
+ if len(self.pipe_data) > RESPONSE_LIMIT:
+ self._request_github()
+
+ def _service_finished(self):
+ if self.requested_directly:
+ return
+ self.timer.stop()
+ try:
+ data = json.loads(self.pipe_data)
+ except ValueError:
+ self._request_github()
+ else:
+ if isinstance(data, dict) and isinstance(data.get('tag_name'), str):
+ self._offer(data)
+ else:
+ self._request_github()
+
+ def _service_error(self, error):
+ if error != QLocalSocket.LocalSocketError.PeerClosedError:
+ self._request_github()
+
+ def _request_github(self):
+ if self.requested_directly:
+ return
+ self.requested_directly = True
+ self.timer.stop()
+ self.pipe.abort()
+ request = QNetworkRequest(QUrl(RELEASE_API))
+ request.setHeader(QNetworkRequest.KnownHeaders.UserAgentHeader, f'ComiTrans/{__version__}')
+ request.setRawHeader(b'Accept', b'application/vnd.github+json')
+ request.setTransferTimeout(5000)
+ reply = self.network.get(request)
+ reply.setReadBufferSize(RESPONSE_LIMIT + 1)
+ reply.readyRead.connect(lambda: reply.abort() if reply.bytesAvailable() > RESPONSE_LIMIT else None)
+ reply.finished.connect(lambda: self._github_finished(reply))
+
+ def _github_finished(self, reply):
+ try:
+ if reply.error() != QNetworkReply.NetworkError.NoError:
+ self._check_failed(reply.errorString())
+ return
+ data = json.loads(bytes(reply.readAll()))
+ if isinstance(data, dict) and isinstance(data.get('tag_name'), str):
+ self._offer(data)
+ else:
+ self._check_failed(tr('发布信息格式无效'))
+ except ValueError:
+ self._check_failed(tr('发布信息格式无效'))
+ finally:
+ reply.deleteLater()
+
+ def _check_failed(self, reason):
+ self.window.diagnostics.append(tr('检查更新失败:{reason}', reason=reason), 'WARNING')
+
+ def _offer(self, data):
+ update = latest_stable(data, __version__, setup=bool(self.product and self.product.setup))
+ self.available_update = update
+ button = self.window.update_button
+ button.setVisible(update is not None)
+ if update is not None:
+ detail = tr('新版本 v{version} 可用,点击查看详情', version=update.version)
+ button.setToolTip(detail)
+ button.setAccessibleName(detail)
+
+ def _show_offer(self):
+ update = self.available_update
+ if update is None or self.poll.isActive():
+ return
+ can_install = bool(self.product and update.installer)
+ notice = UpdateOfferDialog(
+ __version__,
+ update,
+ can_install=can_install,
+ on_release=lambda: QDesktopServices.openUrl(QUrl(update.url)),
+ on_install=lambda: self._download(update),
+ parent=self.window,
+ )
+ self.notice_dialog = notice
+ self.window.update_button.setEnabled(False)
+ notice.finished.connect(self._offer_finished)
+ notice.show()
+
+ def _offer_finished(self):
+ self.window.update_button.setEnabled(not self.poll.isActive())
+
+ def _download(self, update):
+ cache = config.PROJECT_ROOT / 'updates'
+ base = cache / installer_name(__version__, setup=update.setup)
+ if not base.is_file():
+ base = original_package(self.product)
+ canceled = Event()
+ result = SimpleQueue()
+
+ def fetch():
+ try:
+ result.put(prepare_update(update, __version__, cache, base, canceled.is_set))
+ except Exception as exc:
+ result.put(exc)
+
+ progress = UpdateProgressDialog(self.window)
+ progress.canceled.connect(canceled.set)
+ self.window.destroyed.connect(canceled.set)
+ self.download = (result, progress, canceled)
+ self.poll.start()
+ progress.show()
+ Thread(target=fetch, daemon=True).start()
+
+ def _download_finished(self):
+ result, progress, canceled = self.download
+ try:
+ outcome = result.get_nowait()
+ except Empty:
+ return
+ self.poll.stop()
+ self.window.update_button.setEnabled(True)
+ progress.dismiss()
+ progress.deleteLater()
+ if canceled.is_set() or not self.window.isVisible():
+ return
+ if isinstance(outcome, Exception):
+ self.window.diagnostics.append(str(outcome), 'WARNING')
+ QMessageBox.warning(self.window, tr('更新 ComiTrans'), tr('更新下载或验证失败。请在 GitHub 发布页重试。'))
+ else:
+ def launch():
+ try:
+ launch_update(outcome)
+ except OSError as exc:
+ self.window.diagnostics.append(str(exc), 'WARNING')
+
+ self.window.close_for_update(launch)
diff --git a/comic_translate_desktop/ui/workflow_dialogs.py b/comic_translate_desktop/ui/workflow_dialogs.py
new file mode 100644
index 0000000..51203db
--- /dev/null
+++ b/comic_translate_desktop/ui/workflow_dialogs.py
@@ -0,0 +1,239 @@
+"""Focused dialogs for work terminology, trial translation and usage."""
+from copy import deepcopy
+import uuid
+
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import (QCheckBox, QComboBox, QDialog, QDialogButtonBox,
+ QDoubleSpinBox, QFormLayout, QHBoxLayout, QHeaderView, QInputDialog, QLabel,
+ QLineEdit, QMessageBox, QPushButton, QSpinBox, QTableWidget, QTableWidgetItem,
+ QVBoxLayout)
+
+from ..i18n import tr
+from ..productivity import terminology_projects, trial_projection, usage_cost
+
+
+class TerminologyDialog(QDialog):
+ def __init__(self, config, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('作品术语库'))
+ self.resize(660, 460)
+ self.projects = deepcopy(terminology_projects(config.get('terminology_projects')))
+ self._current = ''
+ root = QVBoxLayout(self)
+ hint = QLabel(tr('只填写固定译名即可,AI 会根据上下文自动匹配原文。类型和识别线索可帮助区分同名角色;不确定时不会强行套用。'))
+ hint.setWordWrap(True)
+ root.addWidget(hint)
+ row = QHBoxLayout()
+ self.project = QComboBox()
+ self.project.setMinimumContentsLength(12)
+ self.project.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
+ self.project.addItem(tr('不使用术语库'), '')
+ for identity, project in self.projects.items():
+ self.project.addItem(project['name'], identity)
+ row.addWidget(self.project, 1)
+ new = QPushButton(tr('新建作品'))
+ new.clicked.connect(self._new_project)
+ row.addWidget(new)
+ self.remove_project = QPushButton(tr('删除作品'))
+ self.remove_project.clicked.connect(self._remove_project)
+ row.addWidget(self.remove_project)
+ root.addLayout(row)
+ self.name = QLineEdit()
+ self.name.setPlaceholderText(tr('作品名称'))
+ root.addWidget(self.name)
+ self.table = QTableWidget(0, 3)
+ self.table.setHorizontalHeaderLabels([tr('固定译名'), tr('类型(可选)'), tr('识别线索(可选)')])
+ self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
+ self.table.setWordWrap(False)
+ root.addWidget(self.table, 1)
+ row = QHBoxLayout()
+ self.add_term = QPushButton(tr('添加词条'))
+ self.add_term.clicked.connect(lambda: self.table.insertRow(self.table.rowCount()))
+ self.remove_term = QPushButton(tr('删除选中词条'))
+ self.remove_term.clicked.connect(self._remove_terms)
+ row.addWidget(self.add_term)
+ row.addWidget(self.remove_term)
+ row.addStretch(1)
+ root.addLayout(row)
+ buttons = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+ root.addWidget(buttons)
+ self.project.currentIndexChanged.connect(self._switch_project)
+ self.project.setCurrentIndex(max(0, self.project.findData(config.get('terminology_project', ''))))
+ self._switch_project()
+
+ def _store(self):
+ if self._current not in self.projects:
+ return
+ def text(row, col):
+ item = self.table.item(row, col)
+ return item.text().strip() if item else ''
+ previous = self.projects[self._current]['name']
+ self.projects[self._current] = dict(name=self.name.text().strip() or previous, terms=[
+ dict(term=text(row, 0), kind=text(row, 1), note=text(row, 2))
+ for row in range(self.table.rowCount()) if text(row, 0)])
+ index = self.project.findData(self._current)
+ self.project.setItemText(index, self.projects[self._current]['name'])
+
+ def _switch_project(self):
+ self._store()
+ self._current = self.project.currentData() or ''
+ data = self.projects.get(self._current, {})
+ self.name.setText(data.get('name', ''))
+ self.table.setRowCount(0)
+ for entry in data.get('terms', []):
+ row = self.table.rowCount()
+ self.table.insertRow(row)
+ for col, key in enumerate(('term', 'kind', 'note')):
+ self.table.setItem(row, col, QTableWidgetItem(entry[key]))
+ for widget in (self.name, self.table, self.add_term, self.remove_term, self.remove_project):
+ widget.setEnabled(bool(self._current))
+
+ def _new_project(self):
+ name, ok = QInputDialog.getText(self, tr('新建作品'), tr('作品名称'))
+ if not ok or not name.strip():
+ return
+ identity = uuid.uuid4().hex
+ self.projects[identity] = dict(name=name.strip(), terms=[])
+ self.project.addItem(name.strip(), identity)
+ self.project.setCurrentIndex(self.project.count() - 1)
+
+ def _remove_project(self):
+ if not self._current:
+ return
+ if QMessageBox.question(self, tr('删除作品'), tr('删除此作品的术语库?'),
+ QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
+ return
+ self.projects.pop(self._current, None)
+ self.project.removeItem(self.project.currentIndex())
+
+ def _remove_terms(self):
+ for row in sorted({index.row() for index in self.table.selectedIndexes()}, reverse=True):
+ self.table.removeRow(row)
+
+ def accept(self):
+ # A save click can arrive before the active cell editor loses focus.
+ editor = self.table.indexWidget(self.table.currentIndex())
+ if editor is not None:
+ self.table.commitData(editor)
+ super().accept()
+
+ def values(self):
+ self._store()
+ return dict(terminology_projects=terminology_projects(self.projects),
+ terminology_project=self.project.currentData() or '')
+
+
+class TrialDialog(QDialog):
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle(tr('试译'))
+ root = QVBoxLayout(self)
+ hint = QLabel(tr('试译当前队列开头的 1–3 页,PDF 按页面计数。试译结果单独保存,使用独立上下文,不占用正式任务的断点。'))
+ hint.setWordWrap(True)
+ hint.setMinimumWidth(320)
+ root.addWidget(hint)
+ form = QFormLayout()
+ self.pages = QSpinBox()
+ self.pages.setRange(1, 3)
+ self.pages.setValue(3)
+ form.addRow(tr('试译页数'), self.pages)
+ root.addLayout(form)
+ buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
+ buttons.button(QDialogButtonBox.Ok).setText(tr('开始试译'))
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+ root.addWidget(buttons)
+
+
+class UsageDialog(QDialog):
+ def __init__(self, report, pricing, parent=None):
+ super().__init__(parent)
+ self.report = report
+ self.action = ''
+ self.setWindowTitle(tr('试译报告') if report.get('trial') else tr('翻译消耗'))
+ self.resize(540, 460)
+ root = QVBoxLayout(self)
+ self.summary = QLabel()
+ self.summary.setTextFormat(Qt.PlainText)
+ self.summary.setWordWrap(True)
+ root.addWidget(self.summary)
+ self.enabled = QCheckBox(tr('填写单价以估算费用'))
+ self.enabled.setChecked(bool(pricing.get('enabled')))
+ root.addWidget(self.enabled)
+ form = QFormLayout()
+ self.input_price, self.output_price = QDoubleSpinBox(), QDoubleSpinBox()
+ for spin, key, label in ((self.input_price, 'input', tr('输入 / 百万 token')),
+ (self.output_price, 'output', tr('输出 / 百万 token'))):
+ spin.setRange(0, 1_000_000)
+ spin.setDecimals(6)
+ spin.setValue(float(pricing.get(key) or 0))
+ spin.valueChanged.connect(self._refresh)
+ form.addRow(label, spin)
+ self.currency = QComboBox()
+ self.currency.addItems(['USD', 'CNY', 'JPY', 'EUR'])
+ self.currency.setCurrentText(pricing.get('currency') or 'USD')
+ self.currency.currentTextChanged.connect(self._refresh)
+ form.addRow(tr('币种'), self.currency)
+ root.addLayout(form)
+ self.estimate = QLabel()
+ self.estimate.setWordWrap(True)
+ root.addWidget(self.estimate)
+ note = QLabel(tr('仅统计翻译 API 返回的用量,包含重试响应,不含字体探测。费用按填写单价估算,缓存折扣等以服务商账单为准。整本预估基于样页平均值,受页面密度、上下文长度和并行度影响。'))
+ note.setWordWrap(True)
+ note.setProperty('muted', True)
+ root.addWidget(note)
+ root.addStretch(1)
+ actions = QHBoxLayout()
+ if report.get('trial') and report.get('outputs'):
+ inspect = QPushButton(tr('精修试译'))
+ inspect.clicked.connect(lambda: self._finish('edit'))
+ actions.addWidget(inspect)
+ if report.get('trial') and not report.get('cancelled') and not report.get('failed'):
+ full = QPushButton(tr('翻译整本'))
+ full.clicked.connect(lambda: self._finish('full'))
+ actions.addWidget(full)
+ actions.addStretch(1)
+ close = QPushButton(tr('保存并关闭'))
+ close.clicked.connect(self.accept)
+ actions.addWidget(close)
+ root.addLayout(actions)
+ self.enabled.toggled.connect(self._refresh)
+ self._refresh()
+
+ def pricing(self):
+ return dict(enabled=self.enabled.isChecked(), input=self.input_price.value(),
+ output=self.output_price.value(), currency=self.currency.currentText())
+
+ def _finish(self, action):
+ self.action = action
+ self.accept()
+
+ def _refresh(self):
+ for widget in (self.input_price, self.output_price, self.currency):
+ widget.setEnabled(self.enabled.isChecked())
+ report, usage = self.report, self.report.get('usage', {})
+ text = tr('模型:{_0}\n完成 {_1} / {_2} 页 · 用时 {_3} 秒\n翻译响应 {_4} 次 · 已报告用量 {_5} 次\n输入 {_6} token · 输出 {_7} token',
+ _0=report.get('model', ''), _1=report.get('completed_pages', 0),
+ _2=report.get('planned_pages', 0), _3=round(report.get('elapsed_seconds', 0), 1),
+ _4=usage.get('requests', 0), _5=usage.get('reported', 0),
+ _6=usage.get('prompt_tokens', 0), _7=usage.get('completion_tokens', 0))
+ if report.get('cancelled') or report.get('failed'):
+ text += '\n' + tr('任务已停止或有失败页面,不生成整本预估。')
+ if not report.get('total_pages_known', True):
+ text += '\n' + tr('部分文件无法读取,整本页数未知。')
+ if usage.get('reported', 0) < usage.get('requests', 0):
+ text += '\n' + tr('部分响应未提供用量;以上 token 为已知部分,费用未知。')
+ self.summary.setText(text)
+ pricing = self.pricing()
+ cost = usage_cost(usage, pricing)
+ cost_text = tr('费用未知') if cost is None else f"{cost:.6f} {pricing['currency']}"
+ lines = [tr('本次估算费用:{_0}', _0=cost_text)]
+ if report.get('trial'):
+ projection = trial_projection(report, pricing)
+ if projection:
+ total_cost = tr('费用未知') if projection['cost'] is None else f"{projection['cost']:.6f} {pricing['currency']}"
+ lines.append(tr('队列共 {_0} 页 · 粗估全量 {_1} 分钟 · {_2}',
+ _0=report['total_pages'], _1=round(projection['seconds'] / 60, 1), _2=total_cost))
+ self.estimate.setText('\n'.join(lines))
diff --git a/comic_translate_desktop/worker.py b/comic_translate_desktop/worker.py
index eaec9d4..f51d839 100644
--- a/comic_translate_desktop/worker.py
+++ b/comic_translate_desktop/worker.py
@@ -22,8 +22,11 @@
from . import config as app_config
from .pdf_utils import PdfPageRenderer, plan_pdf_pages, RenderedPdfPage
-from .pdf_project import create_pdf_project, publish_pdf_project, write_project_metadata
+from .cbz import CbzReader, PROJECT_EXTS
+from .pdf_project import create_pdf_project, publish_pdf_project, publish_project, write_project_metadata
from .checkpoints import DocumentCheckpoint
+from .productivity import UsageMeter, desktop_translation_config
+from .desktop_translation import DesktopTranslationMixin
from comic_translate_core.languages import OCR_CONFIG_KEYS
from comic_translate_core.chinese import normalize_target_language
from comic_translate_core.layout_options import normalize_text_color, normalize_vertical_alignment
@@ -110,7 +113,13 @@ def __init__(self, files, output_dir, config, pipeline=None, parent=None):
self.task_id = uuid.uuid4().hex
self._stage_context = threading.local()
self._pdf_renderer = None
- self._pdf_document = None
+ self._cbz_reader = None
+ self._reader_document = None
+ self._usage_meter = UsageMeter(lambda usage: self._emit_workflow('usage', usage=usage))
+ self.usage_report = {}
+ self._trial_limit = max(0, min(3, int(self._config.get('trial_page_limit') or 0)))
+ if self._trial_limit:
+ self._config.update(resume_enabled=False, retain_translation_context=False)
def stop(self) -> None:
self._stop = True
@@ -168,6 +177,7 @@ def _translate_page(self, page, prepared):
raise
def _configure_pipeline(self, pipeline) -> None:
+ pipeline.usage_meter = self._usage_meter
pipeline.cancel_callback = self._is_stopped
pipeline.progress_callback = self._emit_stage
pipeline.watermark_enabled = bool(self._config.get("watermark_enabled", True))
@@ -210,7 +220,9 @@ def _build_pipeline(self):
self.log.emit("[预热] 开始实例化 AI 管线")
with self._capture_pipeline_output():
- pipeline = ComicTranslatorPipeline(
+ class DesktopPipeline(DesktopTranslationMixin, ComicTranslatorPipeline):
+ pass
+ pipeline = DesktopPipeline(
det_model_path=self._config["detector_model"],
cuda_detector_model_path=self._config.get("cuda_detector_model"),
font_map=self._config["font_map"],
@@ -239,6 +251,7 @@ def _build_pipeline(self):
cancel_callback=self._is_stopped,
)
self.log.emit("[预热] 实例化完成")
+ self._apply_api_config(pipeline, self._config)
return pipeline
def _make_document_jobs(self) -> list[_DocumentJob]:
@@ -262,30 +275,38 @@ def _make_document_jobs(self) -> list[_DocumentJob]:
if not input_path.exists():
raise FileNotFoundError(f"文件不存在: {input_path}")
document.checkpoint = DocumentCheckpoint(input_path, document.output_path, self._config)
- if is_pdf:
+ if suffix in PROJECT_EXTS:
source_dir = document.checkpoint.project_directory()
if source_dir is None:
source_dir = create_pdf_project(document.output_path)
document.checkpoint.set_project_directory(source_dir)
document.project_dir = source_dir
- self.log.emit(f"[PDF] {input_path.name}: 精修资料保存在 {source_dir}")
- rendered = plan_pdf_pages(input_path, source_dir / "source", dpi=pdf_dpi,
+ kind = suffix[1:].upper()
+ self.log.emit(f"[{kind}] {input_path.name}: 精修资料保存在 {source_dir}")
+ if is_pdf:
+ plan = plan_pdf_pages(input_path, source_dir / "source", dpi=pdf_dpi,
cancel_callback=self._check_cancelled)
- write_project_metadata(source_dir, input_path.name,
- [(page.width_points, page.height_points) for page in rendered])
- for page in rendered:
+ sizes = [(page.width_points, page.height_points) for page in plan]
+ source_paths = [page.image_path for page in plan]
+ else:
+ with CbzReader(input_path) as reader:
+ sizes = reader.page_sizes(self._check_cancelled)
+ source_paths = [source_dir / "source" / f"page_{n:04d}.png"
+ for n in range(1, len(sizes) + 1)]
+ write_project_metadata(source_dir, input_path.name, sizes)
+ for number, (source, size) in enumerate(zip(source_paths, sizes), 1):
document.pages.append(
_PageJob(
document=document,
- input_path=page.image_path,
+ input_path=source,
output_path=source_dir
/ "translated"
- / f"page_{page.page_index + 1:04d}.png",
- page_number=page.page_index + 1,
- page_size_points=(page.width_points, page.height_points),
+ / f"page_{number:04d}.png",
+ page_number=number,
+ page_size_points=size,
)
)
- self.log.emit(f"[PDF] {input_path.name}: 共 {len(document.pages)} 页,将按批次以原分辨率渲染")
+ self.log.emit(f"[{kind}] {input_path.name}: 共 {len(document.pages)} 页,将按批次准备原分辨率页图")
else:
document.pages.append(
_PageJob(
@@ -302,37 +323,62 @@ def _make_document_jobs(self) -> list[_DocumentJob]:
except Exception as exc:
document.error = str(exc)
document.error_stack = traceback.format_exc().strip()
+ self._total_pages = sum(len(document.pages) for document in documents)
+ self._total_pages_known = all(not document.error for document in documents)
+ if self._trial_limit:
+ remaining, sampled = self._trial_limit, []
+ for document in documents:
+ if remaining <= 0:
+ break
+ if document.error:
+ sampled.append(document)
+ continue
+ document.pages = document.pages[:remaining]
+ remaining -= len(document.pages)
+ if document.project_dir is not None:
+ write_project_metadata(document.project_dir, document.source_path.name,
+ [page.page_size_points for page in document.pages])
+ sampled.append(document)
+ documents = sampled
return documents
def _check_cancelled(self):
if self._is_stopped():
raise TaskCancelledError("任务已取消")
- def _close_pdf_renderer(self):
- if self._pdf_renderer is not None:
- self._pdf_renderer.close()
- self._pdf_renderer = None
- self._pdf_document = None
+ def _close_project_reader(self):
+ reader = self._pdf_renderer or self._cbz_reader
+ if reader is not None:
+ reader.close()
+ self._pdf_renderer = self._cbz_reader = self._reader_document = None
- def _ensure_pdf_page(self, page):
- if not page.document.is_pdf:
+ def _ensure_project_page(self, page):
+ document = page.document
+ if document.project_dir is None:
return
self._check_cancelled()
- if self._pdf_document is not page.document:
- self._close_pdf_renderer()
- dpi = max(96, min(400, int(self._config.get('pdf_dpi') or 200)))
- self._pdf_renderer = PdfPageRenderer(page.document.source_path, dpi)
- self._pdf_document = page.document
+ if self._reader_document is not document:
+ self._close_project_reader()
+ if document.is_pdf:
+ dpi = max(96, min(400, int(self._config.get('pdf_dpi') or 200)))
+ self._pdf_renderer = PdfPageRenderer(document.source_path, dpi)
+ else:
+ self._cbz_reader = CbzReader(document.source_path)
+ self._reader_document = document
started = perf_counter()
- self._page_event('start', 'running', '正在准备原分辨率 PDF 页图')
- self._pdf_renderer.render(
- RenderedPdfPage(page.page_number - 1, page.input_path, *page.page_size_points),
- reuse_cached=True, cancel_callback=self._check_cancelled)
- self.log.emit(f'[耗时] {self._page_label(page)}: PDF 页图准备 {perf_counter() - started:.2f} 秒')
+ kind = document.source_path.suffix[1:].upper()
+ self._page_event('start', 'running', f'正在准备原分辨率 {kind} 页图')
+ if document.is_pdf:
+ self._pdf_renderer.render(
+ RenderedPdfPage(page.page_number - 1, page.input_path, *page.page_size_points),
+ reuse_cached=True, cancel_callback=self._check_cancelled)
+ else:
+ self._cbz_reader.render(page.page_number - 1, page.input_path, self._check_cancelled)
+ self.log.emit(f'[耗时] {self._page_label(page)}: {kind} 页图准备 {perf_counter() - started:.2f} 秒')
@staticmethod
def _page_label(page: _PageJob) -> str:
- if page.document.is_pdf:
+ if page.document.project_dir is not None:
return tr('{_0} 第 {_1}/{_2} 页', _0=page.document.source_path.name,
_1=page.page_number, _2=len(page.document.pages))
return page.document.source_path.name
@@ -350,7 +396,7 @@ def _set_document_error(
@staticmethod
def _apply_api_config(pipeline, config) -> None:
- apply_runtime_settings(pipeline, config)
+ apply_runtime_settings(pipeline, desktop_translation_config(config))
def _cancel_page(self, page):
self._page_event('cancelled', 'cancelled', '已取消')
@@ -367,7 +413,7 @@ def _prepare_page(self, page):
label = self._page_label(page)
self.stage_changed.emit(page.document.index, 'start', tr('{_0}: 准备中', _0=label))
try:
- self._ensure_pdf_page(page)
+ self._ensure_project_page(page)
started = perf_counter()
with inference_cancellation(self._check_cancelled):
prepared = self._preparation_pipeline.prepare_comic_page(str(page.input_path))
@@ -490,6 +536,7 @@ def _finish_page(self, page, prepared, translations):
return False
def run(self) -> None:
+ task_started = perf_counter()
main_dir = str(app_config.MAIN_DIR)
if main_dir not in sys.path:
sys.path.insert(0, main_dir)
@@ -516,8 +563,9 @@ def run(self) -> None:
self.finished.emit(0, 0)
return
self._translation_context = TranslationContext.start(
- app_config.PROJECT_ROOT / '.cache' / 'translation-context.json',
- retain=bool(self._config.get('retain_translation_context', False)))
+ (self._output_dir / '.translation-context.json' if self._trial_limit else
+ app_config.PROJECT_ROOT / '.cache' / 'translation-context.json'),
+ retain=not self._trial_limit and bool(self._config.get('retain_translation_context', False)))
self._pipeline.translation_context = self._translation_context
self._pipeline.translation_context_managed = True
self._translation_settings = TranslationSettings.from_pipeline(self._pipeline)
@@ -528,6 +576,7 @@ def run(self) -> None:
self._output_dir.mkdir(parents=True, exist_ok=True)
documents = self._make_document_jobs()
page_jobs = [page for document in documents for page in document.pages]
+ processing_started = perf_counter()
completed_pages = sum(page.resumed for page in page_jobs)
self.page_progress.emit(completed_pages, len(page_jobs))
max_workers = max(1, int(self._config.get("max_workers") or 4))
@@ -558,7 +607,7 @@ def run(self) -> None:
with self._capture_pipeline_output(), PagePrefetch(
page_jobs, self._prepare_page, self._translate_and_cache,
capacity=max_workers, cancelled=self._is_stopped,
- close_preparation=self._close_pdf_renderer,
+ close_preparation=self._close_project_reader,
translation_workers=1,
repair=self._repair_page if callable(getattr(self._pipeline, 'repair_comic_page', None)) else None,
) as pages:
@@ -585,29 +634,36 @@ def run(self) -> None:
if self._stop:
break
self._current_index = document.index
- if not document.error and document.is_pdf:
+ if not document.error and document.project_dir is not None:
+ kind = document.source_path.suffix[1:].upper()
self._emit_workflow(
'publish',
document_index=document.index,
document_name=document.source_path.name,
+ output_format=kind,
state='running',
)
try:
- publish_pdf_project(document.output_path, document.project_dir)
+ if document.is_pdf:
+ publish_pdf_project(document.output_path, document.project_dir)
+ else:
+ publish_project(document.output_path, document.project_dir,
+ cancel_callback=self._check_cancelled)
self._emit_workflow(
'publish',
document_index=document.index,
document_name=document.source_path.name,
state='done',
)
- self.log.emit(
- f"[PDF] {document.source_path.name}: 已生成 {len(document.pages)} 页译文 PDF"
- )
+ self.log.emit(f"[{kind}] {document.source_path.name}: 已生成 {len(document.pages)} 页译文 {kind}")
+ except TaskCancelledError:
+ break
except Exception as exc:
self._emit_workflow(
'publish',
document_index=document.index,
document_name=document.source_path.name,
+ output_format=kind,
state='failed',
)
self._set_document_error(document, exc)
@@ -631,6 +687,19 @@ def run(self) -> None:
finally:
self._preparation_pipeline = None
- self._close_pdf_renderer()
+ self._close_project_reader()
+ if self._files:
+ pages = locals().get('page_jobs', [])
+ self.usage_report = dict(
+ trial=bool(self._trial_limit), model=self._config.get('translation_model', ''),
+ total_pages=getattr(self, '_total_pages', len(pages)), planned_pages=len(pages),
+ total_pages_known=getattr(self, '_total_pages_known', False),
+ completed_pages=sum(page.completed or page.resumed for page in pages),
+ elapsed_seconds=perf_counter() - task_started,
+ processing_seconds=perf_counter() - locals().get('processing_started', task_started),
+ cancelled=self._stop, failed=failed_count or bool(self._fatal_error),
+ usage=self._usage_meter.snapshot(),
+ outputs=[str(doc.output_path) for doc in locals().get('documents', [])
+ if not doc.error and doc.pages and all(page.completed or page.resumed for page in doc.pages)])
self.finished.emit(success_count, failed_count)
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 6cf11a7..2ca0e52 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -41,7 +41,7 @@ PNG 为 3600 × 3220 像素。SVG 保留文字、方框和连线,可继续编
`EditorPage` 载入清理底图和布局,把文字作为独立可重绘内容。字体、位置、蒙版和白描边修改复用排版器。背景选区交给 `RepairWorker`,复用背景重建与 LaMa。自动流水线与精修按模型路径、文件版本和设备共享 LaMa 会话,同一会话的推理排队;各自保留取消与分块状态。设备或模型设置更新后精修更换引擎,正在运行的修补仍持有原引擎,模型无持有者时释放共享缓存。气泡还原由原图快照和逐块区域记录支持。长条浏览和缩略图按可见范围加载,预览尺寸与修补、保存所用的页图分辨率分别管理。
-精修保存联动写入译图、布局及发生修改的底图。写盘前先准备文件,替换失败时恢复此前文件。背景撤回历史保存在当前会话的内存中,保存成功后释放。PDF 项目通过 `project.json` 保存页尺寸等信息,通过同名 `.comitrans.json` 将译文 PDF 关联到页图项目。
+精修保存联动写入译图、布局及发生修改的底图。写盘前先准备文件,替换失败时恢复此前文件。背景撤回历史保存在当前会话的内存中,保存成功后释放。PDF 项目通过 `project.json` 保存页尺寸等信息,通过同名 `.comitrans` 将译文 PDF 关联到页图项目。已有 `.comitrans.json` 索引可继续读取。
自动批次在全页成功后合成译文 PDF。精修通过显式的“导出 PDF”操作调用 `PdfExportWorker`,从已保存页图按顺序无损合成,并保持原 PDF 的页面物理尺寸。[PDF 工作流](PDF_EDITING.md) · [断点续传](RESUMABLE_TRANSLATION.md) · [精修说明](EDITOR_LIVE_PREVIEW.md)
diff --git a/docs/PDF_EDITING.md b/docs/PDF_EDITING.md
index e1f4880..2d2cc0b 100644
--- a/docs/PDF_EDITING.md
+++ b/docs/PDF_EDITING.md
@@ -15,7 +15,7 @@
```text
漫画_translated.pdf
-漫画_translated.comitrans.json
+漫画_translated.comitrans
漫画_translated_edit_<独立编号>/
project.json # 原文件名、原始页面尺寸与顺序
source/page_0001.png # 原始 PDF 页图
diff --git a/docs/RELEASE-v2.6.0-pre.1.md b/docs/RELEASE-v2.6.0-pre.1.md
new file mode 100644
index 0000000..7809521
--- /dev/null
+++ b/docs/RELEASE-v2.6.0-pre.1.md
@@ -0,0 +1,25 @@
+# ComiTrans v2.6.0-pre.1
+
+这是安装方式变更和 UI 优化的测试包。漫画翻译、OCR、擦字和嵌字功能沿用 v2.5.2。
+
+## 安装与更新
+
+- **一次安装程序和模型。** 下载 `ComiTrans-v2.6.0-pre.1-x64-Setup.exe` 并双击安装。Setup 内置程序、7 个 ONNX 模型和现有字体,CPU 模式安装后可直接加载模型。翻译仍需配置 API。GPU 加速沿用设置中的运行库安装指引。
+- **启动时检查正式版。** 应用在后台查询 GitHub Releases,发现新版后提醒。无签名新版通过「前往发布页下载安装」手动更新。正式版用户不会收到本预发布的更新提醒。
+- **Windows 安装方式。** 安装器创建开始菜单和桌面快捷方式、注册更新查询服务及 `.comitrans` 项目文件关联,并提供系统卸载入口。此 Setup 未签名,Windows 可能提示未知发布者。
+- **迁移旧版。** 已通过 v2.5.2 Setup 安装的用户可关闭程序后运行新版 Setup。使用旧 ZIP 版的用户若要保留设置,可迁移 `config.yaml` 和 `user_fonts/` 到 `%LOCALAPPDATA%\ComiTrans`。本测试包内部安装版本为 `2.5.999`,以便后续升级至正式 `2.6.0`。若已安装此前的本地 `2.6.0` 测试包,先在 Windows 中卸载它,再安装本预发布包。
+
+## 界面优化
+
+- 统一纸白和夜墨主题下的按钮、下拉框、对话框、卡片和选中态,完善控件反馈与过渡动画。
+- 优化自动处理工作流、精修画布和工具栏的交互反馈,同步调整设置、字体库、语言选择和日志窗口。
+
+## English
+
+This pre-release tests the new installer and UI refinements. Manga translation, OCR, inpainting, and lettering features remain the same as in v2.5.2.
+
+- **Install with a single Setup.** Run `ComiTrans-v2.6.0-pre.1-x64-Setup.exe` to install the app, seven ONNX models, and bundled fonts. CPU inference is ready after installation. Translation still requires an API configuration. For GPU acceleration, follow the runtime instructions in Settings.
+- **Check for updates at startup.** ComiTrans checks GitHub for newer stable releases. For unsigned updates, choose **Download from releases** and run the newer Setup yourself. Stable users will not receive an alert for this pre-release.
+- **Windows integration.** Setup adds shortcuts, an update-check service, a `.comitrans` file association, and an uninstall entry. Windows may show an unknown publisher prompt for this unsigned package.
+- **Upgrade or migrate.** Close v2.5.2 before running Setup. From the old ZIP edition, copy `config.yaml` and `user_fonts/` to `%LOCALAPPDATA%\ComiTrans` to migrate settings. This preview uses Windows installer version `2.5.999`, leaving an upgrade path to `2.6.0`. Remove the earlier local `2.6.0` test installer before installing this preview.
+- **UI refinements.** Improved light and dark themes, control feedback, transitions, and consistency across the translation workspace, lettering editor, settings, font library, language chooser, and logs.
diff --git a/docs/RELEASE-v2.6.0.md b/docs/RELEASE-v2.6.0.md
new file mode 100644
index 0000000..292ab62
--- /dev/null
+++ b/docs/RELEASE-v2.6.0.md
@@ -0,0 +1,31 @@
+# ComiTrans v2.6.0
+
+## Windows 安装与升级
+
+下载本页的 `ComiTrans-v2.6.0-x64-Setup.exe` 和 `SHA256SUMS.txt`。安装包为 Windows x64,包含程序、字体和默认 OCR、检测、修补模型。关闭 ComiTrans,核对安装包的 SHA-256 后运行 Setup。安装后在设置中填写翻译 API 密钥与模型。
+
+```powershell
+Get-FileHash -Algorithm SHA256 .\ComiTrans-v2.6.0-x64-Setup.exe
+Get-Content .\SHA256SUMS.txt
+```
+
+两处的十六进制哈希应一致。这个版本的安装包未签名,Windows 可能显示「未知发布者」。请从项目的 GitHub 发布页手动下载和安装。[v2.6.0 发布页](https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.6.0)
+
+- **从预发布 NSIS 版升级**:关闭应用后直接运行新版 Setup,沿用原安装目录和用户配置。
+- **从旧 MSI / WiX 版迁移**:先在 Windows「已安装的应用」中卸载旧版,再运行 Setup。保留用户数据目录。
+- **从 ZIP 版迁移**:原有配置和字体可从旧目录的 `config.yaml`、`user_fonts` 迁入 `%LOCALAPPDATA%\ComiTrans`。保留漫画、项目索引和配套精修目录之间的相对位置。
+
+## 使用变化
+
+- 打开应用后,检测和修补模型在独立进程中预热。加载期间可继续操作界面,顶栏会显示模型状态。
+- 在「作品术语库」里记录角色、地点和统一译名。整批翻译前可以先试译少量页面,查看用量和按已配置单价估算的费用。
+- 精修支持「全书译稿」跨页查找、替换,以及单气泡重译。CBZ 可以按页翻译,已保存的页面可以重新导出为 CBZ。
+- 启动时在后台比较客户端版本与 GitHub 最新正式版。只有发现更高版本时,「模型已就绪」左侧才会出现「有更新」。点击可查看两个版本号及下载入口。
+
+## English
+
+Download `ComiTrans-v2.6.0-x64-Setup.exe` and `SHA256SUMS.txt` from this release. Compare the SHA-256 values using the PowerShell commands above. This Windows x64 installer is **unsigned** and requires a manual download. Windows may display “Unknown publisher.” Setup includes the app, fonts and default models. Enter your translation API key and model in Settings after installation.
+
+Close the app before upgrading an NSIS installation. Uninstall an older MSI or WiX installation through Windows Settings first. ZIP users can migrate `config.yaml` and `user_fonts` into `%LOCALAPPDATA%\ComiTrans`. Keep project indexes and their editing folders together.
+
+Model warm-up runs in a separate process. Project glossaries, trial translations and usage estimates help prepare a batch. The editor supports cross-page transcript search and replacement, single-bubble retranslation and CBZ export. A small **Update** button beside the model status appears when GitHub lists a newer stable version.
diff --git a/docs/UI_MENU_ASSESSMENT_2026-11-22.md b/docs/UI_MENU_ASSESSMENT_2026-11-22.md
new file mode 100644
index 0000000..d37083d
--- /dev/null
+++ b/docs/UI_MENU_ASSESSMENT_2026-11-22.md
@@ -0,0 +1,55 @@
+# 界面密度与次级菜单评估
+
+日期:2026-11-22。范围:以下内容为菜单合并前的界面密度评估。
+
+后续更新:用户已要求合入 `optimize_ui_menu_layout` 工作区对应的 `feat/ui-menu-layout`。分支合并、新功能菜单适配与验收已完成;本文件保留合并前的观察,当前入口与交接状态见 [菜单布局交接](UI_MENU_LAYOUT_HANDOFF_2026-11-22.md)。
+
+## 结论
+
+自动处理页仍适合当前的任务流程;嵌字精修页已经偏密,1024 及以下宽度应优先规划次级菜单和按选择状态显示的工具。当前可以完成操作,但继续平铺新增按钮会进一步压缩画布和译文编辑空间。
+
+本次增加多选与样式刷、作品术语库、试译与消耗报告。术语编辑和报告使用独立对话框,主页面增加紧凑入口;新增样式按钮放入现有“排版与位置”页签,避免继续占用译文页签高度。原有功能入口保持所在分区。后续菜单方案尚未实施。
+
+## 观察依据
+
+使用真实 Qt Widgets 渲染检查浅色、深色,以及 1440×900、1024×720、820×640 三种尺寸;另检查原有 820×480 布局。截图过程隔离配置与用户数据,没有调用付费 API。英文和日文额外检查新增对话框。
+
+- 自动处理页的主要顺序仍是队列、翻译方向、开始处理、结果检查。术语库放在偏好中,试译和消耗放在开始按钮附近,任务入口仍能辨认。
+- 精修页同时存在导航栏、视图工具、九个快捷字体槽、背景工具、气泡操作、样式刷、文本列表和属性面板。操作分散在多条横向区域,功能层级较平。
+- 1024 宽度下,背景工具会分成多行,画布与右侧检查器争夺空间;820 宽度下,页面栏收起后画布仍较窄,原文和操作按钮占据较多纵向空间。在 820×640 中译文输入区域的可视高度已经不足,应列为下一次布局整理的优先验收项。
+- 字体库、字体导入、设置快捷字体同时常驻,与频繁切换字体、修改字号的操作混在一起。
+- 全局中文人名设置与作品术语库存在一定概念重叠。术语库已经支持只填固定译名,由 AI 根据上下文匹配;后续需要进一步明确“通用默认”和“当前作品”的关系。
+
+轻量测量记录中,自动处理页约有 15 个可见文字按钮,精修页约有 24–27 个;该计数受当前页面、折叠状态、工具是否显示等因素影响,仅用于比较层级密度,不作为可用性评分。
+
+## 后续分组建议(待实施)
+
+| 分区 | 保留直达的常用操作 | 可进入次级菜单的操作 |
+|---|---|---|
+| 任务 | 开始、停止、试译、当前进度 | 消耗详情、输出位置、任务相关设置 |
+| 文件与导出 | 保存、导入页面 | 导出 PDF、打开输出目录、关联原图 |
+| 视图 | 适应页面、缩放、当前选择 | 连续长条、面板显隐、专注模式、缩放工具切换 |
+| 字体与样式 | 字体选择、字号、排向、当前多选状态 | 字体库、导入字体、快捷字体管理、变形与描边高级选项 |
+| 背景修补 | 当前工具、执行、撤销 | 填白、填黑、自定义填色、取色等工具选择 |
+| 作品偏好 | 当前作品摘要 | 术语管理、背景设定、通用人名设置 |
+
+气泡右键菜单适合提供取样式、应用样式、还原等与当前气泡直接相关的操作。批量操作继续显示选中数量,明确哪些属性会应用到多个气泡;已还原原图的气泡保持受保护。
+
+建议先整理字体管理与视图操作,再考虑修补工具组;字号、译文编辑和保存继续直达。使用任务含义明确的分组名,每组维持一层次级菜单,配合快捷键提示。
+
+## 后续验收标准
+
+1. 同样三个宽度和浅色/深色分别复查;英文、日文检查标签换行与菜单宽度。
+2. 保存、翻译、译文编辑和字号修改均可直接到达。
+3. 切换工具或收起面板保留当前文本、选区、缩放与未保存状态。
+4. 次级菜单的引入不改变翻译、擦字、排版或导出结果。
+5. 用长篇项目实际比较操作路径与画布面积,再决定是否继续收纳其他入口。
+
+## 本地验证材料
+
+- 常规布局与字体断言:`build/productivity-ui/light/style-review.json`、`build/productivity-ui/dark/style-review.json`。
+- 新功能对话框与多选截图:`build/productivity-ui/features/`,含中文、英文、日文以及两种主题。
+- 轻量测量:`build/productivity-ui/features/measurements.json`。
+- 截图均为验证产物,不提交到仓库。
+
+验证结果:全量运行 518 项测试通过;断点兼容修复与样式刷列表交互另补跑 35 项相关测试通过。浅色、深色常规截图各 66 张,UI 正文字体断言为 Source Han Sans SC。全量运行中的 NSIS 测试需要临时 HKCU 测试键写权限,使用替代服务 API 的隔离夹具验证,不安装真实应用。
diff --git a/docs/UI_MENU_LAYOUT_HANDOFF_2026-11-22.md b/docs/UI_MENU_LAYOUT_HANDOFF_2026-11-22.md
new file mode 100644
index 0000000..0e7b254
--- /dev/null
+++ b/docs/UI_MENU_LAYOUT_HANDOFF_2026-11-22.md
@@ -0,0 +1,125 @@
+# 菜单布局合并与新功能适配交接
+
+日期:2026-11-22。工作目录:`D:\ComiTrans`。
+
+## 分支与交付状态
+
+- 当前分支:`feat/ui-windows-installer`。
+- 来源工作区:`C:\Users\OS\.gemini\antigravity\worktrees\ComiTrans\optimize_ui_menu_layout`。
+- 实际来源分支:`feat/ui-menu-layout`,来源提交:`fa74a8464f67e44d6b345b50285ef4d55f846db7`。
+- 合并前目标提交:`83c2e9c3687e5f0b9e6441227ee04d54c732ddcc`。
+- 合并提交:`6d51704508b12a13e58591306dde64f537fb868a`。
+- 合并、适配与验收进度:已完成;来源分支已合入,新功能入口适配完成,全部验收通过。
+
+合并提交只包含来源分支的 UI 改动。此前安装器、发布修复、翻译工作流等未提交内容恢复到工作区,新功能与菜单的适配也保留在工作区;不要把整个工作区直接作为一个提交。
+
+## 用户入口
+
+| 功能 | 当前入口与行为 |
+|---|---|
+| 试译 | 自动处理页保留“试译”直达按钮;试译队列开头 1–3 页,PDF 按页计数 |
+| 作品术语库 | “任务 → 作品术语库”;翻译偏好中保留管理入口。任务菜单显示当前作品摘要 |
+| 消耗统计 | “任务 → 翻译消耗”;任务结束后可用,支持填写单价与样页预估 |
+| 多选气泡 | 列表 Ctrl/Shift 多选,画布 Ctrl 点击、Shift 拖动框选;计数随选择更新 |
+| 样式取样与应用 | 气泡右上角“⋯”或列表/画布右键菜单中的“取样式”“应用样式到所选气泡” |
+| 连续样式刷 | 同一气泡菜单中的“样式刷”;点击或框选目标应用;Esc 或“退出样式刷”结束 |
+| 样式撤销 | 气泡菜单中的“撤销样式”,逐次撤销本页最近的样式操作 |
+| 视图与文件 | 视图、文件菜单统一收纳面板切换、长条、导出和关联原图等操作 |
+| 填充与字体管理 | 保留来源分支的填充、字体管理菜单;常用编辑操作仍可直接到达 |
+
+所有新增菜单保持单层,菜单内部不嵌套子菜单。样式刷开启时,“退出样式刷”复用原“还原此气泡”按钮的位置;还原命令仍可通过气泡菜单使用。
+
+## 适配约束
+
+1. 右键点击已选中的气泡保留多选组,只切换当前气泡;右键本身不会应用样式。原有画布平移、缩放、取色及背景框选保持独立。
+2. 样式刷与背景框选、添加气泡、取色互斥;样式刷开启时不显示可拖动的气泡调整手柄,避免点击取样意外移动气泡。
+3. 批量属性编辑只同步实际改动的样式字段。译文、原文、蒙版范围、位置、气泡尺寸不随样式刷复制;已还原原图的气泡受保护。
+4. 撤销样式只恢复样式属性,不覆盖后续改过的译文;切页清除本页样式历史,内部样式剪贴板可跨页使用。
+5. 新布局的快捷字号框与原字号框使用同一份值,多选时同样触发批量字号修改。
+6. 术语库只要求固定译名;类型和识别线索可选。AI 在正常翻译请求中根据上下文匹配,无需用户填写原文,也不额外增加一次识别请求。
+7. 试译使用独立结果目录、上下文和断点;完成后可精修试译结果或启动完整任务。失败、取消、页数未知时不生成整本预估。
+8. 消耗以翻译接口返回的 token 用量为依据,计入返回无效内容后重试的响应;缺失用量显示未知。估算不含字体探测,缓存折扣等以服务商账单为准。
+9. 断点指纹只纳入当前生效术语;修改单价或其他作品的术语不会重跑已付费页面。未启用术语库时兼容原有断点。
+
+## 主要代码位置
+
+| 文件 | 责任 |
+|---|---|
+| `comic_translate_desktop/ui/editor_page.py` | 单层气泡菜单、多选、样式刷与模式互斥、快捷字号同步 |
+| `comic_translate_desktop/ui/main_window.py` | 任务菜单、术语摘要、试译入口与消耗报告 |
+| `comic_translate_desktop/ui/preview.py`、`strip_preview.py` | 框选、多选叠加层、画布右键信号转发 |
+| `comic_translate_desktop/ui/workflow_dialogs.py` | 作品术语、试译和消耗对话框 |
+| `comic_translate_desktop/productivity.py` | 样式字段、术语提示词、用量与费用计算 |
+| `comic_translate_desktop/desktop_translation.py`、`worker.py` | 翻译响应计量、试译分页与上下文隔离 |
+| `comic_translate_desktop/config.py` | `usage_pricing`、`terminology_project`、`terminology_projects` 三个持久化字段;同文件仍含此前未提交的模型路径修复,提交时需分开选择 |
+| `comic_translate_desktop/checkpoints.py` | 当前生效配置与断点兼容 |
+| `assets/i18n/en.json`、`ja.json` | 新入口、提示和报告的翻译 |
+| `tests/test_productivity_workflow.py`、`test_editor_ui_redesign.py` | 工作流、菜单、手势、窄窗布局与状态回归 |
+
+## 启动与验证
+
+从仓库根目录启动源码:
+
+```powershell
+.\.venv\Scripts\python.exe run.py
+```
+
+完整测试:
+
+```powershell
+.\.venv\Scripts\python.exe -m unittest discover -s tests -v
+```
+
+NSIS 集成测试会写临时 HKCU 测试键,需要允许此权限的执行环境。它把服务 API 替换为测试 DLL,目录和快捷方式也隔离,不安装真实应用。
+
+界面检查分别执行浅色与深色:
+
+```powershell
+$env:QT_QPA_PLATFORM = 'offscreen'
+.\.venv\Scripts\python.exe scripts/review_ui.py --theme light --screen-size 1920 1080 --output build/menu-merge-ui/light --scratch tmp/menu-merge-review-light
+.\.venv\Scripts\python.exe scripts/review_ui.py --theme dark --screen-size 1920 1080 --output build/menu-merge-ui/dark --scratch tmp/menu-merge-review-dark
+```
+
+`--screen-size` 指定审查脚本的虚拟桌面边界,避免无显示器环境把 1440/1024 的审查图缩成 820。检查报告须确认实际宽度包含 1440、1024、820,并确认字体白名单断言。
+
+审查脚本在页面切换后等待 240 ms,再截取 180/190 ms 淡入动画结束后的稳定画面,避免把过渡中的空画布当成最终界面。
+
+验收记录:
+
+- 完整测试:524 项,1341.498 秒,`OK`,退出码 0。
+- 桌面、编辑器布局、实时预览与大图回归:91 项通过;功能与菜单集成回归最终 12 项通过;主题、字体、语言及偏好回归 44 项通过。上述测试均包含在完整验收中,不相加作为独立覆盖数量。
+- 浅色、深色各生成 73 张审查图,两份报告均为 `success: true`,实际宽度包含 1440、1024、820;另外检查了 820×480 紧凑界面。
+- 两种主题分别检查画布、译文区和工具入口;中文、英文、日文另行检查任务菜单、气泡菜单、样式刷、术语、试译和消耗对话框。
+- `QFontInfo(ui_font()).family()` 为白名单中的 `Source Han Sans SC`;本轮相关三个界面模块的静态 `tr(...)` 文案在英文、日文目录中均有对应项。
+- 与本轮菜单及文档无关的 52 个原文件,和合并前备份逐字节一致;生成的漫画输出未移动或覆盖。
+
+## 工作区与后续处理
+
+- 合并前备份:`build/menu-merge-20261122-170016/`,含文件清单、原文件、补丁、来源提交和菜单合并索引树。
+- 合并后的工作区补丁为同目录的 `final-working-tree.patch`,相对上述合并提交生成;新增工作流模块与更新后的功能测试另存于 `final-untracked/`,用于本机交接恢复。原始备份和任务自建的 stash 也保留。
+- 生成的漫画输出留在原处;模型权重、安装包和本地配置没有作为合并内容提交。
+- `build/menu-merge-full-tests.log` 为完整测试日志;相关快速回归见 `build/menu-merge-targeted-tests.log`、`build/menu-merge-settings-tests.log`、`build/menu-merge-productivity-tests.log`。
+- 布局报告及截图:`build/menu-merge-ui/`;这些验证产物不提交。
+- 原来的界面密度评估见 `UI_MENU_ASSESSMENT_2026-11-22.md`,其中“尚未实施”的结论属于合并前状态,以本文为准。
+- 尚未重新构建安装程序。本地 `release/` 中旧安装包不包含本轮菜单和功能适配。
+- 源码版本当前仍为 `2.5.2`;此前 `2.6.0` 安装包通过构建快照覆盖版本生成。后续打包要从当前完整工作区生成新快照,避免沿用旧快照遗漏菜单、新模块或相对模型路径修复。
+- 后续若提交当前未提交功能,请显式选择实现、配置、翻译和测试依赖,按 `AGENTS.md` 分离 UI、安装器和发布内容,不提交 `build/`、`release/`、`output_layout/`、模型权重、配置与日志。
+
+## 2026-11-22 · 人工开合偏好面板后的动画修复
+
+- 反馈:反复开合翻译偏好时,`_RippleOverlay.paintEvent()` 持续报告缺少 `_target`。
+- 构造边界回归可复现同样异常:原生 QWidget 初始化尚未返回,Qt 绘制回调已读取 Python 动画状态。`motion.py` 中的涟漪与焦点动画层现均先设置空闲绘制状态,再调用 QWidget 构造及几何设置。
+- `tests/test_motion_overlay_lifecycle.py` 覆盖构造期间的 Qt 绘制回调,以及初始化后涟漪正常绘制、结束和停止计时器;旧实现会在构造回归中失败。
+- `tests/test_retouch_and_motion.py` 增加真实按钮点击、动画中途反向开合、浅/深色和三个窗口尺寸的回归;Qt 回调异常纳入失败条件。
+- 本轮相关回归 96 项通过,Windows 原生平台额外执行 3 项通过;浅/深色各 73 张审查图通过,字体为 `Source Han Sans SC`。日志及图像位于 `build/ripple-fix-*`。上文 524 项为菜单合并阶段的完整验收记录。
+- 修复与新增测试保留在当前工作区;已运行的程序需关闭后从源码重新启动。前述菜单交接备份对应此次动画修复之前的状态。
+- 本轮远端同步遇到镜像 403 和直连代理 TLS 错误,重试后仍失败;保留现有远端和协议配置,本地修复与回归已完成。
+
+## 2026-11-22 · 试译、术语与消耗弹窗确认修复
+
+- 人工反馈:试译确认、术语保存后,主窗口访问 `dialog.Accepted` 抛出 `AttributeError`;消耗报告入口也有同样写法。
+- `main_window.py` 的三处返回值判断统一为 `QDialog.DialogCode.Accepted`。
+- 新增 `tests/test_workflow_dialog_actions.py`,通过真实弹窗和按钮触发验证试译页数与取消、术语持久化与取消、消耗单价保存与取消,以及从报告进入完整翻译/精修;同时验证弹窗释放和 Qt 回调不报错。
+- 新增测试在无显示器平台与 Windows 原生平台各 7 项通过;连同生产力、偏好、更新相关回归共 32 项通过。日志为 `build/dialog-actions-tests.log`、`build/dialog-actions-windows-tests.log`、`build/dialog-workflow-regression.log`。
+- `QIODevice::read (QSslSocket): device not open` 尚未形成稳定复现,本轮未修改网络逻辑。代码中 Qt 网络请求由后台更新检查发起,翻译请求走 Python 客户端;目前不能将该网络警告判定为已解决。
+- 修复保留在当前工作区,已运行的程序需关闭后重新启动。远端同步本轮仍遇到代理连接错误,未推送。
diff --git a/docs/UI_UPGRADE_PLAN_2026-11-06.md b/docs/UI_UPGRADE_PLAN_2026-11-06.md
index 48a0d12..2bbd2e7 100644
--- a/docs/UI_UPGRADE_PLAN_2026-11-06.md
+++ b/docs/UI_UPGRADE_PLAN_2026-11-06.md
@@ -6,6 +6,13 @@
## 进度(2026-11-06)
+- [x] 2026-11-23:整合 2.6.0 安装包、术语库、试译、全书译稿和 CBZ 工作流。浅色与深色分别完成 1440 / 1024 / 820 截图检查,字体为 Source Han Sans SC。发布包附 SHA-256,未签名版本手动更新。
+
+- [x] 2026-11-23:启动时比较客户端版本与 GitHub 正式发布标签。发现更高版本时,在模型状态左侧显示「有更新」,点击查看版本详情。
+
+- [x] 启动时异步查询 GitHub 正式发行版,发现新版后用中 / 英 / 日文提示。Windows 安装版可确认下载更新,支持同格式安装包的增量差分。[Windows 安装与更新](WINDOWS_INSTALLER.md)
+- [x] Windows 用户安装入口使用带 ComiTrans 图标的 NSIS 标准安装向导,包含欢迎、安装目录、进度和完成页。Setup 支持对应格式的增量更新。[Windows 安装与更新](WINDOWS_INSTALLER.md)
+
- [x] 翻译偏好新增「保留上下文缓存」:只控制跨任务沿用,说明上下文始终参与翻译、缓存始终保存;开启时勾选并锁定断点续传,关闭时恢复续传选项可编辑。英文、日文文案同步;核心翻译与分叉并行由模型分支实现。
- 2026-11-16 验收:473 项全量测试通过;修正窄窗偏好面板父容器裁切后,93 项 UI 回归通过(包含桌面、实时预览、大编辑器、缓存偏好、语言与主题)。`scripts/review_ui.py --context-only` 完成中 / 英 / 日 × 浅色 / 深色 × 1440 / 1024 / 820 的 36 张缓存选项截图,检查勾选锁定、文案宽度、提示换行及所有祖先容器的裁切边界,中英文字体为 Microsoft YaHei UI,日文为项目白名单内的 Yu Gothic。前后截图保存在本地 `tmp/context-ui-review/before-{light,dark}/` 与 `tmp/context-ui-review/{zh-CN,en,ja}-{light,dark}-final/`;全量与回归日志分别为 `tmp/context-ui-full-tests.log`、`tmp/context-ui-final-regression.log`。
@@ -41,6 +48,14 @@
- [x] 精修文字支持横向 / 纵向拉伸(10–400%)、旋转(±180°)和重置;描边大小支持自动 / 0–30 px,并提供「白字黑边竖排」示例预设。变形仅作用于用户编辑的文字图层,自动排版默认结果保持一致。
- 2026-11-14 验收:448 项单测通过;`scripts/review_ui.py` 浅色 / 深色各 52 张截图(含 1440 / 1024 / 820),新增控件可见与滚动边界文字完整性断言通过,字体为白名单内的 Microsoft YaHei UI。
- [x] 翻译页工作流拓扑可视化:将原有单线 7 步条升级为与真实 Fork-Join 流水线对应的有向工作流画布(`读取 → 检测 → OCR → [按序翻译 ∥ 后台修补] → 排版 → 保存 / PDF`),展示并发在途页角标、修补就绪标记、上下文累计与续传页数,附底部逐页状态矩阵及悬停明细,适配纸白 / 夜墨双主题与 66px 紧凑高度;481 项全量测试及双主题截图门禁通过(随 v2.5.2 发布)。
+- [x] Windows 安装器改为 NSIS Modern UI 2 标准向导,支持中 / 英 / 日、目录选择、原生进度、快捷方式、文件关联与卸载。移除定制动画和 Burn 扩展。
+ - 2026-11-21:重新构建 v2.6.0;旧 MSI 版切换前须先卸载,用户数据保留。
+ - 2026-11-21 修复:目录校验支持不存在的多级路径,自动创建 ComiTrans 子目录;服务配置改用 Windows SCM 接口,修复 sc.exe 引号解析导致的 1639。真实 NSIS 引擎的隔离回归覆盖新建中文目录、已有父目录、显式目录、重复安装、服务参数和卸载保留用户文件。
+ - 2026-11-21 修复:内置模型设置保存为相对路径,旧安装目录的失效模型路径自动迁移;完整安装器默认包含所有默认管线模型,打包前校验清单,避免用户再下载模型包。
+- [x] 页面栏新增「全书译稿」,可跨页搜索原文与译文、跳转到气泡、预览批量替换,并按页保存更新后的译图和布局。
+- [x] 精修页新增单气泡重译,可校正 OCR,填写本次翻译要求,并对比同一位置的新旧译文。确认后把候选译文应用到当前草稿。
+- [x] 自动处理按页码顺序读取 CBZ,支持断点续传和带精修资料的译文 CBZ。精修页可以把保存后的页面重新打包为 CBZ。
+ - 2026-11-21 通过 491 项全量测试。在纸白和夜墨下分别检查 1440、1024、820 px 窗口,字体均为 Source Han Sans SC。专项覆盖跨页替换、保存中断、候选预览时保留原稿、CBZ 页序与像素、续传、重开和再次导出。
---
@@ -565,3 +580,18 @@ class ViewState:
> 执行顺序以 `AGENTS.md` §7 为准:P0-0 → P0-2 → P0-1 → P1-1 → P1-2。
> 备注:本计划基于代码与截图核对,未在真实长篇 PDF 项目上跑完整流程;§11 的人工验收需要在有实际译稿的机器上补测。
+
+## 2026-11-22 · 校对工作流补充
+
+- [x] 气泡多选:列表 Ctrl/Shift 多选、画布 Ctrl 点击和 Shift 框选;批量排版仅同步实际修改的样式属性,译文与几何位置保持独立。
+- [x] 样式刷:复制字体与排版样式、点击/框选应用、Esc 退出、样式撤销;不改已还原原图的气泡。
+- [x] 作品术语库:按作品保存固定译名、可选类型和识别线索,无需填写原文,由翻译 AI 在上下文中匹配。
+- [x] 试译:队列开头 1–3 页,PDF 按页计数,结果、上下文与断点单独保存;报告可进入精修或启动完整任务。
+- [x] 翻译消耗:统计接口报告的输入/输出 token,包括返回无效内容后的重试响应;未报告用量时明确显示未知。按当前接口与模型保存用户填写的单价,基于样页粗估整本费用与时间。
+- [x] 断点兼容:单价和未启用作品的术语编辑不触发重新翻译;当前生效术语改变时才更新翻译配置指纹,未启用新功能的旧任务仍可续传。
+- [x] 界面密度评估:[评估与后续菜单分组建议](UI_MENU_ASSESSMENT_2026-11-22.md)。
+- [x] 菜单布局合并与新功能适配:已按后续要求合入 `feat/ui-menu-layout`,新样式操作接入气泡菜单,术语与消耗接入任务菜单;交接见 [菜单布局交接](UI_MENU_LAYOUT_HANDOFF_2026-11-22.md)。
+- [x] 偏好面板人工反馈修复:涟漪与焦点层在原生 QWidget 构造前初始化绘制状态;补充构造重入和真实点击快速开合回归,覆盖浅/深色与 Windows 原生平台。
+- [x] 工作流弹窗人工反馈修复:试译、术语与消耗的返回值统一使用 `QDialog.DialogCode.Accepted`;真实弹窗验证确认、取消、保存与跳转,覆盖 Windows 原生平台。
+
+新功能的费用只覆盖翻译 API 的已报告用量,不含字体探测;估算并非服务商账单。PDF 试译隔离使用本地五页测试文档验证,真实长篇作品仍需人工体验验收。
diff --git a/docs/WINDOWS_INSTALLER.md b/docs/WINDOWS_INSTALLER.md
new file mode 100644
index 0000000..9593fb0
--- /dev/null
+++ b/docs/WINDOWS_INSTALLER.md
@@ -0,0 +1,34 @@
+# Windows 安装与更新
+
+从 GitHub Releases 下载 `ComiTrans-v<版本>-x64-Setup.exe` 并双击,按 NSIS 标准向导完成「欢迎 → 选择安装目录 → 安装进度 → 完成」。安装需要管理员授权,支持简体中文、繁体中文、英文和日文,语言跟随 Windows。安装器使用系统控件和 ComiTrans 图标。
+
+完整版 Setup 默认包含检测、CharSpot 日语 OCR、韩语 / 英语 OCR 和修补模型,安装后无需另下模型包。程序和模型一起安装,默认目录为 `%ProgramFiles%\ComiTrans`,可在目录页输入或浏览本地安装位置;安装程序自动创建 `ComiTrans` 子文件夹,已选中同名文件夹时直接使用。新建的多级目录和中文路径均受支持。开始菜单和桌面会创建快捷方式,「已安装的应用」提供卸载入口。双击 `.comitrans` 项目索引可进入 PDF 精修。更新检查服务固定安装在 `%ProgramFiles%\ComiTrans Release Service`。
+
+每个 Windows 用户的配置、自定义模型、导入字体、日志、默认输出与下载的更新存放在 `%LOCALAPPDATA%\ComiTrans`,卸载保留这些数据。卸载按安装包的文件清单删除程序,保留安装目录中的其他文件。同一 NSIS 安装可直接覆盖更新或重新安装,沿用原目录;更换目录前请先卸载。内置模型在配置中保存为 `models/...` 相对路径,启动时根据当前安装目录解析;旧版保存的失效安装目录路径自动迁移,用户选择的外部自定义模型路径会保留。旧 MSI / WiX Setup 版须先从 Windows 设置卸载,再安装 NSIS 版,避免两套卸载记录相互覆盖。
+
+从历史 ZIP 版迁移时,关闭旧版,并将 `config.yaml`、`user_fonts` 和 `comic-translate-ai\models` 复制到 `%LOCALAPPDATA%\ComiTrans` 对应位置。可同时复制 `gpu-runtime` 和默认输出目录 `page`。如果曾将设置写成指向旧目录的绝对路径,在新版设置中更新路径。把 PDF、索引和精修资料目录一起保留,旧 `.comitrans.json` 索引仍可通过导入对应 PDF 读取。
+
+每次启动在后台查询 GitHub 的最新正式版。安装版优先通过 `ComiTransReleaseCheck` 服务查询,服务不可用时应用直接查询。无签名新版和预发布版需要从 GitHub 手动下载。签名版发布时,维护者可将已签名的 Setup 在 GitHub 标记为 `SignPath Foundation signed`,启用应用内更新;应用在执行前仍验证 SHA-256 和 Windows Authenticode 签名。符合条件时使用差分包,否则下载完整版。
+
+静默安装使用 NSIS 的 `/S`(区分大小写);`/D=` 必须放在命令最后,目录不加引号。首次安装时自动补上 `ComiTrans` 子目录,已安装版本沿用原目录。省略 `/D=` 时沿用现有目录或默认目录。`/LOG=` 指定 UTF-16LE 安装摘要日志,默认 `%TEMP%\ComiTrans-install.log`。兼容现有应用内更新使用的 `/quiet /norestart /log "路径"`,安装器不会主动重启系统。NSIS 不提供 MSI 事务回滚;失败后可重新安装或通过 Windows 设置卸载。若遇到旧版 NSIS 安装器的服务配置错误(1639),直接用修复版重新安装到原目录即可,无需删除用户数据。服务的创建、配置、启动和删除直接调用 Windows 服务接口,日志会记录失败操作与错误码。
+
+```powershell
+.\ComiTrans-v2.6.0-x64-Setup.exe /S /LOG="D:\install.log" /D=D:\Apps\ComiTrans
+& 'D:\Apps\ComiTrans\Uninstall.exe' /S
+```
+
+## 构建与签名
+
+安装 [NSIS 3.13](https://nsis.sourceforge.io/Download),按 README 构建主程序,然后运行:
+
+```powershell
+.\.venv\Scripts\python.exe installer/build.py --include-models
+# 编译器不在 PATH 时:
+.\.venv\Scripts\python.exe installer/build.py --makensis 'C:\Program Files (x86)\NSIS\makensis.exe' --include-models
+```
+
+构建只需 NSIS 和 Windows 自带的 .NET Framework C# 编译器,不再依赖 WiX、.NET SDK 或 C++ 编译器。版本取自 `comic_translate_desktop/__init__.py`;需要同版的 `docs/RELEASE-v<版本>.md`。`--stage-only` 先生成 payload 和卸载程序,`--payload <目录>` 使用已暂存或签名的文件构建 Setup。卸载程序通过 NSIS `!uninstfinalize` 在编译时导出,不运行安装器来生成。
+
+维护者创建与版本一致的 tag 后,手动运行 `Build and sign Windows installer`。工作流先签名应用、服务和卸载程序,再嵌入这些文件生成并签名最终 Setup;验证信任链、时间戳,并在干净 Windows runner 上测试自定义中文目录、重复安装、更新检查服务、快捷方式、文件关联、卸载和用户数据保留。填写上一版签名 Setup 的版本时,也检查升级或旧 MSI 迁移路径,并尝试生成节省至少 10% 下载量的差分包。发布完整 Setup、差分(如有)和 `SHA256SUMS.txt`;用户直接运行 Setup 即可,无需额外模型包。构建阶段会校验默认模型是否齐全,缺少模型时停止生成安装器。
+
+免费签名需项目所有者申请并获批。将 [应用与卸载程序签名规则](../installer/signpath.xml) 和 [Setup 签名规则](../installer/signpath-setup.xml) 分别导入 SignPath 的 `windows-payload` 和 `windows-setup` 制品配置;为 `windows-release-signing` 环境配置 `SIGNPATH_API_TOKEN`、`SIGNPATH_ORGANIZATION_ID`、`SIGNPATH_PROJECT_SLUG` 和 `SIGNPATH_SIGNING_POLICY_SLUG`。本地构建没有发布签名。[SignPath 申请条件](https://signpath.org/terms)
diff --git a/docs/ui-review/release-260-dark.png b/docs/ui-review/release-260-dark.png
new file mode 100644
index 0000000..f68af6c
Binary files /dev/null and b/docs/ui-review/release-260-dark.png differ
diff --git a/docs/ui-review/release-260-light.png b/docs/ui-review/release-260-light.png
new file mode 100644
index 0000000..6d0676e
Binary files /dev/null and b/docs/ui-review/release-260-light.png differ
diff --git a/installer/ComiTrans.nsi b/installer/ComiTrans.nsi
new file mode 100644
index 0000000..80c50a5
--- /dev/null
+++ b/installer/ComiTrans.nsi
@@ -0,0 +1,481 @@
+; -*- coding: utf-8 -*-
+; Standard NSIS wizard. No custom drawing, animation, or bootstrapper.
+Unicode True
+!include "MUI2.nsh"
+!include "FileFunc.nsh"
+!include "WordFunc.nsh"
+!include "LogicLib.nsh"
+!include "x64.nsh"
+
+Name "ComiTrans ${VERSION}"
+OutFile "${OUTPUT}"
+InstallDir "$PROGRAMFILES64\ComiTrans"
+RequestExecutionLevel admin
+!ifdef GENERATE_UNINSTALLER
+; NSIS exports the final uninstaller at compile time for optional external signing.
+!uninstfinalize 'cmd /D /C copy /Y "%1" "${UNINSTALLER_OUT}" >nul' = 0
+!endif
+ManifestDPIAware True
+SetCompressor zlib
+ShowInstDetails show
+ShowUninstDetails show
+VIProductVersion "${VERSION}.0"
+VIAddVersionKey /LANG=1033 "ProductName" "ComiTrans"
+VIAddVersionKey /LANG=1033 "ProductVersion" "${VERSION}"
+VIAddVersionKey /LANG=1033 "FileVersion" "${VERSION}.0"
+VIAddVersionKey /LANG=1033 "FileDescription" "ComiTrans Setup"
+VIAddVersionKey /LANG=1033 "LegalCopyright" "ComiTrans contributors"
+
+!define INSTALL_KEY "Software\ComiTrans\Installer"
+!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\ComiTrans"
+!define SERVICE_NAME "ComiTransReleaseCheck"
+!define SERVICE_DIR "$PROGRAMFILES64\ComiTrans Release Service"
+!define MUI_ICON "${ICON}"
+!define MUI_UNICON "${ICON}"
+!define MUI_ABORTWARNING
+!ifndef GENERATE_UNINSTALLER
+!insertmacro MUI_PAGE_WELCOME
+!define MUI_DIRECTORYPAGE_TEXT_TOP "$(DirectoryHelp)"
+!define MUI_PAGE_CUSTOMFUNCTION_LEAVE VerifyDirectory
+!insertmacro MUI_PAGE_DIRECTORY
+!insertmacro MUI_PAGE_INSTFILES
+!insertmacro MUI_PAGE_FINISH
+!else
+!insertmacro MUI_UNPAGE_CONFIRM
+!insertmacro MUI_UNPAGE_INSTFILES
+!insertmacro MUI_UNPAGE_FINISH
+!endif
+!insertmacro MUI_LANGUAGE "English"
+!insertmacro MUI_LANGUAGE "SimpChinese"
+!insertmacro MUI_LANGUAGE "TradChinese"
+!insertmacro MUI_LANGUAGE "Japanese"
+!include "${LOCALIZATION}"
+
+Var Parameters
+!ifndef GENERATE_UNINSTALLER
+Var PreviousDirectory
+!endif
+Var LogFile
+Var LogHandle
+Var SetupMutex
+
+!macro Trace TEXT
+ DetailPrint "${TEXT}"
+ FileOpen $LogHandle $LogFile a
+ FileSeek $LogHandle 0 END
+ FileWriteUTF16LE $LogHandle "${TEXT}$\r$\n"
+ FileClose $LogHandle
+!macroend
+
+!macro Fail STRING
+ !insertmacro Trace "ERROR: ${STRING}"
+ MessageBox MB_OK|MB_ICONSTOP "${STRING}" /SD IDOK
+ SetErrorLevel 2
+ Abort
+!macroend
+
+; Compile the same initialization and service-stop code into both programs.
+!macro CommonFunctions PREFIX
+Function ${PREFIX}Initialize
+ SetRegView 64
+ SetShellVarContext all
+ ${GetParameters} $Parameters
+ ClearErrors
+ ${GetOptions} $Parameters "/quiet" $0
+ ${IfNot} ${Errors}
+ SetSilent silent
+ ${EndIf}
+ StrCpy $LogFile "$TEMP\ComiTrans-install.log"
+ ${GetOptions} $Parameters "/log " $0
+ ${If} $0 != ""
+ StrCpy $LogFile $0
+ ${EndIf}
+ ${GetOptions} $Parameters "/LOG=" $0
+ ${If} $0 != ""
+ StrCpy $LogFile $0
+ ${EndIf}
+ ${GetOptions} $Parameters "/LANG=" $0
+ ${If} $0 != ""
+ StrCpy $LANGUAGE $0
+ ${EndIf}
+ System::Call 'kernel32::CreateMutexW(p 0, i 0, w "Global\ComiTransSetup") p.s ?e'
+ Pop $0
+ Pop $SetupMutex
+ ${If} $0 = 183
+ ${OrIf} $SetupMutex = 0
+ !insertmacro Fail "$(AlreadyRunning)"
+ ${EndIf}
+FunctionEnd
+
+Function ${PREFIX}CheckApplicationClosed
+ IfFileExists "$INSTDIR\ComiTrans.exe" 0 done
+ System::Call 'kernel32::CreateFileW(w "$INSTDIR\ComiTrans.exe", i 0x40000000, i 7, p 0, i 3, i 0x80, p 0) p.r0'
+ ${If} $0 = -1
+ !insertmacro Fail "$(CloseApplication)"
+ ${EndIf}
+ System::Call 'kernel32::CloseHandle(p r0)'
+ done:
+FunctionEnd
+
+Function ${PREFIX}StopReleaseService
+ System::Call 'advapi32::OpenSCManagerW(p 0, p 0, i 1) p.r0'
+ ${If} $0 = 0
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ System::Call 'advapi32::OpenServiceW(p r0, w "${SERVICE_NAME}", i 0x24) p.r1 ?e'
+ Pop $2
+ System::Call 'advapi32::CloseServiceHandle(p r0)'
+ ${If} $1 = 0
+ ${If} $2 = 1060
+ Return
+ ${EndIf}
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ System::Alloc 36
+ Pop $2
+ System::Call 'advapi32::ControlService(p r1, i 1, p r2)'
+ StrCpy $5 0
+ ${Do}
+ System::Call 'advapi32::QueryServiceStatus(p r1, p r2) i.r3'
+ ${If} $3 = 0
+ StrCpy $4 0
+ ${Break}
+ ${EndIf}
+ System::Call '*$2(i .r3, i .r4)'
+ ${If} $4 = 1
+ ${Break}
+ ${EndIf}
+ Sleep 500
+ IntOp $5 $5 + 1
+ ${LoopUntil} $5 >= 30
+ System::Free $2
+ System::Call 'advapi32::CloseServiceHandle(p r1)'
+ ${If} $4 != 1
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+FunctionEnd
+!macroend
+!ifndef GENERATE_UNINSTALLER
+!insertmacro CommonFunctions ""
+
+Function ConfigureAndStartReleaseService
+ ; Pass a quoted executable path directly to SCM, without command-line parsing.
+ StrCpy $7 '$\"${SERVICE_DIR}\ComiTransReleaseService.exe$\"'
+ StrCpy $6 "NT AUTHORITY\LocalService"
+ System::Call 'advapi32::OpenSCManagerW(p 0, p 0, i 3) p.r0 ?e'
+ Pop $8
+ ${If} $0 = 0
+ !insertmacro Trace "Open service manager: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ System::Call 'advapi32::OpenServiceW(p r0, w "${SERVICE_NAME}", i 0x16) p.r1 ?e'
+ Pop $8
+ ${If} $1 = 0
+ ${If} $8 != 1060
+ System::Call 'advapi32::CloseServiceHandle(p r0)'
+ !insertmacro Trace "Open service: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ System::Call 'advapi32::CreateServiceW(p r0, w "${SERVICE_NAME}", w "ComiTrans Release Check", i 0x16, i 0x10, i 2, i 1, w r7, p 0, p 0, p 0, w r6, p 0) p.r1 ?e'
+ Pop $8
+ System::Call 'advapi32::CloseServiceHandle(p r0)'
+ ${If} $1 = 0
+ !insertmacro Trace "Create service: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ ${Else}
+ System::Call 'advapi32::ChangeServiceConfigW(p r1, i 0x10, i 2, i 1, w r7, p 0, p 0, p 0, w r6, p 0, w "ComiTrans Release Check") i.r3 ?e'
+ Pop $8
+ System::Call 'advapi32::CloseServiceHandle(p r0)'
+ ${If} $3 = 0
+ System::Call 'advapi32::CloseServiceHandle(p r1)'
+ !insertmacro Trace "Configure service: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ ${EndIf}
+ System::Call 'advapi32::StartServiceW(p r1, i 0, p 0) i.r3 ?e'
+ Pop $8
+ ${If} $3 = 0
+ ${AndIf} $8 != 1056
+ System::Call 'advapi32::CloseServiceHandle(p r1)'
+ !insertmacro Trace "Start service: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ System::Alloc 36
+ Pop $2
+ StrCpy $5 0
+ ${Do}
+ System::Call 'advapi32::QueryServiceStatus(p r1, p r2) i.r3 ?e'
+ Pop $8
+ ${If} $3 = 0
+ StrCpy $4 0
+ ${Break}
+ ${EndIf}
+ System::Call '*$2(i .r3, i .r4)'
+ ${If} $4 != 2
+ ${Break}
+ ${EndIf}
+ Sleep 500
+ IntOp $5 $5 + 1
+ ${LoopUntil} $5 >= 30
+ System::Free $2
+ System::Call 'advapi32::CloseServiceHandle(p r1)'
+ ${If} $4 != 4
+ !insertmacro Trace "Service startup failed: state=$4, error=$8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ !insertmacro Trace "Release service configured and running"
+FunctionEnd
+!else
+!insertmacro CommonFunctions "un."
+!endif
+
+Function .onInit
+!ifdef GENERATE_UNINSTALLER
+ ; Build-time helper only; it never installs files or touches the registry.
+ WriteUninstaller "${UNINSTALLER_OUT}"
+ SetErrorLevel 0
+ Quit
+!else
+ Call Initialize
+ ${IfNot} ${RunningX64}
+ !insertmacro Fail "$(Require64Bit)"
+ ${EndIf}
+ ReadRegStr $PreviousDirectory HKLM "${INSTALL_KEY}" "InstallDir"
+ ${If} $PreviousDirectory != ""
+ ReadRegStr $0 HKLM "${INSTALL_KEY}" "InstallerType"
+ ${If} $0 != "NSIS"
+ !insertmacro Fail "$(LegacyInstaller)"
+ ${EndIf}
+ ReadRegStr $0 HKLM "${INSTALL_KEY}" "Version"
+ ${VersionCompare} $0 "${VERSION}" $1
+ ${If} $1 = 1
+ !insertmacro Fail "$(NewerInstalled)"
+ ${EndIf}
+ ; /D still takes precedence (NSIS applies it after .onInit).
+ StrCpy $INSTDIR $PreviousDirectory
+ ${EndIf}
+ !insertmacro Trace "ComiTrans ${VERSION} NSIS setup started"
+!endif
+FunctionEnd
+
+!ifndef GENERATE_UNINSTALLER
+Function NormalizeDirectory
+ ; NSIS GetFullPathName rejects missing parent folders; the Win32 API does not.
+ System::Call 'kernel32::GetFullPathNameW(w "$INSTDIR", i ${NSIS_MAX_STRLEN}, w .r9, p 0) i.r8'
+ ${If} $8 = 0
+ ${OrIf} $8 >= ${NSIS_MAX_STRLEN}
+ !insertmacro Fail "$(InvalidDirectory)"
+ ${EndIf}
+ StrCpy $INSTDIR $9
+ ${Do}
+ StrLen $8 $INSTDIR
+ StrCpy $9 $INSTDIR 1 -1
+ ${If} $8 <= 3
+ ${OrIf} $9 != "\"
+ ${Break}
+ ${EndIf}
+ StrCpy $INSTDIR $INSTDIR -1
+ ${Loop}
+FunctionEnd
+
+Function VerifyDirectory
+ Call NormalizeDirectory
+ !insertmacro Trace "Selected folder: $INSTDIR"
+ StrLen $0 $WINDIR
+ IntOp $0 $0 + 1
+ StrCpy $1 $INSTDIR $0
+ ${If} $INSTDIR == $WINDIR
+ ${OrIf} $1 == "$WINDIR\"
+ ${OrIf} $INSTDIR == "${SERVICE_DIR}"
+ !insertmacro Fail "$(InvalidDirectory)"
+ ${EndIf}
+ ; Browsing to a parent folder or drive creates an application subfolder.
+ ; Preserve older NSIS installations that used a differently named folder.
+ ${If} $INSTDIR != $PreviousDirectory
+ ${GetFileName} $INSTDIR $0
+ ${If} $0 != "ComiTrans"
+ StrCpy $INSTDIR "$INSTDIR\ComiTrans"
+ Call NormalizeDirectory
+ ${EndIf}
+ ${EndIf}
+ ${If} $PreviousDirectory != ""
+ ${If} $INSTDIR != $PreviousDirectory
+ !insertmacro Fail "$(KeepDirectory)"
+ ${EndIf}
+ Return
+ ${EndIf}
+ ${GetRoot} $INSTDIR $0
+ StrLen $1 $0
+ !insertmacro Trace "Resolved installation folder: $INSTDIR (root=$0)"
+ ${If} $1 != 2
+ ${OrIf} $INSTDIR == "$0\"
+ ${OrIf} $INSTDIR == $WINDIR
+ ${OrIf} $INSTDIR == $SYSDIR
+ ${OrIf} $INSTDIR == $PROGRAMFILES64
+ ${OrIf} $INSTDIR == $PROGRAMFILES32
+ ${OrIf} $INSTDIR == "${SERVICE_DIR}"
+ !insertmacro Fail "$(InvalidDirectory)"
+ ${EndIf}
+ ; A new installation must not take ownership of unrelated files.
+ ; FindFirst leaves the filename unchanged when the directory does not exist.
+ StrCpy $1 ""
+ FindFirst $0 $1 "$INSTDIR\*"
+ ${DoWhile} $1 != ""
+ ${If} $1 != "."
+ ${AndIf} $1 != ".."
+ FindClose $0
+ !insertmacro Fail "$(InvalidDirectory)"
+ ${EndIf}
+ FindNext $0 $1
+ ${Loop}
+ FindClose $0
+FunctionEnd
+!endif
+
+Function .onInstFailed
+ !insertmacro Trace "$(InstallError)"
+ SetErrorLevel 2
+FunctionEnd
+
+Section "ComiTrans" MainSection
+!ifndef GENERATE_UNINSTALLER
+ Call VerifyDirectory
+ Call CheckApplicationClosed
+ Call StopReleaseService
+ !insertmacro Trace "Installing application to $INSTDIR"
+ ClearErrors
+ CreateDirectory "$INSTDIR"
+ ${If} ${Errors}
+ !insertmacro Trace "Creating installation folder failed"
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ SetOutPath "$INSTDIR"
+ SetOverwrite on
+ ClearErrors
+ File "${PAYLOAD}\Uninstall.exe"
+ ${If} ${Errors}
+ !insertmacro Trace "Writing uninstaller failed"
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ ; Register the uninstall entry before extraction so an interrupted install
+ ; can be retried or removed through Windows Settings.
+ WriteRegStr HKLM "${INSTALL_KEY}" "InstallDir" "$INSTDIR"
+ WriteRegStr HKLM "${INSTALL_KEY}" "Version" "${VERSION}"
+ WriteRegStr HKLM "${INSTALL_KEY}" "ProductCode" "NSIS"
+ WriteRegStr HKLM "${INSTALL_KEY}" "InstallerType" "NSIS"
+ WriteRegStr HKLM "${INSTALL_KEY}" "SetupManaged" "1"
+ WriteRegStr HKLM "${INSTALL_KEY}" "SetupSource" "$EXEPATH"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayName" "ComiTrans"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "Publisher" "ComiTrans"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\ComiTrans.exe,0"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "UninstallString" '$\"$INSTDIR\Uninstall.exe$\"'
+ WriteRegStr HKLM "${UNINSTALL_KEY}" "QuietUninstallString" '$\"$INSTDIR\Uninstall.exe$\" /S'
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoModify" 1
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoRepair" 1
+ ${If} ${Errors}
+ !insertmacro Trace "Writing uninstall registration failed"
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ ClearErrors
+ File /r /x ComiTransReleaseService.exe /x Uninstall.exe "${PAYLOAD}\*"
+ ${If} ${Errors}
+ !insertmacro Trace "Extracting application files failed"
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ SetOutPath "${SERVICE_DIR}"
+ ClearErrors
+ File "${PAYLOAD}\ComiTransReleaseService.exe"
+ ${If} ${Errors}
+ !insertmacro Trace "Writing service binary failed"
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ Call ConfigureAndStartReleaseService
+ SetOutPath "$INSTDIR"
+ CreateShortcut "$SMPROGRAMS\ComiTrans.lnk" "$INSTDIR\ComiTrans.exe"
+ CreateShortcut "$DESKTOP\ComiTrans.lnk" "$INSTDIR\ComiTrans.exe"
+ ReadRegStr $0 HKLM "Software\Classes\.comitrans" ""
+ ClearErrors
+ ${If} $0 != "ComiTrans.PdfProject"
+ WriteRegStr HKLM "${INSTALL_KEY}" "PreviousAssociation" "$0"
+ ${EndIf}
+ WriteRegStr HKLM "Software\Classes\.comitrans" "" "ComiTrans.PdfProject"
+ WriteRegStr HKLM "Software\Classes\.comitrans\OpenWithProgids" "ComiTrans.PdfProject" ""
+ WriteRegStr HKLM "Software\Classes\ComiTrans.PdfProject" "" "ComiTrans PDF Project"
+ WriteRegStr HKLM "Software\Classes\ComiTrans.PdfProject\DefaultIcon" "" '$\"$INSTDIR\ComiTrans.exe$\",0'
+ WriteRegStr HKLM "Software\Classes\ComiTrans.PdfProject\shell\open\command" "" '$\"$INSTDIR\ComiTrans.exe$\" $\"%1$\"'
+ ${If} ${Errors}
+ !insertmacro Fail "$(InstallError)"
+ ${EndIf}
+ ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
+ WriteRegDWORD HKLM "${UNINSTALL_KEY}" "EstimatedSize" $0
+ System::Call 'shell32::SHChangeNotify(i 0x08000000, i 0, p 0, p 0)'
+ !insertmacro Trace "Installation completed: ${VERSION}"
+ SetErrorLevel 0
+!endif
+SectionEnd
+
+!ifdef GENERATE_UNINSTALLER
+Function un.onInit
+ Call un.Initialize
+ ReadRegStr $0 HKLM "${INSTALL_KEY}" "InstallerType"
+ ReadRegStr $1 HKLM "${INSTALL_KEY}" "InstallDir"
+ ${If} $0 != "NSIS"
+ ${OrIf} $1 != $INSTDIR
+ !insertmacro Fail "$(InvalidUninstall)"
+ ${EndIf}
+FunctionEnd
+
+Section "Uninstall"
+ Call un.CheckApplicationClosed
+ Call un.StopReleaseService
+ System::Call 'advapi32::OpenSCManagerW(p 0, p 0, i 1) p.r0'
+ System::Call 'advapi32::OpenServiceW(p r0, w "${SERVICE_NAME}", i 0x10000) p.r1 ?e'
+ Pop $8
+ System::Call 'advapi32::CloseServiceHandle(p r0)'
+ ${If} $1 != 0
+ System::Call 'advapi32::DeleteService(p r1) i.r3 ?e'
+ Pop $8
+ System::Call 'advapi32::CloseServiceHandle(p r1)'
+ ${If} $3 = 0
+ !insertmacro Trace "Delete service: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ ${ElseIf} $8 != 1060
+ !insertmacro Trace "Open service for deletion: $8"
+ !insertmacro Fail "$(ServiceError)"
+ ${EndIf}
+ SetOutPath "$TEMP"
+ Delete "${SERVICE_DIR}\ComiTransReleaseService.exe"
+ RMDir "${SERVICE_DIR}"
+ !include "${UNINSTALL_FILES}"
+ Delete "$INSTDIR\Uninstall.exe"
+ RMDir "$INSTDIR"
+ Delete "$SMPROGRAMS\ComiTrans.lnk"
+ Delete "$DESKTOP\ComiTrans.lnk"
+ ReadRegStr $0 HKLM "Software\Classes\.comitrans" ""
+ ${If} $0 == "ComiTrans.PdfProject"
+ ReadRegStr $0 HKLM "${INSTALL_KEY}" "PreviousAssociation"
+ ${If} $0 == ""
+ DeleteRegValue HKLM "Software\Classes\.comitrans" ""
+ ${Else}
+ WriteRegStr HKLM "Software\Classes\.comitrans" "" "$0"
+ ${EndIf}
+ ${EndIf}
+ DeleteRegValue HKLM "Software\Classes\.comitrans\OpenWithProgids" "ComiTrans.PdfProject"
+ DeleteRegKey /ifempty HKLM "Software\Classes\.comitrans\OpenWithProgids"
+ DeleteRegKey /ifempty HKLM "Software\Classes\.comitrans"
+ ReadRegStr $0 HKLM "Software\Classes\ComiTrans.PdfProject\shell\open\command" ""
+ ${If} $0 == '$\"$INSTDIR\ComiTrans.exe$\" $\"%1$\"'
+ DeleteRegKey HKLM "Software\Classes\ComiTrans.PdfProject"
+ ${EndIf}
+ DeleteRegKey HKLM "${UNINSTALL_KEY}"
+ DeleteRegKey HKLM "${INSTALL_KEY}"
+ DeleteRegKey /ifempty HKLM "Software\ComiTrans"
+ System::Call 'shell32::SHChangeNotify(i 0x08000000, i 0, p 0, p 0)'
+ !insertmacro Trace "Uninstallation completed; user data retained"
+ SetErrorLevel 0
+SectionEnd
+!endif
diff --git a/installer/ReleaseService.cs b/installer/ReleaseService.cs
new file mode 100644
index 0000000..2eb2195
--- /dev/null
+++ b/installer/ReleaseService.cs
@@ -0,0 +1,99 @@
+using System;
+using System.IO;
+using System.IO.Pipes;
+using System.Net;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using System.ServiceProcess;
+using System.Threading;
+
+internal sealed class ReleaseService : ServiceBase
+{
+ private const string PipeName = "ComiTrans.ReleaseCheck";
+ private const string ReleaseApi = "https://api.github.com/repos/Aaaaamadeus/ComiTrans/releases/latest";
+ private const int ResponseLimit = 512 * 1024;
+ private readonly ManualResetEvent stopped = new ManualResetEvent(false);
+ private Thread listener;
+
+ private ReleaseService() { ServiceName = "ComiTransReleaseCheck"; }
+
+ public static void Main()
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
+ Run(new ReleaseService());
+ }
+
+ protected override void OnStart(string[] args)
+ {
+ stopped.Reset();
+ listener = new Thread(Listen) { IsBackground = true };
+ listener.Start();
+ }
+
+ protected override void OnStop()
+ {
+ stopped.Set();
+ listener.Join(7000);
+ }
+
+ private void Listen()
+ {
+ var acl = new PipeSecurity();
+ var users = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
+ var network = new SecurityIdentifier(WellKnownSidType.NetworkSid, null);
+ var service = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null);
+ acl.AddAccessRule(new PipeAccessRule(network, PipeAccessRights.FullControl, AccessControlType.Deny));
+ acl.AddAccessRule(new PipeAccessRule(users, PipeAccessRights.Read, AccessControlType.Allow));
+ acl.AddAccessRule(new PipeAccessRule(service, PipeAccessRights.FullControl, AccessControlType.Allow));
+ while (!stopped.WaitOne(0))
+ {
+ try
+ {
+ using (var pipe = new NamedPipeServerStream(PipeName, PipeDirection.Out, 1,
+ PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, acl))
+ {
+ var pending = pipe.BeginWaitForConnection(null, null);
+ using (var ready = pending.AsyncWaitHandle)
+ {
+ if (WaitHandle.WaitAny(new[] { stopped, ready }) == 0) return;
+ pipe.EndWaitForConnection(pending);
+ }
+ var data = ReadRelease();
+ if (data.Length == 0) continue;
+ var write = pipe.BeginWrite(data, 0, data.Length, null, null);
+ using (var ready = write.AsyncWaitHandle)
+ {
+ if (WaitHandle.WaitAny(new[] { stopped, ready }, 1000) == 1) pipe.EndWrite(write);
+ }
+ }
+ }
+ catch (IOException) { stopped.WaitOne(250); }
+ catch (UnauthorizedAccessException) { stopped.WaitOne(1000); }
+ catch (WebException) { }
+ }
+ }
+
+ private static byte[] ReadRelease()
+ {
+ var request = (HttpWebRequest)WebRequest.Create(ReleaseApi);
+ request.UserAgent = "ComiTrans-ReleaseService";
+ request.Accept = "application/vnd.github+json";
+ request.AllowAutoRedirect = false;
+ request.Timeout = 4500;
+ request.ReadWriteTimeout = 1000;
+ using (var response = (HttpWebResponse)request.GetResponse())
+ using (var stream = response.GetResponseStream())
+ using (var output = new MemoryStream())
+ {
+ if (response.StatusCode != HttpStatusCode.OK || response.ContentLength > ResponseLimit) return new byte[0];
+ var buffer = new byte[8192];
+ int count;
+ while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ if (output.Length + count > ResponseLimit) return new byte[0];
+ output.Write(buffer, 0, count);
+ }
+ return output.ToArray();
+ }
+ }
+}
diff --git a/installer/Test-Setup.ps1 b/installer/Test-Setup.ps1
new file mode 100644
index 0000000..18b60d6
--- /dev/null
+++ b/installer/Test-Setup.ps1
@@ -0,0 +1,112 @@
+param(
+ [Parameter(Mandatory)][string]$Setup,
+ [Parameter(Mandatory)][string]$Version,
+ [Parameter(Mandatory)][string]$LogDirectory,
+ [string]$PreviousSetup
+)
+
+# Run only on a disposable Windows runner; this performs a real machine install.
+$ErrorActionPreference = 'Stop'
+$registrationPath = 'HKLM:\Software\ComiTrans\Installer'
+if ((Test-Path $registrationPath) -or (Get-Service ComiTransReleaseCheck -ErrorAction SilentlyContinue)) {
+ throw 'The Setup smoke test requires a fresh Windows runner.'
+}
+$installParent = Join-Path $LogDirectory 'ComiTrans 安装测试'
+$installDirectory = Join-Path $installParent 'ComiTrans'
+if (Test-Path -LiteralPath $installParent) { throw 'The smoke-test folder already exists.' }
+$userSentinel = Join-Path $env:LOCALAPPDATA 'ComiTrans\installer-smoke-sentinel.txt'
+if (Test-Path -LiteralPath $userSentinel) { throw 'The user-data sentinel already exists.' }
+New-Item -ItemType Directory -Force (Split-Path -Parent $userSentinel) | Out-Null
+Set-Content -LiteralPath $userSentinel -Value 'user data must survive'
+$installed = $false
+$legacyInstalled = $false
+$checkKeptFile = $false
+
+function Invoke-Installer($file, $arguments, $expected = 0) {
+ $process = Start-Process -FilePath $file -ArgumentList $arguments -WindowStyle Hidden -Wait -PassThru
+ if ($process.ExitCode -ne $expected) {
+ throw "Installer exited with $($process.ExitCode), expected $expected."
+ }
+}
+
+try {
+ if ($PreviousSetup) {
+ Invoke-Installer $PreviousSetup '/install /quiet /norestart'
+ $previous = Get-ItemProperty -LiteralPath $registrationPath
+ if ($previous.InstallerType -eq 'NSIS') {
+ $installed = $true
+ $installDirectory = $previous.InstallDir
+ $installParent = $installDirectory
+ } else {
+ $legacyInstalled = $true
+ # Refusing the incompatible MSI installation must leave it registered.
+ Invoke-Installer $Setup '/quiet /norestart' 2
+ if (!(Test-Path $registrationPath)) { throw 'MSI migration damaged the old registration.' }
+ Invoke-Installer $PreviousSetup '/uninstall /quiet /norestart'
+ $legacyInstalled = $false
+ if (Test-Path $registrationPath) { throw 'Legacy uninstall did not finish.' }
+ }
+ }
+ $log = Join-Path $LogDirectory 'comitrans-nsis-install.log'
+ $installed = $true # also clean up a partially registered installation on failure
+ Invoke-Installer $Setup ('/S /LOG="' + $log + '" /D=' + $installParent)
+ # Exercise the flags still used by existing installed app update clients.
+ Invoke-Installer $Setup ('/quiet /norestart /log "' + $log + '"')
+ $registration = Get-ItemProperty -LiteralPath $registrationPath
+ $app = Get-Item -LiteralPath (Join-Path $registration.InstallDir 'ComiTrans.exe')
+ if ($app.VersionInfo.ProductVersion -ne $Version -or $registration.Version -ne $Version) {
+ throw 'Installed application and Setup versions differ.'
+ }
+ if ($registration.InstallDir -ine $installDirectory -or $registration.InstallerType -ne 'NSIS' -or
+ $registration.SetupManaged -ne '1' -or $registration.SetupSource -ine $Setup) {
+ throw 'NSIS installation metadata or chosen directory is incorrect.'
+ }
+ if (!(Test-Path $log)) { throw 'The requested installation log is missing.' }
+ $smoke = Join-Path $LogDirectory 'comitrans-installed-smoke'
+ $env:QT_QPA_PLATFORM = 'offscreen'
+ $smokeProcess = Start-Process -FilePath $app.FullName -ArgumentList ('--smoke-test "' + $smoke + '"') -WindowStyle Hidden -PassThru
+ if (!$smokeProcess.WaitForExit(300000)) {
+ $smokeProcess.Kill()
+ throw 'Installed application smoke test timed out.'
+ }
+ $smokeReport = Get-Content (Join-Path $smoke 'smoke-result.json') -Raw | ConvertFrom-Json
+ if ($smokeProcess.ExitCode -ne 0 -or !$smokeReport.success -or $smokeReport.version -ne $Version) {
+ throw 'Installed application failed resource or model verification.'
+ }
+ if ((Get-Service ComiTransReleaseCheck).Status -ne 'Running') { throw 'Release service did not start.' }
+ $service = Get-CimInstance Win32_Service -Filter "Name='ComiTransReleaseCheck'"
+ $serviceExe = Join-Path $env:ProgramFiles 'ComiTrans Release Service\ComiTransReleaseService.exe'
+ if ($service.PathName -ine ('"' + $serviceExe + '"')) { throw 'Service is outside its protected directory.' }
+ $pipe = [IO.Pipes.NamedPipeClientStream]::new('.', 'ComiTrans.ReleaseCheck', [IO.Pipes.PipeDirection]::In)
+ try { $pipe.Connect(8000) } finally { $pipe.Dispose() }
+ $extension = Get-Item -LiteralPath 'HKLM:\Software\Classes\.comitrans'
+ if ($extension.GetValue('') -ne 'ComiTrans.PdfProject') { throw 'PDF project association missing.' }
+ foreach ($folder in 'CommonPrograms', 'CommonDesktopDirectory') {
+ if (!(Test-Path (Join-Path ([Environment]::GetFolderPath($folder)) 'ComiTrans.lnk'))) {
+ throw "Missing $folder shortcut."
+ }
+ }
+ # Uninstall should remove only packaged files, leaving these files alone.
+ Set-Content -LiteralPath (Join-Path $installDirectory 'keep-user-file.txt') -Value 'keep'
+ $checkKeptFile = $true
+} finally {
+ if ($legacyInstalled) { Invoke-Installer $PreviousSetup '/uninstall /quiet /norestart' }
+ if ($installed -and (Test-Path $registrationPath)) {
+ $registration = Get-ItemProperty -LiteralPath $registrationPath
+ $uninstall = Join-Path $registration.InstallDir 'Uninstall.exe'
+ Invoke-Installer $uninstall '/S'
+ for ($attempt = 0; $attempt -lt 20 -and (Test-Path $registrationPath); $attempt++) { Start-Sleep -Milliseconds 500 }
+ if ((Test-Path $registrationPath) -or (Get-Service ComiTransReleaseCheck -ErrorAction SilentlyContinue)) {
+ throw 'Uninstall left its registration or service behind.'
+ }
+ $kept = Join-Path $installDirectory 'keep-user-file.txt'
+ if ($checkKeptFile -and !(Test-Path -LiteralPath $kept)) { throw 'Uninstall deleted an unrelated file.' }
+ if (Test-Path -LiteralPath $kept) { Remove-Item -LiteralPath $kept }
+ if (Test-Path -LiteralPath $installDirectory) {
+ if (Get-ChildItem -LiteralPath $installDirectory -Force) { throw 'Uninstall left packaged files behind.' }
+ Remove-Item -LiteralPath $installDirectory
+ }
+ }
+ if (!(Test-Path -LiteralPath $userSentinel)) { throw 'Uninstall deleted user data.' }
+ Remove-Item -LiteralPath $userSentinel
+}
diff --git a/installer/build.py b/installer/build.py
new file mode 100644
index 0000000..8dd3d9d
--- /dev/null
+++ b/installer/build.py
@@ -0,0 +1,226 @@
+"""Build the ComiTrans Windows installer with NSIS Modern UI 2."""
+
+import argparse
+import json
+import mmap
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+from tempfile import TemporaryDirectory
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from comic_translate_core.release_update import (
+ DELTA_BLOCK_SIZE, DELTA_COPY, DELTA_FRAME, DELTA_LIMIT, DELTA_OVERLAP, SETUP_DELTA_BLOCK_SIZE,
+ VERSION, delta_name, installer_name,
+)
+from comic_translate_desktop import __version__
+from package_release import MODEL_ARCHIVE_PREFIX, MODEL_FILES, collect_app, collect_models, legacy_detector_entry
+
+ICON = ROOT / 'assets/ComiTrans.ico'
+
+
+def nsis_literal(value):
+ return str(value).replace('$', '$$').replace('"', '$\\"').replace('\n', '$\\r$\\n')
+
+
+def find_makensis(command):
+ candidates = [command, shutil.which('makensis')]
+ for folder in ('ProgramFiles(x86)', 'ProgramFiles'):
+ if folder in os.environ:
+ candidates.append(Path(os.environ[folder]) / 'NSIS/makensis.exe')
+ candidates.extend(sorted((ROOT / 'build/installer-native-tools').glob('nsis-*/makensis.exe'), reverse=True))
+ for candidate in candidates:
+ if candidate and Path(candidate).is_file():
+ return str(Path(candidate).resolve())
+ raise FileNotFoundError('Install NSIS 3 or pass --makensis PATH')
+
+
+def nsis_inputs(payload, work):
+ """Embed an explicit uninstall list; never recursively delete an installation directory."""
+ files = sorted(path.relative_to(payload) for path in payload.rglob('*') if path.is_file()
+ and path.name not in {'ComiTransReleaseService.exe', 'Uninstall.exe'})
+ directories = {parent for path in files for parent in path.parents if parent != Path('.')}
+ manifest = work / 'uninstall-files.nsh'
+ manifest.write_text('\n'.join(
+ [f'Delete "$INSTDIR\\{nsis_literal(path)}"' for path in files] +
+ [f'RMDir "$INSTDIR\\{nsis_literal(path)}"' for path in
+ sorted(directories, key=lambda path: (len(path.parts), str(path)), reverse=True)]
+ ) + '\n', encoding='utf-8-sig')
+ languages = {'en': 'ENGLISH', 'zh-CN': 'SIMPCHINESE', 'zh-TW': 'TRADCHINESE', 'ja': 'JAPANESE'}
+ strings = json.loads((ROOT / 'installer/nsis_strings.json').read_text('utf-8'))
+ if set(strings) != set(languages) or any(set(texts) != set(strings['en']) for texts in strings.values()):
+ raise ValueError('Installer languages must contain the same strings')
+ localization = work / 'languages.nsh'
+ localization.write_text('\n'.join(
+ f'LangString {key} ${{LANG_{languages[locale]}}} "{nsis_literal(value)}"'
+ for locale, texts in strings.items() for key, value in texts.items()
+ ) + '\n', encoding='utf-8-sig')
+ return manifest, localization
+
+
+def stage_app(dist, stage, *, include_models=True):
+ files = collect_app(dist, portable_tools=False)
+ if include_models:
+ files.extend((source, f'ComiTrans/_internal/comic-translate-ai/models/{name.removeprefix(MODEL_ARCHIVE_PREFIX)}')
+ for source, name in collect_models())
+ stage.mkdir(parents=True)
+ for source, archive_path in files:
+ target = stage / archive_path.removeprefix('ComiTrans/')
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source, target)
+ license_file = ROOT / 'LICENSE'
+ if license_file.is_file():
+ shutil.copyfile(license_file, stage / 'LICENSE')
+ compiler = Path(os.environ['SystemRoot']) / 'Microsoft.NET/Framework64/v4.0.30319/csc.exe'
+ version_file = stage.parent / f'{stage.name}-version.cs'
+ version_file.write_text(
+ f'[assembly: System.Reflection.AssemblyVersion("{__version__}.0")]\n'
+ '[assembly: System.Reflection.AssemblyProduct("ComiTrans")]\n'
+ f'[assembly: System.Reflection.AssemblyInformationalVersion("{__version__}")]\n',
+ encoding='ascii',
+ )
+ try:
+ subprocess.run([str(compiler), '/nologo', '/target:winexe', '/platform:x64', '/optimize+',
+ '/reference:System.ServiceProcess.dll', f'/out:{stage / "ComiTransReleaseService.exe"}',
+ str(ROOT / 'installer/ReleaseService.cs'), str(version_file)], check=True)
+ finally:
+ version_file.unlink()
+
+
+def compile_nsis(makensis, payload, work, output, **extra):
+ manifest, localization = nsis_inputs(payload, work)
+ defines = {'VERSION': __version__, 'PAYLOAD': payload, 'ICON': ICON, 'OUTPUT': output,
+ 'UNINSTALL_FILES': manifest, 'LOCALIZATION': localization, **extra}
+ command = [makensis, '/V2', '/WX', '/INPUTCHARSET', 'UTF8']
+ command.extend(f'/D{key}={nsis_literal(value)}' for key, value in defines.items())
+ command.append(str(ROOT / 'installer/ComiTrans.nsi'))
+ subprocess.run(command, check=True)
+
+
+def build_uninstaller(makensis, payload, work):
+ generator = work / 'write-uninstaller.exe'
+ target = payload / 'Uninstall.exe'
+ compile_nsis(makensis, payload, work, generator, GENERATE_UNINSTALLER='1', UNINSTALLER_OUT=target)
+ if not target.is_file():
+ raise FileNotFoundError('NSIS did not generate the uninstaller')
+
+
+def build_setup(makensis, payload, output, work):
+ for name in ('ComiTrans.exe', 'ComiTransReleaseService.exe', 'Uninstall.exe'):
+ if not (payload / name).is_file():
+ raise FileNotFoundError(f'Missing installer payload: {payload / name}')
+ validate_installer_models(payload)
+ output.mkdir(parents=True, exist_ok=True)
+ target = output / installer_name(__version__, setup=True)
+ compile_nsis(makensis, payload, work, target)
+ print(target, flush=True)
+ return target
+
+
+def validate_installer_models(payload):
+ """A direct installer must contain every model needed by its default pipeline."""
+ from scripts.model_package import verify
+
+ models = payload / '_internal/comic-translate-ai/models'
+ for relative in (*MODEL_FILES, legacy_detector_entry()['path']):
+ path = models / relative
+ if not path.is_file() or path.stat().st_size == 0:
+ raise FileNotFoundError(f'Full installer is missing a required model: {path}')
+ for name in ('charspot-small', 'split-detector'):
+ manifest = ROOT / f'docs/models/{name}.json'
+ verify(models / name, json.loads(manifest.read_text('utf-8')))
+ if (models / name / 'model-manifest.json').read_bytes() != manifest.read_bytes():
+ raise ValueError(f'Full installer has an inconsistent {name} manifest')
+
+
+def build_delta(base, target):
+ """Build a delta using the exact signed installers distributed to users."""
+ import zstandard as zstd
+
+ setup = target.suffix == '.exe'
+ block_size = SETUP_DELTA_BLOCK_SIZE if setup else DELTA_BLOCK_SIZE
+ suffix = installer_name('', setup=setup).removeprefix('ComiTrans-v')
+
+ def version(path):
+ name = path.name.removeprefix('ComiTrans-v').removesuffix(suffix)
+ if not VERSION.fullmatch(name) or path.name != installer_name(name, setup=setup):
+ raise ValueError(f'Unexpected installer filename: {path.name}')
+ return name
+
+ source, destination = map(version, (base, target))
+ if tuple(map(int, source.split('.'))) >= tuple(map(int, destination.split('.'))):
+ raise ValueError('Delta target must be newer than its base')
+ base_size, target_size = base.stat().st_size, target.stat().st_size
+ if not base_size or not target_size:
+ raise ValueError('Delta installers must be non-empty')
+ if max(base_size, target_size) > DELTA_LIMIT:
+ print('Installer exceeds delta size limit. Distribute the full installer.', flush=True)
+ return
+ delta = target.parent / delta_name(source, destination, setup=setup)
+ temporary = delta.with_suffix('.partial')
+ encoder = zstd.ZstdCompressor(level=5)
+ try:
+ with (base.open('rb') as previous, target.open('rb') as source_file, temporary.open('wb') as output,
+ mmap.mmap(previous.fileno(), 0, access=mmap.ACCESS_READ) as base_bytes):
+ for offset in range(0, target_size, block_size):
+ block = source_file.read(block_size)
+ # Compressed installer data can shift. Search nearby blocks for reusable bytes.
+ start = max(0, offset - DELTA_OVERLAP)
+ position = base_bytes.find(block, start, offset + len(block) + DELTA_OVERLAP)
+ if position >= 0:
+ output.write(DELTA_FRAME.pack(DELTA_COPY | position))
+ continue
+ frame = encoder.compress(block)
+ output.write(DELTA_FRAME.pack(len(frame)))
+ output.write(frame)
+ if temporary.stat().st_size * 10 > target_size * 9:
+ print('Delta saves less than 10% of the full installer download.', flush=True)
+ else:
+ temporary.replace(delta)
+ print(delta, flush=True)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--dist', type=Path, default=ROOT / 'dist/ComiTrans')
+ parser.add_argument('--output', type=Path, default=ROOT / 'release' / f'v{__version__}')
+ parser.add_argument('--makensis', help='Path to the NSIS 3 makensis.exe compiler')
+ parser.add_argument('--include-models', action='store_true', default=True,
+ help='Embed release models in Setup (always enabled for a direct installer)')
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument('--stage-only', action='store_true', help='Stage payload and uninstaller for signing')
+ mode.add_argument('--payload', type=Path, help='Build Setup from an already staged/signed payload')
+ mode.add_argument('--delta', nargs=2, type=Path, metavar=('PREVIOUS_INSTALLER', 'NEW_INSTALLER'))
+ args = parser.parse_args()
+ if args.delta:
+ build_delta(*args.delta)
+ return
+ makensis = find_makensis(args.makensis)
+ parts = __version__.split('.')
+ if len(parts) != 3 or any(not part.isdigit() or int(part) > 65535 for part in parts):
+ raise ValueError('NSIS requires a three-part numeric release version')
+ work_root = ROOT / 'build'
+ work_root.mkdir(exist_ok=True)
+ with TemporaryDirectory(prefix='nsis-', dir=work_root) as directory:
+ work = Path(directory)
+ output = args.output.resolve()
+ if args.payload:
+ payload = args.payload.resolve()
+ else:
+ payload = output / 'payload' if args.stage_only else work / 'payload'
+ stage_app(args.dist.resolve(), payload, include_models=args.include_models)
+ build_uninstaller(makensis, payload, work)
+ if args.stage_only:
+ print(payload, flush=True)
+ else:
+ build_setup(makensis, payload, output, work)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/installer/nsis_strings.json b/installer/nsis_strings.json
new file mode 100644
index 0000000..320ff3a
--- /dev/null
+++ b/installer/nsis_strings.json
@@ -0,0 +1,54 @@
+{
+ "en": {
+ "Require64Bit": "ComiTrans requires 64-bit Windows.",
+ "LegacyInstaller": "An MSI installation of ComiTrans was found. Uninstall it from Windows Settings before installing this version. Your user data will be kept.",
+ "NewerInstalled": "A newer version of ComiTrans is already installed.",
+ "KeepDirectory": "To change the installation folder, uninstall the current version first. Your user data will be kept.",
+ "InvalidDirectory": "Choose an empty folder on a local drive, or the folder of the current NSIS installation. Do not select a drive root or a Windows system folder.",
+ "CloseApplication": "Close ComiTrans before installing or uninstalling, then try again.",
+ "ServiceError": "The ComiTrans update service could not be configured. See the installation log for details.",
+ "InstallError": "Installation did not complete. Check the available disk space and folder permissions, then try again.",
+ "AlreadyRunning": "Another ComiTrans installer or uninstaller is running.",
+ "InvalidUninstall": "This uninstaller does not match the registered ComiTrans installation. Open Windows Settings to uninstall ComiTrans.",
+ "DirectoryHelp": "Choose where to install ComiTrans. Setup creates a ComiTrans subfolder automatically. If the selected folder is already named ComiTrans, it is used directly."
+ },
+ "zh-CN": {
+ "Require64Bit": "ComiTrans 需要 64 位 Windows。",
+ "LegacyInstaller": "检测到 MSI 版 ComiTrans。请先在 Windows 设置中卸载旧版,再安装此版本。用户数据会保留。",
+ "NewerInstalled": "已安装更新版本的 ComiTrans。",
+ "KeepDirectory": "如需更换安装目录,请先卸载当前版本。用户数据会保留。",
+ "InvalidDirectory": "请选择本地磁盘上的空文件夹,或当前 NSIS 版的安装目录。不能选择磁盘根目录或 Windows 系统目录。",
+ "CloseApplication": "请先关闭 ComiTrans,再重试安装或卸载。",
+ "ServiceError": "无法配置 ComiTrans 更新检查服务,请查看安装日志。",
+ "InstallError": "安装未完成,请检查磁盘空间和目录权限后重试。",
+ "AlreadyRunning": "另一个 ComiTrans 安装或卸载程序正在运行。",
+ "InvalidUninstall": "此卸载程序与已注册的 ComiTrans 安装不匹配,请从 Windows 设置中卸载。",
+ "DirectoryHelp": "请选择安装位置。安装程序会自动创建 ComiTrans 子文件夹;已选择 ComiTrans 文件夹时直接使用。"
+ },
+ "zh-TW": {
+ "Require64Bit": "ComiTrans 需要 64 位元 Windows。",
+ "LegacyInstaller": "偵測到 MSI 版 ComiTrans。請先在 Windows 設定中解除安裝舊版,再安裝此版本。使用者資料會保留。",
+ "NewerInstalled": "已安裝較新版本的 ComiTrans。",
+ "KeepDirectory": "若要更換安裝目錄,請先解除安裝目前版本。使用者資料會保留。",
+ "InvalidDirectory": "請選擇本機磁碟上的空資料夾,或目前 NSIS 版的安裝目錄。不能選擇磁碟根目錄或 Windows 系統目錄。",
+ "CloseApplication": "請先關閉 ComiTrans,再重試安裝或解除安裝。",
+ "ServiceError": "無法設定 ComiTrans 更新檢查服務,請查看安裝記錄。",
+ "InstallError": "安裝未完成,請檢查磁碟空間和目錄權限後重試。",
+ "AlreadyRunning": "另一個 ComiTrans 安裝或解除安裝程式正在執行。",
+ "InvalidUninstall": "此解除安裝程式與已註冊的 ComiTrans 安裝不符,請從 Windows 設定中解除安裝。",
+ "DirectoryHelp": "請選擇安裝位置。安裝程式會自動建立 ComiTrans 子資料夾;已選擇 ComiTrans 資料夾時直接使用。"
+ },
+ "ja": {
+ "Require64Bit": "ComiTrans には 64 ビット版 Windows が必要です。",
+ "LegacyInstaller": "MSI 版の ComiTrans が見つかりました。Windows の設定から旧版をアンインストールしてから、このバージョンをインストールしてください。ユーザーデータは保持されます。",
+ "NewerInstalled": "新しいバージョンの ComiTrans が既にインストールされています。",
+ "KeepDirectory": "インストール先を変更するには、現在のバージョンを先にアンインストールしてください。ユーザーデータは保持されます。",
+ "InvalidDirectory": "ローカルドライブの空のフォルダー、または現在の NSIS 版のインストール先を選択してください。ドライブのルートや Windows のシステムフォルダーは選択できません。",
+ "CloseApplication": "ComiTrans を終了してから、インストールまたはアンインストールをやり直してください。",
+ "ServiceError": "ComiTrans 更新確認サービスを設定できませんでした。インストールログを確認してください。",
+ "InstallError": "インストールが完了しませんでした。空き容量とフォルダーのアクセス権を確認して、やり直してください。",
+ "AlreadyRunning": "別の ComiTrans インストーラーまたはアンインストーラーが実行中です。",
+ "InvalidUninstall": "このアンインストーラーは登録済みの ComiTrans と一致しません。Windows の設定からアンインストールしてください。",
+ "DirectoryHelp": "インストール先を選択してください。ComiTrans サブフォルダーは自動作成されます。選択したフォルダー名が ComiTrans の場合は、そのフォルダーを使用します。"
+ }
+}
diff --git a/installer/signpath-setup.xml b/installer/signpath-setup.xml
new file mode 100644
index 0000000..d7c4927
--- /dev/null
+++ b/installer/signpath-setup.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/installer/signpath.xml b/installer/signpath.xml
new file mode 100644
index 0000000..b481a05
--- /dev/null
+++ b/installer/signpath.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/package_release.py b/package_release.py
index 9d5347f..5939a41 100644
--- a/package_release.py
+++ b/package_release.py
@@ -24,7 +24,7 @@
SKIP_DIRS = {"models", "gpu-runtime", "user_fonts", "Log", "logs", "__pycache__", ".cache"}
-def collect_app(dist: Path):
+def collect_app(dist: Path, *, portable_tools=True):
required = ["ComiTrans.exe", "_internal/assets/gpu-runtime-windows.json", "_internal/assets/ui/fonts/Skribble.ttf",
"_internal/assets/ui/fonts/AaJinRiHuaQing-ChunLanMaoKun.ttf",
"_internal/assets/ui/icons/chevron-down.svg",
@@ -67,10 +67,12 @@ def collect_app(dist: Path):
('cublas', 'cudnn', 'cudart', 'cufft', 'nvrtc', 'nvjitlink', 'curand', 'cusolver', 'cusparse')):
continue # NVIDIA runtimes are installed by users, never released here.
files.append((path, "ComiTrans/" + rel.as_posix()))
- for path, name in ((ROOT / f"docs/RELEASE-v{__version__}.md", "README-release.md"),
- (ROOT / "CHANGELOG.md", "CHANGELOG.md"),
- (ROOT / "scripts/apply_patch.ps1", "Apply-Update.ps1"),
- (ROOT / "scripts/apply_patch.bat", "Update-ComiTrans.bat")):
+ documents = [(ROOT / f"docs/RELEASE-v{__version__}.md", "README-release.md"),
+ (ROOT / "CHANGELOG.md", "CHANGELOG.md")]
+ if portable_tools:
+ documents.extend(((ROOT / "scripts/apply_patch.ps1", "Apply-Update.ps1"),
+ (ROOT / "scripts/apply_patch.bat", "Update-ComiTrans.bat")))
+ for path, name in documents:
if not path.is_file():
raise FileNotFoundError(f"Missing release documentation: {path}")
files.append((path, "ComiTrans/" + name))
@@ -150,14 +152,21 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dist", type=Path, default=ROOT / "dist" / "ComiTrans")
parser.add_argument("--output", type=Path, default=ROOT / "release")
- parser.add_argument('--app-only', action='store_true', help='Reuse an existing model archive')
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument('--app-only', action='store_true', help='Reuse an existing model archive')
+ mode.add_argument('--models-only', action='store_true', help='Package audited models for the MSI release')
parser.add_argument('--metadata-dir', type=Path,
default=ROOT / 'docs' / 'releases' / f'v{__version__}',
help='Repository directory for the baseline and checksums')
args = parser.parse_args()
+ model_target = args.output / f'ComiTrans-v{__version__}-models.zip'
+ if args.models_only:
+ files = collect_models()
+ args.output.mkdir(parents=True, exist_ok=True)
+ write_archive(model_target, files)
+ return
# Validate all inputs before creating either archive.
app_files = collect_app(args.dist)
- model_target = args.output / f'ComiTrans-v{__version__}-models.zip'
if args.app_only and not model_target.is_file():
raise FileNotFoundError(f'--app-only requires an existing model archive: {model_target}')
if args.app_only:
diff --git a/run.py b/run.py
index e360501..3119889 100644
--- a/run.py
+++ b/run.py
@@ -8,8 +8,13 @@
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)
-from comic_translate_desktop.main import main
+def main():
+ from comic_translate_desktop.main import main as desktop_main
+ return desktop_main()
if __name__ == "__main__":
+ from multiprocessing import freeze_support
+
+ freeze_support()
raise SystemExit(main())
diff --git a/scripts/review_ui.py b/scripts/review_ui.py
index 12be4d9..1f1faa2 100644
--- a/scripts/review_ui.py
+++ b/scripts/review_ui.py
@@ -16,7 +16,7 @@
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from PIL import Image, ImageDraw, ImageFont
-from PySide6.QtCore import QSettings, QTimer, QPointF, Qt, QEvent
+from PySide6.QtCore import QSettings, QTimer, QPointF, Qt, QEvent, QRect
from PySide6.QtGui import QFontInfo, QMouseEvent
from PySide6.QtTest import QTest
from PySide6.QtWidgets import (QApplication, QWidget, QToolButton, QLabel, QAbstractSpinBox,
@@ -40,6 +40,8 @@ def main():
parser.add_argument('--theme', choices=('light', 'dark'), default='light',
help='Capture the paper (light) or night ink (dark) palette')
parser.add_argument('--language', choices=('zh-CN', 'en', 'ja'), default='zh-CN')
+ parser.add_argument('--screen-size', nargs=2, type=int, metavar=('WIDTH', 'HEIGHT'),
+ help='Virtual desktop bounds for reproducible headless captures')
parser.add_argument('--editor-tools-only', action='store_true',
help='Review fill/color/font controls at every supported width')
parser.add_argument('--context-only', action='store_true',
@@ -86,14 +88,16 @@ def check_font_search(combo):
patch.object(MainWindow, '_start_warmup'):
config.save_ai_config({'ui_theme': args.theme, 'ui_language': args.language})
window = MainWindow()
- screen = app.primaryScreen().availableGeometry()
+ screen = (QRect(0, 0, *args.screen_size) if args.screen_size
+ else app.primaryScreen().availableGeometry())
window.resize(min(1440, int(screen.width() * .94)), min(900, int(screen.height() * .94)))
window.show()
def capture(name, page, buttons=(), ensure_visible=None):
window.tabs.setCurrentWidget(page)
app.processEvents()
- QTest.qWait(80)
+ # Capture settled pages, after the 180/190 ms preview/tab fades.
+ QTest.qWait(240)
if ensure_visible is not None:
window._pref_container.ensureWidgetVisible(ensure_visible, 0, 0)
app.processEvents()
@@ -195,8 +199,7 @@ def review():
window._pref_toggle.setChecked(True)
QTest.qWait(320)
capture('automatic-preferences', window.translate_tab,
- (window._font_picker.combo, window._font_picker.import_button,
- window._font_picker.library_button))
+ (window._font_picker.combo, window._font_picker.manage_button))
check_font_search(window._font_picker.combo)
capture_context(1440)
library = FontLibraryDialog(window.config, window)
@@ -218,10 +221,10 @@ def review():
imported_font = window._font_picker.import_paths([config.AI_ROOT / 'font_file/CN/special/851tegaki_zatsu_normal_0883.ttf'])[0]
assert window._font_picker.combo.currentData() == font_reference(imported_font.path)
assert config.load_ai_config()['translation_font_active']
- capture('automatic-custom-font', window.translate_tab, (window._font_picker.combo, window._font_picker.import_button))
+ capture('automatic-custom-font', window.translate_tab, (window._font_picker.combo, window._font_picker.manage_button))
window._font_picker.combo.setCurrentIndex(0)
editor = window.editor_page
- capture('editor-empty', editor, (editor.preview.import_button, editor._focus_btn))
+ capture('editor-empty', editor, (editor.preview.import_button, editor._view_menu_btn, editor._file_menu_btn))
settings = window.api_config_page
settings._model_input.setText('你的翻译模型')
capture('settings', settings, (settings._save_btn,))
@@ -268,7 +271,7 @@ def review():
editor._repair_box = (60, 120, 300, 320)
editor._update_region_guide()
editor._update_repair_controls()
- capture('editor-fill', editor, (editor._fill_white_btn, editor._fill_black_btn))
+ capture('editor-fill', editor, (editor._repair_btn, editor._fill_menu_btn))
favorite_references = [font_reference(font.path) for font in available_fonts(editor.config)][:9]
editor._favorite_fonts.set_slots(favorite_references)
@@ -277,31 +280,30 @@ def capture_fill_fonts(suffix):
editor._repair_box = (60, 120, 300, 320)
editor._update_region_guide()
editor._update_repair_controls()
+ assert editor._favorite_fonts.isVisible()
controls = (editor._repair_mode, editor._add_bubble_btn, editor._repair_btn,
- editor._pages_toggle, editor._properties_toggle, editor._focus_btn,
- editor._zoom_tool_btn, editor._strip_toggle, editor._save_btn,
- editor._export_pdf_btn,
- editor._repair_undo, editor._fill_white_btn, editor._fill_black_btn,
- editor._fill_color_btn, editor._pick_fill_btn, editor._fill_custom_btn,
- editor._favorite_fonts.add_button, editor._favorite_fonts.settings_button,
+ editor._fill_menu_btn, editor._repair_undo,
+ editor._view_menu_btn, editor._file_menu_btn, editor._save_btn,
+ editor._favorite_fonts.manage_button,
*editor._favorite_fonts.buttons)
capture(f'editor-fill-fonts-{suffix}', editor, controls)
for button in controls:
- assert button.width() >= button.fontMetrics().horizontalAdvance(button.text()) + 16, (
+ extra = 26 if button.property('menuButton') else 16
+ assert button.width() >= button.fontMetrics().horizontalAdvance(button.text()) + extra, (
suffix, button.text(), button.width())
parent = button.parentWidget()
assert parent.rect().contains(button.geometry()), (suffix, button.text(), parent.size())
editor._pick_fill_btn.click()
- capture(f'editor-color-pick-{suffix}', editor, (editor._pick_fill_btn,))
+ capture(f'editor-color-pick-{suffix}', editor, (editor._pick_cancel_btn,))
editor.preview.cancel_color_picking()
editor._repair_mode.setChecked(False)
capture_fill_fonts(1440)
if args.editor_tools_only:
- for width, height in ((1024, 720), (820, 480)):
+ for width, height in ((1024, 720), (820, 640), (820, 480)):
window.resize(width, height)
editor._properties_toggle.setChecked(True)
- capture_fill_fonts(width)
+ capture_fill_fonts(width if height != 640 else '820x640')
report['success'] = True
return
editor._repair_mode.setChecked(False)
@@ -381,7 +383,7 @@ def capture_fill_fonts(suffix):
assert editor.items[0]['font_reference'] == font_reference(config.AI_ROOT / config.FONT_DEFAULTS['serious'])
assert 'font_reference' not in editor.items[1]
editor._properties_scroll.ensureWidgetVisible(editor._style_combo)
- capture('editor-font-switch', editor, (editor._style_combo, editor._font_library_btn, editor._save_btn))
+ capture('editor-font-switch', editor, (editor._style_combo, editor._font_menu_btn, editor._save_btn))
check_font_search(editor._style_combo)
assert editor.save_image()
restored = type(editor)()
@@ -416,6 +418,7 @@ def capture_lettering(suffix):
window.tabs.setCurrentWidget(editor)
editor._properties_toggle.setChecked(True)
editor._inspector_tabs.setCurrentIndex(1)
+ editor._advanced_style_toggle.setChecked(True)
app.processEvents()
for name, fields in (
('outline', (editor._outline_width, editor._hollow_preset_btn)),
@@ -475,46 +478,57 @@ def capture_lettering(suffix):
capture('automatic-preview', window.translate_tab)
window._on_image_done(str(page), str(page))
capture('automatic-complete', window.translate_tab)
- for width, height in ((1024, 720), (960, 540), (820, 480)):
+ for width, height in ((1024, 720), (960, 540), (820, 640), (820, 480)):
window.resize(min(width, int(screen.width() * .94)), min(height, int(screen.height() * .94)))
- if width in (1024, 820):
+ tag = '820x640' if (width, height) == (820, 640) else width
+ if width in (1024, 820) and height != 640:
capture_context(width)
- capture(f'automatic-{width}', window.translate_tab,
- (window._add_btn, window._cuda_toggle, window._cuda_help, window._start_btn))
- settings._sections.setCurrentIndex(2)
- capture(f'settings-{width}', settings, (settings._save_btn,))
- settings._sections.setCurrentIndex(3)
- window.tabs.setCurrentWidget(settings)
- app.processEvents()
- model_browser = settings._advanced._browse_buttons['detector_model']
- model_path = settings._advanced._path_fields['detector_model']
- scroll = settings._sections.currentWidget()
- scroll.ensureWidgetVisible(model_path, 0, 12)
- capture(f'settings-advanced-{width}', settings, (settings._save_btn, model_browser))
- for widget in (model_path, model_browser):
- for point in (widget.rect().topLeft(), widget.rect().bottomRight()):
- assert scroll.viewport().rect().contains(widget.mapTo(scroll.viewport(), point))
- capture(f'diagnosis-{width}', diagnosis, (diagnosis._send_btn,))
+ if (width, height) != (820, 640):
+ capture(f'automatic-{width}', window.translate_tab,
+ (window._add_btn, window._cuda_toggle, window._cuda_help, window._start_btn))
+ settings._sections.setCurrentIndex(2)
+ capture(f'settings-{width}', settings, (settings._save_btn,))
+ settings._sections.setCurrentIndex(3)
+ window.tabs.setCurrentWidget(settings)
+ app.processEvents()
+ model_browser = settings._advanced._browse_buttons['detector_model']
+ model_path = settings._advanced._path_fields['detector_model']
+ scroll = settings._sections.currentWidget()
+ scroll.ensureWidgetVisible(model_path, 0, 12)
+ capture(f'settings-advanced-{width}', settings, (settings._save_btn, model_browser))
+ for widget in (model_path, model_browser):
+ for point in (widget.rect().topLeft(), widget.rect().bottomRight()):
+ assert scroll.viewport().rect().contains(widget.mapTo(scroll.viewport(), point))
+ capture(f'diagnosis-{width}', diagnosis, (diagnosis._send_btn,))
window.tabs.setCurrentWidget(editor)
app.processEvents()
editor._properties_toggle.setChecked(True)
- capture(f'editor-{width}', editor, (editor._save_btn, editor._apply_btn))
+ editor._inspector_tabs.setCurrentIndex(0)
+ app.processEvents()
+ if (width, height) == (820, 640):
+ assert editor._text_input.height() >= 110, editor._text_input.height()
+ if width == 1024:
+ canvas_bar = editor.preview.parentWidget().findChild(type(editor._pages_panel), 'canvasToolBar')
+ assert not editor._pages_panel.isVisible(), 'pages panel stayed visible at 1024px'
+ assert canvas_bar is not None and canvas_bar.height() <= 46, canvas_bar.height()
+ assert editor._text_input.height() >= 110, editor._text_input.height()
+ capture(f'editor-{tag}', editor, (editor._save_btn, editor._apply_btn, editor._quick_size_spin))
editor._inspector_tabs.setCurrentIndex(1)
editor._properties_scroll.ensureWidgetVisible(editor._mask_height)
app.processEvents()
check_action(window, editor._mask_height)
assert editor._properties_scroll.viewport().rect().contains(
editor._mask_height.mapTo(editor._properties_scroll.viewport(), editor._mask_height.rect().center()))
- editor._properties_scroll.ensureWidgetVisible(editor._font_library_btn)
+ editor._properties_scroll.ensureWidgetVisible(editor._font_menu_btn)
app.processEvents()
- check_action(window, editor._font_library_btn)
+ check_action(window, editor._font_menu_btn)
assert editor._properties_scroll.viewport().rect().contains(
- editor._font_library_btn.mapTo(editor._properties_scroll.viewport(), editor._font_library_btn.rect().center()))
- capture_lettering(width)
- capture_fill_fonts(width)
+ editor._font_menu_btn.mapTo(editor._properties_scroll.viewport(), editor._font_menu_btn.rect().center()))
+ capture_lettering(tag)
+ capture_fill_fonts(tag)
editor._inspector_tabs.setCurrentIndex(0)
editor._focus_btn.setChecked(True)
- capture(f'editor-focus-{width}', editor, (editor._save_btn, editor._focus_btn))
+ capture(f'editor-focus-{tag}', editor, (editor._save_btn, editor._focus_btn))
assert not editor._pages_panel.isVisible()
assert not editor._properties_panel.isVisible()
editor._focus_btn.setChecked(False)
diff --git a/tests/installer_fixtures/service_api.c b/tests/installer_fixtures/service_api.c
new file mode 100644
index 0000000..4cd7feb
--- /dev/null
+++ b/tests/installer_fixtures/service_api.c
@@ -0,0 +1,108 @@
+/* Validates NSIS SCM arguments without changing Windows services. */
+#define WINADVAPI
+#include
+#include
+#include
+
+static void trace(const wchar_t *message) {
+ wchar_t path[2048];
+ if (!GetEnvironmentVariableW(L"COMITRANS_FIXTURE_LOG", path, 2048)) return;
+ HANDLE file = CreateFileW(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (file == INVALID_HANDLE_VALUE) return;
+ DWORD written;
+ WriteFile(file, message, (DWORD)(wcslen(message) * sizeof(wchar_t)), &written, NULL);
+ WriteFile(file, L"\r\n", 4, &written, NULL);
+ CloseHandle(file);
+}
+
+static DWORD state(DWORD replacement) {
+ wchar_t path[2048];
+ if (!GetEnvironmentVariableW(L"COMITRANS_FIXTURE_STATE", path, 2048)) return 0;
+ if (replacement == 0xffffffff) { DeleteFileW(path); return 0; }
+ HANDLE file = CreateFileW(path, GENERIC_READ | (replacement ? GENERIC_WRITE : 0),
+ FILE_SHARE_READ, NULL, replacement ? OPEN_ALWAYS : OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if (file == INVALID_HANDLE_VALUE) return 0;
+ DWORD current = 0, count;
+ if (replacement) WriteFile(file, &replacement, sizeof(replacement), &count, NULL);
+ else ReadFile(file, ¤t, sizeof(current), &count, NULL);
+ CloseHandle(file);
+ return replacement ? replacement : current;
+}
+
+static BOOL configuration(LPCWSTR binary, LPCWSTR account, DWORD type, DWORD start, DWORD error) {
+ wchar_t expected[2048];
+ GetEnvironmentVariableW(L"COMITRANS_FIXTURE_BINARY", expected, 2048);
+ if (!binary || !account || wcscmp(binary, expected) ||
+ wcscmp(account, L"NT AUTHORITY\\LocalService") ||
+ type != SERVICE_WIN32_OWN_PROCESS || start != SERVICE_AUTO_START || error != SERVICE_ERROR_NORMAL) {
+ trace(L"INVALID CONFIGURATION");
+ SetLastError(ERROR_INVALID_PARAMETER);
+ return FALSE;
+ }
+ trace(binary);
+ SetLastError(ERROR_SUCCESS);
+ return TRUE;
+}
+
+__declspec(dllexport) SC_HANDLE WINAPI OpenSCManagerW(LPCWSTR machine, LPCWSTR database, DWORD access) {
+ if (machine || database || (access != 1 && access != 3)) {
+ SetLastError(ERROR_INVALID_PARAMETER); return NULL;
+ }
+ return (SC_HANDLE)1;
+}
+
+__declspec(dllexport) SC_HANDLE WINAPI OpenServiceW(SC_HANDLE manager, LPCWSTR name, DWORD access) {
+ if (manager != (SC_HANDLE)1 || !name || (access != 0x24 && access != 0x16 && access != DELETE)) {
+ SetLastError(ERROR_INVALID_PARAMETER); return NULL;
+ }
+ if (!state(0)) { SetLastError(ERROR_SERVICE_DOES_NOT_EXIST); return NULL; }
+ return (SC_HANDLE)2;
+}
+
+__declspec(dllexport) SC_HANDLE WINAPI CreateServiceW(SC_HANDLE manager, LPCWSTR name, LPCWSTR display,
+ DWORD access, DWORD type, DWORD start, DWORD error, LPCWSTR binary, LPCWSTR group,
+ LPDWORD tag, LPCWSTR dependencies, LPCWSTR account, LPCWSTR password) {
+ if (manager != (SC_HANDLE)1 || !name || !display || access != 0x16 ||
+ group || tag || dependencies || password || !configuration(binary, account, type, start, error)) {
+ SetLastError(ERROR_INVALID_PARAMETER); return NULL;
+ }
+ trace(L"create"); state(SERVICE_STOPPED);
+ return (SC_HANDLE)2;
+}
+
+__declspec(dllexport) BOOL WINAPI ChangeServiceConfigW(SC_HANDLE service, DWORD type, DWORD start,
+ DWORD error, LPCWSTR binary, LPCWSTR group, LPDWORD tag, LPCWSTR dependencies,
+ LPCWSTR account, LPCWSTR password, LPCWSTR display) {
+ if (service != (SC_HANDLE)2 || !display || group || tag || dependencies || password ||
+ !configuration(binary, account, type, start, error)) return FALSE;
+ trace(L"configure"); return TRUE;
+}
+
+__declspec(dllexport) BOOL WINAPI StartServiceW(SC_HANDLE service, DWORD count, LPCWSTR *arguments) {
+ if (service != (SC_HANDLE)2 || count || arguments) return FALSE;
+ state(SERVICE_RUNNING); trace(L"start"); return TRUE;
+}
+
+__declspec(dllexport) BOOL WINAPI QueryServiceStatus(SC_HANDLE service, LPSERVICE_STATUS status) {
+ if (service != (SC_HANDLE)2 || !status) return FALSE;
+ ZeroMemory(status, sizeof(*status));
+ status->dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+ status->dwCurrentState = state(0);
+ return TRUE;
+}
+
+__declspec(dllexport) BOOL WINAPI ControlService(SC_HANDLE service, DWORD control, LPSERVICE_STATUS status) {
+ if (service != (SC_HANDLE)2 || control != SERVICE_CONTROL_STOP) return FALSE;
+ state(SERVICE_STOPPED); trace(L"stop"); return QueryServiceStatus(service, status);
+}
+
+__declspec(dllexport) BOOL WINAPI DeleteService(SC_HANDLE service) {
+ if (service != (SC_HANDLE)2) return FALSE;
+ state(0xffffffff); trace(L"delete"); return TRUE;
+}
+
+__declspec(dllexport) BOOL WINAPI CloseServiceHandle(SC_HANDLE handle) {
+ return handle == (SC_HANDLE)1 || handle == (SC_HANDLE)2;
+}
diff --git a/tests/test_context_preferences.py b/tests/test_context_preferences.py
index 46601a4..decc17a 100644
--- a/tests/test_context_preferences.py
+++ b/tests/test_context_preferences.py
@@ -3,11 +3,14 @@
from pathlib import Path
from unittest.mock import patch
-from PySide6.QtWidgets import QApplication
+from PySide6.QtCore import QRect, QSettings, Qt
+from PySide6.QtWidgets import QApplication, QHBoxLayout
from PySide6.QtTest import QTest
from comic_translate_desktop import config
+from comic_translate_desktop.ui import main_window
from comic_translate_desktop.ui.main_window import MainWindow
+from comic_translate_desktop.ui.motion import set_reduced_motion
from tests.qt_utils import destroy_widget
@@ -15,6 +18,18 @@ class ContextPreferencesTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = QApplication.instance() or QApplication([])
+ cls.preferences = tempfile.TemporaryDirectory()
+ QSettings.setDefaultFormat(QSettings.IniFormat)
+ QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, cls.preferences.name)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.preferences.cleanup()
+
+ def setUp(self):
+ self.addCleanup(set_reduced_motion, False)
+ set_reduced_motion(False)
+ QSettings().remove('ui/preferencesVisible')
def test_retention_persists_locks_resume_and_never_clears_cache_on_toggle(self):
with tempfile.TemporaryDirectory() as temporary:
@@ -76,3 +91,98 @@ def test_context_controls_are_inside_every_clipping_parent_in_short_windows(self
parent = parent.parentWidget()
finally:
destroy_widget(window)
+
+ def test_preferences_opened_before_show_use_final_layout_height(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ with patch.object(config, 'CONFIG_PATH', root / 'config.yaml'), \
+ patch.object(config, 'PROJECT_ROOT', root), \
+ patch.object(MainWindow, '_start_warmup'):
+ first = MainWindow()
+ try:
+ first.resize(820, 480)
+ first._pref_toggle.setChecked(False)
+ first._pref_toggle.setChecked(True)
+ self.assertFalse(first._pref_container.isHidden())
+ self.assertIsNone(first._pref_animation)
+ self.assertEqual(first._pref_toggle.arrowType(), Qt.DownArrow)
+ first._ui_settings.sync()
+ finally:
+ destroy_widget(first)
+
+ restored = MainWindow()
+ try:
+ self.assertTrue(restored._pref_toggle.isChecked())
+ restored.resize(1440, 900)
+ restored.show()
+ self.app.processEvents()
+ self.assertTrue(restored._pref_container.isVisible())
+ self.assertIsNone(restored._pref_animation)
+ self.assertEqual(restored._pref_columns.direction(), QHBoxLayout.LeftToRight)
+ self.assertEqual(restored._pref_container.maximumHeight(), restored._pref_target_height())
+ finally:
+ destroy_widget(restored)
+
+ def test_preferences_reversal_resize_and_bar_geometry_stay_stable(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ with patch.object(config, 'CONFIG_PATH', root / 'config.yaml'), \
+ patch.object(config, 'PROJECT_ROOT', root), \
+ patch.object(MainWindow, '_start_warmup'), \
+ patch.object(main_window, 'reduced_motion', return_value=False):
+ window = MainWindow()
+ try:
+ window.resize(1280, 800)
+ window._pref_toggle.setChecked(False)
+ window.show()
+ self.app.processEvents()
+
+ bar_heights = []
+ src_heights = []
+ window._pref_toggle.setChecked(True)
+ opening = window._pref_animation
+ self.assertIsNotNone(opening)
+ self.assertEqual(window._pref_columns.direction(), QHBoxLayout.LeftToRight)
+ for step in range(1, 5):
+ opening.setCurrentTime((opening.duration() * step) // 4)
+ self.app.processEvents()
+ bar_heights.append(window._control_bar.height())
+ src_heights.append(window._source_language.height())
+ self.assertTrue(all(h >= 34 for h in bar_heights), bar_heights)
+ self.assertTrue(all(h >= 34 for h in src_heights), src_heights)
+
+ # Finish at 1280x800 and confirm bottom rows fit without clipping.
+ QTest.qWait(320)
+ self.app.processEvents()
+ vp_rect = window._pref_container.viewport().rect()
+ for widget in (window._resume_enabled, window._names_input):
+ box = QRect(
+ widget.mapTo(window._pref_container.viewport(), widget.rect().topLeft()),
+ widget.size(),
+ )
+ self.assertTrue(vp_rect.contains(box), (widget.objectName(), box, vp_rect))
+
+ # Test rapid reversal and mid-animation resize.
+ window._pref_toggle.setChecked(False)
+ closing = window._pref_animation
+ self.assertIsNotNone(closing)
+ closing.setCurrentTime(closing.duration() // 2)
+
+ window._pref_toggle.setChecked(True)
+ reopened = window._pref_animation
+ self.assertIsNotNone(reopened)
+ window._finish_preferences_animation(False, closing)
+ self.assertIs(window._pref_animation, reopened)
+ self.assertTrue(window._pref_container.isVisible())
+
+ window.resize(1024, 760)
+ self.app.processEvents()
+ self.assertIs(window._pref_animation, reopened)
+ self.assertTrue(window._pref_container.widgetResizable())
+ reopened.setCurrentTime(reopened.duration())
+ self.app.processEvents()
+ self.assertIsNone(window._pref_animation)
+ self.assertTrue(window._pref_container.isVisible())
+ self.assertEqual(window._pref_container.maximumHeight(), window._pref_target_height())
+ finally:
+ destroy_widget(window)
diff --git a/tests/test_editor_ui_redesign.py b/tests/test_editor_ui_redesign.py
index 04185f4..25ca502 100644
--- a/tests/test_editor_ui_redesign.py
+++ b/tests/test_editor_ui_redesign.py
@@ -3,13 +3,16 @@
import tempfile
import unittest
from pathlib import Path
+from unittest.mock import patch
from PIL import Image
-from PySide6.QtCore import QRect, QSettings, Qt
-from PySide6.QtGui import QTextCursor
+from PySide6.QtCore import QPoint, QPointF, QRect, QSettings, Qt
+from PySide6.QtGui import QContextMenuEvent, QTextCursor
from PySide6.QtTest import QTest
-from PySide6.QtWidgets import QApplication, QCheckBox, QPushButton, QScrollArea
+from PySide6.QtWidgets import QApplication, QCheckBox, QMenu, QPushButton, QScrollArea
+from comic_translate_desktop import config
+from comic_translate_desktop.i18n import install_qt_language, set_ui_language
from comic_translate_desktop.ui.editor_page import EditorPage
from comic_translate_desktop.ui.main_window import MainWindow
from comic_translate_desktop.ui.text_editor_dialog import TextEditorDialog
@@ -70,8 +73,13 @@ def setUp(self):
self.addCleanup(lambda: QSettings.setDefaultFormat(self._prev_fmt))
def _make_window(self, width=1280, height=800) -> MainWindow:
- window = MainWindow()
- self.addCleanup(lambda: (window.close(), self.app.processEvents()))
+ with patch.object(MainWindow, '_start_warmup'):
+ window = MainWindow()
+ def _cleanup():
+ window.editor_page._dirty = False
+ window.close()
+ self.app.processEvents()
+ self.addCleanup(_cleanup)
window.resize(width, height)
window.show()
self.app.processEvents()
@@ -143,15 +151,12 @@ def test_zoom_buttons_and_canvas_toolbar_containment(self):
editor._repair_mode,
editor._add_bubble_btn,
editor._repair_btn,
+ editor._fill_menu_btn,
editor._repair_undo,
- editor._fill_white_btn,
- editor._fill_black_btn,
- editor._fill_color_btn,
- editor._pick_fill_btn,
- editor._fill_custom_btn,
):
mapped = QRect(btn.mapTo(toolbar, btn.rect().topLeft()), btn.size())
self.assertTrue(bar_rect.contains(mapped), f'{btn.text()} clipped inside canvasToolBar: {mapped} vs {bar_rect}')
+ self.assertLessEqual(toolbar.height(), 46, f'canvasToolBar wrapped to multiple rows at 1024x720: {toolbar.height()}px')
def test_compact_820x480_editor_layout_keeps_text_and_outline_unclipped(self):
window = self._make_window(820, 480)
@@ -171,6 +176,8 @@ def test_compact_820x480_editor_layout_keeps_text_and_outline_unclipped(self):
self.assertFalse(src_rect.intersects(inp_rect))
editor._inspector_tabs.setCurrentIndex(1)
+ editor._advanced_style_toggle.setChecked(True)
+ self.app.processEvents()
QTest.qWait(40)
self.assertIs(editor._properties_scroll.parentWidget().parentWidget().parentWidget(),
editor._inspector_tabs.findChildren(QScrollArea)[0].parentWidget().parentWidget().parentWidget())
@@ -225,6 +232,192 @@ def test_main_window_context_preferences_fit_at_820x480_with_queue(self):
card_box = QRect(box.mapTo(card, box.rect().topLeft()), box.size())
self.assertTrue(card_rect.contains(card_box), f'{box.text()} overflowed controlCard: {card_box} vs {card_rect}')
+ def test_820x640_text_editor_height_and_direct_quick_size_sync(self):
+ window = self._make_window(820, 640)
+ window._nav_editor.click()
+ editor = window.editor_page
+ self._load_editor_sample(editor)
+ QTest.qWait(60)
+
+ self.assertFalse(editor._favorite_fonts.isVisible())
+ self.assertFalse(editor._source_text.isVisible())
+ self.assertTrue(editor._text_input.isVisible())
+ self.assertGreaterEqual(editor._text_input.height(), 110)
+ self.assertTrue(editor._quick_size_spin.isVisible())
+ self.assertEqual(editor._quick_size_spin.value(), 26)
+
+ editor._quick_size_spin.setValue(33)
+ self.assertEqual(editor._size_spin.value(), 33)
+ QTest.qWait(90)
+ self.assertEqual(editor.items[0]['font_size'], 33)
+ self.assertEqual(editor.items[0]['rendered_font_size'], 33)
+
+ editor._size_spin.setValue(27)
+ self.assertEqual(editor._quick_size_spin.value(), 27)
+
+ editor._source_toggle.click()
+ QTest.qWait(240)
+ self.assertTrue(editor._source_text.isVisible())
+ self.assertLessEqual(editor._source_text.height(), 60)
+ self.assertGreaterEqual(editor._text_input.height(), 110)
+
+ def test_secondary_menus_single_level_containment_and_state_preservation(self):
+ window = self._make_window(1440, 900)
+ window._nav_editor.click()
+ editor = window.editor_page
+ self._load_editor_sample(editor)
+ QTest.qWait(50)
+
+ for menu in (
+ editor._view_menu,
+ editor._file_menu,
+ editor._fill_menu,
+ editor._font_menu,
+ editor._favorite_fonts.manage_menu,
+ window._font_picker.manage_menu,
+ ):
+ self.assertFalse(any(action.menu() is not None for action in menu.actions()))
+
+ self.assertFalse(editor._advanced_style_toggle.isChecked())
+ self.assertFalse(editor._advanced_style_panel.isVisible())
+ self.assertNotIn('已自定义', editor._advanced_style_toggle.text())
+ editor._outline_width.setValue(3.0)
+ self.assertIn('已自定义', editor._advanced_style_toggle.text())
+
+ editor._text_input.setPlainText('保留这段未保存译文')
+ editor.preview.set_zoom(1.5)
+ editor._repair_mode.setChecked(True)
+ editor._repair_box = (40, 40, 120, 120)
+ editor._update_repair_controls()
+ QTest.qWait(70)
+
+ editor._pages_action.trigger()
+ self.assertFalse(editor._pages_panel.isVisible())
+ editor._pages_action.trigger()
+ self.assertTrue(editor._pages_panel.isVisible())
+
+ self.assertFalse(editor._focus_btn.isVisible())
+ editor._focus_action.trigger()
+ self.assertTrue(editor._focus_btn.isChecked())
+ self.assertTrue(editor._focus_btn.isVisible())
+ self.assertFalse(editor._pages_panel.isVisible())
+ self.assertFalse(editor._properties_panel.isVisible())
+ self.assertEqual(editor._text_input.toPlainText(), '保留这段未保存译文')
+ self.assertEqual(editor.block_list.currentRow(), 0)
+ self.assertEqual(editor._repair_box, (40, 40, 120, 120))
+ self.assertAlmostEqual(editor.preview._zoom, 1.5)
+ self.assertTrue(editor._dirty)
+
+ editor._focus_btn.click()
+ self.assertFalse(editor._focus_btn.isChecked())
+ self.assertFalse(editor._focus_btn.isVisible())
+ self.assertTrue(editor._properties_panel.isVisible())
+
+ self.assertFalse(editor._pick_cancel_btn.isVisible())
+ editor._pick_fill_action.trigger()
+ self.assertTrue(editor._pick_fill_btn.isChecked())
+ self.assertTrue(editor._pick_cancel_btn.isVisible())
+ editor._pick_cancel_btn.click()
+ self.assertFalse(editor._pick_fill_btn.isChecked())
+ self.assertFalse(editor._pick_cancel_btn.isVisible())
+
+ editor._repair_mode.setChecked(False)
+ bubble_menu = QMenu(editor)
+ editor._populate_bubble_menu(bubble_menu)
+ self.assertFalse(any(action.menu() is not None for action in bubble_menu.actions()))
+ by_text = {action.text().split('\t')[0]: action for action in bubble_menu.actions() if not action.isSeparator()}
+ self.assertTrue(by_text['全屏编辑译文'].isEnabled())
+ self.assertTrue(by_text['白字黑边竖排'].isEnabled())
+
+ editor.items[0]['restore_original'] = True
+ editor._set_editable(True)
+ editor._populate_bubble_menu(bubble_menu)
+ by_text = {action.text().split('\t')[0]: action for action in bubble_menu.actions() if not action.isSeparator()}
+ self.assertTrue(by_text['恢复处理结果'].isEnabled())
+ self.assertFalse(by_text['全屏编辑译文'].isEnabled())
+ self.assertFalse(by_text['字体库…'].isEnabled())
+ self.assertFalse(by_text['白字黑边竖排'].isEnabled())
+ self.assertFalse(by_text['重置文字变形'].isEnabled())
+
+ editor.items[0]['restore_original'] = False
+ editor._set_editable(True)
+ canvas = editor.preview._label
+ page_rect = canvas.page_rect()
+ x1, y1, x2, y2 = editor.items[1]['box']
+ cx = page_rect.left() + ((x1 + x2) / 2) * page_rect.width() / canvas.image_size.width()
+ cy = page_rect.top() + ((y1 + y2) / 2) * page_rect.height() / canvas.image_size.height()
+ seen = []
+ with patch.object(editor, '_show_bubble_context_menu', side_effect=lambda pos: seen.append(pos)):
+ QApplication.sendEvent(
+ canvas,
+ QContextMenuEvent(QContextMenuEvent.Mouse, QPoint(round(cx), round(cy)), QPoint(100, 100)),
+ )
+ self.assertEqual(len(seen), 1)
+ self.assertEqual(editor.block_list.currentRow(), 1)
+
+ editor._pick_fill_btn.setChecked(True)
+ with patch.object(editor, '_show_bubble_context_menu', side_effect=lambda pos: seen.append(pos)):
+ QTest.mouseClick(canvas, Qt.RightButton, pos=QPoint(round(cx), round(cy)))
+ QApplication.sendEvent(
+ canvas,
+ QContextMenuEvent(QContextMenuEvent.Mouse, QPoint(round(cx), round(cy)), QPoint(100, 100)),
+ )
+ self.assertEqual(len(seen), 1)
+ self.assertFalse(editor._pick_fill_btn.isChecked())
+
+ def test_en_and_ja_toolbar_and_canvas_toolbar_unclipped_at_820_and_1024(self):
+ self.addCleanup(lambda: (set_ui_language('zh-CN'), install_qt_language(self.app)))
+ for lang in ('en', 'ja'):
+ with patch.object(config, 'PROJECT_ROOT', Path(self._tmp.name)), \
+ patch.object(config, 'CONFIG_PATH', Path(self._tmp.name) / 'config.yaml'):
+ config.save_ai_config({'ui_language': lang, 'ui_language_selected': True})
+ set_ui_language(lang)
+ install_qt_language(self.app)
+ for width, height in ((1024, 720), (820, 640)):
+ with self.subTest(language=lang, width=width, height=height):
+ window = self._make_window(width, height)
+ window._nav_editor.click()
+ editor = window.editor_page
+ self._load_editor_sample(editor)
+ QTest.qWait(50)
+
+ toolbar = editor.findChild(type(editor._pages_panel), 'editorToolbar')
+ self.assertIsNotNone(toolbar)
+ toolbar_buttons = [
+ editor._view_menu_btn, editor._zoom_out_btn, editor._zoom,
+ editor._zoom_in_btn, editor._file_menu_btn, editor._save_btn,
+ ]
+ for prev, nxt in zip(toolbar_buttons, toolbar_buttons[1:]):
+ gap = nxt.mapTo(toolbar, nxt.rect().topLeft()).x() - prev.mapTo(toolbar, prev.rect().topRight()).x()
+ self.assertGreaterEqual(gap, 0, (lang, width, prev.objectName(), nxt.objectName()))
+ for widget in toolbar_buttons:
+ mapped = QRect(widget.mapTo(toolbar, widget.rect().topLeft()), widget.size())
+ self.assertTrue(toolbar.rect().contains(mapped), (lang, width, mapped, toolbar.rect()))
+
+ canvas_bar = editor.preview.parentWidget().findChild(type(editor._pages_panel), 'canvasToolBar')
+ self.assertIsNotNone(canvas_bar)
+ for btn in (
+ editor._repair_mode, editor._add_bubble_btn, editor._repair_btn,
+ editor._fill_menu_btn, editor._repair_undo,
+ ):
+ mapped = QRect(btn.mapTo(canvas_bar, btn.rect().topLeft()), btn.size())
+ self.assertTrue(canvas_bar.rect().contains(mapped), (lang, width, btn.text(), mapped, canvas_bar.rect()))
+ extra = 26 if btn.property('menuButton') else 16
+ self.assertGreaterEqual(btn.width(), btn.fontMetrics().horizontalAdvance(btn.text()) + extra)
+ if width == 1024:
+ self.assertLessEqual(canvas_bar.height(), 46, (lang, canvas_bar.height()))
+
+ for btn in (editor._line_break_btn, editor._expand_btn):
+ self.assertTrue(btn.isVisible(), (lang, width, btn.text()))
+ self.assertGreaterEqual(btn.width(), btn.fontMetrics().horizontalAdvance(btn.text()) + 14, (lang, width, btn.text(), btn.width()))
+ parent = btn.parentWidget()
+ mapped = QRect(btn.mapTo(parent, btn.rect().topLeft()), btn.size())
+ self.assertTrue(parent.rect().contains(mapped), (lang, width, btn.text(), mapped, parent.rect()))
+ self.assertLess(
+ editor._line_break_btn.mapTo(editor._properties_panel, editor._line_break_btn.rect().topRight()).x(),
+ editor._expand_btn.mapTo(editor._properties_panel, editor._expand_btn.rect().topLeft()).x(),
+ )
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/test_font_catalog.py b/tests/test_font_catalog.py
index 5fdb660..39045b4 100644
--- a/tests/test_font_catalog.py
+++ b/tests/test_font_catalog.py
@@ -192,6 +192,21 @@ def test_catalog_entry_without_license_cannot_start_download(self):
with self.assertRaisesRegex(ValueError, '许可证'):
download_face(family, family['faces'][0])
+ def test_font_preview_matches_dark_theme_surface_and_ink(self):
+ import sys
+ from comic_translate_desktop.ui.theme import apply_theme
+ main_dir = str(ROOT / 'comic-translate-ai' / 'main')
+ if main_dir not in sys.path:
+ sys.path.insert(0, main_dir)
+ apply_theme(self.app, 'dark')
+ self.addCleanup(lambda: apply_theme(self.app, 'light'))
+ dialog = self.dialog()
+ font_path = ROOT / 'comic-translate-ai' / 'font_file' / 'CN' / 'SourceHanSansSC-Medium-2.otf'
+ dialog._show_preview(str(font_path))
+ pixmap = dialog.preview.pixmap()
+ self.assertFalse(pixmap.isNull())
+ self.assertLess(pixmap.toImage().pixelColor(0, 0).lightness(), 40)
+
if __name__ == '__main__':
unittest.main()
diff --git a/tests/test_gpu_setup.py b/tests/test_gpu_setup.py
index 81582d2..9dc07d5 100644
--- a/tests/test_gpu_setup.py
+++ b/tests/test_gpu_setup.py
@@ -63,3 +63,20 @@ def test_download_buttons_open_only_the_corresponding_official_link_when_clicked
self.assertEqual(open_url.call_count, 3)
finally:
destroy_widget(dialog)
+
+ def test_gpu_setup_dialog_styles_actions_and_toggles_progress(self):
+ app = QApplication.instance() or QApplication([])
+ dialog = GpuSetupDialog()
+ self.addCleanup(destroy_widget, dialog)
+ self.assertEqual(dialog.install_button.property('role'), 'primary')
+ for button in dialog.download_buttons:
+ self.assertEqual(button.property('role'), 'utility')
+ self.assertFalse(dialog.install_progress.isVisible())
+ with patch.object(dialog.installer, 'start'):
+ dialog.show()
+ dialog.start_install()
+ self.assertTrue(dialog.install_progress.isVisible())
+ self.assertFalse(dialog.install_button.isEnabled())
+ dialog._install_finished()
+ self.assertFalse(dialog.install_progress.isVisible())
+ self.assertTrue(dialog.install_button.isEnabled())
diff --git a/tests/test_image_session.py b/tests/test_image_session.py
new file mode 100644
index 0000000..b58ff09
--- /dev/null
+++ b/tests/test_image_session.py
@@ -0,0 +1,39 @@
+import os
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from unittest.mock import patch
+
+import numpy as np
+from onnxruntime.datasets import get_example
+
+from comic_translate_core import image_session
+
+
+class ImageSessionTests(unittest.TestCase):
+ def test_desktop_worker_survives_a_bad_model_and_matches_local_inference(self):
+ path = get_example('mul_1.onnx')
+ direct = image_session.create_image_session(path)
+ values = np.arange(6, dtype=np.float32).reshape(3, 2)
+ expected = direct.run(None, {'X': values})[0]
+
+ with patch.object(image_session, '_host', None), patch.object(image_session, '_desktop', True):
+ try:
+ with self.assertRaisesRegex(Exception, 'does-not-exist'):
+ image_session.create_image_session(Path(path).with_name('does-not-exist.onnx'))
+ remote = image_session.create_image_session(path)
+ self.assertNotEqual(image_session._host._process.pid, os.getpid())
+ self.assertEqual(remote.get_providers(), direct.get_providers())
+ self.assertEqual(remote.get_inputs()[0].shape, [3, 2])
+ self.assertEqual(remote.get_outputs()[0].name, 'Y')
+ with ThreadPoolExecutor(2) as workers:
+ calls = [workers.submit(remote.run, ['Y'], {'X': values}) for _ in range(2)]
+ for call in calls:
+ np.testing.assert_array_equal(call.result(timeout=10)[0], expected)
+ process = image_session._host._process
+ process.terminate()
+ process.join(5)
+ np.testing.assert_array_equal(remote.run(None, {'X': values})[0], expected)
+ finally:
+ if image_session._host is not None:
+ image_session._host.shutdown()
diff --git a/tests/test_installed_model_paths.py b/tests/test_installed_model_paths.py
new file mode 100644
index 0000000..eaeb367
--- /dev/null
+++ b/tests/test_installed_model_paths.py
@@ -0,0 +1,99 @@
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import patch
+
+import yaml
+
+from comic_translate_desktop import config
+from comic_translate_core.detector_paths import SPLIT_PATH, LINE_FILE, LEGACY_PATH
+
+
+class InstalledModelPathTests(unittest.TestCase):
+ def test_relative_paths_preserve_explicit_legacy_detector_selection(self):
+ with TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundled = root / 'install/_internal/comic-translate-ai/models'
+ for relative in (LEGACY_PATH, SPLIT_PATH, SPLIT_PATH.with_name(LINE_FILE)):
+ target = bundled / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.touch()
+ with (patch.object(config, 'MODELS_ROOT', root / 'profile/models'),
+ patch.object(config, 'BUNDLED_MODELS_ROOT', bundled),
+ patch.object(config, 'CONFIG_PATH', root / 'config.yaml')):
+ config.save_ai_config({'detector_model': str(bundled / LEGACY_PATH)})
+ raw = yaml.safe_load(config.CONFIG_PATH.read_text('utf-8'))
+ self.assertFalse(Path(raw['detector_model']).is_absolute())
+ loaded = config.load_ai_config()
+ self.assertEqual(loaded['detector_model'], str(bundled / LEGACY_PATH))
+ self.assertNotEqual(loaded['detector_model_setting'], 'auto')
+ self.assertIsNone(loaded['cuda_detector_model'])
+
+ def test_moved_installation_recovers_saved_default_paths(self):
+ with TemporaryDirectory() as directory:
+ root = Path(directory)
+ old = root / 'removed install' / '_internal/comic-translate-ai/models'
+ bundled = root / 'new install' / '_internal/comic-translate-ai/models'
+ profile = root / 'profile/comic-translate-ai/models'
+ defaults = {
+ 'charspot_ocr_model': 'charspot-small',
+ 'lama_model': 'manga-lama/lama-manga-dynamic.onnx',
+ 'korean_ocr_model': 'ppocr/korean_PP-OCRv5_rec_mobile.onnx',
+ 'english_ocr_model': 'ppocr/en_PP-OCRv5_rec_mobile.onnx',
+ }
+ for relative in (SPLIT_PATH, SPLIT_PATH.with_name(LINE_FILE),
+ 'charspot-small/model.onnx', 'charspot-small/config.json',
+ 'charspot-small/vocab.json', *list(defaults.values())[1:]):
+ target = bundled / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.touch()
+ raw = {key: str(old / relative) for key, relative in defaults.items()}
+ raw.update(ocr_backend='auto', use_gpu=False, api_key='test-credential',
+ translation_model='test-model')
+ preferences = root / 'config.yaml'
+ preferences.write_text(yaml.safe_dump(raw), encoding='utf-8')
+ with (patch.object(config, 'MODELS_ROOT', profile),
+ patch.object(config, 'BUNDLED_MODELS_ROOT', bundled),
+ patch.object(config, 'CONFIG_PATH', preferences)):
+ loaded = config.load_ai_config()
+ for key, relative in defaults.items():
+ self.assertEqual(loaded[key], str(bundled / relative))
+ self.assertEqual(config.missing_models(loaded), [])
+ self.assertEqual(loaded['ocr_backend'], 'auto')
+ config.save_ai_config({'font_size': 20})
+ saved = yaml.safe_load(preferences.read_text('utf-8'))
+ self.assertEqual(saved['api_key'], raw['api_key'])
+ self.assertEqual(saved['translation_model'], raw['translation_model'])
+ for key, relative in defaults.items():
+ self.assertEqual(saved[key], 'models/' + relative)
+ # The same saved profile must also work after a second move.
+ relocated = root / 'third install/_internal/comic-translate-ai/models'
+ relocated.parent.mkdir(parents=True)
+ bundled.rename(relocated)
+ with patch.object(config, 'BUNDLED_MODELS_ROOT', relocated):
+ loaded = config.load_ai_config()
+ for key, relative in defaults.items():
+ self.assertEqual(loaded[key], str(relocated / relative))
+
+ def test_existing_models_and_unrelated_missing_custom_paths_are_preserved(self):
+ with TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundled = root / 'install/_internal/comic-translate-ai/models'
+ target = bundled / 'charspot-small'
+ target.mkdir(parents=True)
+ old = root / 'old/_internal/comic-translate-ai/models/charspot-small'
+ old.mkdir(parents=True)
+ custom = root / 'custom/charspot-small'
+ with (patch.object(config, 'MODELS_ROOT', root / 'profile/models'),
+ patch.object(config, 'BUNDLED_MODELS_ROOT', bundled)):
+ self.assertEqual(config._resolve_model_path(old, 'charspot-small'), old)
+ self.assertEqual(config._resolve_model_path(custom, 'charspot-small'), custom)
+ self.assertEqual(config._model_path_setting(custom, 'charspot-small'), custom)
+ custom.mkdir(parents=True)
+ self.assertEqual(config._resolve_model_path(custom, 'charspot-small'), custom)
+ # Traversal outside the former bundle must not become an installed default.
+ escaped = old / '../different'
+ self.assertEqual(config._resolve_model_path(escaped, 'charspot-small'), escaped)
+ # Optional legacy packages are not part of the current bundle.
+ manga = root / 'old/_internal/comic-translate-ai/models/manga-ocr-onnx'
+ self.assertEqual(config._resolve_model_path(manga, 'manga-ocr-onnx'), manga)
diff --git a/tests/test_model_upgrade.py b/tests/test_model_upgrade.py
index 037bf3e..7664cfb 100644
--- a/tests/test_model_upgrade.py
+++ b/tests/test_model_upgrade.py
@@ -50,11 +50,39 @@ def test_detector_migration_and_explicit_rollback(self):
explicit = config.save_ai_config({"use_gpu": True, "detector_model": str(new)})
self.assertIsNone(explicit["cuda_detector_model"])
+ def test_installed_defaults_use_bundled_models_with_an_empty_profile(self):
+ from comic_translate_core.detector_paths import LEGACY_PATH, SPLIT_PATH, LINE_FILE
+ from comic_translate_desktop import config
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundled = root / 'install' / 'models'
+ user_models = root / 'profile' / 'models'
+ for relative in (SPLIT_PATH, SPLIT_PATH.with_name(LINE_FILE), LEGACY_PATH,
+ config.MODEL_DEFAULTS['lama_model'], 'charspot-small/model.onnx',
+ 'charspot-small/config.json', 'charspot-small/vocab.json'):
+ path = bundled / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.touch()
+ with (patch.object(config, 'MODELS_ROOT', user_models),
+ patch.object(config, 'BUNDLED_MODELS_ROOT', bundled),
+ patch.object(config, 'CONFIG_PATH', root / 'config.yaml')):
+ defaults = config.load_ai_config()
+ self.assertEqual(config.missing_models(defaults), [])
+ self.assertEqual(defaults['detector_model'], str(bundled / SPLIT_PATH))
+ self.assertEqual(defaults['cuda_detector_model'], str(bundled / LEGACY_PATH))
+ relative = config.MODEL_DEFAULTS['lama_model']
+ previous = user_models / relative
+ self.assertEqual(config._resolve_model_path(previous, relative), bundled / relative)
+ previous.parent.mkdir(parents=True)
+ previous.touch()
+ self.assertEqual(config._resolve_model_path(previous, relative), previous)
+
def test_auto_detector_uses_legacy_only_when_cuda_is_active(self):
from onnx_text_detector import create_text_detector
from comic_translate_core.detector_paths import REGION_FILE
- with (patch('onnx_text_detector.create_onnx_session') as session,
+ with (patch('onnx_text_detector.create_image_session') as session,
patch('onnx_split_detector.SplitTextDetector') as split):
self.assertIs(create_text_detector(REGION_FILE, "cpu", cuda_model_path="fast.onnx"),
split.return_value)
diff --git a/tests/test_motion_overlay_lifecycle.py b/tests/test_motion_overlay_lifecycle.py
new file mode 100644
index 0000000..8531b17
--- /dev/null
+++ b/tests/test_motion_overlay_lifecycle.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import os
+import unittest
+from unittest.mock import patch
+
+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+from PySide6.QtCore import QPointF, Qt
+from PySide6.QtGui import QPaintEvent
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton, QWidget
+from shiboken6 import delete
+
+from comic_translate_desktop.ui.motion import (
+ _FocusLineOverlay, _MaterialMotionController, _RippleOverlay, reduced_motion, set_reduced_motion,
+)
+
+
+class MotionOverlayLifecycleTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+
+ def test_saving_dialog_stops_the_pressed_buttons_ripple_before_deletion(self):
+ self.addCleanup(set_reduced_motion, reduced_motion())
+ set_reduced_motion(False)
+ dialog = QDialog()
+ self.addCleanup(delete, dialog)
+ save = QPushButton('Save', dialog)
+ motion = _MaterialMotionController(dialog)
+ save.installEventFilter(motion)
+ save.clicked.connect(dialog.accept)
+ dialog.show()
+ QTest.mousePress(save, Qt.LeftButton)
+ ripple = save._motion_ripple_overlay
+ self.assertTrue(ripple._timer.isActive())
+ QTest.mouseRelease(save, Qt.LeftButton)
+ self.assertEqual(dialog.result(), QDialog.Accepted)
+ self.assertFalse(ripple._timer.isActive())
+ self.assertFalse(ripple._ripples)
+
+ def test_paint_with_only_native_widget_state(self):
+ # Qt can dispatch paint while the Python wrapper has no animation state.
+ for overlay_type in (_FocusLineOverlay, _RippleOverlay):
+ with self.subTest(overlay=overlay_type.__name__):
+ overlay = overlay_type.__new__(overlay_type)
+ QWidget.__init__(overlay)
+ try:
+ QApplication.sendEvent(overlay, QPaintEvent(overlay.rect()))
+ finally:
+ delete(overlay)
+
+ def test_native_initialization_can_dispatch_paint_before_constructor_returns(self):
+ native_init = QWidget.__init__
+ errors = []
+ painted = []
+
+ def record_error(kind, value, _traceback):
+ errors.append(f'{kind.__name__}: {value}')
+
+ def initialize_and_paint(widget, *args, **kwargs):
+ native_init(widget, *args, **kwargs)
+ if isinstance(widget, (_RippleOverlay, _FocusLineOverlay)):
+ painted.append(type(widget).__name__)
+ # Exercise a Qt virtual callback at the native constructor boundary.
+ QApplication.sendEvent(widget, QPaintEvent(widget.rect()))
+
+ for overlay_type, target_type in (
+ (_RippleOverlay, QPushButton), (_FocusLineOverlay, QLineEdit),
+ ):
+ with self.subTest(overlay=overlay_type.__name__):
+ target = target_type()
+ try:
+ with patch('sys.excepthook', record_error), \
+ patch.object(QWidget, '__init__', initialize_and_paint):
+ overlay_type(target)
+ finally:
+ delete(target)
+ self.assertEqual(painted, ['_RippleOverlay', '_FocusLineOverlay'])
+ self.assertEqual(errors, [])
+
+ def test_initialized_overlay_still_draws_and_finishes_its_animation(self):
+ errors = []
+ target = QPushButton('Preferences')
+ target.resize(180, 44)
+ set_reduced_motion(False)
+ try:
+ with patch('sys.excepthook', lambda kind, value, tb: errors.append(str(value))):
+ target.show()
+ overlay = _RippleOverlay(target)
+ overlay.trigger_ripple(QPointF(target.rect().center()))
+ overlay.release_ripples()
+ QTest.qWait(40)
+ self.assertTrue(overlay._ripples)
+ self.assertTrue(overlay._timer.isActive())
+ self.assertFalse(target.grab().isNull())
+ QTest.qWait(540)
+ self.assertFalse(overlay._ripples)
+ self.assertFalse(overlay._timer.isActive())
+ self.assertEqual(errors, [])
+ finally:
+ delete(target)
+ set_reduced_motion(False)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_nsis_installer.py b/tests/test_nsis_installer.py
new file mode 100644
index 0000000..ce10ed1
--- /dev/null
+++ b/tests/test_nsis_installer.py
@@ -0,0 +1,203 @@
+import json
+import os
+from pathlib import Path
+import subprocess
+from tempfile import TemporaryDirectory
+import time
+import unittest
+from unittest.mock import patch
+from uuid import uuid4
+
+from installer.build import (build_setup, build_uninstaller, find_makensis, nsis_inputs,
+ nsis_literal, validate_installer_models)
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class NsisInstallerTests(unittest.TestCase):
+ def test_full_installer_rejects_missing_models(self):
+ with TemporaryDirectory() as directory:
+ with self.assertRaisesRegex(FileNotFoundError, 'missing a required model'):
+ validate_installer_models(Path(directory))
+
+ @unittest.skipUnless(os.name == 'nt', 'NSIS integration requires Windows')
+ def test_folder_creation_reinstall_and_uninstall_with_native_service_arguments(self):
+ """Run real NSIS programs, isolating registry/shortcuts and substituting only SCM."""
+ try:
+ compiler = find_makensis(None)
+ except FileNotFoundError as error:
+ self.skipTest(str(error))
+ zig = next((ROOT / 'build/installer-native-tools').glob('zig-*/zig.exe'), None)
+ if not zig:
+ self.skipTest('Native SCM argument fixture requires portable Zig')
+ import pefile
+ import winreg
+
+ with TemporaryDirectory() as directory:
+ work = Path(directory)
+ fixture = work / 'service-api.dll'
+ subprocess.run([str(zig), 'cc', '-target', 'x86-windows-gnu', '-shared', '-O2',
+ '-Wno-dll-attribute-on-redeclaration',
+ str(ROOT / 'tests/installer_fixtures/service_api.c'),
+ '-o', str(fixture)], check=True,
+ env={**os.environ, 'ZIG_GLOBAL_CACHE_DIR': str(ROOT / 'build/zig-cache')})
+ key = 'Software\\ComiTransInstallerTest_' + uuid4().hex
+ service_dir = work / '服务 with spaces'
+ menu, desktop = work / 'menu', work / 'desktop'
+ menu.mkdir()
+ desktop.mkdir()
+ source = (ROOT / 'installer/ComiTrans.nsi').read_text('utf-8')
+ source = source.replace('RequestExecutionLevel admin', 'RequestExecutionLevel user')
+ source = source.replace('HKLM', 'HKCU').replace('Software\\ComiTrans', key)
+ source = source.replace('Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\ComiTrans', key + '\\Uninstall')
+ source = source.replace('Software\\Classes', key + '\\Classes')
+ source = source.replace('$PROGRAMFILES64\\ComiTrans Release Service', nsis_literal(service_dir))
+ source = source.replace('$SMPROGRAMS', nsis_literal(menu)).replace('$DESKTOP', nsis_literal(desktop))
+ source = source.replace('Global\\ComiTransSetup', 'Local\\' + key.rsplit('\\', 1)[-1])
+ with pefile.PE(str(fixture)) as pe:
+ exports = [entry.name.decode('ascii') for entry in pe.DIRECTORY_ENTRY_EXPORT.symbols]
+ for name in ('OpenSCManagerW', 'OpenServiceW', 'CreateServiceW', 'ChangeServiceConfigW',
+ 'StartServiceW', 'QueryServiceStatus', 'ControlService', 'DeleteService', 'CloseServiceHandle'):
+ exported = next(entry for entry in exports if entry == name or entry.startswith(name + '@'))
+ source = source.replace('advapi32::' + name + '(', str(fixture) + '::' + exported + '(')
+ script = work / 'installer.nsi'
+ script.write_text(source, encoding='utf-8')
+ payload = work / 'payload'
+ payload.mkdir()
+ (payload / 'ComiTrans.exe').write_bytes(b'fixture application')
+ (payload / 'ComiTransReleaseService.exe').write_bytes(b'fixture service')
+ nested = payload / '_internal' / '中文'
+ nested.mkdir(parents=True)
+ (nested / 'runtime.txt').write_text('runtime', encoding='utf-8')
+ manifest, languages = nsis_inputs(payload, work)
+
+ def compile_fixture(output, **extra):
+ defines = {'VERSION': '2.6.0', 'OUTPUT': output, 'PAYLOAD': payload,
+ 'ICON': ROOT / 'assets/ComiTrans.ico', 'UNINSTALL_FILES': manifest,
+ 'LOCALIZATION': languages, **extra}
+ command = [compiler, '/V2', '/WX', '/INPUTCHARSET', 'UTF8']
+ command.extend(f'/D{name}={nsis_literal(value)}' for name, value in defines.items())
+ subprocess.run([*command, str(script)], check=True)
+
+ compile_fixture(work / 'generator.exe', GENERATE_UNINSTALLER='1',
+ UNINSTALLER_OUT=payload / 'Uninstall.exe')
+ setup = work / 'ComiTrans-Fixture.exe'
+ compile_fixture(setup)
+ api_log = work / 'service-api.log'
+ state_file = work / 'service-state'
+ environment = {**os.environ, 'COMITRANS_FIXTURE_LOG': str(api_log),
+ 'COMITRANS_FIXTURE_STATE': str(state_file),
+ 'COMITRANS_FIXTURE_BINARY': f'"{service_dir / "ComiTransReleaseService.exe"}"'}
+
+ def run(executable, *arguments):
+ # NSIS requires /D= to be the final, unquoted command-line tail.
+ command = subprocess.list2cmdline([str(executable)]) + ' /S /LOG="' + str(work / 'install.log') + '"'
+ command += ''.join(' ' + argument for argument in arguments)
+ result = subprocess.run(command, env=environment, timeout=30)
+ log = work / 'install.log'
+ self.assertEqual(result.returncode, 0, log.read_text('utf-16-le') if log.exists() else command)
+
+ def read_registration():
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key + '\\Installer', 0,
+ winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as installed:
+ return winreg.QueryValueEx(installed, 'InstallDir')[0]
+
+ for name, full_path in (('new nested 中文', False), ('existing parent', False), ('explicit', True)):
+ with self.subTest(directory=name):
+ parent = work / name
+ if name == 'existing parent':
+ parent.mkdir()
+ (parent / 'parent-data.txt').write_text('keep', encoding='utf-8')
+ destination = parent / 'ComiTrans'
+ run(setup, '/D=' + str(destination if full_path else parent))
+ self.assertEqual(Path(read_registration()), destination)
+ self.assertTrue((destination / '_internal/中文/runtime.txt').is_file())
+ self.assertFalse((destination / 'ComiTrans').exists())
+ # A reinstall must stop/configure/start the same service and preserve the path.
+ run(setup)
+ self.assertEqual(Path(read_registration()), destination)
+ sentinel = destination / 'keep-user-file.txt'
+ sentinel.write_text('keep', encoding='utf-8')
+ run(destination / 'Uninstall.exe')
+ for _ in range(50):
+ if not (destination / 'Uninstall.exe').exists():
+ break
+ time.sleep(0.1)
+ self.assertEqual(list(destination.iterdir()), [sentinel])
+ self.assertFalse(state_file.exists())
+ self.assertFalse(service_dir.exists())
+ with self.assertRaises(FileNotFoundError):
+ read_registration()
+ if name == 'existing parent':
+ self.assertTrue((parent / 'parent-data.txt').exists())
+ calls = api_log.read_text('utf-16-le').splitlines()
+ self.assertNotIn('INVALID CONFIGURATION', calls)
+ self.assertEqual(calls.count('create'), 3)
+ self.assertEqual(calls.count('configure'), 3)
+ self.assertEqual(calls.count('start'), 6)
+ self.assertEqual(calls.count('delete'), 3)
+ # Only empty keys under this test's unique namespace can remain.
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key + '\\Classes')
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key)
+
+ def test_uninstall_manifest_only_removes_packaged_files(self):
+ with TemporaryDirectory() as directory:
+ work = Path(directory)
+ payload = work / 'payload'
+ nested = payload / '_internal' / '中文 $asset'
+ nested.mkdir(parents=True)
+ (nested / 'runtime.dll').write_bytes(b'runtime')
+ (payload / 'ComiTrans.exe').write_bytes(b'app')
+ (payload / 'ComiTransReleaseService.exe').write_bytes(b'service')
+ (payload / 'Uninstall.exe').write_bytes(b'uninstall')
+ manifest, _ = nsis_inputs(payload, work)
+ text = manifest.read_text('utf-8-sig')
+ self.assertIn('Delete "$INSTDIR\\_internal\\中文 $$asset\\runtime.dll"', text)
+ self.assertIn('Delete "$INSTDIR\\ComiTrans.exe"', text)
+ self.assertNotIn('ReleaseService', text)
+ self.assertNotIn('Uninstall.exe', text)
+ self.assertNotIn('/r', text)
+ self.assertNotIn('*', text)
+ self.assertNotIn('$LOCALAPPDATA', text)
+ self.assertLess(text.index('runtime.dll'), text.index('RMDir'))
+ self.assertLess(text.index('RMDir "$INSTDIR\\_internal\\中文'),
+ text.index('RMDir "$INSTDIR\\_internal"'))
+
+ def test_installer_translations_match_application_catalogs(self):
+ strings = json.loads((ROOT / 'installer/nsis_strings.json').read_text('utf-8'))
+ self.assertEqual(set(strings), {'en', 'ja', 'zh-CN', 'zh-TW'})
+ for locale, texts in strings.items():
+ self.assertEqual(set(texts), set(strings['en']))
+ if locale in {'en', 'ja'}:
+ catalog = json.loads((ROOT / f'assets/i18n/{locale}.json').read_text('utf-8'))
+ for key, value in texts.items():
+ self.assertEqual(catalog[f'installer.{key}'], value)
+
+ @unittest.skipUnless(os.name == 'nt', 'NSIS PE compilation requires Windows')
+ def test_setup_and_exported_uninstaller_compile_with_admin_manifests(self):
+ try:
+ compiler = find_makensis(None)
+ except FileNotFoundError as error:
+ self.skipTest(str(error))
+ import pefile
+
+ with TemporaryDirectory() as directory:
+ work = Path(directory)
+ payload = work / 'payload'
+ payload.mkdir()
+ (payload / 'ComiTrans.exe').write_bytes(b'fixture app')
+ (payload / 'ComiTransReleaseService.exe').write_bytes(b'fixture service')
+ (payload / '中文 $file.txt').write_text('fixture', encoding='utf-8')
+ build_uninstaller(compiler, payload, work)
+ with patch('installer.build.validate_installer_models'):
+ setup = build_setup(compiler, payload, work, work)
+ for executable in (setup, payload / 'Uninstall.exe'):
+ with self.subTest(executable=executable.name), pefile.PE(str(executable)) as pe:
+ manifests = [entry for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries if entry.id == 24]
+ self.assertEqual(len(manifests), 1)
+ entry = manifests[0].directory.entries[0].directory.entries[0].data.struct
+ manifest = pe.get_data(entry.OffsetToData, entry.Size).decode('utf-8')
+ self.assertIn('level="requireAdministrator"', manifest)
+ strings = pe.FileInfo[0][0].StringTable[0].entries
+ self.assertEqual(strings[b'ProductName'], b'ComiTrans')
diff --git a/tests/test_productivity_workflow.py b/tests/test_productivity_workflow.py
new file mode 100644
index 0000000..7163891
--- /dev/null
+++ b/tests/test_productivity_workflow.py
@@ -0,0 +1,341 @@
+import json
+import os
+from copy import deepcopy
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+from PIL import ImageChops
+from PySide6.QtCore import QSettings, Qt, QPointF, QPoint
+from PySide6.QtTest import QTest
+from PySide6.QtWidgets import QApplication, QTableWidgetItem, QMenu
+
+from comic_translate_desktop import config
+from comic_translate_desktop.desktop_translation import DesktopTranslationMixin
+from comic_translate_desktop.productivity import (
+ UsageMeter, usage_cost, trial_projection, desktop_translation_config,
+ terminology_projects, lettering_style, apply_lettering_style)
+from comic_translate_desktop.ui.editor_page import EditorPage
+from comic_translate_desktop.ui.main_window import MainWindow
+from comic_translate_desktop.ui.workflow_dialogs import TerminologyDialog, UsageDialog
+from comic_translate_desktop.i18n import tr
+from comic_translate_desktop.worker import BatchWorker
+from comic_translate_desktop.pdf_project import load_pdf_project
+from comic_translate_desktop.pdf_utils import build_pdf_from_images
+from tests import test_editor_live_preview as editor_fixtures
+from tests import test_translation_contract as translation_fixtures
+from tests import test_resume_translation as worker_fixtures
+
+
+class ProductivityDataTests(unittest.TestCase):
+ def test_target_only_terms_reach_the_real_translation_prompt_and_usage_counts_retries(self):
+ projects = {'work': dict(name='作品甲', terms=[dict(term='真子', kind='角色', note='猫头鹰装的女孩')])}
+ settings = dict(terminology_projects=projects, terminology_project='work', translation_prompt='背景')
+ pipeline = translation_fixtures._pipeline()
+ desktop_type = type('DesktopPipeline', (DesktopTranslationMixin, type(pipeline)), {})
+ desktop = desktop_type.__new__(desktop_type)
+ desktop.__dict__.update(pipeline.__dict__)
+ BatchWorker._apply_api_config(desktop, {**desktop.__dict__, **settings})
+ desktop.usage_meter = UsageMeter()
+ sdk = Mock()
+ responses = [translation_fixtures.response('bad JSON'),
+ translation_fixtures.response('{"translations":["真子回来了"]}')]
+ for response in responses:
+ response.usage = SimpleNamespace(prompt_tokens=100, completion_tokens=20)
+ sdk.chat.completions.create.side_effect = responses
+ with patch('openai.OpenAI', return_value=sdk):
+ self.assertEqual(desktop.translate_page_batch(['マコが帰ってきた'], None), ['真子回来了'])
+ prompt = sdk.chat.completions.create.call_args.kwargs['messages'][0]['content']
+ self.assertIn('自行匹配', prompt)
+ self.assertIn('猫头鹰装的女孩', prompt)
+ self.assertNotIn('source_term', prompt)
+ self.assertEqual(desktop.usage_meter.snapshot()['prompt_tokens'], 200)
+ self.assertEqual(desktop.usage_meter.snapshot()['requests'], 2)
+ self.assertEqual(settings['translation_prompt'], '背景')
+
+ def test_missing_partial_and_invalid_usage_never_claim_zero_or_complete_cost(self):
+ meter = UsageMeter()
+ meter.record(SimpleNamespace(usage=dict(prompt_tokens=120, completion_tokens=30)))
+ pricing = dict(enabled=True, input=2, output=6)
+ self.assertAlmostEqual(usage_cost(meter.snapshot(), pricing), .00042)
+ meter.record(SimpleNamespace(usage=None))
+ self.assertIsNone(usage_cost(meter.snapshot(), pricing))
+ meter.record(SimpleNamespace(usage=dict(prompt_tokens=-1, completion_tokens=True)))
+ self.assertEqual(meter.snapshot()['reported'], 1)
+ self.assertIsNone(usage_cost(meter.snapshot(), pricing))
+ report = dict(completed_pages=2, total_pages=20, processing_seconds=12,
+ usage=meter.snapshot())
+ self.assertEqual(trial_projection(report, pricing)['seconds'], 120)
+ self.assertIsNone(trial_projection({**report, 'failed': True}, pricing))
+ self.assertIsNone(trial_projection({**report, 'cancelled': True}, pricing))
+ self.assertIsNone(trial_projection({**report, 'total_pages_known': False}, pricing))
+
+ def test_style_never_copies_text_geometry_or_modifies_restored_bubbles(self):
+ source = dict(font_size=24, text_color='#ff0000', direction=0, text='甲', box=[0, 0, 90, 90])
+ target = dict(font_size=18, text='乙', source_text='乙原文', box=[20, 30, 50, 60], offset_x=8)
+ self.assertTrue(apply_lettering_style(target, lettering_style(source)))
+ self.assertEqual(target['text'], '乙')
+ self.assertEqual(target['source_text'], '乙原文')
+ self.assertEqual(target['box'], [20, 30, 50, 60])
+ self.assertEqual(target['offset_x'], 8)
+ target['restore_original'] = True
+ before = deepcopy(target)
+ self.assertFalse(apply_lettering_style(target, dict(font_size=60)))
+ self.assertEqual(target, before)
+
+
+class ProductivityUiTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+ cls.settings = tempfile.TemporaryDirectory()
+ QSettings.setDefaultFormat(QSettings.IniFormat)
+ QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, cls.settings.name)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.settings.cleanup()
+
+ def setUp(self):
+ temp = tempfile.TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.root = Path(temp.name)
+ setting = patch.object(config, 'CONFIG_PATH', self.root / 'config.yaml')
+ setting.start()
+ self.addCleanup(setting.stop)
+ config.save_ai_config({'watermark_enabled': False})
+
+ def editor(self):
+ output, layout = editor_fixtures.EditorLivePreviewTests.page(self, two_blocks=True)
+ editor = EditorPage()
+ self.assertTrue(editor.load_page(output))
+ self.addCleanup(editor_fixtures.EditorLivePreviewTests.destroy_editor, editor)
+ return editor, output, layout
+
+ def test_multiselect_changes_only_the_edited_attribute_and_survives_save_reload(self):
+ editor, output, layout = self.editor()
+ original = deepcopy(editor.items)
+ editor._select_blocks([0, 1])
+ editor._outline_width.setValue(4)
+ self.assertTrue(editor.apply_changes())
+ for row, item in enumerate(editor.items):
+ self.assertEqual(item['outline_width'], 4)
+ for key in ('text', 'source_text', 'box', 'mask_box'):
+ self.assertEqual(item[key], original[row][key])
+ self.assertEqual(editor.items[1]['font_size'], 20)
+ # Text edits remain local even while several bubbles are selected.
+ editor._text_input.setPlainText('只改这一个气泡')
+ editor.apply_changes()
+ self.assertEqual(editor.items[1]['text'], original[1]['text'])
+ self.assertTrue(editor.save_image())
+ saved = json.loads(layout.read_text(encoding='utf-8'))
+ self.assertEqual([item['outline_width'] for item in saved], [4, 4])
+ self.assertEqual(saved[1]['text'], original[1]['text'])
+
+ def test_brush_undo_preserves_text_and_next_page_clears_undo(self):
+ editor, _, _ = self.editor()
+ before = deepcopy(editor.items[1])
+ editor.resize(1440, 900)
+ editor.show()
+ self.app.processEvents()
+ editor.copy_style()
+ point = editor.block_list.visualItemRect(editor.block_list.item(1)).center()
+ QTest.mouseClick(editor.block_list.viewport(), Qt.LeftButton, Qt.NoModifier, point)
+ self.assertEqual(editor.items[1]['font_size'], 24)
+ self.assertEqual(editor.items[1]['text'], before['text'])
+ self.assertEqual(editor.items[1]['box'], before['box'])
+ self.assertTrue(editor.undo_style())
+ self.assertEqual(editor.items[1]['font_size'], 20)
+ self.assertEqual(editor.items[1]['text'], before['text'])
+ second, _ = editor_fixtures.EditorLivePreviewTests.page(self, name='second', two_blocks=True)
+ editor._dirty = False
+ self.assertTrue(editor.load_page(second))
+ self.assertFalse(editor.undo_style())
+
+ def test_selection_overlay_does_not_change_export_pixels_and_ctrl_click_toggles(self):
+ editor, _, _ = self.editor()
+ editor.resize(1440, 900)
+ editor.show()
+ self.app.processEvents()
+ self.assertTrue(editor.apply_changes())
+ before = editor._rendered.copy()
+ editor._show_mask.setChecked(True)
+ canvas = editor.preview._label
+ point = canvas._box_rect(editor.items[1]['mask_box']).center().toPoint()
+ QTest.mouseClick(canvas, Qt.LeftButton, Qt.ControlModifier, point)
+ self.assertEqual(editor.selected_blocks(), [0, 1])
+ QTest.mouseClick(canvas, Qt.LeftButton, Qt.ControlModifier, point)
+ self.assertEqual(editor.selected_blocks(), [0])
+ start = (canvas._box_rect(editor.items[0]['mask_box']).topLeft() - QPointF(3, 3)).toPoint()
+ end = (canvas._box_rect(editor.items[1]['mask_box']).bottomRight() + QPointF(3, 3)).toPoint()
+ QTest.mousePress(canvas, Qt.LeftButton, Qt.ShiftModifier, start)
+ QTest.mouseMove(canvas, end)
+ QTest.mouseRelease(canvas, Qt.LeftButton, Qt.ShiftModifier, end)
+ self.assertEqual(editor.selected_blocks(), [0, 1])
+ self.assertIsNone(ImageChops.difference(before, editor._rendered).getbbox())
+
+ def test_switching_bubble_before_debounce_does_not_apply_style_to_new_selection(self):
+ editor, _, _ = self.editor()
+ editor._outline_width.setValue(5)
+ editor.block_list.setCurrentRow(1)
+ editor.apply_changes()
+ self.assertEqual(editor.items[0]['outline_width'], 5)
+ self.assertIsNone(editor.items[1].get('outline_width'))
+
+ def test_flat_style_menu_preserves_batch_selection_and_right_click_never_paints(self):
+ editor, _, _ = self.editor()
+ editor.resize(1024, 720)
+ editor.show()
+ self.app.processEvents()
+ editor.copy_style()
+ editor._stop_style_brush()
+ editor._select_blocks([0, 1])
+ editor._style_brush_btn.setChecked(True)
+ before = deepcopy(editor.items)
+ with patch.object(editor, '_show_bubble_context_menu'):
+ editor._show_canvas_bubble_context_menu(1, QPoint(100, 100))
+ self.assertEqual(editor.selected_blocks(), [0, 1])
+ self.assertEqual(editor.items, before)
+ self.assertTrue(editor._brush_cancel_btn.isVisible())
+ self.assertFalse(editor.preview._label.region_editable)
+ menu = QMenu(editor)
+ self.addCleanup(menu.deleteLater)
+ editor._populate_bubble_menu(menu)
+ self.assertTrue(all(action.menu() is None for action in menu.actions()))
+ actions = {action.text(): action for action in menu.actions()}
+ actions[tr('应用样式到所选气泡')].trigger()
+ self.assertEqual([item['font_size'] for item in editor.items], [24, 24])
+ self.assertEqual([item['text'] for item in editor.items], [item['text'] for item in before])
+ editor._populate_bubble_menu(menu)
+ {action.text(): action for action in menu.actions()}[tr('撤销样式')].trigger()
+ self.assertEqual(editor.items[1]['font_size'], 20)
+ editor._brush_cancel_btn.click()
+ self.assertFalse(editor._style_brush_btn.isChecked())
+ self.assertTrue(editor._restore_bubble_btn.isVisible())
+ editor.copy_style()
+ editor._repair_mode.setChecked(True)
+ self.assertFalse(editor._style_brush_btn.isChecked())
+
+ def test_project_switch_keeps_target_only_terms_and_cancel_does_not_mutate_config(self):
+ original = dict(terminology_project='a', terminology_projects={
+ 'a': dict(name='作品甲', terms=[dict(term='真子', kind='角色', note='女孩')]),
+ 'b': dict(name='作品乙', terms=[])})
+ dialog = TerminologyDialog(original)
+ self.addCleanup(dialog.deleteLater)
+ self.assertEqual(dialog.table.columnCount(), 3)
+ dialog.table.setItem(0, 0, QTableWidgetItem('小真'))
+ dialog.project.setCurrentIndex(dialog.project.findData('b'))
+ dialog.table.insertRow(0)
+ dialog.table.setItem(0, 0, QTableWidgetItem('苍蓝城'))
+ values = dialog.values()
+ self.assertEqual(values['terminology_projects']['a']['terms'][0]['term'], '小真')
+ self.assertEqual(values['terminology_projects']['b']['terms'][0]['term'], '苍蓝城')
+ self.assertEqual(original['terminology_projects']['a']['terms'][0]['term'], '真子')
+ config.save_ai_config(values)
+ loaded = config.load_ai_config()
+ self.assertIn('苍蓝城', desktop_translation_config(loaded)['translation_prompt'])
+ self.assertNotIn('小真', desktop_translation_config(loaded)['translation_prompt'])
+
+ def test_task_menu_groups_optional_actions_and_locks_them_during_a_job(self):
+ with patch.object(config, 'PROJECT_ROOT', self.root), patch.object(MainWindow, '_start_warmup'):
+ window = MainWindow()
+ self.addCleanup(self.destroy_main, window)
+ window._warmup_timer.stop()
+ window.resize(820, 640)
+ window.show()
+ self.app.processEvents()
+ self.assertTrue(window._trial_btn.isVisible())
+ self.assertTrue(window._task_menu_btn.isVisible())
+ self.assertFalse(window._usage_btn.isVisible())
+ self.assertFalse(window._task_usage_action.isEnabled())
+ self.assertTrue(all(action.menu() is None for action in window._task_menu.actions()))
+ window.config.update(terminology_project='a', terminology_projects={
+ 'a': dict(name='作品甲', terms=[dict(term='真子')])})
+ window._refresh_terminology_summary()
+ self.assertIn('作品甲', window._task_work_info.toolTip())
+ window._last_usage_report = dict(completed_pages=1)
+ window._update_actions()
+ self.assertTrue(window._task_usage_action.isEnabled())
+ window.worker = SimpleNamespace()
+ window._update_actions()
+ self.assertFalse(window._task_menu_btn.isEnabled())
+ self.assertFalse(window._task_terms_action.isEnabled())
+ self.assertFalse(window._task_usage_action.isEnabled())
+
+ @staticmethod
+ def destroy_main(window):
+ window.worker = None
+ window.editor_page._dirty = False
+ window.close()
+ window.deleteLater()
+
+
+class TrialIsolationTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+
+ def test_pdf_trial_uses_real_partial_project_and_formal_run_still_processes_every_page(self):
+ from PIL import Image
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ images = []
+ for number in range(5):
+ image = root / f'{number}.png'
+ Image.new('RGB', (100, 120), 'white').save(image)
+ images.append(image)
+ source = build_pdf_from_images(images, [(100, 120)] * 5, root / 'book.pdf')
+ context = root / '.cache/translation-context.json'
+ context.parent.mkdir()
+ context.write_text('formal-context-untouched', encoding='utf-8')
+ settings = dict(api_key='test', api_base_url='https://example.invalid',
+ translation_model='test', pdf_dpi=96, max_workers=2,
+ resume_enabled=True, retain_translation_context=True)
+ with patch.object(config, 'PROJECT_ROOT', root):
+ trial = BatchWorker([source], root / 'output/trial/sample',
+ {**settings, 'trial_page_limit': 2},
+ pipeline=worker_fixtures.RecordingPipeline())
+ trial.run()
+ report = trial.usage_report
+ self.assertEqual((report['completed_pages'], report['planned_pages'], report['total_pages']), (2, 2, 5))
+ self.assertEqual(len(load_pdf_project(report['outputs'][0]).images), 2)
+ self.assertEqual(context.read_text(encoding='utf-8'), 'formal-context-untouched')
+ pipeline = worker_fixtures.RecordingPipeline()
+ full = BatchWorker([source], root / 'output', {**settings, 'retain_translation_context': False}, pipeline=pipeline)
+ full.run()
+ self.assertEqual(full.usage_report['completed_pages'], 5)
+ self.assertEqual(len(pipeline.requests), 5)
+ self.assertEqual(len(load_pdf_project(root / 'output/book_translated.pdf').images), 5)
+
+ def test_prices_and_inactive_terms_preserve_resume_but_active_terms_invalidate(self):
+ from PIL import Image
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ source = root / 'page.png'
+ Image.new('RGB', (100, 120), 'white').save(source)
+ settings = dict(api_key='test', api_base_url='https://example.invalid',
+ translation_model='test', resume_enabled=True,
+ terminology_project='a', terminology_projects={
+ 'a': dict(name='甲', terms=[dict(term='真子')]),
+ 'b': dict(name='乙', terms=[])})
+ def run(values):
+ pipeline = worker_fixtures.RecordingPipeline()
+ worker = BatchWorker([source], root / 'output', values, pipeline=pipeline)
+ worker.run()
+ self.assertFalse(worker.usage_report['failed'])
+ return pipeline.requests
+ with patch.object(config, 'PROJECT_ROOT', root):
+ legacy = {key: value for key, value in settings.items() if not key.startswith('terminology_')}
+ self.assertEqual(run(legacy), ['page.png'])
+ migrated = {**legacy, 'terminology_project': '', 'terminology_projects': {}, 'usage_pricing': {}}
+ self.assertEqual(run(migrated), [])
+ self.assertEqual(run(settings), ['page.png'])
+ updated = deepcopy(settings)
+ updated['usage_pricing'] = dict(enabled=True, input=2, output=5)
+ updated['terminology_projects']['b']['terms'] = [dict(term='苍蓝城')]
+ self.assertEqual(run(updated), [])
+ updated['terminology_projects']['a']['terms'] = [dict(term='小真')]
+ self.assertEqual(run(updated), ['page.png'])
diff --git a/tests/test_release_update.py b/tests/test_release_update.py
new file mode 100644
index 0000000..e71b9c5
--- /dev/null
+++ b/tests/test_release_update.py
@@ -0,0 +1,237 @@
+from contextlib import nullcontext
+import hashlib
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import unittest
+from unittest.mock import Mock, patch
+
+from comic_translate_core.release_update import (
+ Asset, Release, REPOSITORY_URL, SIGNPATH_ASSET_LABEL, delta_name, installer_name, latest_stable, prepare_update,
+)
+from comic_translate_desktop.pdf_project import project_link_path
+from comic_translate_core.windows_install import InstalledProduct, installed_product, original_package
+from installer.build import build_delta
+
+
+class ReleaseUpdateTests(unittest.TestCase):
+ def test_only_newer_stable_versions_are_offered(self):
+ for release in (None, {}, {'tag_name': 'v2.5.1'}, {'tag_name': 'v2.5.2'},
+ {'tag_name': 'v2.6.0-rc.1'}, {'tag_name': 'v2.6.0', 'prerelease': True},
+ {'tag_name': 'v2.6.0', 'draft': True}):
+ with self.subTest(release=release):
+ self.assertIsNone(latest_stable(release, '2.5.2'))
+ self.assertEqual(latest_stable({'tag_name': 'v2.10.0'}, '2.9.0').version, '2.10.0')
+
+ def test_only_exact_signed_release_assets_with_digest_can_be_downloaded(self):
+ name = installer_name('2.6.0')
+ item = {'name': name, 'size': 1024, 'digest': 'sha256:' + 'a' * 64,
+ 'browser_download_url': f'{REPOSITORY_URL}/releases/download/v2.6.0/{name}'}
+ data = {'tag_name': 'v2.6.0', 'html_url': 'https://example.com/fake', 'assets': [item]}
+ release = latest_stable(data, '2.5.2')
+ self.assertEqual(release.url, f'{REPOSITORY_URL}/releases/tag/v2.6.0')
+ self.assertIsNone(release.installer)
+ item['label'] = SIGNPATH_ASSET_LABEL
+ release = latest_stable(data, '2.5.2')
+ self.assertEqual(release.installer.sha256, 'a' * 64)
+ item['browser_download_url'] = 'https://example.com/' + name
+ self.assertIsNone(latest_stable(data, '2.5.2').installer)
+
+ def test_release_selects_the_installed_format_and_its_delta(self):
+ names = [installer_name('2.6.0'), installer_name('2.6.0', setup=True),
+ delta_name('2.5.2', '2.6.0'), delta_name('2.5.2', '2.6.0', setup=True)]
+ url = f'{REPOSITORY_URL}/releases/download/v2.6.0/'
+ assets = [{'name': name, 'label': SIGNPATH_ASSET_LABEL, 'size': 1024, 'digest': 'sha256:' + 'a' * 64,
+ 'browser_download_url': url + name} for name in names]
+ published = {'tag_name': 'v2.6.0', 'assets': assets}
+ for setup in (False, True):
+ with self.subTest(setup=setup):
+ release = latest_stable(published, '2.5.2', setup=setup)
+ self.assertEqual(release.installer.url, url + names[setup])
+ self.assertEqual(release.delta.url, url + names[2 + setup])
+ self.assertIsNone(latest_stable({**published, 'assets': assets[:1]}, '2.5.2', setup=True).installer)
+
+ def test_registry_preserves_msi_and_setup_installations(self):
+ root = Path.cwd()
+ source = root / installer_name('2.5.2', setup=True)
+ values = {'InstallDir': str(root), 'ProductCode': 'product'}
+ registry = Mock(HKEY_LOCAL_MACHINE=1, KEY_READ=2, KEY_WOW64_64KEY=4)
+
+ def read(_key, name):
+ if name not in values:
+ raise FileNotFoundError(name)
+ return values[name], 1
+
+ registry.OpenKey.return_value = nullcontext(object())
+ registry.QueryValueEx.side_effect = read
+ with patch.dict('sys.modules', winreg=registry), patch('sys.platform', 'win32'), \
+ patch('sys.frozen', True, create=True):
+ self.assertEqual(installed_product(root), InstalledProduct('product'))
+ values['SetupManaged'] = '1'
+ self.assertEqual(installed_product(root), InstalledProduct('product', setup=True))
+ values['SetupSource'] = str(source)
+ product = installed_product(root)
+ self.assertTrue(product.setup)
+ self.assertEqual(original_package(product), source)
+ self.assertIsNone(installed_product(root / 'other'))
+
+ def test_delta_restore_and_fallback_verify_the_full_signed_package(self):
+ for setup in (False, True):
+ with self.subTest(setup=setup):
+ self._check_delta_and_signature(setup)
+
+ def _check_delta_and_signature(self, setup):
+ with TemporaryDirectory() as directory:
+ root = Path(directory)
+ base = root / installer_name('2.5.2', setup=setup)
+ target = root / installer_name('2.6.0', setup=setup)
+ payload = hashlib.shake_256(b'WiX cabinet data').digest(950_000)
+ base.write_bytes(payload)
+ target.write_bytes(b'new header' + payload)
+ build_delta(base, target)
+ delta = root / delta_name('2.5.2', '2.6.0', setup=setup)
+
+ def metadata(path):
+ return Asset(str(path), path.stat().st_size, hashlib.sha256(path.read_bytes()).hexdigest())
+
+ release = Release('2.6.0', '', metadata(target), metadata(delta), setup)
+ downloaded = []
+
+ def download(asset, output, canceled):
+ downloaded.append(asset)
+ output.write_bytes(Path(asset.url).read_bytes())
+
+ with patch('comic_translate_core.release_update._download', side_effect=download), \
+ patch('comic_translate_core.release_update._powershell', return_value=Mock(**{'wait.return_value': 0})):
+ cache = root / 'cache'
+ prepared = prepare_update(release, '2.5.2', cache, base, lambda: False)
+ self.assertEqual(prepared.read_bytes(), target.read_bytes())
+ self.assertEqual(downloaded, [release.delta])
+ downloaded.clear()
+ base.write_bytes(b'wrong base file')
+ prepared = prepare_update(release, '2.5.2', cache, base, lambda: False)
+ self.assertEqual(prepared.read_bytes(), target.read_bytes())
+ self.assertEqual(downloaded, [release.delta, release.installer])
+
+ with patch('comic_translate_core.release_update._download', side_effect=download), \
+ patch('comic_translate_core.release_update._powershell', return_value=Mock(**{'wait.return_value': 1})):
+ blocked = root / 'blocked'
+ with self.assertRaisesRegex(ValueError, 'signature'):
+ prepare_update(release, '2.5.2', blocked, None, lambda: False)
+ self.assertFalse((blocked / target.name).exists())
+
+ def test_pdf_links_use_the_association_or_find_the_existing_index(self):
+ with TemporaryDirectory() as directory:
+ pdf = Path(directory) / '漫画.sample.pdf'
+ new = pdf.with_suffix('.comitrans')
+ old = pdf.with_suffix('.comitrans.json')
+ self.assertEqual(project_link_path(pdf), new)
+ old.touch()
+ self.assertEqual(project_link_path(pdf), old)
+ new.touch()
+ self.assertEqual(project_link_path(pdf), new)
+
+ def test_update_offer_dialog_dispatches_actions_and_respects_installer_capability(self):
+ import os
+ os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+ from PySide6.QtCore import Qt
+ from PySide6.QtWidgets import QApplication
+ from shiboken6 import isValid
+ from comic_translate_desktop.ui.update_notice import UpdateOfferDialog
+ from tests.qt_utils import destroy_widget
+
+ app = QApplication.instance() or QApplication([])
+ release = Release('2.6.0', 'https://github.com/Aaaaamadeus/ComiTrans/releases/tag/v2.6.0',
+ Asset('https://example.com/setup.exe', 100, 'a' * 64), None, True)
+ events = []
+ installed = UpdateOfferDialog('2.5.2', release, can_install=True,
+ on_release=lambda: events.append('release'),
+ on_install=lambda: events.append('install'))
+ self.addCleanup(lambda: isValid(installed) and destroy_widget(installed))
+ self.assertEqual(installed.windowModality(), Qt.WindowModality.NonModal)
+ self.assertIsNotNone(installed.install_button)
+ self.assertEqual(installed.install_button.property('role'), 'primary')
+ self.assertEqual(installed.release_button.property('role'), 'utility')
+ installed.install_button.click()
+ self.assertEqual(events, ['install'])
+
+ portable = UpdateOfferDialog('2.5.2', release, can_install=False,
+ on_release=lambda: events.append('release'),
+ on_install=lambda: events.append('install'))
+ self.addCleanup(lambda: isValid(portable) and destroy_widget(portable))
+ self.assertIsNone(portable.install_button)
+ self.assertEqual(portable.release_button.property('role'), 'primary')
+ portable.release_button.click()
+ self.assertEqual(events, ['install', 'release'])
+
+ def test_update_progress_dialog_emits_cancel_without_hardcoded_hex_colors(self):
+ import ast
+ import inspect
+ import os
+ import re
+ import textwrap
+
+ os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+
+ from PySide6.QtCore import QCoreApplication, QEvent
+ from PySide6.QtWidgets import QApplication, QAbstractButton, QWidget
+
+ from comic_translate_desktop.ui.motion import MonochromeShimmerBar
+ from comic_translate_desktop.ui.update_notice import UpdateProgressDialog
+
+ hex_color = re.compile(
+ r'(?